Skip to content

performance cache: stop after a complete prompt prefix match - #2477

Open
yezhengli-Mr9 wants to merge 3 commits into
abetlen:mainfrom
yezhengli-Mr9:perf/complete-prefix-20261204
Open

yezhengli-Mr9 wants to merge 3 commits into
abetlen:mainfrom
yezhengli-Mr9:perf/complete-prefix-20261204

Conversation

@yezhengli-Mr9

@yezhengli-Mr9 yezhengli-Mr9 commented Dec 4, 2026 •

Copy link
Copy Markdown

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.

Counterpart Reference PR and title Comparable behavior Difference from this PR
SGLang #7 - Fix radix cache match Radix-tree prefix matching, including requests ending inside a cached tree edge. Related lookup logic, but a matching-correctness fix, not the same linear-scan early exit.
vLLM #2762 - Add Automatic Prefix Caching Finds reusable computed token blocks through prefix-derived hashes. Uses hash-indexed block reuse rather than scanning saved prompt states.
Ollama - MLX runner #14887 - Share KV cache across conversations with common prefixes A prefix trie tracks shared regions across conversations, with paging and LRU eviction. Broader cache-sharing feature; applies specifically to the MLX runner.
MLX-LM #138 - Optimize prompt cache handling and add tests Finds the common prefix and trims the existing cache instead of resetting it entirely. Optimizes retained cache state, not selection among multiple cached states.
llama.cpp #1169 - Save and restore prompt evaluation state for much faster startup times Restores saved state, compares prompt prefixes, and skips already evaluated tokens. Foundational persistent prompt caching, not a multi-entry lookup optimization.

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.

Area Change / compatibility
RAM and disk Add the same complete-request termination rule to each existing prefix-search loop.
Selection semantics Preserve the first longest match, including ties and longer cached continuations; no exact-key shortcut, sorting, or changed iteration order.
Partial hits, misses, empty requests Retain the full scan whenever no nonempty complete request matches.
State loading / RAM recency Unchanged; the existing __getitem__ LRU update still runs.
Production scope Four executable lines plus the cache contract docstring.
Test cleanup Reduce the added test file from 75 to 48 lines. Remove the state helper, redundant containment/getitem assertions, and unrelated LRU-eviction test. Keep only direct prefix-search regressions.
Repository scope Exactly two files: llama_cpp/llama_cache.py and tests/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.

Step Cached tokens Common-prefix length with request Before: keep searching After: stop at a complete request match
1: A [1, 2, 3, 4, 8] 4 Select A, but continue scanning. Select A and stop: all 4 requested tokens match.
2: B [1, 2, 3, 4] 4 Compare anyway; equal-length tie, so keep A and continue. Not visited.
3: C [1, 2, 9] 2 Compare anyway; shorter match, so keep A and continue. Not visited.
4: D [9, 8] 0 Compare anyway; keep A, then finish the scan. Not visited.
Result Before After
Selected cached state A A (unchanged)
Prefix comparisons 4 1
Requested tokens 4 4 (unchanged)

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

Sample detail What actually ran
Source Actual LlamaRAMCache._find_longest_prefix_key source from upstream base 77fbb5d7190149d20870cd8d73646a5df3e72b05, included verbatim in an agent-style edit prompt.
Model Existing local qwen2.5-coder:1.5b GGUF; model blob SHA-256 29d8c98fa6b098e200069bfb88b9508dc3e85586d20cba59f8dda9a808165104.
Native execution Ubuntu CPU inference: eight prompt variants differing only in Task ID: 0 through 7; max_tokens=4, temperature=0, seed 1729.
First actual request 175 model-tokenizer tokens, not synthetic ordinal token IDs.
First actual continuation Four generated tokens, rendering as a Python-code fence, a newline, and def. These tokens only populate a real cached continuation; no patch correctness/model-quality claim is made.
First saved state 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.
Cache corpus Eight real saved states populated RAM and disk caches; each arm searches the same cache object. Query first/fifth/last entries according to each backend's actual order, not assumed insertion order for disk.
Uncached control Tokenize the same source/task with Task ID: 99: 176 tokens. No complete cached request matches, so the full scan remains necessary.
Windows scope Replay those exact captured token keys/requests with minimal state payload fixtures. Native model initialization on this Windows machine fails with an illegal CPU instruction; Windows results are not native-model execution or state-loading timings.
Representativeness Constructed, reproducible agent-style sample using real source, completions, tokenizer IDs, and Ubuntu model states; not a captured production agent-session trace.
Exact prompt used for the first native request
You are a local coding agent. Make the smallest behavior-preserving performance change. Preserve empty misses and first-match ties.
Repository: abetlen/llama-cpp-python
File: llama_cpp/llama_cache.py

