diff --git a/llama_cpp/llama_cache.py b/llama_cpp/llama_cache.py index 5fed2431a..80a45af78 100644 --- a/llama_cpp/llama_cache.py +++ b/llama_cpp/llama_cache.py @@ -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 @@ -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": @@ -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": diff --git a/tests/test_llama_cache.py b/tests/test_llama_cache.py new file mode 100644 index 000000000..355f9df4d --- /dev/null +++ b/tests/test_llama_cache.py @@ -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