Skip to content

Add cross-request LRU prompt cache (PromptTrie + byte-bounded eviction) - #436

Open
GoodOlClint wants to merge 1 commit into
ml-explore:mainfrom
GoodOlClint:pr/prompt-cache-lru
Open

GoodOlClint wants to merge 1 commit into
ml-explore:mainfrom
GoodOlClint:pr/prompt-cache-lru

Conversation

@GoodOlClint

Copy link
Copy Markdown
Contributor

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. Python mlx_lm has had a cross-request store for exactly this — PromptTrie + LRUPromptCache in mlx_lm/models/cache.py, used by server.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 implements nbytes; no Swift cache did. The basis is the allocated (step-rounded) buffers from innerState(), not the offset-sliced state, matching Python's KVCache.nbytes.

    It is declared as an open var on BaseKVCache rather than left to the protocol-extension default, so subclasses get a dynamically-dispatched override point. (A protocol-extension default becomes the witness at BaseKVCache'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 / maxBytes eviction, type-aware eviction ordering (assistant → user → system, so system prompts survive longest), and statsByType().

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:

  1. A value stored at a single-token prefix never matched (search used > 0 where >= 0 is correct).
  2. Eviction ignored fetch recency, making the store FIFO rather than truly LRU.

Both are pinned by regression tests (PromptTrieTests, LRUPromptCacheTests).

Scope / notes

  • No existing behavior changes. This adds new types plus one protocol requirement that ships with a default implementation. Nothing is wired into 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 the ChatSession level. The two are complementary rather than competing: Reuse cached chat transcript prefixes #370 adds supportsStaticPrefixReuse and this adds nbytes; both touch only the KVCache protocol block, so they should merge cleanly in either order.
  • LRUPromptCache is a non-Sendable final class, mirroring Python's single-server-thread assumption. Cross-task consumers wrap it in SerialAccessContainer, as ChatSession already does elsewhere.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

🤖 Generated with Claude Code

/// 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> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"]) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() }, [])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +110 to +111
public func fetchNearestCache(model: Model, tokens: [Int]) -> (
cache: [KVCache]?, remainder: [Int]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 -> PrepareResult

This 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 davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
div0-space added a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Dec 2, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants