Repository navigation
perf(mlx): --state-cache-gb and --prefix-cache on --mode mlx (15x with a fixed 2k-token prefix, up to 2.7x on growing dialogues, Apple M4) - #50
Conversation
Reviewer's GuideExtends MLX with opt-in state and prefix KV caching using the existing server cut model, including incremental growing-state reuse, memory-safe MLX copies, packed-path integration, and a precision-motivated minimum continuation length; updates CLI validation, documentation, and comprehensive tests. Sequence diagram for MLX state cache reusesequenceDiagram
participant Server
participant MLXBackend
participant StateCache
participant MLXModel
Server->>MLXBackend: run_shared(groups)
MLXBackend->>MLXBackend: encode(prompts)
MLXBackend->>MLXBackend: _group(tokens, labels, cut)
MLXBackend->>StateCache: get(cache.key(root))
alt cached state exists
StateCache-->>MLXBackend: keys and values
else cache miss
MLXBackend->>StateCache: longest(root)
StateCache-->>MLXBackend: reusable prefix or none
MLXBackend->>MLXBackend: _prefix(root, initial)
MLXBackend->>MLXModel: forward new tokens over initial cache
MLXModel-->>MLXBackend: keys and values
MLXBackend->>MLXBackend: mx.contiguous(keys and values)
MLXBackend->>StateCache: put(cache.key(root), kv, tokens, replaces)
end
MLXBackend->>MLXModel: _forward(suffixes, prefix)
MLXModel-->>MLXBackend: logits
MLXBackend-->>Server: probabilities
Flow diagram for MLX cached and packed request routingflowchart TD
A[run_shared groups] --> B{State cache enabled and group has cut?}
B -->|Yes| C[_group with cut]
C --> D[_state loads or builds root KV]
D --> E[KV-cache path for shared prefix and suffixes]
B -->|No| F{mlx-packed enabled?}
F -->|Yes| G[_packed for eligible uncut groups]
F -->|No| H[_singles or _group]
G --> I[probabilities]
E --> I
H --> I
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
61ed15f to
2b1e7e9
Compare
There was a problem hiding this comment.
Hey - I've found 4 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="basal/engine.py" line_range="3059-3060" />
<code_context>
+ mx, cache = self.mx, self.state_cache
+ key = cache.key(root)
+ kv = cache.get(key)
+ if kv is not None:
+ return kv
+ initial, replaces = None, None
+ found = cache.longest(root)
</code_context>
<issue_to_address>
**Cached state presence leaks**
When an untrusted caller can reach a shared server with state caching enabled and can submit guesses for another caller’s state, `_state` returns immediately on an exact cache hit, skipping the state prefill; a caller can compare response times for requests containing guessed states and learn whether another caller’s state is cached.
Require authenticated tenant identity and isolate cache keys and entries by tenant, or disable state caching on shared unauthenticated servers.
</issue_to_address>
### Comment 2
<location path="basal/engine.py" line_range="3062-3067" />
<code_context>
+ if kv is not None:
+ return kv
+ initial, replaces = None, None
+ found = cache.longest(root)
+ if found is not None:
+ old, pkv, m, n = found
+ if cache.BLOCK <= m < len(root):
+ initial = [(k[..., :m, :], v[..., :m, :]) for k, v in pkv]
+ replaces = old if m == n else None
+ kv = [(mx.contiguous(k), mx.contiguous(v)) for k, v in self._prefix(root, initial)]
+ mx.eval(kv)
</code_context>
<issue_to_address>
**Request order changes probabilities**
When a request’s state extends a previously cached state by at least one full 256-token block, the first request for a growing state is prefetched in one forward when no matching state is cached, but is continued over a cached prefix when an earlier request populated one. Those different forward partitions produce different probabilities, so the same request’s result depends on request order.
Make the prefill partition for a state independent of cache history, or revise the bit-identical, any-order guarantee.
</issue_to_address>
### Comment 3
<location path="basal/engine.py" line_range="3044" />
<code_context>
+ if initial is not None:
+ for c, (k, v) in zip(cache, initial): # the forward writes into new buffers, never into these
+ c.keys, c.values, c.offset = k, v, m
+ self.lm.model(mx.array([list(toks[m:])]), cache=cache)
kv = [(c.keys[..., : c.offset, :], c.values[..., : c.offset, :]) for c in cache]
mx.eval(kv)
</code_context>
<issue_to_address>
**Dynamic RoPE cache changes answers**
When a model uses sequence-length-dependent RoPE and the state-cache cut is shorter than the group’s shared prefix, the cached root keys are produced by `_prefix(root)` at the root’s sequence length, then reused while `_prefix` continues at the longer shared-prefix length. For sequence-length-dependent RoPE, the root’s keys therefore use a different scaling than in the uncached shared-prefix forward, changing probabilities beyond ordinary rounding.
Avoid reusing cached keys across sequence-length-dependent RoPE scaling boundaries, or otherwise ensure the cached root keys use the same scaling as the full shared-prefix prefill.
</issue_to_address>
### Comment 4
<location path="basal/engine.py" line_range="3062" />
<code_context>
+ if kv is not None:
+ return kv
+ initial, replaces = None, None
+ found = cache.longest(root)
+ if found is not None:
+ old, pkv, m, n = found
</code_context>
<issue_to_address>
**Evicted states stop matching prefixes**
When two cached states share an indexed 256-token block and the newer entry is evicted while the older one remains resident, `cache.longest(root)` misses a still-resident state when another entry that shares its indexed block was inserted later and then evicted. The growing state is recomputed from scratch instead of continuing the cached prefix, so the incremental-cache benefit is lost.
Preserve a fallback index for other resident entries sharing each block, or rebuild the index when an entry is evicted.
</issue_to_address>MLXBackend exposes state_cache / prefix / PREFIX_SFX like GraphBackend, so the server's existing cut_of drives it: a group cut at its state takes the state's keys / values from the cache across requests, and a state that begins with a cached one (an instruction prefix before changing content, an agent trace, a chat history) computes only its new tokens. Entries are copies (mx.contiguous: a slice of mlx-lm's KVCache buffer keeps the whole buffer alive), the wired limit grows by the budget, and a continuation never runs 2-8 tokens (MIN_CONTINUE: MLX 0.32.4's fused attention loses bf16 precision there). StateCache counts bytes with .nbytes (torch and MLX alike). Cold and cached requests are bit-identical; against the uncached server fp32 is equal (max |dp| 6e-8) and the 8-bit ports keep every top answer at margin >= 0.2 (2,303 decisions, four public datasets). MacBook Air M4: a 2.1k-token moderation policy before each BAN-PL comment 15.1x (4.5B) / 13.7x (mini), MultiRC 2.6x / 2.7x, MultiWOZ 1.5x (>= 512 state tokens 2.7x / 2.5x), MASSIVE pl --prefix-cache 1.12x / 1.13x (docs/HARDWARE.md).
2b1e7e9 to
3a1d9b3
Compare
…rder and shared servers - MLXBackend refuses --state-cache-gb / --prefix-cache when a layer's RoPE depends on the sequence length (dynamic NTK, yarn, ...): cached keys are continued in forwards of other lengths. Default, linear, llama3 and Gemma 4's proportional RoPE are accepted (_cache_rope_ok; test for each). - HARDWARE.md: a repeated state gives its first request's probabilities; a state continued from another cached one may differ in the last bits from the same state computed whole (it depends on what was cached before). - --state-cache-gb help and SERVING.md: the cache is shared by all clients, so its timing tells whether a state is cached.
|
Thank you, Grzegorz! I tested this carefully, and it moves to basal 2.5.1 rather than 2.5. Here is why.
I ran it on an M4 Pro (48 GB) with basal-2.0-mini-MLX-8bit and basal-omni-1.0-mini-MLX, on both --mlx-forward paths: 1,032 readouts per run, covering five-question requests over ~1.5k-token states, single questions and growing states.
So nothing is broken: bf16 / 8-bit rounding moves near-ties when the state and the rest run in two forwards. A bar fixed in advance still has to hold, though. For 2.5.1 I'll try to make the continued forward match the cold one more closely, or move to a margin-based rule, then rerun the check. I'll keep this PR open and merge it in 2.5.1 together with a small fix of ours for --mlx-forward basal. |
|
Good news, Grzegorz: a correction to my comment above, this is in basal 2.5 after all. The 12 / 6 flips came from MLX choosing kernels by the shape of each call, so the cached path (split into forwards of other shapes) summed near-ties in a different order. On top of your commits, the cached forwards now run at the uncached forward's shapes, and a growing state reuses its cache only where that keeps the bits. The same check (48 GB M4 Pro, both models, both |
…ed keys and values #50 added the continuation to mlx-lm's path only: with basal's forward (2.5) a cut group recomputed its whole shared prefix, so a cached state saved nothing. MLXForward.prefix takes past (the cached keys / values, positions after them) and MLXBackend._prefix passes it after the same MIN_CONTINUE guard. #50's tests run with both forwards; the token counts of the growing-state and 2-8-token tests fail for basal's forward without this.
… for the seven 2.5 pull requests
Its acceptance check on Apple Silicon (1,032 readouts per run, basal-2.0-mini-MLX-8bit and basal-omni-1.0-mini-MLX, both --mlx-forward paths) found cached states bit-identical when hit and no flip above a 0.05 margin, but the top answer with the cache on matched the cache off on 98.84-99.42% of readouts, under the 99.5% bar fixed before the run. Reverts the merge of #50 (88f56c6), the fix on top of it (a4f1c3f), and its WHATS_NEW entry and README credit; it is planned for 2.5.1.
|
Thank you, Grzegorz: the state cache on |
…5, now bit-identical to the cache off (branch mlx50-25) G50c (G50b's rule): 4 runs of 1,032 readouts, exact hits 864 / 864, top-1 1,032 / 1,032 against the cache off, max |dp| 0.
….5 with #50 (branch pr56-25) Conflict in StateCache.longest: #56's lookup and usable() check (with 2.5's 8-bit unpack) kept, #50's use(key) counts the prefix hit at the return; longest(tokens, usable=None, use=None). A test takes both together; #50's test reads the entry as (kv, size, tokens, blocks). Gated again on this head (G56M on f6, G50c on the Mac) before it goes into release-2.5.
…ac-25 MLXBackend._prefix keeps #50's continuation (initial, _uncut) and Qwen3.5's ArraysCache states; _group keeps #50's cut and Qwen3.5's token-bounded suffix batches. The state cache holds attention keys and values only, so --state-cache-gb / --prefix-cache on --mode mlx are refused for Qwen3.5. The merged head reads pico's gate rows bit-identically (50 single, 500 q5o2 readouts).
…e longest usable one (#56, Marcin Brzeżański), with #50's hit counting (branch merge56-25) G56M on the merged code (release-2.5 178659d vs merge56-25 9f08617, H100): exact hits bit-identical, no flip at margin >= 0.05, top-1 against the cache off 0.9902 / 0.9892 (basal-2.0-mini) and 0.9961 (omni-1.0-mini); G50c on 9f08617: 1,032 / 1,032, max |dp| 0.
|
Thank you, Grzegorz! Your work here shipped in basal 2.6.0 with your authorship. Your check that the MLX state cache needs a RoPE that does not depend on the sequence length shipped in 2.6.0, under your name. On top: yarn and longrope are accepted, since mlx-lm 0.32 fixes their frequencies at build time and a split rotation is bit-identical. Dynamic NTK and any unknown kind are refused, and no basal model uses one. Commits on main:
|
Problem
--state-cache-gband--prefix-cacheare refused on--mode mlx, so on a Mac every request computes its state again. This includes a long instruction prefix that never changes, and an agent trace or chat history that grows by one message per step.Change
MLXBackendgetsstate_cache/prefix/PREFIX_SFXlikeGraphBackend. The server's existingcut_ofworks unchanged, and there are no new flags._state). A state that begins with a cached one computes only its new tokens (StateCache.longest).--mlx-packed, cut groups use the KV-cache path.mx.contiguous). A slice of mlx-lm's 256-tokenKVCachebuffer keeps the whole buffer alive.MIN_CONTINUE = 9). In MLX 0.32.4,mx.fast.scaled_dot_product_attentionloses bf16 precision there whenever queries × query heads per KV head > 32: an error of 4-6e-2 against fp32, versus 5-8e-3 otherwise (repro below). Before this guard, one decision on mini moved from 0.46 to 0.16.StateCachecounts bytes with.nbytes.Answers
Measured
MacBook Air M4 (16 GB), mains power,
-MLX-8bit, one client, ABBA order. p50 per request:--prefix-cacheDialogues under 256 tokens cannot hit the cache and run at 0.96x. Method and details are in
docs/HARDWARE.md.Tests
tests/test_mlx_state_cache.pyadds 9 tests: cache reuse, growing states, single and packed prompts, copies and eviction, fp32 equality, and the 2-8 token guard. Each was checked against a deliberately broken implementation. The full suite on 2.4.1: 770 passed, 53 skipped.MLX bf16 SDPA repro
Summary by Sourcery
Add opt-in state and prefix KV caching to MLX serving so repeated and growing prompts can avoid recomputing shared context.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: