From 95b630517a20a02a23af099c67917e8686fd7e82 Mon Sep 17 00:00:00 2001 From: Steven Huang <134844631+remote-controlled-man@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:39:08 +0800 Subject: [PATCH 1/4] fix(cache): preserve disk cache entries on lookup --- CHANGELOG.md | 1 + llama_cpp/llama_cache.py | 5 +-- tests/test_llama_cache.py | 77 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+), 4 deletions(-) create mode 100644 tests/test_llama_cache.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c582001020..be2a14cd19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- fix(cache): preserve disk cache entries on lookup by @remote-controlled-man - fix(ci): remove unsupported macOS 14 release runners by @abetlen in #2416 ## [0.3.37] diff --git a/llama_cpp/llama_cache.py b/llama_cpp/llama_cache.py index 5220c79337..b7d68c227d 100644 --- a/llama_cpp/llama_cache.py +++ b/llama_cpp/llama_cache.py @@ -132,10 +132,7 @@ def __getitem__(self, key: Sequence[int]) -> "llama_cpp.llama.LlamaState": _key = self._find_longest_prefix_key(key) if _key is None: raise KeyError("Key not found") - value: "llama_cpp.llama.LlamaState" = self.cache.pop(_key) # type: ignore - # NOTE: This puts an integer as key in cache, which breaks, - # Llama.longest_token_prefix(k, key) above since k is not a tuple of ints/tokens - # self.cache.push(_key, side="front") # type: ignore + value: "llama_cpp.llama.LlamaState" = self.cache[_key] # type: ignore return value def __contains__(self, key: Sequence[int]) -> bool: diff --git a/tests/test_llama_cache.py b/tests/test_llama_cache.py new file mode 100644 index 0000000000..bb49778961 --- /dev/null +++ b/tests/test_llama_cache.py @@ -0,0 +1,77 @@ +import numpy as np +import pytest + +from llama_cpp import LlamaState +from llama_cpp.llama_cache import LlamaDiskCache, LlamaRAMCache + + +@pytest.fixture(params=[LlamaRAMCache, LlamaDiskCache]) +def cache(request, tmp_path): + if request.param is LlamaDiskCache: + cache = request.param(cache_dir=str(tmp_path / "cache")) + else: + cache = request.param() + try: + yield cache + finally: + if isinstance(cache, LlamaDiskCache): + cache.cache.close() + + +@pytest.fixture +def state(): + return LlamaState( + input_ids=np.array([1, 2, 3], dtype=np.intc), + scores=np.zeros((3, 4), dtype=np.single), + n_tokens=3, + llama_state=b"saved model state", + llama_state_size=17, + seed=42, + ) + + +@pytest.mark.parametrize("query", [(1, 2, 3), (1, 2, 3, 4), (1, 2), (1, 2, 9)]) +def test_cache_hits_remain_available(cache, state, query): + cache[[1, 2, 3]] = state + + for _ in range(3): + assert query in cache + result = cache[query] + np.testing.assert_array_equal(result.input_ids, state.input_ids) + np.testing.assert_array_equal(result.scores, state.scores) + assert result.n_tokens == state.n_tokens + assert result.llama_state == state.llama_state + assert result.llama_state_size == state.llama_state_size + assert result.seed == state.seed + assert [1, 2, 3] in cache + + +@pytest.mark.parametrize("query", [(), (9,)]) +def test_cache_misses_leave_saved_states_available(cache, state, query): + assert query not in cache + with pytest.raises(KeyError): + cache[query] + + cache[[1, 2, 3]] = state + assert query not in cache + with pytest.raises(KeyError): + cache[query] + assert [1, 2, 3] in cache + + +def test_disk_cache_hit_survives_reopening(tmp_path, state): + directory = str(tmp_path / "cache") + cache = LlamaDiskCache(cache_dir=directory) + try: + cache[[1, 2, 3]] = state + assert cache[[1, 2, 3, 4]].llama_state == state.llama_state + finally: + cache.cache.close() + + reopened = LlamaDiskCache(cache_dir=directory) + try: + assert [1, 2, 3] in reopened + assert reopened[[1, 2, 9]].llama_state == state.llama_state + assert [1, 2, 3] in reopened + finally: + reopened.cache.close() From 7045862475615fa15b22213d1ee19eb79e956dc1 Mon Sep 17 00:00:00 2001 From: Steven Huang <134844631+remote-controlled-man@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:53:45 +0800 Subject: [PATCH 2/4] docs: link disk cache fix in changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index be2a14cd19..b1abe8d8f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -- fix(cache): preserve disk cache entries on lookup by @remote-controlled-man +- fix(cache): preserve disk cache entries on lookup by @remote-controlled-man in #2423 - fix(ci): remove unsupported macOS 14 release runners by @abetlen in #2416 ## [0.3.37] From ba2c9cacfc2a106f80fff236f89fa2f21a996805 Mon Sep 17 00:00:00 2001 From: abetlen Date: Sat, 21 Nov 2026 22:17:56 -0800 Subject: [PATCH 3/4] test: remove cache tests from PR --- tests/test_llama_cache.py | 77 --------------------------------------- 1 file changed, 77 deletions(-) delete mode 100644 tests/test_llama_cache.py diff --git a/tests/test_llama_cache.py b/tests/test_llama_cache.py deleted file mode 100644 index bb49778961..0000000000 --- a/tests/test_llama_cache.py +++ /dev/null @@ -1,77 +0,0 @@ -import numpy as np -import pytest - -from llama_cpp import LlamaState -from llama_cpp.llama_cache import LlamaDiskCache, LlamaRAMCache - - -@pytest.fixture(params=[LlamaRAMCache, LlamaDiskCache]) -def cache(request, tmp_path): - if request.param is LlamaDiskCache: - cache = request.param(cache_dir=str(tmp_path / "cache")) - else: - cache = request.param() - try: - yield cache - finally: - if isinstance(cache, LlamaDiskCache): - cache.cache.close() - - -@pytest.fixture -def state(): - return LlamaState( - input_ids=np.array([1, 2, 3], dtype=np.intc), - scores=np.zeros((3, 4), dtype=np.single), - n_tokens=3, - llama_state=b"saved model state", - llama_state_size=17, - seed=42, - ) - - -@pytest.mark.parametrize("query", [(1, 2, 3), (1, 2, 3, 4), (1, 2), (1, 2, 9)]) -def test_cache_hits_remain_available(cache, state, query): - cache[[1, 2, 3]] = state - - for _ in range(3): - assert query in cache - result = cache[query] - np.testing.assert_array_equal(result.input_ids, state.input_ids) - np.testing.assert_array_equal(result.scores, state.scores) - assert result.n_tokens == state.n_tokens - assert result.llama_state == state.llama_state - assert result.llama_state_size == state.llama_state_size - assert result.seed == state.seed - assert [1, 2, 3] in cache - - -@pytest.mark.parametrize("query", [(), (9,)]) -def test_cache_misses_leave_saved_states_available(cache, state, query): - assert query not in cache - with pytest.raises(KeyError): - cache[query] - - cache[[1, 2, 3]] = state - assert query not in cache - with pytest.raises(KeyError): - cache[query] - assert [1, 2, 3] in cache - - -def test_disk_cache_hit_survives_reopening(tmp_path, state): - directory = str(tmp_path / "cache") - cache = LlamaDiskCache(cache_dir=directory) - try: - cache[[1, 2, 3]] = state - assert cache[[1, 2, 3, 4]].llama_state == state.llama_state - finally: - cache.cache.close() - - reopened = LlamaDiskCache(cache_dir=directory) - try: - assert [1, 2, 3] in reopened - assert reopened[[1, 2, 9]].llama_state == state.llama_state - assert [1, 2, 3] in reopened - finally: - reopened.cache.close() From c6f070277cc3633b12377ecc56aca26c72b5268f Mon Sep 17 00:00:00 2001 From: abetlen Date: Sat, 21 Nov 2026 22:42:13 -0800 Subject: [PATCH 4/4] fix(cache): use built-in LRU disk eviction --- CHANGELOG.md | 2 +- llama_cpp/llama_cache.py | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c4f8949265..530bf2bf07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -- fix(cache): preserve disk cache entries on lookup by @remote-controlled-man in #2423 +- fix(cache): preserve disk cache entries on lookup and evict least-recently-used states by @remote-controlled-man in #2423 - fix: size Python buffers to the actual context by @remote-controlled-man in #2436 - feat: update llama.cpp to ggml-org/llama.cpp@afe77e18f - fix(ci): remove unsupported macOS 14 release runners by @abetlen in #2416 diff --git a/llama_cpp/llama_cache.py b/llama_cpp/llama_cache.py index b7d68c227d..6ae8cfa2fb 100644 --- a/llama_cpp/llama_cache.py +++ b/llama_cpp/llama_cache.py @@ -108,7 +108,12 @@ def __init__( self, cache_dir: str = ".cache/llama_cache", capacity_bytes: int = (2 << 30) ): super().__init__(capacity_bytes) - self.cache = diskcache.Cache(cache_dir) + self.cache = diskcache.Cache( + cache_dir, + size_limit=capacity_bytes, + eviction_policy="least-recently-used", + cull_limit=0, + ) @property def cache_size(self): @@ -141,12 +146,7 @@ def __contains__(self, key: Sequence[int]) -> bool: def __setitem__(self, key: Sequence[int], value: "llama_cpp.llama.LlamaState"): print("LlamaDiskCache.__setitem__: called", file=sys.stderr) key = tuple(key) - if key in self.cache: - print("LlamaDiskCache.__setitem__: delete", file=sys.stderr) - del self.cache[key] self.cache[key] = value print("LlamaDiskCache.__setitem__: set", file=sys.stderr) - while self.cache_size > self.capacity_bytes and len(self.cache) > 0: - key_to_remove = next(iter(self.cache)) - del self.cache[key_to_remove] + self.cache.cull() print("LlamaDiskCache.__setitem__: trim", file=sys.stderr)