Repository navigation
feat: snapshot quantized KV cache modes for prompt-cache reuse - #3498
Conversation
Families that reuse prompt prefixes through model-state snapshots stored nothing once the server ran with a non-FP16 KV cache. On GB10 with gemma-4-12B-it-4bit and --cache-type-k int8 --cache-type-v int8, every turn of a 5.8k-token conversation reported snapshot_inserts=0, last_reject_reason=empty_set and cached_tokens=0, and prefilled its whole prompt. Two defects sat behind the one refusal: a sliding ring that stores plain FP16 rows was refused for its Int8 label, and a full-attention cache really holds quantized state the snapshot did not carry. A RotatingKVCache snapshot is now judged by the mode the ring stores. Under Int8, Turbo4, Turbo4Delegated and Turbo3Asym the ring holds plain rows and is stored as the FP16 ring it is, keeping its label; restore_fp16_snapshot_state becomes restore_snapshot_state. A KVCache in Int8, Turbo4Asym or Turbo4 is stored with its sidecars (scales, packed K and V, norms, rescale), its Turbo seed and its live-window start, through KVCache::snapshot_parts and restore_snapshot_parts in the new cache/snapshot_parts.rs, and an aligned Turbo4Asym ring is stored with its packed V. One layout check runs on both sides, so a restore assigns nothing unless every buffer its mode needs is present and covers the stored length. An FP16 snapshot writes exactly the tensors and scalars it wrote before. The hybrid attention arm is implemented once in hybrid_snapshot for Qwen3-Next, Qwen4-Exp and Qwen 3.5, and the LFM2 and Bailing MoE Linear arms, which were copies of it, now call it. The scheduler-owned restore check in state_snapshot.rs validates a quantized layer against its own layout. Symmetric Turbo4 holds no keys buffer, so the places that read a missing keys buffer as an empty layer (standard_truncatable_to, truncate_standard, the hybrid donor cut and Gemma 4's is_populated) now ask about every buffer; otherwise a truncated restore would have left such a layer uncut. Turbo4Delegated and Turbo3Asym on a full-attention layer are still not stored. The server warns once at startup that prefix reuse is disabled for the model, and each skipped donation is counted as kv_mode_not_snapshotable in /v1/cache/stats and mlxcel_prompt_cache_reject_total instead of empty_set. Quantized sequences stay on the ring path: nothing here moves them to paged storage. Closes lablup#3250
# Conflicts: # CHANGELOG.md
#3492) When a prompt-cache warm-up extends a cached conversation, the store now keeps the boundary snapshot the warm-up restored from (`insert_snapshot_preserving`) instead of superseding it, so an identical retry of the same turn still hits the cache. At most one extra entry per conversation is kept, and byte accounting still runs after the supersede, so LRU caps apply. Hardening review: merged main locally, ran fmt, the repo checks, 937 CUDA prompt-cache, batch and cache-route tests, a revert experiment (8 of the 25 new tests fail without the fix), a composition check with #3498 (1853 tests), and a real-model check on gemma-3-1b-it-4bit where four identical 2,659-token requests give `cached_tokens` 0/2656/2656/2656 with replies identical to the cold run. Closes #3467
Hardening reviewReviewed against #3250. Restores validate the whole layout before assigning anything ( Pushed (
|
The int8 snapshot test asserted that an Int8 attention table skips prompt-cache donation, which stopped being true when lablup#3498 taught snapshots to carry Int8, Turbo4Asym and Turbo4 KV state. It failed on Metal against the PR's own base. The test now checks that an Int8 snapshot restores into a fresh sequence and continues with identical logits, and that a Turbo4Delegated table, which still has no stored form on full-attention layers, donates nothing. The LFM3 CHANGELOG entry sat under Changed; it is a new model family, so it moves to Added.
Summary
Closes #3250.
Families that reuse prompt prefixes through model-state snapshots stored nothing once the server ran with a non-FP16 KV cache. On GB10 with
gemma-4-12B-it-4bitand--cache-type-k int8 --cache-type-v int8, unmodifiedmain(944dbfc2d) reportssnapshot_inserts=0,last_reject_reason=empty_setandcached_tokens=0on every turn of a 5.8k-token conversation, with about 4.8 s to the first token on each continuation. The same conversation in fp16 reuses 5799 of 5820 tokens and answers in 0.34 s.This PR makes a snapshot carry what a quantized cache holds, on the existing ring and
KVCachesnapshot path:RotatingKVCacheis judged by the mode it stores, not by its label. UnderInt8,Turbo4,Turbo4DelegatedandTurbo3Asymthe ring holds plain rows and its snapshot is an FP16 ring snapshot that keeps the label.KVCacheinInt8,Turbo4AsymorTurbo4is stored with its sidecars (scales, packed K and V, norms, rescale), its Turbo seed and its live-window start.Turbo4Asymring is stored with its packed V.Turbo4DelegatedandTurbo3Asymon a full-attention layer are still not stored. The server now warns once at startup and counts each skipped donation askv_mode_not_snapshotableinstead ofempty_set.Scope and the maintainer's comment of 2026-11-24
The comment on this issue says to "keep quantized sliding sequences on the existing ring path" until the "Turbo4 prefix clone/trim support", the quantized-state reuse acceptance and the sliding-window performance gate (#3256, draft #3334) are resolved.
I read that through the section of draft #3334 it summarises, "Implication for #3250 (quantized sliding blocks)", which names the two things that block quantized paged blocks: the remaining B=1 decode cost, and that
clone_detached_paged_prefixandtrim_detached_paged_tostill reject Turbo4 layouts (src/lib/mlxcel-core/src/cache/paged_detach.rs:865,:1014on944dbfc2d). The same draft says Gemma 3 "keeps the ring and its snapshots for quantized modes".So this PR stays on the ring path:
LayerState::newstill maps a sliding layer to aRotatingKVCache, and Int8 and Turbo sequences are still never pool-backed.paged_detach.rsare not touched.RotatingKVCacheandKVCachemodel-state snapshots, so none of them was left out for this reason.If the comment was meant more strictly (no quantized-state reuse at all yet), items 2 and 3 would have to come out, and Gemma 4 Int8 would still get no reuse, because its eight full-attention layers hold real int8 rows. That is the maintainer's call; the reading above is mine.
What changed
Numbered as in the issue's "Proposed Solution".
Rotating snapshots follow the stored mode.
RotatingKVCacheSnapshotState::can_truncate_toand the newstores_snapshotable_rows(src/lib/mlxcel-core/src/cache.rs) readRotatingKVCache::stored_mode(max_size, mode).restore_fp16_snapshot_stateis renamedrestore_snapshot_state, takes aRotatingKVCacheSnapshotBuffers, and keeps the label the snapshot recorded instead of overwriting it withFp16.kv_snapshot::snapshot_rotatingandrestore_rotatingno longer refuse a label; a restore still requires the snapshot's label to equal the live ring's.rotating_mode_for_layeris unchanged; its doc comment and the one onLayerStateKind::build_modenow say that snapshots read the stored mode.Quantized
KVCachestate. New modulesrc/lib/mlxcel-core/src/cache/snapshot_parts.rs:KVCache::snapshot_parts() -> KVCacheSnapshotParts<'_>andKVCache::restore_snapshot_parts(KVCacheSnapshotOwned). The field set isDetachedKVCache's minus what onlyTurbo4Delegateduses, and the sidecar names live in one list,KV_SIDECAR_FIELDS. One layout check,KVCacheSnapshotParts::validate, runs on both sides: a snapshot refuses a cache whose buffers are not the layout its mode writes, and a restore runs the same check before it assigns anything. Insrc/models/kv_snapshot.rs,push_kv_sidecarsandrestore_kv_sidecarsstore and load the sidecars and theturbo_seedandlive_startscalars, andsnapshot_standard,restore_standard,standard_truncatable_toandtruncate_standardhandleInt8,Turbo4AsymandTurbo4. An FP16 snapshot writes exactly the tensors and scalars it wrote before.{prefix}.{standard}.Fp16keys,values,offset,mode(unchanged)Int8keys,values,key_scales,val_scales,turbo_seed,live_start,offset,modeTurbo4Asymkeys,v_packed,v_norms,v_rescale,turbo_seed,live_start,offset,modeTurbo4v_packed,v_norms,v_rescale,k_packed,k_norms,turbo_seed,live_start,offset,modeThe hybrid families' attention arm is implemented once, in
hybrid_snapshot::{snapshot_attention, restore_attention, restore_attention_from_donor}(Qwen3-Next, Qwen4-Exp, Qwen 3.5). The LFM2 and Bailing MoE Linear arms were line-for-line copies of it and now call it; their FP16 tensor names ({prefix}.attention.{mode,keys,values}) are unchanged.Rotating
Turbo4Asym.RotatingKVCache::snapshot_parts()andrestore_snapshot_statecarrykeys,v_packed,v_normsandv_rescalebeside the ring scalars. Truncation keeps the unwrapped-ring rule.Visible refusal.
kv_snapshot::first_snapshot_unsupported_modereadsmodel.kv_cache_storage_modes().log_effective_kv_cache_application(src/server/batch/scheduler/paged_layout.rs) warns once when the model supports snapshot reuse, the prompt cache is installed and a layer storesTurbo4DelegatedorTurbo3Asym.insert_model_state_snapshotchecks the table before it callssnapshot_sequence_stateand records the newPromptCacheRejectReason::KvModeNotSnapshotable(kv_mode_not_snapshotable), which is exposed asreject_kv_mode_not_snapshotablein/v1/cache/statsand as areasonlabel ofmlxcel_prompt_cache_reject_total.Also changed, because
mainmoved after the issue was written (#3305 put Gemma 3 and Qwen 3.5 on scheduler-owned state):src/server/prompt_cache/state_snapshot.rs:check_kv_tensors, which every scheduler-owned restore runs, required a keys and values pair of one dtype. That refusesTurbo4Asym(no values) andTurbo4(neither). A quantized layer is now checked against its own mode's layout; the FP16 arm is unchanged.docs/turbo-kv-cache.md(two passages that said non-FP16 snapshots fail closed) andCHANGELOG.md.Where this differs from the issue text
turbo_paramsis built at restore time, not leftNone. The issue says to leave it for the lazy init in the update paths.KVCache::install_detachedandRotatingKVCache::install_detachedalready build it from the packed width "so dequantize-only consumers (which don't go through update_*) still work", and a restore puts a cache in the same position. The parameters are a pure function of the head dim and the seed, so the ones built here equal the lazily built ones (a test compares the sign vectors).TurboQuantParams::newpanics on a head dim that is not a power of two, so the layout check refuses such a packed width first.turbo_seed, asinstall_detacheddoes. Packed rows only decode under the seed they were written with. Every production cache is built withTURBO_DEFAULT_SEED(no non-test caller ofnew_with_mode_and_seed), so this changes nothing today; a test restores under a different seed.keysork_packed, notkeys. SymmetricTurbo4stores nokeys.standard_truncatable_toread "nokeystensor" as "nothing stored, vacuously truncatable",truncate_standardreturned early on "no keys and no values", andhybrid_snapshot::restore_attention_from_donorreported "holds no attention rows". Each would have let a truncated restore of a populatedTurbo4layer through uncut. They now ask about every buffer.restore_standardpicks the layout from the mode tag, not from whetherkeysis present, for the same reason.live_startis restored exactly, as the issue asks.standard_truncatable_toadditionally returnsfalsewhen the storedlive_startis not zero: the rows a shorter prefix starts with are gone, the same reason a front-trimmedChunkedKVCachedoes not truncate.Int8cache holding a quantized MLA latent is refused by name.cache/latent_quant.rsstores an absorbed MLA latent in the four slots of a per-head Int8 cache with a different layout (uint32 packed rows inkeys). The issue does not mention it. Raon-1 mini is the snapshot family that builds such a cache; see "Verification limits".kv_cache_storage_modes()isNone, nothing is concluded.log_effective_kv_cache_applicationfalls back to the configured table for its summary line; using that fallback here would warn about, and stop donations for, a family that ignores the table and stores FP16.--cache-type-k fp16 --cache-type-v fp16only, as the issue says.int8andfp16+turbo4would also restore reuse.enable_speculative_bufferrefuses every label butFp16, so a ring snapshot that carriesbuffer_size > 0under another label was not written by a ring.Every other caller
Every site that writes a cache's keys or values into a
ModelStateSnapshotor reads them back (grep -rnE 'push_optional\(|push_tensor\(|restore_optional\(' src | grep -E 'keys|values', test files excluded), and every site that treats a missingkeysbuffer as an empty cache (grep -rnE '\.keys\.is_(some|none)\(\)' src/models src/server src/vision):kv_snapshot::{snapshot,restore}_standard,truncate_standard,standard_truncatable_togemma3::Cache), Gemma 4, Llama 4, Qwen4-Exp, Raon-1 minikv_snapshot::{snapshot,restore}_rotating,truncate_rotating,rotating_truncatable_toserver::prompt_cache::state_snapshot(StatePolicy,check_kv_tensors)hybrid_snapshot::{snapshot,restore}_attention,restore_attention_from_donorkv_ring_checkpoint(ring_checkpoint,restore_standard_from_donor,restore_rotating_from_checkpoint)layer{n}.{rotating}.*) picks up the packed-V tensors. Tested.gemma4::Cache::is_populated(used bytruncate_to)keysalone, so a populated symmetric-Turbo4full layer looked empty and its truncation was skipped. Unreachable onmain, where the snapshot was refused; reachable with this PR.qwen4_exp_snapshotkv.keysandkv.valuesapplies only when the tensor is present, and the cut-back usesKVCache::trimraon1_mini_snapshotInt8(quantized MLA latent); FP16 unchanged. Its Turbo modes are built FP16 (latent_pair_cache_mode).muse_glimmer_cachekv_snapshot::{snapshot,restore,truncate}_chunkedChunkedKVCachehas no quantized modeattn.keys/attention.keyssnapshots innemotron_h.rs,plamo2.rs,falcon_h1.rs,granitemoehybrid.rs,jamba.rs,inkling_layer/cache.rsKVCache::new()only and have noset_kv_cache_layer_modes, so their caches are FP16 by constructiongemma4::Cache::zero_partial_accept_tail,enable_mtp_rotating_buffer(MTP rollback and verify buffer)values(aTurbo4Asymring), andenable_speculative_bufferrefuses every label butFp16. Both as onmain.KVCache::trim,RotatingKVCache::trim(speculative rollback, pad trim),cache/prefill_rewind.rsprefill_rewindrefusesTurbo4Asymring storage by name, as onmain.cache/detach.rs,cache/paged_detach.rs(dense and paged KV entries, TP and disaggregated handoff)The four review lessons
offset == max_size, not yet wrapped), one past, and three windows past; a prefill longer than the window (the oversized one-step buffer); truncation to the whole snapshot, to one token and to zero; a target one past the stored length and a negative one; an offset past the physical buffers and a negative one; alive_startpast the offset and a negative one; packed widths of 0, 3, 24 and 48 bytes, which are not half a power of two and would panic inTurboQuantParams::newif a restore did not refuse them first; a snapshot missing each buffer in turn and each scalar in turn.ffi::copy), andvalidatereads shapes and dtypes only, so neither depends on the token count.snapshot_and_restore_do_not_scale_with_the_cache_lengthruns both at 4,096 and 32,768 tokens for each quantized mode under a 2 s bound; the measured times are in "Size" below. The donation gate reads one mode per layer per donation.gemma4::Cache::is_populated) and three places with the same "nokeysmeans empty" rule.cargo fmt --checkbefore finishing. The first run on the working tree failed at 39 places, all in files written for this PR on a host without rustfmt. They were formatted on Spark2, the formatting diff was checked to be layout only (whitespace, trailing commas and three closure-body braces), andcargo fmt --all -- --checkpasses on the commit's tree.Verification
Spark2: NVIDIA GB10, CUDA 13, aarch64 Linux, rustc 1.97.1 (the pinned toolchain),
--features cuda,--profile test-fast,MLX_ENABLE_TF32=0 MLXCEL_SDPA_DETERMINISTIC=1, private 0700TMPDIR. Base944dbfc2ddd6ccab2b051dadc995e99d9d796c83. Tested treecee95a8165e2c38ea37d83a9bb6250bf7294499f, the tree of the commit; the working tree was clean before and after each step.Not every step ran on that exact tree. The commit was amended once after the server runs, and the amend changed one file,
src/lib/mlxcel-core/src/cache/snapshot_parts_tests.rs(a test file ofmlxcel-core; see "Mutations"). What ran where:On the commit's tree
cee95a81: fmt, clippy, the six CI scripts, all ofmlxcel-corecache::, the 13mlxcel-coremutations, the focusedmlxcelsets (models::kv_snapshot,models::hybrid_snapshot,models::kv_ring_checkpoint,gemma4_quantized_snapshot_tests,models::gemma3,models::gemma4,models::qwen3_next, the LFM2 and Bailing tests,scheduler_quantized_snapshot_tests,server::routes::cache), the--ignoredsets, andmake verify-test-cuda.On
9076ab58, one amend earlier: the wider module runs (server::prompt_cache,server::routes,server::batch, and the other families), the 9mlxcelmutations, and every server run. The gate on the commit's tree runs those module sets again.mlxcel-serverrebuilt from the commit's tree has the same sha256 as the binary the server runs used (70f56e6771f0d71ea4a66c5b6aa5eeacce636d4c719c0ebc2a90f056eadce320), so the server results are results of the commit.cargo fmt --all -- --checkcargo clippy --locked --workspace --all-targets --features cuda -- -D warningspython3 scripts/ci/check_used_by.py,bash scripts/ci/check_used_by_test.sh,python3 scripts/insert_apache_header.py --check,python3 scripts/ci/check_env_var_docs.py,python3 scripts/ci/check_kernel_dtype_keys.py,python3 scripts/ci/check_cross_repo_refs.pyThe issue's verification block, each with
cargo test --locked --profile test-fast --features cuda -p <crate> --lib -- --test-threads=1 <filter>:-p mlxcel-core --lib cache::646 passed, 1 ignored;--lib models::kv_snapshot60 passed;--lib server::prompt_cache254 passed;--lib server::routes643 passed, 1 ignored (includesserver::routes::cache, 21);--lib server::batch641 passed, 10 ignored (includes the scheduler tests);--lib models::gemma370 passed, 16 ignored.The families around it:
models::hybrid_snapshot8,models::kv_ring_checkpoint11,gemma4_quantized_snapshot_tests3,models::gemma4141 (16 ignored),models::lfm246,models::bailing_moe_linear39,models::qwen3_next19,models::qwen4_exp197,models::llama422 (6 ignored),models::afmoe32,models::kolibri120,models::muse_glimmer27,models::qwen3_558 (22 ignored),models::model_owned_kv_mode_tests23. All passed.The existing model-level snapshot tests that are
#[ignore = "requires serial MLX execution"]and therefore not part of the gate, run with-- --ignored --test-threads=1:snapshot_prompt_cache17,gemma4_ring_checkpoint_tests1,models::gemma316,models::gemma416,models::llama46,models::qwen3_522. All passed. They cover the FP16 snapshot paths of Gemma 3, Gemma 4, Llama 4 and Qwen 3.5.models::raon1_mini: 34 passed, 4 failed, all inraon1_mini::speculative(a_verify_block_equals_the_decode_chain_byte_for_byte,a_steered_verify_block_applies_the_alpha_exactly_as_decode_does,rollback_after_a_partial_accept_equals_a_fresh_decode_of_the_accepted_tokens,the_exactness_probe_passes_on_the_tiny_model). They compare a verify block with a decode chain and do not touch snapshots; Raon-1 mini's two snapshot tests pass. The same four fail on unmodifiedmain(next item).make verify-test-cudawith a private 0700TMPDIR: 17,481 passed, 5 failed, 517 ignored over 199test resultlines, 38 minutes, the treecee95a81before and after and a cleangit status. All 75 new tests ran inside the gate and passed. The five failures are all in themlxcellibrary target and all Raon: the fourraon1_mini::speculativetests above andmodels::raon_mhc::tests::compiled_site_equals_the_eager_site_bit_for_bit(panics atraon1_mini_speculative_tests.rs:116,:116,:155,:204andraon_mhc_tests.rs:273). On unmodifiedmain(944dbfc2d) the same five fail whenmodels::raon1_mini(34 passed, 4 failed) andmodels::raon_mhc(7 passed, 1 failed) are run on their own, with panics at the same five locations, so they are not caused by this change. No test outside themlxcellibrary target failed; themlxcel-xlaPLaMo 2 golden tests, which have failed in some other runs on this host, did not fail here.Tests
75 new tests, 5 rewritten, 1 extended.
Before and after: 46 of the new tests use only API that exists on
main(kv_snapshot_quantized_tests.rs,hybrid_snapshot_tests.rs,kv_ring_checkpoint_quantized_tests.rs,gemma3_quantized_snapshot_tests.rs,gemma4_quantized_snapshot_tests.rs). On a local branch that ismainplus those files and themodlines that wire them in (no other source change), 39 fail and 7 pass; on this commit all 46 pass. The other 29 call functions this PR adds and do not compile onmain.mainmainmodels::kv_snapshot::quantized_tests(25)models::hybrid_snapshot::tests(8)models::kv_ring_checkpoint::quantized_tests(4)gemma3_tests::quantized_snapshot(6)gemma4_quantized_snapshot_tests(3)The failures on
maincarry the refusals the issue quotes (standard cache mode Int8 is not supported by model-state snapshots,rotating cache mode Int8 ...,rotating cache mode Turbo4Asym ...). The seven that pass onmainare the ones that must hold on both sides: an empty quantized cache stores nothing, an FP16 snapshot keeps its tensor names,Turbo4DelegatedandTurbo3Asymare refused by name (three tests), and two checks of the fixtures themselves. The existingmodels::kv_snapshot::tests(25) andmodels::kv_ring_checkpoint::tests(7) pass onmain.New files:
src/lib/mlxcel-core/src/cache/snapshot_parts_tests.rs(13). Every stored buffer of a restoredKVCacheandRotatingKVCacheequals the source's byte for byte, dtype and shape included, in every mode; each mode stores exactly its own buffers; the restored cache takes the snapshot's seed and its Turbo4 parameters equal the lazily built ones; a restore shares the snapshot's buffers without changing them; a malformed set (each buffer missing in turn, offsets and live starts out of range, wrong rank, dtype, head count, length or packed width, speculative buffer state under a label, a misalignedTurbo4Asymwindow) is refused before anything is assigned; a quantized MLA latent underInt8is refused by name.src/models/kv_snapshot_quantized_tests.rs(25). Through the encoders and the caches' public surface only, so the file also compiles onmain. A restored cache returns the K/V an uninterrupted cache of the same mode returns, at every decode step and for a prefill suffix, from prefills of 1, 31, 32, 37, 255, 256 and 257 tokens; a truncated restore equals a cold fill of the prefix; a ring under anInt8,Turbo4,Turbo4DelegatedorTurbo3Asymlabel round-trips before, at and after the wrap and stores exactly what an FP16 ring stores apart from themodescalar; aTurbo4Asymring round-trips before and after the wrap and after an over-window prefill; truncation is allowed only while a ring is unwrapped; a snapshot lands only in a cache of its mode; snapshot bytes per mode at 4,096 and 32,768 tokens; an FP16 snapshot's tensor names.src/models/kv_snapshot_parts_tests.rs(10). The tensor names each quantized mode writes; every buffer after a restore and after a truncated restore, byte for byte; a snapshot missing a scalar is refused;first_snapshot_unsupported_mode; snapshot and restore at 4k and 32k tokens under a time bound.src/models/hybrid_snapshot_tests.rs(8), plus one test each inlfm2_tests.rsandbailing_moe_linear_tests.rs. The hybrid attention arm inInt8,Turbo4AsymandTurbo4, through the shared functions and through the Qwen3-Next, LFM2 and Bailing MoE Linear cache enums, including the cut-back from a longer donor that state checkpoints use.src/models/kv_ring_checkpoint_quantized_tests.rs(4). Ring checkpoints (feat: Support --ctx-checkpoints and --checkpoint-min-step for sliding-window families #3255) under a quantized table: the checkpoint is the whole ring, packed V included, and the restored pair matches a cold run to the same length.src/models/gemma3_quantized_snapshot_tests.rs(6). On the two-layer Gemma 3 fixture (one sliding layer, one global) underInt8,Turbo4andTurbo4Asymtables with windows of 8, 32 and 64: a snapshot taken at 1, 6,window,window + 5, 256 and 257 tokens and restored into a fresh sequence gives the rest of the prompt logits that equal a cold split prefill's bit for bit, and so does the decode step after it and a second restore of the same snapshot; a truncated restore equals a cold prefill of the prefix bit for bit; a wrapped ring does not truncate; a snapshot does not restore under another table.src/models/gemma4_quantized_snapshot_tests.rs(3). Gemma 4's layer vector (sliding, full, sliding, KV-shared) under each quantized table: whole and truncated restores against cold layers, including the symmetric-Turbo4full layer thatis_populatedused to read as empty.src/server/batch/scheduler_quantized_snapshot_tests.rs(4). On the tiny Gemma 3 scheduler built in the server's builder order: a turn underInt8,Turbo4AsymorTurbo4donates a snapshot that holds the mode's sidecars, the next turn resumes from the stored boundary (cached_tokensequals the history length) and decodes what a cold run decodes; a mode that is not carried is warned about exactly once and counted askv_mode_not_snapshotable, notempty_set; a carried mode, and a server without a prompt cache, are not warned about.Rewritten, because they pinned the refusal this issue removes:
kv_snapshot_tests.rs:populated_turbo_caches_are_refused_by_modeandnon_fp16_mode_is_rejected, the two the issue names. No other test in that file changed; one comment in an FP16 test now namesrestore_snapshot_state.cache.rs(rotating_truncation_tests):non_fp16_storage_is_refused.gemma4.rs(inlinegemma4_unified_mask_tests):turbo4_snapshot_donation_names_the_mode.qwen3_next.rs(inlinecache_tests):qwen3_next_attention_snapshot_refuses_non_fp16_modes. The issue does not list these two; they failed on the first full module run. Each keeps itsTurbo4DelegatedandTurbo3Asymrefusal case.Extended:
routes/cache_tests.rs(thereject_kv_mode_not_snapshotablekey in/v1/cache/stats). Four call sites infirst_fill_tests.rsandrotating_ring_tests.rsfollow the rename.Mutations
22 mutations, each of which reverts or breaks one piece of the change; a mutation counts as detected when a test fails with it applied. The 13 in
mlxcel-coreran one at a time. The 9 in themlxcelcrate ran in three groups of three, because that crate's test binary takes minutes to rebuild; within a group the detecting tests do not overlap, and the failure named below is specific to the mutation.rotating_truncation_tests::the_label_does_not_decide_truncation_the_ring_doesmode = Fp16)a_restored_ring_holds_the_source_buffers_byte_for_bytethe_restored_cache_takes_the_snapshot_seed_and_its_parameterslive_startnot restoredan_int8_front_trim_survives_the_round_tripkey_scalesandval_scalesswapped on restorea_restored_cache_holds_the_source_buffers_byte_for_bytetruncate_standardskips a cache with nokeys/valuesa_truncated_quantized_restore_matches_a_cold_fill_of_the_prefix(Turbo4 37 tokens cut to 36), and the Gemma 3 model test (Turbo4 ... the suffix logits differ from a cold prefill of the prefix)Turbo4Asymring tests (a Turbo4Asym cache needs v_packed)an_uncarried_kv_mode_is_counted_under_its_own_reasonstandard_truncatable_toreads "no keys" as "nothing stored"quantized_truncation_is_refused_past_the_stored_length(Turbo4: a target past the stored length is refused)is_populatedreadskeysalonea_truncated_gemma4_restore_cuts_every_populated_layer(Turbo4, 40 tokens cut to 25: layer1)a_carried_kv_mode_and_a_server_without_a_prompt_cache_are_not_warned_abouta_front_trimmed_int8_snapshot_truncates_only_to_its_own_lengthcheck_kv_tensorsFP16-shaped for every modeGemma 3 layer1: no keys or values behind an offset of 1) and the scheduler multi-turn testkeysandvaluesin every modea_quantized_attention_layer_is_cut_back_from_a_longer_donora_malformed_set_is_refused_before_anything_is_assigned(an offset past the buffers)a_malformed_set_is_refused_before_anything_is_assignedanda_malformed_ring_set_is_refused_before_anything_is_assigned(the mutated restore panics inTurboQuantParams::new, which is what the guard is there to prevent)a_malformed_set_is_refused_before_anything_is_assigneda_malformed_set_is_refused_before_anything_is_assigneda_malformed_set_is_refused_before_anything_is_assigneda_malformed_set_is_refused_before_anything_is_assigneda_malformed_ring_set_is_refused_before_anything_is_assignedOne mutation survived the first run, and two things came out of that. Removing the packed-width guard (the one that keeps
TurboQuantParams::newfrom panicking on a restore) failed no test: the "malformed width" cases replaced a buffer with one of the wrong width and the wrong row count, so the length check refused them either way. The malformed-set tests now build every case from the source's own buffer with exactly one property changed, and each guard of the layout check has its own mutation (the last seven rows of the table). On the commit's tree all 13mlxcel-coremutations are detected, including the one that survived. The two malformed-set tests each hold many cases in one test function, so a row that names only the test says the function failed, not which case.Planning the mutations also showed that the rule "a front-trimmed cache does not truncate" had no test; it has one now.
Size
Snapshot bytes of one full-attention layer, asserted exactly by
a_quantized_snapshot_weighs_what_the_cache_holdson the test fixture (2 heads, head dim 64). The snapshot'snbytes()equals the cache'snbytes()plus its 4-byte scalars, which is the numberModelSnapshotEntry::size_bytesand the store's byte budget use.Fp16Int8Turbo4AsymTurbo4A ring under an
Int8,Turbo4,Turbo4DelegatedorTurbo3Asymlabel weighs what the FP16 ring weighs, because that is what it holds. The real-model numbers are under "Real servers".Time to take a snapshot, restore it and ask whether it truncates (
snapshot_and_restore_do_not_scale_with_the_cache_length, three runs with--nocaptureon the commit's tree, after the source buffers are evaluated): 24 to 213 µs at 4,096 tokens and 29 to 125 µs at 32,768 tokens across the three modes. The 32k runs are not slower than the 4k runs; the spread is run-to-run noise at this scale.Real servers,
mainagainst this commitmlxcel-serveron loopback, GB10, one server process at a time. Each server ran under a watchdog that stops it if hostMemAvailabledrops under 25 GiB or its RSS exceeds 30 GiB, and never beside a build or a test run: 69 server runs, no watchdog trip, peak RSS 17.9 GiB, lowestMemAvailable95.9 GiB. Binaries:main944dbfc2d(sha256239425c9…) and tree9076ab58(sha25670f56e67…; see the note on trees above), bothcargo build --locked --profile test-fast --features cuda --bin mlxcel-server.The conversation is the issue's manual check: a system line and a 60-paragraph user message (5,785 tokens after the template on Gemma 4), then three continuations that each append the model's reply and a new question.
temperature0,max_tokens48, streaming. After each request the driver waits for the background snapshot warm-up and reads/v1/cache/stats. Every arm was repeated with a fresh server process; counts were identical across repetitions, and TTFT is the median of the repetitions after the first.mlx-community/gemma-4-12B-it-4bit,--cache-type-k int8 --cache-type-v int8(4 repetitions per arm):cached_tokensmaincached_tokensthis PRsnapshot_insertssnapshot_lookups/snapshot_hitslast_reject_reasonempty_setreject_empty_setGemma4 snapshot prompt-cache donation skipped error="Gemma 4 snapshot layer0: rotating cache mode Int8 is not supported by model-state snapshots"The startup line on both is
kv_cache_mode_effective=int8 kv_cache_mode_applied_layers=8 kv_cache_mode_total_layers=48: eight full-attention layers hold int8 rows and forty sliding rings hold plain rows under the label.The reply text of every turn is identical across
main(every turn a cold prefill), this PR with the prompt cache, and this PR with--no-prompt-cache(TTFT 4.67 to 4.80 s).The same model in fp16 (4 repetitions on
main, 3 on this PR):cached_tokens0 / 5799 / 5835 / 5866 on both, TTFT 4.414 / 0.336 / 0.249 / 0.249 s onmainand 4.402 / 0.341 / 0.252 / 0.250 s on this PR,snapshot_inserts8 andsnapshot_hits3 on both, same reply text. The stored entries have the same byte counts on both binaries (first entry 982,844,736, later ones 434,636,096 to 442,877,248).Snapshot bytes, Int8 against fp16, from the server's
prompt-cache snapshot insertedlog lines. The Int8 entries are smaller than the fp16 entries of the same turn by exactly 48,046,016 bytes each (934,798,720 against 982,844,736; 390,522,240 against 438,568,256). That is 5,888 buffer rows (5,778 tokens rounded up to the 256-row growth step) times 8,160 bytes, the saving of the eight full layers alone: fp16 K and V at 512 wide is 2,048 bytes per row and layer, int8 K and V plus two scales is 1,028. The store's byte accounting therefore sees the quantized size, and the rings are stored as the FP16 they hold.mlx-community/gemma-3-1b-it-4bit, Int8 (3 repetitions per arm). Gemma 3 is scheduler-owned since #3305, so this goes throughstate_snapshot.rs.kv_cache_mode_applied_layers=4of 26.cached_tokensmaincached_tokensthis PRmain:snapshot_inserts0,empty_set. This PR:snapshot_inserts8,snapshot_hits3, no reject. Reply text identical betweenmainand this PR on all four turns. In fp16, both binaries report 0 / 5830 / 5876 / 5906 and the same text.Gemma 4 with
--kv-cache-mode fp16+turbo4(2 repetitions per arm).kv_cache_mode_applied_layers=44of 48: the rings have a 1,024-token window, a multiple of 32, so they hold packed V. This is the case that needs items 2 and 3 together.cached_tokensmaincached_tokensthis PRmainlogsGemma 4 snapshot layer2: rotating cache mode Turbo4Asym is not supported by model-state snapshotsand reportsempty_set. This PR:snapshot_inserts8,snapshot_hits3, first entry 647,097,368 bytes. Reply text identical acrossmain, this PR, and this PR with--no-prompt-cache(TTFT 14.2 to 15.6 s).Gemma 4 with
--kv-cache-mode turbo4-delegated, which is still not stored (two turns):cached_tokensWARN ... prompt-cache prefix reuse is disabled for this model: its turbo4-delegated KV cache cannot be stored in a model-state snapshot, so every request prefills its whole prompt. Use --cache-type-k fp16 --cache-type-v fp16 to turn prefix reuse back onWARN ... Gemma 4 snapshot layer2: rotating cache mode Turbo4Delegated is not supported by model-state snapshotslast_reject_reasonempty_setkv_mode_not_snapshotablereject_empty_set/reject_kv_mode_not_snapshotable/metricsmlxcel_prompt_cache_reject_total{reason="empty_set"} 2mlxcel_prompt_cache_reject_total{reason="kv_mode_not_snapshotable"} 2A cache-on and a cache-off server do not always agree, on
maineitherOn Gemma 3 with Int8, the replies of this PR with the prompt cache differ from the replies of the same binary with
--no-prompt-cacheon turns 1 to 3. Turn 1 restores nothing in either arm, so I ran the same pair onmain:main, prompt cache on (every turn cold)7a8a00a39a921e7f2130b9274d0f59ed7a8a00a39a921e7f2130b9274d0f59edmain,--no-prompt-cache7ce43e5c3817bf86002f2fe04d0f59ed--no-prompt-cache7ce43e5c3817bf86002f2fe04d0f59edThe two configurations already differ on unmodified
main, and this PR equalsmainin each. A second experiment removes the feedback of replies into later prompts: with a fixed assistant line in the history, every arm receives byte-identical prompts and nothing can be restored (see the limits). There the cache-on and cache-off servers differ on turn 1 for Gemma 3 and on turn 4 for Gemma 4 12B, onmainand on this PR alike, and the two binaries agree with each other in both configurations (2 runs each on this PR). I did not look for the cause; the two servers run the prompt through different prefill pieces, because the cache-on server stops at the history boundary to take a snapshot.So the statement this PR supports is: a turn that restores a snapshot answers what a cold run of the same server configuration answers. It was checked against
--no-prompt-cachewhere that comparison is meaningful (Gemma 4 Int8 andfp16+turbo4, identical on all four turns) and againstmaineverywhere.Verification limits
gemma-4-12B-it-4bitandgemma-3-1b-it-4bitonly. AFMoE, Kolibri-1, Llama 4, LFM2, Qwen3-Next, Qwen4-Exp, Bailing MoE Linear and Qwen 3.5 are covered by unit tests on small fixtures, not by a server run.int8,fp16+turbo4,turbo4-delegatedand fp16 were run on a server. Symmetricturbo4andturbo3-asymwere not;Turbo4is covered at unit level only.Turbo3Asymis not exercised through a forward pass.TurboQuantParams3needs a head dim that is a multiple of 8 and the tiny fixtures have head dim 2. The tests cover the refusal by name, the startup warning and the storage-mode table for it; the request that is counted askv_mode_not_snapshotableruns underTurbo4Delegated.empty_set. Its MLA latent is refused by name inside the snapshot encoder, after the donation gate; the gate readskv_cache_storage_modes(), which reportsInt8for it, a mode the gate treats as carried. No startup warning is printed for it either.Fp16(enable_speculative_buffer), as onmain. Gemma 4 MTP with a quantized KV cache was not run.fp16+turbo4) and differs on Gemma 3 Int8 turns 1 to 3, where it differs on unmodifiedmainin the same way. I did not find the cause. On the Gemma 4 prompt the Int8 and fp16 replies are also identical, so the text comparison there would not notice a restore that lost Int8 precision; the byte-for-byte and bit-for-bit comparisons are in the unit and model tests.mainin fp16 too. Reuse was therefore measured only on the natural conversation, where each turn appends the model's own reply.mlxcelmutations ran in groups of three, not one at a time, and on the tree one amend before the commit's (the two trees have identicalmlxcelsources).log_effective_kv_cache_application, which needs the prompt cache to be installed before it runs. The scheduler test builds in the server's order; a caller that installs the prompt cache later would not get the warning, only the reject counter.scheduler_model_owned_cache_tests.rs. Gemma 3 is scheduler-owned since refactor: move per-layer sequence state from models to the scheduler #3305, so the test is in a new file,scheduler_quantized_snapshot_tests.rs, next to the snapshot tests it shares a helper with.src/models/kv_snapshot.rsis 1,075 lines after this change (838 onmain); the tests moved to their own files, the encoder did not.