Repository navigation
feat(core): share KV snapshot serialization across attention cache families - #1752
Conversation
Implementation reviewRoot cause of the "What is not validated" Gemma 3 divergenceIt is a pre-existing scheduler defect this PR exposes, not one it introduces. The restore side resumes from The other two insert sites are exact by construction, which is why 334, 335, 339 and 344 are clean: the warm-up forwards No family compensates, and none ever did: Other findings
VerifiedShared module factoring, Gate re-run locally: fmt and the narrow clippy clean; Acceptance criteriaAll met except the turn-2 byte-identity criterion, which the PR body correctly reports it could not run as written and substituted with a warm-versus-cold comparison, and which still fails at the one-decoded-token Gemma 3 boundary for the reason above. No changes made in this pass. |
Review findings on #1752. `try_adopt_cached_prefix` enforced `require_whole_entry` only on the KV branch, so a multimodal request could adopt a truncating snapshot restore. `admission.rs` drops the prepared VLM embeddings as soon as `prefill_start_offset > 0`, so any image or audio placeholder left in the suffix would then be forwarded as an ordinary token id. Harmless before, because the only VLM wrappers on the snapshot path could not truncate; reachable now that `vision::VisionLanguageModel` forwards the hooks to Gemma 3 and Llama 4 text models, whose standard and unwrapped rotating or untrimmed chunked layers do truncate. The gate now sits on both branches and declines before allocating a sequence slot, leaving the entry available for a later exact match. Text-only requests pass `require_whole_entry == false` and are unaffected, and an exact-prefix restore never sets `partial`. Also corrects the stale doc comment and assertion message on `sliding_cache_live_len_matches_returned_keys`, which still said `CacheInterface::live_len` returns `seq_len()` after this branch changed it to `visible_len()`. Refs #1335
Security and performance reviewFixed
Found, not fixed
Checked, no finding
Gate
The push moved the remote branch from 4c1c3b3 to e46eae1, so adcecb3 ( |
`RotatingKVCache::restore_fp16_snapshot_state` rejected `idx > max_size` whenever `buffer_size == 0`, but that shape is legitimate: `update_concat` stores more than one window after a prefill longer than `max_size` and pins `idx` to the stored length, so a snapshot captured between that prefill and the next single-token step carries `idx == physical_len > max_size`. The old check therefore sent every over-window first turn down a cold prefill instead of restoring it. The constraint that actually matters is that the write position lands inside the buffer being restored against, so the check is now `idx <= physical_len`. That still catches a genuinely corrupt idx, and it is the tighter of the two bounds while the buffer is still growing towards `max_size`. Refs #1335
Exact-prefix prompt-cache reuse made every model-owned family hand-write its own per-cache-type serializer, and only Gemma 4 and Muse Glimmer had one. Gemma 3, AFMoE and Llama 4 were silently excluded from every prompt-cache path and re-prefilled the whole conversation on each turn. `src/models/kv_snapshot.rs` now owns the layout for all three ordinary attention cache types and the rule for what a truncating restore may do to each: `KVCache` always, because every token keeps its own slot; `RotatingKVCache` only while its ring is unwrapped, since a wrapped ring no longer holds logical token `t` at slot `t`; `ChunkedKVCache` only while its front is untrimmed, because a cold prefill of the shorter prompt would hold a wider window than a front-trimmed buffer can offer. A `KvSnapshotNames` parameter carries each family's tensor names, so Gemma 4 keeps writing `standard` / `rotating` and Muse Glimmer `full` / `sliding`. Only `KVCacheMode::Fp16` is accepted; any other mode is refused rather than reinterpreted. The three families now declare `supports_snapshot_reuse()` and implement the four state hooks, and `vision::VisionLanguageModel` forwards all five to its text model so the Gemma 3 and Llama 4 VLM checkpoints inherit the capability. `RotatingKVCache`'s `CacheInterface::live_len` returned the physical buffer length where the prefill mask must be sized from `visible_len()`. Decode grows the ring by `step` blocks, so a cache that has generated one token has `physical > offset`, while `update_concat` concatenates only `visible_len()` prior keys; the wider mask tripped `broadcast_shapes` on the first multi-token append after a decode. That is exactly a snapshot restore followed by the appended-token prefill, which is why live prefill-only sequences never hit it. The three families also decline NA tile-aligned padded prefill. That is a scoped workaround, not the fix: the scheduler trims a padded chunk out of the `CachePool`'s caches, a model-owned family has none there, so the pad positions stay in the model's own caches and run `offset` past the real token count. The general repair is a sequence-aware trim hook the scheduler can call for model-owned families, since `trim_internal_caches` takes no `SequenceId` and is wired only into the CLI generate paths. Gemma 4's existing opt-out gains the same note so a future profiling result cannot flip it back alone. Closes #1335
Review findings on #1752. `try_adopt_cached_prefix` enforced `require_whole_entry` only on the KV branch, so a multimodal request could adopt a truncating snapshot restore. `admission.rs` drops the prepared VLM embeddings as soon as `prefill_start_offset > 0`, so any image or audio placeholder left in the suffix would then be forwarded as an ordinary token id. Harmless before, because the only VLM wrappers on the snapshot path could not truncate; reachable now that `vision::VisionLanguageModel` forwards the hooks to Gemma 3 and Llama 4 text models, whose standard and unwrapped rotating or untrimmed chunked layers do truncate. The gate now sits on both branches and declines before allocating a sequence slot, leaving the entry available for a later exact match. Text-only requests pass `require_whole_entry == false` and are unaffected, and an exact-prefix restore never sets `partial`. Also corrects the stale doc comment and assertion message on `sliding_cache_live_len_matches_returned_keys`, which still said `CacheInterface::live_len` returns `seq_len()` after this branch changed it to `visible_len()`. Refs #1335
`restore_standard` and `restore_chunked` installed the snapshot's `offset`, `start_position`, keys and values into a live cache without checking that they agree. The sliding-window path never had that gap: `RotatingKVCache::restore_fp16_snapshot_state` validates the ring geometry against the buffers it is handed. A declared length running past its own buffer installs cleanly on the other two paths, and the next append then slices past the sequence axis, reaching the caller as an MLX throw at the FFI boundary instead of a declined restore. Only this process's own caches produce a snapshot today, so these shapes are not reachable through the server. The checks are here because `restore_*` is where a stored state becomes a live GPU cache, and because the rotating path already treats it as one. Refused now: keys and values that disagree on rank, batch, heads or length; a declared length that does not fit the buffer; a chunked `[start_position, offset)` that is not a valid range; and a rotating `max_size` that differs from the live cache, matching the refusal `restore_chunked` already made for `chunk_size`, since the window width is model configuration rather than sequence state. `truncate_chunked` builds both slices before installing either, so a failure on the value buffer cannot leave a shortened key buffer beside a full-length one, and a negative truncate target is refused by name. Refs #1335
`model_owned_paged_family_never_donates_or_adopts` failed on this branch. It asserts `store.len() == 0` after a Gemma 3 request finishes, and Gemma 3 answers `supports_snapshot_reuse()` as of this change, so the store holds one snapshot entry. `len()` and `PromptCacheStats::entries` both count the two buckets together. #1346's guarantee is about the K/V bucket and the K/V lookup, and both still hold, so the test now asserts them directly: `entries - snapshot_entries == 0`, `inserts == 0`, and `lookups == 0`. Turn 2 skips the shared 40-token prefix through the snapshot restore instead of prefilling from zero, which is the behavior #1335 exists to produce, and the shadow block table it must not adopt is still never consulted. `prompt_cache_reject_model_owned_state` is dropped rather than moved: Gemma 3 returns on the snapshot branch before that decline, and this file has no model-owned family without snapshot reuse to exercise it with. Also corrects the whole-entry gate comments in `prompt_cache.rs`. That gate was not first reachable through `vision::VisionLanguageModel`: `vision::gemma4_vl` and `vision::gemma4_unified` have forwarded `snapshot_truncatable_to` since Gemma 4 first answered it, so a multimodal partial snapshot restore could already bypass the rule. This change widens the reach rather than creating it. Refs #1335, #1346
The 983b8ba bounds-checking fix (restore_standard, restore_chunked, truncate_chunked) had unit coverage for offset-past-buffer, inverted windows, and the rotating window mismatch, but not a negative truncate target on the rotating path or the truncate_chunked atomicity guarantee its own commit message describes (a failed value slice must not leave a shortened key buffer installed beside the original value buffer). Both are added to kv_snapshot_tests.rs. Gemma 3, Llama 4, and AFMoE each declared snapshot reuse, refused a foreign family's snapshot, and round-tripped, but none had a test for refusing a quantized (non-Fp16) cache mode at the family-hook level, and AFMoE had no test for the truncation predicate answering false once its sliding ring has wrapped. Added one quantized-mode-decline test per family (via set_kv_cache_layer_modes plus restore_sequence_state, which needs no forward pass since the mode mismatch is caught before any cache is populated) and a wrapped-ring truncation-decline test for AFMoE, mirroring Gemma 3's existing one. The require_whole_entry gate on the snapshot branch of try_adopt_cached_prefix (adcecb3) had no direct test. try_adopt_cached_prefix is pub(super) and reachable straight from a scheduler test, so scheduler_model_owned_cache_tests.rs now drives a real partial-match divergence through it directly with the gate on and off, without needing a multimodal harness. Validation: cargo test --profile test-fast --features metal,accelerate --lib for models::kv_snapshot (23), models::gemma3 (25, 6 more under --ignored), models::llama4 (5, 3 more under --ignored), models::afmoe (28), server::batch::scheduler::scheduler_model_owned_cache_tests (3); cargo clippy --lib --tests and -p mlxcel-core --lib, both -D warnings, clean; cargo fmt --all -- --check clean. Refs #1335
…milies docs/turbo-kv-cache.md already documents the shared serializer and the Gemma 3 / AFMoE / Llama 4 roster, but supported-models.md described their architectures with no mention of the new supports_snapshot_reuse() capability, unlike the existing Qwen 3.5-VL entry which already calls out prompt-cache reuse. Added a one-clause pointer to each of the three entries (and the previously bare "Llama 4 text" line) naming the truncation precondition specific to that family and linking to the turbo-kv-cache.md section for the details. Verified turbo-kv-cache.md itself against the current code: the family roster matches a fresh grep -rn 'fn supports_snapshot_reuse' src/models src/vision, the RotatingKVCache is_unwrapped() formula quoted there matches cache.rs verbatim, and the supports_padded_prefill() == false claim holds for gemma3.rs, llama4.rs, and afmoe.rs; no changes needed there. Refs #1335
66bce6d to
a0f9692
Compare
Covers the shared `kv_snapshot` module and its per-type truncation contract (standard always, rotating while unwrapped, chunked while untrimmed), the three family opt-ins, the two defects fixed as causes (the rotating `live_len` mask width and the `idx > max_size` restore bound), the whole-entry gate on the snapshot adopt branch, and the restore-side bounds and shape refusals. Records the validation design finding that prompt cache on against off is not a valid isolation test, because the history-boundary snapshot splits even a cold first turn, plus the warm-restore against cold-substitution comparison used in its place with the Gemma 3, Llama 4 Scout and AFMoE figures. Also states what limits the feature on merge: the 512 MiB snapshot bucket against measured 384 and 480 MiB Llama 4 entries (#1761), the pre-existing whole-prompt hit (#1760), and the counter-evidence posted on #1754. Refs #1335
## Summary `AnyKVCache::live_len` (exaone_moe) and both Gemma 4 sliding lookups read `RotatingKVCache::seq_len()`, the physical buffer length, to size the sliding prefill mask. PR #1752 showed for Gemma 3 that this is the wrong accessor: after a decode step (`update_in_place` grows the buffer by 256 slots) or a `trim` (truncated snapshot restore, rollback of an unbuffered cache), the buffer runs ahead of `offset`, while `update_concat` returns only `visible_len()` prior keys for an FP16 rotating cache. - All three sites now read `visible_len()`, and their comments no longer claim `seq_len()` reports the live window. - `Gemma4StageModel` had a private copy of the lookup. It now calls the free `first_cache_live_len` (whose parameter becomes `&[Cache]`), so one function and one guard cover both Gemma 4 call sites. - `sliding_cache_live_len_matches_returned_keys` and `first_cache_live_len_sliding_matches_returned_keys` now decode once before the multi-token append and assert `physical > offset` and `offset < window - 1`. The second condition matters: once `offset >= window - 1` the clamp makes both accessors give the same mask, and the old fixtures' 4-token prefill plus one decode landed exactly there (offset 5 in a 6-slot window), so they could not fail. ## Gemma 4 outcome The right-crop already produced the correct band. `pre_fix_sliding_mask_right_crop_is_the_visible_band` crops the `seq_len()`-sized mask with `trim_mask_to_keys` and compares it value for value with a band built from logical positions. It covers both ways of reaching `physical > offset` (decode, trim) and appends inside the window and across it. The band depends only on `k - q - kept_prior`, and `trim_mask_to_keys` keeps the trailing columns, so the crop equals the `visible_len()` mask, and decoded Gemma 4 output does not change on the default paths (confirmed on a real checkpoint below). As a mutation check, cropping from the left instead fails the test (`decoded/3: pre-fix crop mask disagrees with the logical band at row 0, key 6: 0 vs -inf`, a causal leak). The lookup also feeds `mask_stale_key_gap`, which uses left-aligned columns. That runs only on batched MTP verify, where the rotating caches are buffered and both accessors return `idx`. One consumer does change behavior: the caller-mask rebuild check in the forward (`sliding_returned`) now sees the narrower count, so an unbuffered FP16 cache whose buffer runs ahead of `offset` keeps a correctly sized caller mask (padding or a draft tree) instead of replacing it with plain causal masks. That is a fix, and nothing reaches it by default: Gemma 4 does not use padded prefill, cold batched prefill runs at offset 0, and tree verify runs on buffered caches unless `enable_speculative_buffer` fails on a non-FP16 rotating mode. A turbo-quantized sliding cache (`update_turbo4_concat`) still returns the whole physical buffer, so after this change its mask is narrower than the keys and `trim_mask_to_keys` rebuilds it, which gives the same band as before plus a warning per sliding layer; that append reading the full physical buffer predates this PR and is a follow-up. ## Revert arm Both one-liners set back to `seq_len()`, same two modules: ``` test models::exaone_moe::exaone_moe_mask_tests::sliding_cache_live_len_matches_returned_keys ... FAILED test models::gemma4::gemma4_unified_mask_tests::first_cache_live_len_sliding_matches_returned_keys ... FAILED assertion `left == right` failed: AnyKVCache::live_len() = 262 sized a sliding mask with 265 key columns, but the append returned 10 keys assertion `left == right` failed: first_cache_live_len = 262 sized a sliding mask with 265 key columns, but the append returned 10 keys test result: FAILED. 13 passed; 2 failed ``` ## Test plan - [x] `cargo test --profile test-fast --features metal,accelerate --lib -- exaone_moe gemma4 kv_snapshot rotating_live_len`: 258 passed, 35 ignored, on the pushed commit - [x] `cargo clippy --lib --tests --profile test-fast --features metal,accelerate -- -D warnings`, `cargo fmt --all -- --check` - [x] Workspace gate on 824b01e: 123 binaries, 11016 passed, 0 failed, 359 ignored; workspace clippy `-D warnings`, fmt, `make verify-versions` / `verify-kernel-dtype-keys` / `verify-llama-compat` clean. The follow-up commit is comment-only (clippy and the two mask modules re-run clean). - [x] Multi-turn greedy run on `gemma-4-12b-it-4bit` through `mlxcel-server` (temperature 0, seed 0, 128 tokens per turn, assistant text fed back), pre-fix bb146ef vs post-fix binaries, prompt cache on and off. The trace shows T2 and T3 adopting restored prefixes of 311 and 517 tokens, both under the 1023-token clamp, so the changed lookup ran. Pre-fix and post-fix are token-identical on all four turns with the cache on and with it off, and again in a variant whose T3 append runs from 517 to 1261 tokens across the 1024 window. Cache on vs off differ at T3 identically in both binaries (94 vs 121 generated tokens), which is the existing model-owned-cache class tracked in #1346, not this change. exaone_moe has no checkpoint in the store, so the unit guard is its only check. Closes #1764
…hes (#2129) ## Summary The code defects named in #1761 already landed in #1978 (`d7279c52`): `gemma3`, `llama4` and `afmoe` are in the model-aware family list, and `model_types()` strips `_text`. This PR adds what the issue still required: tests built from the geometry the real checkpoints carry (including the `gemma4_unified_text` and `muse_glimmer_text` spellings), the real-checkpoint measurement of the default memory change, and the policy wording in `docs/environment-variables.md`. The sizing module's tests move to `snapshot_sizing_tests.rs` (the file was 643 lines). No runtime code changes, so this does not touch admission or restore. ## Default policy `capacity = max(512 MiB, min(6 * entry, left / 4))`, raised to one `entry` when it fits in `left / 2`. `entry` is the unwindowed snapshot at `min(ctx, 8192)` tokens (8192 on a default launch) and `left` is memory after the model's estimated footprint. It is a cap, not an allocation: resident bytes grow only as snapshots are inserted. An explicit flag or env value is never replaced. ## Measurement (GB10, default launch, multi-turn `mlxcel-server`) "Before" is the same binary with `MLXCEL_PROMPT_CACHE_SNAPSHOT_CAPACITY_BYTES=536870912`, which marks the capacity explicit and skips the raise (`startup.rs`), reproducing the fixed bucket the issue describes. | Checkpoint | Capacity | Peak stored | Oversized rejects | Snapshot hits | Last turn | |---|---|---|---|---|---| | gemma-3-4b-it-4bit, 8 turns to 31.8k tokens | 512 MiB -> 6.375 GiB | 532 MB -> 2.02 GB | 13 -> 0 | 15/16 both; before stalls at cached=19918 from turn 6 | 15.5 s -> 2.07 s | | gemma-4-12b-it-4bit (`gemma4_unified_text`), 6 turns to 15.8k | 512 MiB -> 15.75 GiB | 512 MB -> 4.39 GB | 8 -> 0 | 0/12 -> 11/12 | 37.7 s -> 4.3 s | | muse-glimmer-30b-4bit (`muse_glimmer_text`), 6 turns to 17.4k | 512 MiB -> 2.44 GiB | 315 MB -> 739 MB | 0 -> 0 | 5/6 both; self-evictions 6 -> 0 | 7.4 s both | On Gemma 4 12B the "before" completion entries fit, but the next-turn warm-ups were all skipped (0 run, 6 skipped against 5 run, 0 skipped after) once the boundary entries (0.9 to 5.4 GB) were rejected, so no turn hit. Per-token estimates against first-turn boundary snapshots: 139,264 vs 140,847 measured (Gemma 3), 344,064 vs 345,330 (Gemma 4 unified), 53,248 vs 53,465 (Muse Glimmer), all within 1.2% and now asserted at 2%. ## Test plan - [x] `prompt_cache::snapshot_sizing` (14), `execution::kv_arch` (28), `server::prompt_cache` (184) with `--features cuda --release`, `--test-threads=1` - [x] `cargo clippy --lib --tests --features cuda -- -D warnings`, `cargo fmt --check` - [x] Real multi-turn runs above ## Not verified on this host - Llama 4 Scout real run: the checkpoint is 57 GB, over this host's 40 GB rule. Covered by a unit test against the #1752 measurement (192 KiB per token, within 1%). - AFMoE real run: no local checkpoint; unit test only. - Metal, and the issue's workspace-wide `cargo test` and `clippy --workspace` (narrow selectors run instead). Closes #1761
) ## Summary The scheduler trimmed padded-prefill positions only from the `CachePool` entry's `KVCache`s. A family whose own layout is model-owned keeps its K/V inside the model, so that trim reached nothing and `offset` ran ahead of the real token count; PR #1752 opted Gemma 3, AFMoE and Llama 4 out of padded prefill for that reason. This adds `LanguageModel::trim_sequence_state(seq_id, excess)` and routes all four scheduler pad trims (batched, full, chunked first chunk, continuation) through one helper that trims the pool caches and, for a model-owned layout, calls the hook. A failed rewind aborts the request instead of decoding from a desynchronized offset. - Gemma 3 implements the hook (server) and `trim_internal_caches` (CLI) and takes padded prefill again. `RotatingKVCache::rewind_padded_prefill` also cuts the physical ring back: a plain `trim` leaves the pad keys in the slots the next decode step keeps once a padded chunk outgrows the window. - `deepseek_v4` (pooled compression caches), `bailing_moe_linear` (GLA state), `qwen3_next` (gated-delta state) and `PipelineServerModel` (state behind the pipeline runtime) now answer `supports_padded_prefill() -> false` with the reason. AFMoE and Llama 4 stay opted out; their comments say what lifting it takes. - The trait doc states the model-owned exception. The hook default delegates to `trim_internal_caches` for non-batching models and fails closed for batching ones. - Other behavior changes: new `MLXCEL_FORCE_PADDED_PREFILL` forces tile alignment on any hardware (CLI and server); the server now honors `MLXCEL_NO_PADDED_PREFILL`; `LoadedModel` and the VLM wrapper delegate both trim hooks (`LoadedModel` previously dropped `trim_internal_caches` for every family); the continuation-chunk mask offset falls back to the prefill cursor when the pool entry is empty. ## CUDA reachability (negative result) Model-owned families never reach padded prefill on CUDA today. The only model-owned family with `supports_batched_prefill() == true` is qwen3_5, which declines padding, so the longest-row padded batched site is unreachable for them; the single-sequence sites were hardware-gated with no force override. The forced-alignment env is what makes the path testable here. ## Test plan (GB10, CUDA, release) - [x] New `cache::prefill_rewind` tests (5) and `scheduler_model_owned_pad_trim_tests` (4: full prefill inside and past the window on dense and paged backends, chunked prefill, snapshot reuse after a padded turn). With the Gemma 3 rewind disabled the scheduler tests fail: offset 32 vs 13, 96 vs 37. - [x] `server::batch::scheduler` 178 passed, `block_reclaim` 23, `lookahead` 11, `speculative` 175, `generate::tests` 36, `models::gemma3`, `models::afmoe` 28, `muse_glimmer` 109. Clippy (both crates, `-D warnings`) and fmt clean. - [x] `mlxcel-server` with gemma-3-4b-it-4bit, `--prefill-chunk-size 500`, greedy, prompts of 176, 730 and 1852 tokens (none a multiple of 32, the last past the 1024 window). Forced padding vs unpadded, `--parallel 1` sequential and `--parallel 4` concurrent: the short prompt is identical everywhere; the others diverge only where the top-2 logprobs are equal at the reported resolution (0.25), and unpadded `--parallel 1` vs `--parallel 4` diverge at the same long-prompt position with no padding involved. With the rewind disabled, outputs diverge at token 1 (top-2 gap 1.0 and 1.5) and the 730-token prompt degenerates into repeated `texId`. - [x] `mlxcel generate` with gemma-3-4b-it-4bit, forced padding vs unpadded: identical 40-token output. ## Not verified on this host - The M5 manual check from the issue and Metal numerics of the padded path (no Neural Accelerator here). - `cudaStreamEndCapture` aborts hit about one in four repeated runs of several suites, including the comment-only gemma4 suite; every suite passed on rerun. Follow-up: decode lookahead stays off for model-owned families (#2139). The hook cannot serve that teardown as is, because the rewind requires a chronological buffer and a decode write into a wrapped ring is not one. Closes #1755
What this does
Moves the snapshot serialization for
KVCache,RotatingKVCacheandChunkedKVCacheinto one shared module,src/models/kv_snapshot.rs, and opts Gemma 3, AFMoE and Llama 4 into exact-prefix prompt-cache reuse. Before this they held ordinary attention state inModelOwnedSequenceStatebut declared no snapshot support, so every multi-turn request on them re-prefilled the whole conversation.The module owns the truncation contract as well as the byte layout, because that is the part a per-family copy gets wrong.
KVCacheis always truncatable, since every token keeps its own slot.RotatingKVCacheonly while its ring is unwrapped, since a wrapped ring no longer holds logical tokentat slott.ChunkedKVCacheonly while its front is untrimmed, because a cold prefill of the shorter prompt would hold[target_len - chunk_size, target_len)while a front-trimmed buffer only offers[start_position, offset). Exact-prefix restore is unaffected by all three; only the shorter-prefix variant declines.A
KvSnapshotNamesparameter carries each family's tensor-name and error vocabulary, so Gemma 4 keeps writingstandard/rotatingand Muse Glimmer keeps writingfull/sliding, and both still restore snapshots written by earlier builds. OnlyKVCacheMode::Fp16is accepted, at snapshot and at restore, and every restore path now checks the state it installs against the buffers it is handed: keys and values that disagree on rank, batch, heads or length, a declared length that does not fit its buffer, an invalid chunked[start_position, offset)range, and a rotatingmax_sizethat differs from the live cache are all refused rather than installed.vision::VisionLanguageModelforwards the five hooks to its text model, which is what lets the Gemma 3 and Llama 4 VLM checkpoints inherit the capability.Two defects fixed as causes
RotatingKVCache'sCacheInterface::live_lenreturnedseq_len(), the physical buffer length, where the prefill mask has to be sized fromvisible_len().update_in_placegrows the ring bystep(256) blocks during decode, so a cache that has generated even one token holdsphysical > offset, whileupdate_concatconcatenates onlyvisible_len()prior keys. Sizing the mask from the physical length made it wider than the returned K/V and trippedbroadcast_shapeson the first multi-token append after a decode, which is exactly a snapshot restore followed by an appended-token prefill. Live prefill-only sequences never hit it because concat leavesphysical == offset. Guarded bylive_len_matches_the_keys_a_multi_token_append_returns.restore_fp16_snapshot_staterejectedidx > max_sizewheneverbuffer_size == 0, butupdate_concatstores more than one window after a prefill longer thanmax_sizeand pinsidxto the stored length, so a snapshot captured between that prefill and the next single-token step legitimately carriesidx == physical_len > max_size. The old check sent every over-window first turn down a cold prefill. The bound is nowidx <= physical_len. Guarded byrotating_round_trip_survives_an_over_window_prefill.Scoped opt-outs
Gemma 3, AFMoE and Llama 4 answer
supports_padded_prefill()withfalse, and Gemma 4's existing opt-out gains the same note. The reason is a missing hook, not a property of these models: the contract requires trimming the caches back to the real prompt length after an NA tile-aligned padded chunk, the scheduler honours it by trimming theCachePool'sVec<KVCache>, and amodel_ownedfamily's pool entry has an emptycachesvector. The trim reaches nothing, the pad positions stay in the model's own caches, andoffsetruns past the real token count (M5-only, gated byshould_align_prefill()). The sequence-aware trim hook that would fix it properly is #1755.try_adopt_cached_prefixenforced the multimodal whole-entry policy only on its KV branch, so a truncating snapshot restore was reachable for a multimodal request, andadmission.rsdrops the prepared VLM embeddings onceprefill_start_offset > 0, leaving placeholder tokens in the suffix to forward as ordinary ids. That gap predates this branch:vision::gemma4_vlandvision::gemma4_unifiedhave forwardedsnapshot_truncatable_tosince Gemma 4 first answered it, so this change widens the reach tovision::VisionLanguageModelrather than creating it. The gate now sits on both branches and declines before allocating a slot.Validation
Gate:
cargo fmt --all -- --checkclean,cargo clippy --lib --tests --features metal,accelerateandcargo clippy -p mlxcel-core --libclean, andmodels::kv_snapshot(16),models::gemma3(25),models::llama4(5),models::afmoe(26),models::gemma4_tests(10) andmodels::muse_glimmer(13) pass. The 14 model-level snapshot tests carrying#[ignore = "requires serial MLX execution"]were each run alone by exact name; all pass.Real checkpoints, Apple M5 Max,
mlxcel-serveron port 19335, prompt cache on, greedy (temperature 0,seed 0),preserve_thinkingpinned in every arm.Prompt cache on against
--no-prompt-cachedoes not isolate the snapshot, so it is not the test used here. With the cache on,capture_history_boundary_snapshot(#1143) splits even a cold first turn at the conversation boundary: Gemma 3's 1323-token turn 1 is forwarded as 1320 then 3 where the cache-off arm forwards 512/512/299, and that width change reproducibly flips one near-tied token (a straight versus curly apostrophe) in an 89-token reply. Two controls pin the cause: reruns of the same arm in separate processes are bit-identical, andmodels/qwen2.5-7b-instruct-4bit, which has no snapshot support and so takes no boundary split, is byte-identical across the flag. The comparison below therefore holds the cache on in both arms and varies only whether the turn is served from a restored snapshot or computed cold in a fresh process.Gemma 3 (
models/gemma-3-4b-it-4bit, rotating 1024 plus standard). Turn 1 is 1323 prompt tokens over a 1024 window, the over-window shape the restore-bound fix admits, and generates 89. The completion donate storestoken_len=1412, exactly turn-1 prompt plus generated, which the warm-up extends to the turn-2 boundary at 1417. Turn 2 adoptsrestored 1417/1435, stored=1417, partial=false; turn 3 adoptsrestored 1547/1567, partial=falsewith the ring long since wrapped. Against cold, turn 2 is byte-identical over 104 of 104 tokens, 103 with bitwise-equal logprobs and a minimum top-2 gap of 0.25, and turn 3 is byte-identical over 18 of 18 with every logprob bitwise equal.Llama 4 Scout (
models/llama-4-scout-17b-16e-instruct-4bit, chunked plus standard). Turn 1 is 1305 prompt tokens and 512 generated; the completion entry is1817 = 1305 + 512, extended to 1822. Turn 2 adoptsrestored 1822/1840, partial=falseand is byte-identical to cold over all 512 tokens, 338 with bitwise-equal logprobs and a minimum top-2 gap of 0.0, so it agreed even at exactly tied positions.AFMoE (
models/trinity-nano-preview-4bit). Turn 1 is 1281 prompt tokens and 512 generated, and the completion entry is1793 = 1281 + 512. Turn 2 adoptsrestored 1280/1755, stored=1793, partial=true: the reply does not re-tokenize as a prefix of the stored tail, so the store truncates to the end of turn 1's prompt, exercising the truncation predicate on real weights. Output identity is not a usable signal for this checkpoint, whichdocs/supported-models.mdrecords as emitting degenerate repetitive text under the mlx-lm reference as well as here, and both arms do exactly that. Its snapshot machinery is covered by unit tests instead, including a non-ignoredsnapshot_restore_matches_cold_decode.The contract also declines correctly on real weights: replaying Gemma 3's 1323-token prompt finds the 1417-token entry, refuses to truncate into a wrapped ring, and rejects with
snapshot_diverged (context_len=1323, entry_len=1417)instead of restoring a wrong window.Not fixed here
Replaying an identical prompt inside one process diverges from the first reply on every family tested,
models/gemma-4-12b-it-4bitincluded, which has shipped this path since before this branch and is untouched by it. The adopt covers the whole prompt andadmission.rsbacks the prefill cursor off one token without rewinding the restored cache. Pre-existing and filed as #1760, with the Gemma 4 control as the evidence that this branch does not cause it.The snapshot bucket is still sized by the fixed 512 MiB default for these three families, because
snapshot_family_is_model_awarelists only recurrent ones, whose state is O(1) in context where an attention cache is O(context). Llama 4 Scout stores about 192 KiB per token, so a conversation of a few thousand tokens is rejectedOversizedand the feature silently stops working. The Llama 4 entries measured above were 402,653,712 bytes for the 1817-token turn and 503,317,008 for the 2352-token one, which is 384 and 480 MiB of step-aligned buffer, so this two-turn validation sits just under the cap and a third turn would not fit. Filed as #1761, deliberately outside this diff because it changes a default memory policy and needs its own measurement.#1754 claims completion-origin snapshots claim one more token than their caches hold. Llama 4's turn 1 above finished on
length, the finish class that issue names, and the restored turn 2 was still byte-identical to cold, so the premise needs confirming before the donate arithmetic changes; noted on the issue.Closes #1335, closes #1756