def _find_longest_prefix_key(
        self,
        key: Tuple[int, ...],
    ) -> Optional[Tuple[int, ...]]:
        min_len = 0
        min_key = None
        keys = (
            (k, llama_cpp.llama.Llama.longest_token_prefix(k, key))
            for k in self.cache_state.keys()
        )
        for k, prefix_len in keys:
            if prefix_len > min_len:
                min_len = prefix_len
                min_key = k
        return min_key

Task: Avoid redundant comparisons after the whole request matches.
Task ID: 0
Patch:

Measured lookup time saved

Scope: warmed _find_longest_prefix_key only, 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.

Method / environment Exact setting
Hardware AMD EPYC 7763 host; Windows reports 8 cores / 16 logical processors. Shared host, not a dedicated benchmark machine.
Ubuntu Ubuntu 24.04 container, Python 3.12.3; network disabled, two-CPU quota, 4 GiB memory cap. Model uses n_ctx=512, n_batch=128, n_threads=2, n_threads_batch=2.
Windows Windows 11, Python 3.13.17; native host lookup replay, no model initialization.
Sampling 10 warmups per arm, then 31 paired blocks of 1,000 lookups per arm/case; reverse arm order every block.
Table calculation Original/patched columns are medians of block-average lookup times. Saved ms = original median minus patched median; saved % uses the original median.
Correctness checks Assert identical selected keys before measurement, during warmup, and after each timed block. Count comparisons in separate untimed calls; assert expected 8 -> 1 / 5 / 8 counts.
Measurement limits Descriptive measurements, not guaranteed percentages. Keep negative outcomes; shared-host scheduling/runtime variation can affect the unchanged-work controls too.

Ubuntu

Cache Lookup Original ms Patched ms Time saved ms Time saved % Comparisons
RAM Complete, first entry 0.1420 0.0182 +0.1238 +87.2% 8 -> 1
RAM Complete, fifth entry 0.1509 0.0960 +0.0549 +36.4% 8 -> 5
RAM Complete, last entry (control) 0.1355 0.1205 +0.0150 +11.1% 8 -> 8
RAM Uncached task / partial match (control) 0.1446 0.1619 -0.0173 -11.9% 8 -> 8
DISK Complete, first entry 0.3058 0.0473 +0.2585 +84.5% 8 -> 1
DISK Complete, fifth entry 0.2428 0.1769 +0.0659 +27.1% 8 -> 5
DISK Complete, last entry (control) 0.3387 0.3221 +0.0165 +4.9% 8 -> 8
DISK Uncached task / partial match (control) 0.3516 0.3382 +0.0134 +3.8% 8 -> 8

Windows

Cache Lookup Original ms Patched ms Time saved ms Time saved % Comparisons
RAM Complete, first entry 0.1523 0.0200 +0.1323 +86.9% 8 -> 1
RAM Complete, fifth entry 0.1814 0.1035 +0.0779 +42.9% 8 -> 5
RAM Complete, last entry (control) 0.1748 0.1658 +0.0091 +5.2% 8 -> 8
RAM Uncached task / partial match (control) 0.1493 0.1402 +0.0091 +6.1% 8 -> 8
DISK Complete, first entry 0.3850 0.0489 +0.3361 +87.3% 8 -> 1
DISK Complete, fifth entry 0.3384 0.2173 +0.1210 +35.8% 8 -> 5
DISK Complete, last entry (control) 0.3515 0.2932 +0.0583 +16.6% 8 -> 8
DISK Uncached task / partial match (control) 0.2634 0.2810 -0.0177 -6.7% 8 -> 8

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.

