Repository navigation
performance cache: stop after a complete prompt prefix match - #2477
Open
yezhengli-Mr9 wants to merge 3 commits into
Open
yezhengli-Mr9 wants to merge 3 commits into
yezhengli-Mr9 wants to merge 3 commits into
Conversation
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.
yezhengli-Mr9
marked this pull request as ready for review
December 4, 2026 02:47
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Counterpart reference PRs
Related prompt-prefix caching implementations are listed below. This PR is narrower: it stops scanning RAM/disk cache entries once the entire requested prompt matches, preserving the first longest match. It optimizes host-side lookup, not model inference itself.
All reference PRs above are merged. They establish related prefix-reuse implementations, not an identical implementation of this PR's complete-request-match early exit.
Review overview
Stop scanning cached states after finding a match covering the entire requested prompt. A later entry cannot have a longer common prefix than the requested sequence itself.
__getitem__LRU update still runs.llama_cpp/llama_cache.pyandtests/test_llama_cache.py. No Markdown, dependency, model, native, benchmark, or workflow files added to the branch.This is a small host-side cache-search optimization. It does not enable KV caching, reduce prompt tokens, or establish an end-to-end agent/inference speedup.
Logic example: stop when the whole request matches
Requested tokens:
[1, 2, 3, 4](length 4). Suppose the cache visits the entries below in this order. This is an illustrative order, not a guarantee about disk-cache ordering.[1, 2, 3, 4, 8][1, 2, 3, 4][1, 2, 9][9, 8]The maximum possible common-prefix length is the request length: 4. Once A reaches it, no later entry can improve the result. A cached key may be longer than the request; it need not equal it. Even though B is an exact key, both versions retain the first longest match, A.
This example has been checked against the pinned original and patched search methods: both select A, while the visited entries change from A/B/C/D to A only. If no complete request matches, the search still checks the remaining entries; empty requests retain their existing miss behavior. The counts above illustrate logic, not measured time savings.
Real local-model sample
LlamaRAMCache._find_longest_prefix_keysource from upstream base77fbb5d7190149d20870cd8d73646a5df3e72b05, included verbatim in an agent-style edit prompt.qwen2.5-coder:1.5bGGUF; model blob SHA-25629d8c98fa6b098e200069bfb88b9508dc3e85586d20cba59f8dda9a808165104.Task ID: 0through7;max_tokens=4,temperature=0, seed1729.def. These tokens only populate a real cached continuation; no patch correctness/model-quality claim is made.Llama.save_state()captured 178 evaluated tokens, 5,106,457 native-state bytes, and 77,791,232 score-array bytes. The state key is longer than the 175-token request.Task ID: 99: 176 tokens. No complete cached request matches, so the full scan remains necessary.Exact prompt used for the first native request
Measured lookup time saved
Scope: warmed
_find_longest_prefix_keyonly, excluding prompt evaluation, generation, cache population, serialization, state deserialization/loading, and full__getitem__. Values are milliseconds per lookup, not per generated token or agent task.n_ctx=512,n_batch=128,n_threads=2,n_threads_batch=2.Ubuntu
Windows
Early complete matches save about 0.055-0.336 ms per lookup in this eight-entry sample. The controls still perform eight comparisons: their apparent gains/regressions are not credited to this optimization. In particular, Ubuntu RAM's uncached-task row and Windows disk's uncached-task row are slower in the median-of-blocks measurements.
Paired-block variability, including unchanged-work controls
These are paired baseline-minus-patched block deltas, so their medians need not equal the difference of the two independently computed medians above. Q1/Q3 are descriptive quartiles, not confidence intervals. Ubuntu no-short-circuit control IQRs all cross zero.
Validation and feature-only test coverage
python -m ruff check llama_cpp testspassed;python -m ruff format --check llama_cpp testspassed for all 30 Python files.Reproduction
1fcbdc6febdacb37afa1e13464fceef8e1f87163and its Python package sources with a compatible native runtime, NumPy, and diskcache.git show 77fbb5d7190149d20870cd8d73646a5df3e72b05:llama_cpp/llama_cache.pyas UTF-8 bytes tobaseline_llama_cache.py. The command below avoids Windows shell encoding conversion.real_prefix_sample.pyoutside the repository. No benchmark or Markdown files are added to this feature branch.python real_prefix_sample.py --root . --baseline baseline_llama_cache.py --model PATH_TO_QWEN_GGUF --output real-prefix-ubuntu.jsonpython real_prefix_sample.py --root . --baseline baseline_llama_cache.py --tokens-from real-prefix-ubuntu.json --output real-prefix-windows.json562cb1ab5dca2f556cbcd5e5d18a1091741fce79e0de48d10671cafb9692e83e; patchedcaea8ea37e282224527b6c52065a26b2c915d20b771a85a69d861d0594f5eeec. The runner asserts imports resolve to the requested checkout.python -c "import subprocess; from pathlib import Path; Path('baseline_llama_cache.py').write_bytes(subprocess.check_output(['git', 'show', '77fbb5d7190149d20870cd8d73646a5df3e72b05:llama_cpp/llama_cache.py']))"Set
PYTHONPATHto the checkout if the external script directory would otherwise select an installed copy. Where using wheel-provided shared libraries, setLLAMA_CPP_LIB_PATHto that compatible library directory. Use an already downloaded model; the experiment itself needs no network access.Standalone paired timing / real-state capture script
Prior synthetic comparison-count construction
tuple(range(prefix_length)) + (i, 9999).9998; miss(-1,).random.Random(1729); 100 per cache/count/prefix combination. Truncate a chosen cached key or replace one token with-1; compare selected keys orNoneagainst the original implementation. 800 equivalent outputs.Related issues, work items, and PRs
Review boundaries
len(query). Stop only after updating the selected best key, preserving first-match ties.