diff --git a/CHANGELOG.md b/CHANGELOG.md index 139e9a47c..530bf2bf0 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 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 5220c7933..6ae8cfa2f 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): @@ -132,10 +137,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: @@ -144,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)