Skip to content

feat(models): prompt-cache snapshots for qwen4_exp, then mid-prompt checkpoints for model-owned recurrent families #2885

Open

Description

@inureyes

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.md line 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.rs lines 31-33 list prompt-cache snapshots as out of scope.
  • The hooks exist on LanguageModel and are delegated by LoadedModel (src/loaded_model.rs:655-700): supports_snapshot_reuse, snapshot_sequence_state, restore_sequence_state, snapshot_truncatable_to, restore_sequence_state_truncated. qwen4_exp implements none of them.
  • The closest template is Qwen 3.5 (src/models/qwen3_5.rs:4192), which snapshots each layer's cache into a ModelStateSnapshot tagged "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:
  • APC block sharing is correctly unavailable for this family: it uses SequenceStateLayout::model_owned (qwen4_exp.rs:571), and model-owned sequences are refused by CachePool::detach (see src/server/prompt_cache/hybrid_ssm.rs, "Why this is safe"). qwen4_exp is not listed in HYBRID_SSM_MODEL_TYPES, unlike qwen3_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

  1. Implement snapshot_sequence_state / restore_sequence_state on Qwen4ExpModel following Qwen 3.5: one tagged ModelStateSnapshot ("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.
  2. supports_snapshot_reuse returns true. Truncation (snapshot_truncatable_to) stays false for now: the recurrent state forbids it, the same as Qwen 3.5.
  3. 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).
  4. Add qwen4_exp to 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.
  5. 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 once prefill_start_offset > 0), or decline snapshot reuse for them with a named reason. Pick one explicitly and test it.
  6. Update docs/supported-models.md and 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:

  1. 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.
  2. 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.
  3. 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_exp fixture (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/stats hits 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):

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

  1. added
    status:ready
    type:enhancement
    priority:medium
    area:models
    area:inference
    modelsize:xlarge
    arch:hybrid
    on Nov 8, 2026
  2. added
    status:review
    and removed
    status:ready
    on Nov 9, 2026
  3. added
    status:done
    and removed
    status:review
    on Nov 9, 2026
  4. added
    status:ready
    and removed
    status:done
    on Nov 9, 2026
  5. inureyes commented on Nov 12, 2026

    @inureyes
    MemberAuthor

    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:

    Context, edit depth, budget Edited turn, LRU Edited turn, gap
    28K, edit at ~20K, 4 GiB root (4,744), 22.17 s root, 22.13 s
    28K, edit at ~20K, 6 GiB root, 22.30 s root, 22.13 s
    51K, edit at ~17K, 8 GiB root, 44.35 s root, 44.34 s

    Why it is dropped:

    • The goal is an agent that rewrites or compacts recent history. Within one conversation LRU already evicts the oldest, which is the shallowest, checkpoint, so the recent ones it keeps are the ones such an edit needs. The gap rule only does better for edits far back in a long context, which the replays above tried and still lost to the byte budget.
    • An offline model with equal-cost checkpoints and uniformly placed edits does favor the gap rule (for example 27K against 19K expected reused tokens at 64K with six checkpoints kept), but uniform edit placement is not the workload this item targets.
    • In every run the binding limit was the budget: only two to five checkpoints fit, because a checkpoint's KV grows with its depth. The replay also overstated the pressure: its assistant replies are scripted, so each turn's completion snapshot never matches the next turn and lingers. A real chat that feeds the model's replies back keeps two snapshots per conversation (completion snapshots match and are superseded), checked over three turns.

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    arch:hybridarea:inferencearea:modelsmodelsize:xlargepriority:mediumstatus:readytype:enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions