Repository navigation
Description
Summary
Implement prompt-cache snapshot and restore for qwen4_exp (Qwen3.8-Flash-Next) so multi-turn chats and agent loops stop re-reading their whole history on every turn. Today the family is documented as not supporting prompt-cache snapshots, so every request prefills from token zero. At the measured 1,057 tok/s prefill on M3 Ultra (4,608 tokens), a 30K-token agent context costs about half a minute per turn before the first output token.
Then, as a second part, evaluate mid-prompt checkpoints for model-owned recurrent families, where a cached state cannot be truncated and reuse depends entirely on where exact checkpoints were taken.
Current mlxcel state
docs/supported-models.mdline 114,qwen4_exp: "Scheduled batched prefill, padded prefill, the paged decode backend, prompt-cache snapshots and KV-cache quantization are not supported."src/models/qwen4_exp.rslines 31-33 list prompt-cache snapshots as out of scope.- The hooks exist on
LanguageModeland are delegated byLoadedModel(src/loaded_model.rs:655-700):supports_snapshot_reuse,snapshot_sequence_state,restore_sequence_state,snapshot_truncatable_to,restore_sequence_state_truncated.qwen4_expimplements none of them. - The closest template is Qwen 3.5 (
src/models/qwen3_5.rs:4192), which snapshots each layer's cache into aModelStateSnapshottagged"qwen3_5"and restores into freshly made caches. Other recurrent families do the same (qwen3_next.rs:2228,nemotron_h.rs:3346,jamba.rs:1754, ...). - Server-side reuse that would start working as soon as the hooks exist:
- the whole-prefix snapshot store (
src/server/prompt_cache/store.rs), sized bysrc/server/prompt_cache/snapshot_sizing.rs(recommend_model_snapshot_capacity_from_config); - the history-boundary snapshot donated during prefill for snapshot-only families (feat: Donate a history-boundary snapshot during prefill for snapshot-only families #1143,
src/server/prompt_cache/policy.rs:76, kill switchMLXCEL_DISABLE_BOUNDARY_SNAPSHOT); - the background next-turn warm-up (feat: Post-completion incremental warm-up snapshot for the next turn's history prefix #1144,
MLXCEL_DISABLE_CACHE_WARMUP).
- the whole-prefix snapshot store (
- APC block sharing is correctly unavailable for this family: it uses
SequenceStateLayout::model_owned(qwen4_exp.rs:571), and model-owned sequences are refused byCachePool::detach(seesrc/server/prompt_cache/hybrid_ssm.rs, "Why this is safe").qwen4_expis not listed inHYBRID_SSM_MODEL_TYPES, unlikeqwen3_next; it is protected by the model-owned layout, not by the list.
State that a snapshot must capture
Per sequence, from Qwen4ExpCache (src/models/qwen4_exp.rs:79):
| Layer kind | State | Notes |
|---|---|---|
| Linear (GatedDeltaNet), 36 layers | GatedDeltaCache: recurrent state (float32, see the arithmetic notes in supported-models.md) and conv state |
not truncatable |
Linear layers in ple_layer_ids |
PleCache.conv_state (dilated depthwise conv window) |
not truncatable |
PleCache.contexts: last ngram_size - 1 tokens per row, reset at EOS |
host-side Vec<Vec<i64>>; must be in the snapshot, otherwise the first n-gram ids after a restore are wrong |
|
| Attention (QSA), 12 layers | KVCache (respecting the layer's KVCacheMode, #2766 / #2790) |
truncatable in principle |
QsaIndexCache.raw_keys [B, T, 128], .positions [3, B, T] |
per token | |
QsaIndexCache.block_keys [B, 1, blocks, 128] (pooled complete 4-token blocks) |
whole blocks only | |
| Model level | per-sequence MRoPE state (mrope_state, released in release_sequence_state_by_id) |
needed for requests with images or video |
A missing piece fails silently: restoring KV but not the n-gram context or the block keys still produces fluent text, only different from a cold run. The acceptance tests below therefore compare against cold prefill, not against "looks right".
Part A: snapshot and restore for qwen4_exp
- Implement
snapshot_sequence_state/restore_sequence_stateonQwen4ExpModelfollowing Qwen 3.5: one taggedModelStateSnapshot("qwen4_exp"), per-layer keys, every tensor in the table above at its stored dtype (no promotion), plus the host-side n-gram contexts and the per-sequence MRoPE state. supports_snapshot_reusereturns true. Truncation (snapshot_truncatable_to) stays false for now: the recurrent state forbids it, the same as Qwen 3.5.- Restore validates the snapshot family, layer count and shapes, and fails with a named error on mismatch (for example a snapshot taken under a different
KVCacheMode). - Add
qwen4_expto the snapshot sizing so the store's default capacity reflects its per-token cost (KV and index keys on 12 layers) plus the fixed recurrent cost (36 GatedDeltaNet layers plus the PLE window), and report the per-snapshot size in the log. - Requests with images or video: either carry the MRoPE state in the snapshot and make sure reuse respects the whole-entry rule for multimodal requests in
try_adopt_cached_prefix(src/server/batch/scheduler/prompt_cache.rs, feat(core): shared snapshot serialization for KVCache / RotatingKVCache / ChunkedKVCache so Gemma 3, AFMoE and Llama 4 join exact-prefix prompt-cache reuse #1335: prepared VLM embeddings are dropped onceprefill_start_offset > 0), or decline snapshot reuse for them with a named reason. Pick one explicitly and test it. - Update
docs/supported-models.mdand the module comment.
Part B: mid-prompt checkpoints for model-owned recurrent families (evaluate, opt-in)
For a recurrent family a cached state is reusable only if a new prompt starts with exactly its tokens; a cached 30K-token state is worthless to a request that changed token 25,000. The history boundary from #1143 covers "the next turn appends to the previous one". It does not cover an agent that rewrites or compacts history a few thousand tokens back, or a fresh conversation that shares only the system prompt and tool list.
Strata (MIT, https://github.com/Niko1221/Strata, read at 146df3c) runs the same model and handles this with exact checkpoints taken during prefill. From docs/DETAILS.md ("Conversation cache"), docs/PROMPT_CACHE_TAIL.md and docs/MESSAGE_BOUNDARY_CACHE.md:
- Up to 6 checkpoints in RAM, about 118 MB each, taken at the start of each new assistant turn and every 16K prompt tokens.
- The oldest checkpoint, in practice the end of the system prompt every chat of a client shares, is kept for good, so a new chat with the same prefix starts after it. A prompt of 2,048 tokens or more is also checkpointed at the end of its system prompt.
--prompt-cache-spread(opt-in): evict the checkpoint whose removal leaves the smallest gap, so kept points thin out geometrically from the end. An agent that rewrites history a few thousand tokens back resumes near the edit.--prompt-cache-tail(opt-in): at most one extra checkpoint at the last prefill chunk boundary before the end of the prompt, without splitting chunks.STRATA_CACHE_MESSAGE_BOUNDARY=1(opt-in): one checkpoint at the previous turn boundary, for agents that keep the history but replace the last user message. In their combined measurement (boundary plus larger chunks), the first edit's time fell 33.1% and the reused prefix grew from 22,016 to 32,831 tokens; cold 8K requests cost about 0.2 s more."strata_prefix"per request: pin the checkpoint at the end of a long document so many questions about it cost one read.
Proposed for mlxcel, behind switches and adopted per the measure-then-keep policy:
- System-prompt root. When a prompt of at least N tokens (start from 2,048) is prefilled, donate a snapshot at the end of its leading system message (or the end of the tool block, whichever the template renders last before the first user turn), and protect it from LRU eviction while it keeps getting hits.
- Periodic checkpoints. Optionally donate a snapshot every K prefill tokens (start from 16,384), aligned to chunk boundaries so no chunk is split and numerics do not change.
- Eviction by gap. An optional eviction policy that removes the snapshot whose loss leaves the smallest gap in a conversation's chain, instead of plain LRU.
These apply to every snapshot-only family, not just qwen4_exp; land them generically in the scheduler once Part A gives a model to measure on.
Scope
Part A: in scope for the first PR. Part B: separate PRs, each behind its own switch, after Part A.
Acceptance criteria
Part A:
- Unit test on a tiny
qwen4_expfixture (one PLE layer, one QSA layer, MoE): prefill P tokens, snapshot, restore into a fresh sequence, decode 16 tokens; logits equal a cold prefill of the same tokens bit for bit. Cases: P below 2,052 (dense QSA), P above it with selected blocks, P ending mid-block, and a prompt containing EOS (n-gram context reset). - Negative tests: omitting the n-gram contexts or the block keys from the snapshot makes the comparison fail (proves the test covers them); restoring a snapshot with mismatched shapes or family fails with a named error.
- On the OptiQ 2-bit checkpoint through
mlxcel-server: a second turn reuses the first turn's prefix (/v1/cache/statshits and reused tokens), and its greedy output equals the same request with the cache reset. - Time to first token for the second turn of a 16K and a 32K-token conversation, with and without the cache, recorded in
docs/benchmark_results/, together with snapshot size and store capacity.
Part B (each switch):
- Replay a recorded agent session (system prompt plus tools plus at least 10 turns, including one that edits history) and report reused tokens per turn and total prefill time against Part A alone, with outputs identical at temperature 0.
- Memory: the extra snapshots stay inside the store's byte budget and respect the macOS memory guardrails from feat(core): macOS memory guardrails for large resident models (available-memory preflight, idle compression, optional wiring) #2883.
Verification
cargo build --release --features metal,accelerate
cargo test --workspace --profile test-fast --features metal,accelerate qwen4_exp
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
./target/release/mlxcel-server -m models/Qwen3.8-Flash-Next-OptiQ-2bit --port 8080 &
# two turns of the same conversation, then:
curl -s http://127.0.0.1:8080/v1/cache/stats
Activity
feat(core): add macOS memory guardrails for large resident models (#2909
feat(speculative): wire the native MTP head and rollback for qwen4_exp
feat(speculative): wire the native MTP head and rollback for qwen4_exp (
fix(models): refuse qwen4_exp snapshots missing recurrent state
feat(models): add prompt-cache snapshots for qwen4_exp (#2911)
docs(bench): record deferred qwen4_exp measurements on M3 Ultra (#2926)
feat(prompt-cache): add opt-in system-prompt root snapshot (#2950)
feat(prompt-cache): add opt-in periodic prefill checkpoints (#2973)
inureyes commentedon Nov 12, 2026
Evaluation of Part B item 3 (eviction by gap): not adopted.
Implemented as an opt-in switch: when snapshot LRU picks a checkpoint, evict instead the checkpoint of the same conversation whose removal leaves the smallest gap between the remaining checkpoints and roots. Replayed on Qwen3.8-Flash-Next-OptiQ-2bit with checkpoints every 4,096 tokens:
Why it is dropped:
Next: make the replay feed back the model's own replies, then measure recent-history edits with checkpoints on at the model-aware default budget, and size that default for checkpoints if it is what blocks them.
feat(prompt-cache): keep the previous turn's restore point (#3037)