Platform / cache Lookup Paired time saved: median [Q1, Q3], ms
Ubuntu / RAM Complete, first entry +0.1258 [+0.1089, +0.1372]
Ubuntu / RAM Complete, fifth entry +0.0523 [+0.0414, +0.0833]
Ubuntu / RAM Complete, last entry (control) +0.0095 [-0.0104, +0.0266]
Ubuntu / RAM Uncached task / partial match (control) -0.0063 [-0.0284, +0.0182]
Ubuntu / DISK Complete, first entry +0.2612 [+0.2271, +0.2964]
Ubuntu / DISK Complete, fifth entry +0.0778 [+0.0561, +0.1202]
Ubuntu / DISK Complete, last entry (control) +0.0126 [-0.0173, +0.0262]
Ubuntu / DISK Uncached task / partial match (control) -0.0033 [-0.0305, +0.0386]
Windows / RAM Complete, first entry +0.1338 [+0.1216, +0.1626]
Windows / RAM Complete, fifth entry +0.0623 [+0.0390, +0.0923]
Windows / RAM Complete, last entry (control) +0.0107 [-0.0236, +0.0321]
Windows / RAM Uncached task / partial match (control) +0.0056 [-0.0087, +0.0141]
Windows / DISK Complete, first entry +0.3379 [+0.3116, +0.3605]
Windows / DISK Complete, fifth entry +0.1207 [+0.1101, +0.1422]
Windows / DISK Complete, last entry (control) +0.0560 [+0.0240, +0.1073]
Windows / DISK Uncached task / partial match (control) +0.0031 [-0.0181, +0.0125]

Validation and feature-only test coverage

Check Executed result
Windows / Python 3.13 focused cache tests 2 passed, one RAM and one disk case, with six request scenarios each.
Ubuntu / Python 3.12 focused cache tests 2 passed, using the same source checkout and actual disk cache.
Necessary scenarios Full request equal to key; full request that is a prefix of a longer cached key; cached key shorter than request; equal partial matches; miss; empty request. Assert selected key and exact number of comparisons.
Baseline negative control Run the same reduced tests with only search methods replaced by the pinned original methods: both fail because a complete request performs 3 comparisons rather than 1. No source-file changes needed for this proof.
Upstream lint / format scope python -m ruff check llama_cpp tests passed; python -m ruff format --check llama_cpp tests passed for all 30 Python files.
Prior broader synthetic check 40 paired cases and 800 deterministic randomized queries returned identical selected keys/misses. This is supplementary synthetic evidence, separate from the real-token timing sample above.
Automatic CI Exact-head upstream Lint and Tests workflows are action_required, pending maintainer approval. Neither job has executed; upstream CI is not green. Local passing checks are not substituted for those workflows.

Reproduction

python -m pytest tests/test_llama_cache.py -q
python -m ruff check llama_cpp tests
python -m ruff format --check llama_cpp tests
Timing reproduction step Instruction
Source checkout Use PR head 1fcbdc6febdacb37afa1e13464fceef8e1f87163 and its Python package sources with a compatible native runtime, NumPy, and diskcache.
Baseline Export git show 77fbb5d7190149d20870cd8d73646a5df3e72b05:llama_cpp/llama_cache.py as UTF-8 bytes to baseline_llama_cache.py. The command below avoids Windows shell encoding conversion.
Script Save the collapsed script below as real_prefix_sample.py outside the repository. No benchmark or Markdown files are added to this feature branch.
Native run python real_prefix_sample.py --root . --baseline baseline_llama_cache.py --model PATH_TO_QWEN_GGUF --output real-prefix-ubuntu.json
Windows key replay Use the captured Ubuntu JSON: python real_prefix_sample.py --root . --baseline baseline_llama_cache.py --tokens-from real-prefix-ubuntu.json --output real-prefix-windows.json
Output JSON includes the exact prompt, generated text, complete native token keys/requests, source hashes, state sizes, comparison counts, and all 31 block samples for every arm/case.
Source integrity Original normalized SHA-256 562cb1ab5dca2f556cbcd5e5d18a1091741fce79e0de48d10671cafb9692e83e; patched caea8ea37e282224527b6c52065a26b2c915d20b771a85a69d861d0594f5eeec. 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 PYTHONPATH to the checkout if the external script directory would otherwise select an installed copy. Where using wheel-provided shared libraries, set LLAMA_CPP_LIB_PATH to that compatible library directory. Use an already downloaded model; the experiment itself needs no network access.

