From 849c5ae561c509aa31538dac3d528befb76366c3 Mon Sep 17 00:00:00 2001 From: yezhengli-Mr9 <16505983+yezhengli-Mr9@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:06:58 -0800 Subject: [PATCH 1/3] perf(cache): stop after a complete prompt prefix match Stop RAM and disk prefix searches once the requested sequence is fully matched. Preserve first-match tie selection, partial-match scans, empty misses, and RAM LRU updates. Add focused behavioral and comparison-count regressions. --- llama_cpp/llama_cache.py | 10 +++++- tests/test_llama_cache.py | 74 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 tests/test_llama_cache.py 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..9ed1b4362 --- /dev/null +++ b/tests/test_llama_cache.py @@ -0,0 +1,74 @@ +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): + if request.param == "ram": + yield LlamaRAMCache() + else: + instance = LlamaDiskCache(str(tmp_path / "cache")) + try: + yield instance + finally: + instance.cache.close() + + +def _state(tokens, seed): + return LlamaState( + input_ids=np.array(tokens, dtype=np.intc), + scores=np.empty((0, 0), dtype=np.single), + n_tokens=len(tokens), + llama_state=b"state", + llama_state_size=5, + seed=seed, + ) + + +@pytest.mark.parametrize("query", [(1, 2), (1, 2, 0)]) +def test_complete_prefix_avoids_remaining_comparisons(cache, query): + keys = [(1, 2, 0), (1, 2, 1), (1, 3, 0)] + for seed, key in enumerate(keys): + cache[key] = _state(key, seed) + first = next( + iter(cache.cache_state) + if isinstance(cache, LlamaRAMCache) + else cache.cache.iterkeys() + ) + with patch.object( + Llama, "longest_token_prefix", wraps=Llama.longest_token_prefix + ) as compare: + assert cache[query].seed == keys.index(first) + assert compare.call_count == 1 + + +@pytest.mark.parametrize( + "query,expected", + [((1, 2, 9), 1), ((1, 9), 0), ((9,), None), ((), None)], +) +def test_partial_matches_and_misses_preserve_selection(cache, query, expected): + keys = [(1, 0), (1, 2, 3), (2, 0)] + for seed, key in enumerate(keys): + cache[key] = _state(key, seed) + if expected is None: + with pytest.raises(KeyError): + cache[query] + assert query not in cache + else: + assert cache[query].seed == expected + assert query in cache + + +def test_ram_complete_prefix_hit_updates_recency(): + cache = LlamaRAMCache(capacity_bytes=10) + first, second, third = (1, 2, 0), (2, 0), (3, 0) + for seed, key in enumerate((first, second)): + cache[key] = _state(key, seed) + assert cache[(1, 2)].seed == 0 + cache[third] = _state(third, 2) + assert list(cache.cache_state) == [first, third] From 1a137b663f94ab5a5b85ab4fd63666d7dd61e80d Mon Sep 17 00:00:00 2001 From: yezhengli-Mr9 <16505983+yezhengli-Mr9@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:11:16 -0800 Subject: [PATCH 2/3] test(cache): derive full requests from actual iteration order --- tests/test_llama_cache.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/test_llama_cache.py b/tests/test_llama_cache.py index 9ed1b4362..a2546cab5 100644 --- a/tests/test_llama_cache.py +++ b/tests/test_llama_cache.py @@ -30,9 +30,9 @@ def _state(tokens, seed): ) -@pytest.mark.parametrize("query", [(1, 2), (1, 2, 0)]) -def test_complete_prefix_avoids_remaining_comparisons(cache, query): - keys = [(1, 2, 0), (1, 2, 1), (1, 3, 0)] +@pytest.mark.parametrize("request_length", [2, 3]) +def test_complete_prefix_avoids_remaining_comparisons(cache, request_length): + keys = [(1, 2, 0), (1, 2, 1), (1, 2, 2)] for seed, key in enumerate(keys): cache[key] = _state(key, seed) first = next( @@ -40,6 +40,7 @@ def test_complete_prefix_avoids_remaining_comparisons(cache, query): if isinstance(cache, LlamaRAMCache) else cache.cache.iterkeys() ) + query = first[:request_length] with patch.object( Llama, "longest_token_prefix", wraps=Llama.longest_token_prefix ) as compare: From 1fcbdc6febdacb37afa1e13464fceef8e1f87163 Mon Sep 17 00:00:00 2001 From: yezhengli-Mr9 <16505983+yezhengli-Mr9@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:35:58 -0800 Subject: [PATCH 3/3] test(cache): keep prefix search regressions focused --- tests/test_llama_cache.py | 81 +++++++++++++-------------------------- 1 file changed, 27 insertions(+), 54 deletions(-) diff --git a/tests/test_llama_cache.py b/tests/test_llama_cache.py index a2546cab5..355f9df4d 100644 --- a/tests/test_llama_cache.py +++ b/tests/test_llama_cache.py @@ -9,67 +9,40 @@ @pytest.fixture(params=["ram", "disk"]) def cache(request, tmp_path): - if request.param == "ram": - yield LlamaRAMCache() - else: - instance = LlamaDiskCache(str(tmp_path / "cache")) - try: - yield instance - finally: + instance = ( + LlamaRAMCache() + if request.param == "ram" + else LlamaDiskCache(str(tmp_path / "cache")) + ) + try: + yield instance + finally: + if isinstance(instance, LlamaDiskCache): instance.cache.close() -def _state(tokens, seed): - return LlamaState( - input_ids=np.array(tokens, dtype=np.intc), - scores=np.empty((0, 0), dtype=np.single), - n_tokens=len(tokens), - llama_state=b"state", - llama_state_size=5, - seed=seed, +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 ) - - -@pytest.mark.parametrize("request_length", [2, 3]) -def test_complete_prefix_avoids_remaining_comparisons(cache, request_length): keys = [(1, 2, 0), (1, 2, 1), (1, 2, 2)] - for seed, key in enumerate(keys): - cache[key] = _state(key, seed) + for key in keys: + cache[key] = state first = next( iter(cache.cache_state) if isinstance(cache, LlamaRAMCache) else cache.cache.iterkeys() ) - query = first[:request_length] - with patch.object( - Llama, "longest_token_prefix", wraps=Llama.longest_token_prefix - ) as compare: - assert cache[query].seed == keys.index(first) - assert compare.call_count == 1 - - -@pytest.mark.parametrize( - "query,expected", - [((1, 2, 9), 1), ((1, 9), 0), ((9,), None), ((), None)], -) -def test_partial_matches_and_misses_preserve_selection(cache, query, expected): - keys = [(1, 0), (1, 2, 3), (2, 0)] - for seed, key in enumerate(keys): - cache[key] = _state(key, seed) - if expected is None: - with pytest.raises(KeyError): - cache[query] - assert query not in cache - else: - assert cache[query].seed == expected - assert query in cache - - -def test_ram_complete_prefix_hit_updates_recency(): - cache = LlamaRAMCache(capacity_bytes=10) - first, second, third = (1, 2, 0), (2, 0), (3, 0) - for seed, key in enumerate((first, second)): - cache[key] = _state(key, seed) - assert cache[(1, 2)].seed == 0 - cache[third] = _state(third, 2) - assert list(cache.cache_state) == [first, third] + 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