Repository navigation
Conversation
…ecency on fetch - PromptTrie.search: a stored one-token key matches at last_index == 0, so the shorter-prefix check must be >= 0. Without it, one-token prefixes are unreachable for non-trimmable caches (full recompute). - LRUPromptCache.fetch_nearest_cache now refreshes an entry's recency on every hit (exact, shorter, and longer), so eviction is LRU rather than insertion order. - MockCache now models its state as the token list it was computed from, with a real trim(), so tests can verify that a fetched cache's contents match the tokens it is served under. Fixes ml-explore#1495
This was referenced Jul 7, 2026
T0mSIlver
added a commit
to T0mSIlver/localvoxtral
that referenced
this pull request
Jul 7, 2026
Picks up the prompt-cache correctness fixes from the fork: reuse can no longer serve KV that doesn't match the request prefix (T0mSIlver/mlx-lm#2, upstream ml-explore/mlx-lm#1494), and the server cache is actually LRU with one-token prefix hits fixed (T0mSIlver/mlx-lm#3, upstream PR ml-explore/mlx-lm#1496). Wheel SHA-256 verified against the published release asset.
rajanshxrma
approved these changes
Jul 9, 2026
rajanshxrma
left a comment
Contributor
There was a problem hiding this comment.
Following up from #1495 — reviewed the diff and verified this branch independently.
Verification:
- Full
TestLRUPromptCachepasses locally (8/8). - The new tests are genuine regression coverage: with the
cache.pychanges reverted and the new tests kept,test_lru_one_token_prefixandtest_lru_fetch_refreshes_recencyboth fail at their documented assertions, and pass again with the fix restored. black --checkis clean on both files.
Notes on the changes:
last_index >= 0: exact matches are still caught earlier bylast_index == len(tokens) - 1 >= 0, and an empty-token query returns before the walk, so widening the shorter branch adds only the previously dropped one-token case. It also has a nice side effect: when a one-token entry and a longer trimmable entry offer the same reusable length (common_prefix == short_length), the fetch now serves the smaller entry directly instead of deep-copying and trimming the longer one.touch()mirrorsremove()'s tier scan, so recency refreshes within an entry's own tier andpop()'s per-type eviction priority is preserved. All three hit paths touch the key of the entry actually served — includingresult.longeron the trim path, which stays the correct stored key since trimming happens on a deepcopy.- The
MockCacheupgrade makes thetest_lruassertions verify real key/content correspondence — e.g. the post-trimMockCache([])andMockCache([1])expectations weren't expressible with the old opaque-value mock.
LGTM — approving as a non-maintainer; happy to defer to the maintainers on anything further.
Open
4 tasks done
GoodOlClint
added a commit
to GoodOlClint/mlx-swift-lm
that referenced
this pull request
Jul 17, 2026
Swift only reuses a KV cache within a single `ChatSession`. A new request whose prompt shares a prefix with an earlier one re-processes that prefix from scratch. Python `mlx_lm` has had a cross-request store for this (`PromptTrie` + `LRUPromptCache` in `mlx_lm/models/cache.py`, used by `server.py`); this ports it. Adds: - `KVCache.nbytes` — byte accounting, the prerequisite for any byte-bounded policy. Every Python cache implements `nbytes`; no Swift cache did. The basis is the allocated (step-rounded) buffers from `innerState()`, not the offset-sliced `state`, matching Python. Declared as an `open var` on `BaseKVCache` rather than left to the protocol-extension default, so subclasses get a dynamically-dispatched override point. - `PromptTrie` — prefix trie returning the nearest stored sequence (exact / shorter / longer, plus the common-prefix length). - `LRUPromptCache` — the store: `fetchNearestCache` returning a deep copy and the token remainder still to process, prefix trim-reuse, `maxSize`/`maxBytes` eviction, type-aware eviction ordering (assistant -> user -> system), and `statsByType()`. The port does not inherit two bugs still open in the Python implementation, reported in ml-explore/mlx-lm#1495 and fixed there by ml-explore/mlx-lm#1496: a value stored at a single-token prefix never matched (`search` used `> 0` where `>= 0` is correct), and eviction ignored fetch recency, making the store FIFO rather than LRU. Both are pinned by regression tests. No existing behavior changes: this adds new types plus one protocol requirement with a default implementation. Nothing is wired into `ChatSession`/`Evaluate`. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Member
|
Thanks for the PR but at the moment the number of PRs is way beyond our capacity to review so I'm closing the non-essential ones so we can actually work on this repo. |
GoodOlClint
added a commit
to GoodOlClint/mlx-swift-lm
that referenced
this pull request
Sep 26, 2026
Swift only reuses a KV cache within a single `ChatSession`. A new request whose
prompt shares a prefix with an earlier one re-processes that prefix from scratch.
Python `mlx_lm` has had a cross-request store for this (`PromptTrie` +
`LRUPromptCache` in `mlx_lm/models/cache.py`, used by `server.py`); this ports it.
Adds:
- `KVCache.nbytes`: byte accounting, the prerequisite for any byte-bounded
policy. The basis is the allocated (step-rounded) buffers from
`innerState()`, not the offset-sliced `state`, matching Python. Declared as an
`open var` on `BaseKVCache` rather than left to the protocol-extension
default, so subclasses get a dynamically-dispatched override point.
- `PromptTrie`: prefix trie returning the nearest stored sequence
(exact / shorter / longer, plus the common-prefix length).
- `LRUPromptCache`: the store.
- Caches are copied on insert and on fetch.
- `LMOutput.State?` is stored with each cache, and a fetch returns the pair
as a `PromptCacheSnapshot`.
- An entry carrying state is never trimmed, the rule `PromptCacheReusePolicy`
applies through `carriesModelState`.
- A fetch never returns an empty token remainder.
- `maxSize`/`maxBytes` eviction, ordered by `Chat.Message.Role`
(tool -> assistant -> user -> system).
- `statsByType()`.
- Keys are input token ids; the store is documented as text-only.
The port does not inherit two bugs still open in the Python implementation,
reported in ml-explore/mlx-lm#1495 and fixed there by ml-explore/mlx-lm#1496:
a value stored at a single-token prefix never matched (`search` used `> 0` where
`>= 0` is correct), and eviction ignored fetch recency, making the store FIFO
rather than LRU. Both are pinned by regression tests.
No existing behavior changes: this adds new types plus one protocol requirement
with a default implementation. Nothing is wired into `ChatSession`/`Evaluate`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GoodOlClint
added a commit
to GoodOlClint/mlx-swift-lm
that referenced
this pull request
Oct 14, 2026
Swift only reuses a KV cache within a single `ChatSession`. A new request whose
prompt shares a prefix with an earlier one re-processes that prefix from scratch.
Python `mlx_lm` has had a cross-request store for this (`PromptTrie` +
`LRUPromptCache` in `mlx_lm/models/cache.py`, used by `server.py`); this ports it.
Adds:
- `KVCache.nbytes`: byte accounting, the prerequisite for any byte-bounded
policy. The basis is the allocated (step-rounded) buffers from
`innerState()`, not the offset-sliced `state`, matching Python. Declared as an
`open var` on `BaseKVCache` rather than left to the protocol-extension
default, so subclasses get a dynamically-dispatched override point.
- `PromptTrie`: prefix trie returning the nearest stored sequence
(exact / shorter / longer, plus the common-prefix length).
- `LRUPromptCache`: the store.
- Caches are copied on insert and on fetch.
- `LMOutput.State?` is stored with each cache, and a fetch returns the pair
as a `PromptCacheSnapshot`.
- An entry carrying state is never trimmed, the rule `PromptCacheReusePolicy`
applies through `carriesModelState`.
- A fetch never returns an empty token remainder.
- `maxSize`/`maxBytes` eviction, ordered by `Chat.Message.Role`
(tool -> assistant -> user -> system).
- `statsByType()`.
- Keys are input token ids; the store is documented as text-only.
The port does not inherit two bugs still open in the Python implementation,
reported in ml-explore/mlx-lm#1495 and fixed there by ml-explore/mlx-lm#1496:
a value stored at a single-token prefix never matched (`search` used `> 0` where
`>= 0` is correct), and eviction ignored fetch recency, making the store FIFO
rather than LRU. Both are pinned by regression tests.
No existing behavior changes: this adds new types plus one protocol requirement
with a default implementation. Nothing is wired into `ChatSession`/`Evaluate`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.
Fixes #1495.
Two small fixes in the server's
LRUPromptCache, plus aMockCacheupgrade so the tests can catch this class of bug:PromptTrie.searchnever returned a one-token prefix match.last_indexis the index of the deepest node holding a value (-1= none), so a stored one-token key matches atlast_index == 0and the shorter-prefix check needs>= 0, not> 0. Before this change the entry leaked out aslonger=[t]instead, which the longer branch happens to serve for trimmable caches (deepcopy + trim 0) — but for non-trimmable caches the entry was unreachable: the longer branch is skipped and the fetch returned(None, tokens), a full recompute of a cached prefix.Fetches never refreshed recency, so eviction was FIFO, not LRU.
CacheOrderonly recorded insertion order andfetch_nearest_cachenever touched it, so a hot entry (e.g. a shared system prompt) could be evicted while cold entries survived.fetch_nearest_cachenow refreshes the hit entry's position on exact, shorter, and longer hits via a newCacheOrder.touch. The per-type eviction priority is unchanged.MockCachenow has real content semantics: its state is the token list it was computed from,trim()actually slices it and returns the true trimmed count, and__eq__compares content. The existingtest_lruassertions now verify that a fetched cache's contents match the tokens it is served under (previouslytrim()was a no-op and__eq__compared an opaque value, so trie navigation was tested but key↔state correspondence was not). Existing tests updated accordingly; two regression tests added (test_lru_one_token_prefix,test_lru_fetch_refreshes_recency).Both defects and the repros are described in detail in #1495.
python -m unittest tests.test_server.TestLRUPromptCachepasses (8 tests);blackclean.