Standalone paired timing / real-state capture script
import argparse
import ast
import contextlib
import hashlib
import io
import json
import platform
import statistics
import tempfile
import time
import types
from pathlib import Path
from unittest.mock import patch

from llama_cpp import Llama
from llama_cpp import llama_cache

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", type=Path, required=True)
    parser.add_argument("--baseline", type=Path, required=True)
    parser.add_argument("--model", type=Path)
    parser.add_argument("--tokens-from", type=Path)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--states", type=int, default=8)
    parser.add_argument("--blocks", type=int, default=31)
    parser.add_argument("--iterations", type=int, default=1000)
    args = parser.parse_args()
    assert Path(llama_cache.__file__).resolve() == (
        args.root / "llama_cpp" / "llama_cache.py"
    ).resolve()
    source = args.baseline.read_text(encoding="utf-8")
    original = types.ModuleType("llama_cpp.original_cache")
    original.__package__ = "llama_cpp"
    exec(compile(source, str(args.baseline), "exec"), original.__dict__)
    tree = ast.parse(source)
    cls = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "LlamaRAMCache")
    method = next(
        node for node in cls.body
        if isinstance(node, ast.FunctionDef) and node.name == "_find_longest_prefix_key"
    )
    snippet = ast.get_source_segment(source, method)
    prefix = (
        "You are a local coding agent. Make the smallest behavior-preserving "
        "performance change. Preserve empty misses and first-match ties.\n"
        "Repository: abetlen/llama-cpp-python\n"
        "File: llama_cpp/llama_cache.py\n\n"
        + snippet
        + "\n\nTask: Avoid redundant comparisons after the whole request matches.\n"
    )

    def prompt(task):
        return prefix + f"Task ID: {task}\nPatch:\n"

    report = {
        "system": platform.platform(),
        "python": platform.python_version(),
        "model": args.model.name if args.model else None,
        "native_package_version": __import__("llama_cpp").__version__,
        "base_commit": "77fbb5d7190149d20870cd8d73646a5df3e72b05",
        "source_sha256_lf": {
            "baseline": hashlib.sha256(source.replace("\r\n", "\n").encode()).hexdigest(),
            "patched": hashlib.sha256(
                (args.root / "llama_cpp" / "llama_cache.py").read_bytes().replace(b"\r\n", b"\n")
            ).hexdigest(),
        },
        "sample_prompt": prompt(0),
        "settings": {
            "states": args.states, "blocks": args.blocks,
            "iterations_per_block": args.iterations,
            "n_ctx": 512, "n_batch": 128, "n_threads": 2, "n_threads_batch": 2,
            "max_tokens": 4, "temperature": 0.0, "seed": 1729,
        },
        "captured_states": [],
        "records": [],
        "limitations": (
            "Real local-model completions for agent-style prompts containing actual "
            "upstream source. Native mode uses unmodified save_state snapshots; "
            "tokens-from mode replays captured keys with minimal state fixtures. This is a "
            "constructed sample, not a production agent-session trace. Timings cover "
            "only warmed prefix-key search; exclude model work, state serialization, "
            "state loading and database population. Not a model-quality or total "
            "agent-latency measurement. Original and patched methods use the same "
            "cache objects. Arm order alternates by block."
        ),
    }

    def checkpoint():
        args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")

    states = {}
    queries = {}
    if args.tokens_from:
        import numpy as np
        from llama_cpp import LlamaState

        captured = json.loads(args.tokens_from.read_text(encoding="utf-8"))
        assert captured["source_sha256_lf"] == report["source_sha256_lf"]
        report["model"] = captured["model"]
        report["sample_prompt"] = captured["sample_prompt"]
        report["captured_states"] = captured["captured_states"]
        report["capture_mode"] = "Captured native token keys; minimal state payload fixtures"
        assert len(captured["captured_states"]) == args.states
        for row in captured["captured_states"]:
            key = tuple(row["key_tokens"])
            queries[key] = tuple(row["request_token_ids"])
            states[key] = LlamaState(
                np.array(key, dtype=np.intc), np.empty((0, 0), dtype=np.single),
                len(key), b"", 0, 1729,
            )
        unseen = tuple(captured["uncached_request_tokens"])
    else:
        if args.model is None:
            parser.error("--model is required without --tokens-from")
        report["capture_mode"] = "Native completions and unmodified Llama.save_state snapshots"
        model = Llama(
            model_path=str(args.model), n_ctx=512, n_batch=128,
            n_threads=2, n_threads_batch=2, verbose=False,
        )
        try:
            for task in range(args.states):
                tokens = model.tokenize(prompt(task).encode(), special=True)
                response = model.create_completion(
                    tokens, max_tokens=4, temperature=0.0, seed=1729
                )
                state = model.save_state()
                key = tuple(int(token) for token in state.input_ids[:state.n_tokens])
                assert key[:len(tokens)] == tuple(tokens)
                assert key not in states
                states[key] = state
                queries[key] = tuple(tokens)
                report["captured_states"].append({
                    "task_id": task, "request_tokens": len(tokens),
                    "state_tokens": state.n_tokens, "native_state_bytes": state.llama_state_size,
                    "score_array_bytes": state.scores.nbytes,
                    "generated_text": response["choices"][0]["text"],
                    "usage": response["usage"], "key_tokens": list(key),
                    "request_token_ids": tokens,
                })
                checkpoint()
                print("captured", task, len(tokens), state.n_tokens, flush=True)
            unseen = tuple(model.tokenize(prompt(99).encode(), special=True))
        finally:
            model.close()
    report["uncached_request_tokens"] = list(unseen)

    with tempfile.TemporaryDirectory(prefix="real-prefix-cache-") as directory:
        for kind in ("ram", "disk"):
            cache = (
                llama_cache.LlamaRAMCache(capacity_bytes=1 << 40)
                if kind == "ram"
                else llama_cache.LlamaDiskCache(directory, capacity_bytes=1 << 40)
            )
            try:
                with contextlib.redirect_stderr(io.StringIO()):
                    for key, state in states.items():
                        cache[key] = state
                keys = (
                    list(cache.cache_state)
                    if kind == "ram"
                    else list(cache.cache.iterkeys())
                )
                assert len(keys) == args.states
                methods = {
                    "baseline": getattr(original, type(cache).__name__)._find_longest_prefix_key,
                    "patched": type(cache)._find_longest_prefix_key,
                }
                for case, query in [
                    ("complete_first", queries[keys[0]]),
                    ("complete_middle", queries[keys[len(keys) // 2]]),
                    ("complete_last", queries[keys[-1]]),
                    ("uncached_task", unseen),
                ]:
                    matches = [method(cache, query) for method in methods.values()]
                    assert matches[0] == matches[1]
                    expected = matches[0]
                    counts = {}
                    for arm, method in methods.items():
                        with patch.object(
                            Llama, "longest_token_prefix", wraps=Llama.longest_token_prefix
                        ) as compare:
                            assert method(cache, query) == expected
                        counts[arm] = compare.call_count
                    assert counts["baseline"] == len(keys)
                    if case.startswith("complete_"):
                        position = {
                            "complete_first": 0,
                            "complete_middle": len(keys) // 2,
                            "complete_last": len(keys) - 1,
                        }[case]
                        assert expected == keys[position]
                        assert counts["patched"] == position + 1
                    else:
                        assert counts["patched"] == len(keys)
                    for method in methods.values():
                        for _ in range(10):
                            assert method(cache, query) == expected
                    samples = {arm: [] for arm in methods}
                    paired_saved = []
                    for block in range(args.blocks):
                        order = list(methods) if block % 2 == 0 else list(reversed(methods))
                        block_times = {}
                        for arm in order:
                            method = methods[arm]
                            started = time.perf_counter_ns()
                            for _ in range(args.iterations):
                                result = method(cache, query)
                            per_lookup_ns = (time.perf_counter_ns() - started) / args.iterations
                            assert result == expected
                            samples[arm].append(per_lookup_ns)
                            block_times[arm] = per_lookup_ns
                        paired_saved.append(block_times["baseline"] - block_times["patched"])
                    before = statistics.median(samples["baseline"]) / 1e6
                    after = statistics.median(samples["patched"]) / 1e6
                    row = {
                        "cache": kind, "case": case, "request_tokens": len(query),
                        "comparisons": counts,
                        "baseline_median_ms": before, "patched_median_ms": after,
                        "saved_ms": before - after,
                        "saved_percent": 100 * (before - after) / before,
                        "paired_saved_median_ms": statistics.median(paired_saved) / 1e6,
                        "baseline_block_ns_per_lookup": samples["baseline"],
                        "patched_block_ns_per_lookup": samples["patched"],
                    }
                    report["records"].append(row)
                    checkpoint()
                    print(json.dumps({k: v for k, v in row.items() if not k.endswith("lookup")}), flush=True)
            finally:
                if kind == "disk":
                    cache.cache.close()
    checkpoint()

if __name__ == "__main__":
    main()
Prior synthetic comparison-count construction
Input / outcome Construction / result
Entries 32/128 entries; 64/1,024-token shared prefixes. Keys: tuple(range(prefix_length)) + (i, 9999).
Queries Complete prefix of first/middle/last actual iterated key; partial request with last token replaced by 9998; miss (-1,).
128-entry complete first / middle / last Comparisons 128 -> 1 / 65 / 128, respectively.
Partial / miss Comparisons 128 -> 128.
All 40 paired cases 3,200 -> 2,256 comparisons. A synthetic workload mixture, not production frequency weighting.
Random equivalence random.Random(1729); 100 per cache/count/prefix combination. Truncate a chosen cached key or replace one token with -1; compare selected keys or None against the original implementation. 800 equivalent outputs.

Related issues, work items, and PRs

Reference Relationship / boundary
Public issue / work item No directly matching issue identified in the reviewed open cache work. No private references or automatic-closing keywords added.
abetlen/llama-cpp-python#2179 Related per-comparison vectorization; this PR instead avoids comparisons after reaching the maximum possible match. No dependency on that unmerged change.
abetlen/llama-cpp-python#2457 Separate RAM capacity-accounting correction; unchanged here.
abetlen/llama-cpp-python#2474 Separate model-state copy optimization; unchanged here.

Review boundaries

Boundary Detail
Safety A common-prefix length cannot exceed len(query). Stop only after updating the selected best key, preserving first-match ties.
No full match Worst-case order and comparison count remain unchanged. Disk iteration may still prefetch keys in existing batches; no promise to eliminate every database read.
Repository eligibility Latest upstream commit verified on 2026-12-04 was dated 2026-11-23; at least nine human contributors verified among the first ten records.
Test scope Focused cache suite on Windows/Ubuntu and full configured lint/format scope. Full model/server/multimodal suites and GPU experiments not run.

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 yezhengli-Mr9 changed the title perf(cache): stop after a complete prompt prefix match performance cache: stop after a complete prompt prefix match Dec 4, 2026
@yezhengli-Mr9
yezhengli-Mr9 marked this pull request as ready for review December 4, 2026 02:47

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant