Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion llama_cpp/llama_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@


class BaseLlamaCache(ABC):
"""Base cache class for a llama.cpp model."""
"""Base cache class for a llama.cpp model.

Prefix lookup retains the first longest match and stops once the entire
requested token sequence matches, since no later entry can improve it.
"""

def __init__(self, capacity_bytes: int = (2 << 30)):
self.capacity_bytes = capacity_bytes
Expand Down Expand Up @@ -75,6 +79,8 @@ def _find_longest_prefix_key(
if prefix_len > min_len:
min_len = prefix_len
min_key = k
if prefix_len == len(key):
break
return min_key

def __getitem__(self, key: Sequence[int]) -> "llama_cpp.llama.LlamaState":
Expand Down Expand Up @@ -131,6 +137,8 @@ def _find_longest_prefix_key(
if prefix_len > min_len:
min_len = prefix_len
min_key = k # type: ignore
if prefix_len == len(key):
break
return min_key

def __getitem__(self, key: Sequence[int]) -> "llama_cpp.llama.LlamaState":
Expand Down
48 changes: 48 additions & 0 deletions tests/test_llama_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from unittest.mock import patch

import numpy as np
import pytest

from llama_cpp import Llama, LlamaState
from llama_cpp.llama_cache import LlamaDiskCache, LlamaRAMCache


@pytest.fixture(params=["ram", "disk"])
def cache(request, tmp_path):
instance = (
LlamaRAMCache()
if request.param == "ram"
else LlamaDiskCache(str(tmp_path / "cache"))
)
try:
yield instance
finally:
if isinstance(instance, LlamaDiskCache):
instance.cache.close()


def test_prefix_search_stops_only_when_the_request_is_fully_matched(cache):
state = LlamaState(
np.empty(0, dtype=np.intc), np.empty((0, 0), dtype=np.single), 0, b"", 0, 0
)
keys = [(1, 2, 0), (1, 2, 1), (1, 2, 2)]
for key in keys:
cache[key] = state
first = next(
iter(cache.cache_state)
if isinstance(cache, LlamaRAMCache)
else cache.cache.iterkeys()
)
for query, expected, comparisons in (
(first[:-1], first, 1),
(first, first, 1),
(first + (9,), first, len(keys)),
((1, 2, 9), first, len(keys)),
((9,), None, len(keys)),
((), None, len(keys)),
):
with patch.object(
Llama, "longest_token_prefix", wraps=Llama.longest_token_prefix
) as compare:
assert cache._find_longest_prefix_key(query) == expected, query
assert compare.call_count == comparisons, query