Repository navigation
Add cross-request LRU prompt cache (PromptTrie + byte-bounded eviction) - #436
GoodOlClint wants to merge 1 commit into
Conversation
0726927 to
7283688
Compare
| /// This is a plain non-`Sendable` `final class`, mirroring Python's | ||
| /// single-server-thread assumption. Cross-task consumers must wrap an instance | ||
| /// in a `SerialAccessContainer` (see `Utilities/SerialAccessContainer.swift`). | ||
| public final class LRUPromptCache<Model: Hashable> { |
There was a problem hiding this comment.
What would be the type for Model in a typical system? A String for the hugginface model id?
| let ordering: [String] | ||
| var lrus: [String: [(Model, [Int])]] | ||
|
|
||
| init(ordering: [String] = ["assistant", "user", "system"]) { |
There was a problem hiding this comment.
I wonder if the ordering should be an enum? This is all private and nothing seems to supply a custom order. Some functions, like push(), take a cacheType (which looks like a member of ordering). Other functions, like remove(), enumerate the fixed ordering and would ignore other values (if present).
There was a problem hiding this comment.
I think this is meant to match Chat.Message.Role, right? tool is present there.
| /// Insert `cache` at `tokens` for `model`, updating byte accounting, purging | ||
| /// now-redundant prefixes of a trimmable cache, and evicting to satisfy the | ||
| /// size/byte limits. | ||
| public func insertCache( |
There was a problem hiding this comment.
I think this has to make a copy of the KVCache on the way in -- these are mutable reference types and will move forward as they are used (mutating what lives in the cache).
main has moved ahead quite a bit on KVCache -- I wonder if this would be better using KVCacheStorage?
| if let exact = result.exact { | ||
| let entry = trie.get(model: result.model, tokens: exact) | ||
| refreshRecency(model: result.model, tokens: exact, cacheType: entry.cacheType) | ||
| return (entry.promptCache.map { $0.copy() }, []) |
There was a problem hiding this comment.
This may not work with LLMModel.prepare -- it will return .tokens(y) where y is this empty array. The callers may not be able to handle that. It could be an issue in the LLMModel/token code or perhaps an issue here. The code below seems to leave one token in place: prefix = min(tokens.count - 1, result.commonPrefix)
|
|
||
| /// One stored cache plus its byte size and type. | ||
| public struct CacheEntry { | ||
| public var promptCache: [KVCache] |
There was a problem hiding this comment.
This probably needs LMOutput.State as well -- quite a few models are using this for per-token state management and it is expected to be passed in for the next token. If we broke this on turns I think we would be OK.
| public func fetchNearestCache(model: Model, tokens: [Int]) -> ( | ||
| cache: [KVCache]?, remainder: [Int] |
There was a problem hiding this comment.
For VLMs we would need to be careful which tokens we were processing. Would it hook in right after the applyChatTemplate? That is [Int]:
public func prepare(input: UserInput) async throws -> LMInput {
// Use structured content message generator for Gemma3's chat template
let messages = Qwen2VLMessageGenerator().generate(from: input)
var promptTokens = try tokenizer.applyChatTemplate(
messages: messages, tools: input.tools,
additionalContext: input.additionalContext)Or would it consume LMInput, which has <image> tokens in it according to the image size, but not the contents. The processedImage is separate from the tokens and is mixed in (potentially) here:
func prepare(_ input: LMInput, cache: [KVCache], state: LMOutput.State?, windowSize: Int?)
throws -> PrepareResultThis isn't integrated so I can't tell for sure how it fits in, but since it comes from mlx-lm (LLMs only) I wonder if it considers this case?
davidkoski
left a comment
There was a problem hiding this comment.
See comments. I think there are a lot of edge cases that need covering here (and some of them are new since you made the PR -- my fault for not reviewing earlier). The VLM is likely trouble and LMOutput.State might be an issue. For sure this needs to store copies in the cache.
If you are interested in moving this forward, please rebase and take a look at KVCacheStorage and friends.
Thanks!
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>
7283688 to
5f8788d
Compare
…20cb09) into unified LibraxisAI core - Integrates MLXWhisper Swift 6 library, POST /v1/audio/transcriptions (--whisper-model), ml-explore#854 compiled SwiGLU, ml-explore#436 PromptTrie/LRUPromptCache, ml-explore#643 bounded Prompt-Lookup Decoding, and ml-explore#392/ml-explore#400 Gemma 4 audio/video - Reconciles Package.swift (both MLXGuidedGeneration and MLXWhisper linked into MLXLMServer), ServerConfiguration (--batch-v2/--max-concurrency/--kv-cache-mb/--served-model-name + --whisper-model), and MLXServerRunner (CBv2 + Whisper + Embeddings in one mlx-server process) Authored-By: gemini <agents@vetcoders.io>
Proposed changes
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. Pythonmlx_lmhas had a cross-request store for exactly this —PromptTrie+LRUPromptCacheinmlx_lm/models/cache.py, used byserver.py— and this ports it to Swift.What's added
KVCache.nbytes(Libraries/MLXLMCommon/KVCache.swift) — byte accounting, the prerequisite for any byte-bounded policy. Every Python cache implementsnbytes; no Swift cache did. The basis is the allocated (step-rounded) buffers frominnerState(), not the offset-slicedstate, matching Python'sKVCache.nbytes.It is declared as an
open varonBaseKVCacherather than left to the protocol-extension default, so subclasses get a dynamically-dispatched override point. (A protocol-extension default becomes the witness atBaseKVCache's conformance and a subclass property would only shadow it statically.)PromptTrie— prefix trie returning the nearest stored sequence:exact/shorter/longer, plus the common-prefix length.LRUPromptCache— the store itself:fetchNearestCache(returns a deep copy plus the token remainder still to process), prefix trim-reuse,maxSize/maxByteseviction, type-aware eviction ordering (assistant→user→system, so system prompts survive longest), andstatsByType().Two Python bugs fixed at port time
The port deliberately 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:
searchused> 0where>= 0is correct).Both are pinned by regression tests (
PromptTrieTests,LRUPromptCacheTests).Scope / notes
ChatSession/Evaluate— that is deliberate, to keep this reviewable on its own and to stay out of the way of Reuse cached chat transcript prefixes #370, which approaches prefix reuse at theChatSessionlevel. The two are complementary rather than competing: Reuse cached chat transcript prefixes #370 addssupportsStaticPrefixReuseand this addsnbytes; both touch only theKVCacheprotocol block, so they should merge cleanly in either order.LRUPromptCacheis a non-Sendablefinal class, mirroring Python's single-server-thread assumption. Cross-task consumers wrap it inSerialAccessContainer, asChatSessionalready does elsewhere.Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes🤖 Generated with Claude Code