Skip to content

feat: snapshot quantized KV cache modes for prompt-cache reuse - #3498

Merged
inureyes merged 3 commits into
lablup:mainfrom
Jaeyeong-CHOI:feat/3250-quantized-kv-snapshots
Nov 28, 2026
Merged

inureyes merged 3 commits into
lablup:mainfrom
Jaeyeong-CHOI:feat/3250-quantized-kv-snapshots

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

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-4bit and --cache-type-k int8 --cache-type-v int8, unmodified main (944dbfc2d) reports snapshot_inserts=0, last_reject_reason=empty_set and cached_tokens=0 on 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 KVCache snapshot path:

  1. A sliding RotatingKVCache is judged by the mode it stores, not by its label. Under Int8, Turbo4, Turbo4Delegated and Turbo3Asym the ring holds plain rows and its snapshot is an FP16 ring snapshot that keeps the label.
  2. A full-attention 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.
  3. An aligned Turbo4Asym ring is stored with its packed V.
  4. Turbo4Delegated and Turbo3Asym on a full-attention layer are still not stored. The server now warns once at startup and counts each skipped donation as kv_mode_not_snapshotable instead of empty_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_prefix and trim_detached_paged_to still reject Turbo4 layouts (src/lib/mlxcel-core/src/cache/paged_detach.rs:865, :1014 on 944dbfc2d). The same draft says Gemma 3 "keeps the ring and its snapshots for quantized modes".

So this PR stays on the ring path:

  • Quantized sequences are not moved to paged storage. LayerState::new still maps a sliding layer to a RotatingKVCache, and Int8 and Turbo sequences are still never pool-backed.
  • The two paged Turbo4 refusals in paged_detach.rs are not touched.
  • All four items of the issue operate on RotatingKVCache and KVCache model-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".

  1. Rotating snapshots follow the stored mode. RotatingKVCacheSnapshotState::can_truncate_to and the new stores_snapshotable_rows (src/lib/mlxcel-core/src/cache.rs) read RotatingKVCache::stored_mode(max_size, mode). restore_fp16_snapshot_state is renamed restore_snapshot_state, takes a RotatingKVCacheSnapshotBuffers, and keeps the label the snapshot recorded instead of overwriting it with Fp16. kv_snapshot::snapshot_rotating and restore_rotating no longer refuse a label; a restore still requires the snapshot's label to equal the live ring's. rotating_mode_for_layer is unchanged; its doc comment and the one on LayerStateKind::build_mode now say that snapshots read the stored mode.

  2. Quantized KVCache state. New module src/lib/mlxcel-core/src/cache/snapshot_parts.rs: KVCache::snapshot_parts() -> KVCacheSnapshotParts<'_> and KVCache::restore_snapshot_parts(KVCacheSnapshotOwned). The field set is DetachedKVCache's minus what only Turbo4Delegated uses, 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. In src/models/kv_snapshot.rs, push_kv_sidecars and restore_kv_sidecars store and load the sidecars and the turbo_seed and live_start scalars, and snapshot_standard, restore_standard, standard_truncatable_to and truncate_standard handle Int8, Turbo4Asym and Turbo4. An FP16 snapshot writes exactly the tensors and scalars it wrote before.

    Mode Tensors under {prefix}.{standard}.
    Fp16 keys, values, offset, mode (unchanged)
    Int8 keys, values, key_scales, val_scales, turbo_seed, live_start, offset, mode
    Turbo4Asym keys, v_packed, v_norms, v_rescale, turbo_seed, live_start, offset, mode
    Turbo4 v_packed, v_norms, v_rescale, k_packed, k_norms, turbo_seed, live_start, offset, mode

    The 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.

  3. Rotating Turbo4Asym. RotatingKVCache::snapshot_parts() and restore_snapshot_state carry keys, v_packed, v_norms and v_rescale beside the ring scalars. Truncation keeps the unwrapped-ring rule.

  4. Visible refusal. kv_snapshot::first_snapshot_unsupported_mode reads model.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 stores Turbo4Delegated or Turbo3Asym. insert_model_state_snapshot checks the table before it calls snapshot_sequence_state and records the new PromptCacheRejectReason::KvModeNotSnapshotable (kv_mode_not_snapshotable), which is exposed as reject_kv_mode_not_snapshotable in /v1/cache/stats and as a reason label of mlxcel_prompt_cache_reject_total.

Also changed, because main moved 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 refuses Turbo4Asym (no values) and Turbo4 (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) and CHANGELOG.md.

Where this differs from the issue text

  • turbo_params is built at restore time, not left None. The issue says to leave it for the lazy init in the update paths. KVCache::install_detached and RotatingKVCache::install_detached already 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::new panics on a head dim that is not a power of two, so the layout check refuses such a packed width first.
  • The restored cache takes the snapshot's turbo_seed, as install_detached does. Packed rows only decode under the seed they were written with. Every production cache is built with TURBO_DEFAULT_SEED (no non-test caller of new_with_mode_and_seed), so this changes nothing today; a test restores under a different seed.
  • Presence is keys or k_packed, not keys. Symmetric Turbo4 stores no keys. standard_truncatable_to read "no keys tensor" as "nothing stored, vacuously truncatable", truncate_standard returned early on "no keys and no values", and hybrid_snapshot::restore_attention_from_donor reported "holds no attention rows". Each would have let a truncated restore of a populated Turbo4 layer through uncut. They now ask about every buffer.
  • restore_standard picks the layout from the mode tag, not from whether keys is present, for the same reason.
  • A front-trimmed cache does not truncate. live_start is restored exactly, as the issue asks. standard_truncatable_to additionally returns false when the stored live_start is not zero: the rows a shorter prefix starts with are gone, the same reason a front-trimmed ChunkedKVCache does not truncate.
  • An Int8 cache holding a quantized MLA latent is refused by name. cache/latent_quant.rs stores an absorbed MLA latent in the four slots of a per-head Int8 cache with a different layout (uint32 packed rows in keys). The issue does not mention it. Raon-1 mini is the snapshot family that builds such a cache; see "Verification limits".
  • The startup warning and the reject reason are driven only by a table the model reports. When kv_cache_storage_modes() is None, nothing is concluded. log_effective_kv_cache_application falls 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.
  • The warning suggests --cache-type-k fp16 --cache-type-v fp16 only, as the issue says. int8 and fp16+turbo4 would also restore reuse.
  • Speculative buffer state under a label is refused on restore. enable_speculative_buffer refuses every label but Fp16, so a ring snapshot that carries buffer_size > 0 under another label was not written by a ring.

Every other caller

Every site that writes a cache's keys or values into a ModelStateSnapshot or 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 missing keys buffer as an empty cache (grep -rnE '\.keys\.is_(some|none)\(\)' src/models src/server src/vision):

Path Families Quantized state
kv_snapshot::{snapshot,restore}_standard, truncate_standard, standard_truncatable_to Gemma 3, AFMoE, Kolibri-1 (through gemma3::Cache), Gemma 4, Llama 4, Qwen4-Exp, Raon-1 mini handled here
kv_snapshot::{snapshot,restore}_rotating, truncate_rotating, rotating_truncatable_to Gemma 3, AFMoE, Kolibri-1, Gemma 4, Muse Glimmer handled here
server::prompt_cache::state_snapshot (StatePolicy, check_kv_tensors) Gemma 3, Qwen 3.5 (scheduler-owned) handled here
hybrid_snapshot::{snapshot,restore}_attention, restore_attention_from_donor Qwen3-Next, Qwen4-Exp, Qwen 3.5, and now LFM2 and Bailing MoE Linear handled here
kv_ring_checkpoint (ring_checkpoint, restore_standard_from_donor, restore_rotating_from_checkpoint) Gemma 3, Gemma 4, AFMoE no code change: it calls the functions above, and its ring filter (layer{n}.{rotating}.*) picks up the packed-V tensors. Tested.
gemma4::Cache::is_populated (used by truncate_to) Gemma 4 fixed here. It read keys alone, so a populated symmetric-Turbo4 full layer looked empty and its truncation was skipped. Unreachable on main, where the snapshot was refused; reachable with this PR.
qwen4_exp_snapshot Qwen4-Exp no change needed: its shape check on kv.keys and kv.values applies only when the tensor is present, and the cut-back uses KVCache::trim
raon1_mini_snapshot Raon-1 mini refused by name under Int8 (quantized MLA latent); FP16 unchanged. Its Turbo modes are built FP16 (latent_pair_cache_mode).
muse_glimmer_cache Muse Glimmer unchanged: startup refuses every non-FP16 mode
kv_snapshot::{snapshot,restore,truncate}_chunked Llama 4 chunked layers unchanged: ChunkedKVCache has no quantized mode
inline attn.keys / attention.keys snapshots in nemotron_h.rs, plamo2.rs, falcon_h1.rs, granitemoehybrid.rs, jamba.rs, inkling_layer/cache.rs Nemotron-H, PLaMo 2, Falcon-H1, Granite MoE Hybrid, Jamba, Inkling unchanged: these families build KVCache::new() only and have no set_kv_cache_layer_modes, so their caches are FP16 by construction
gemma4::Cache::zero_partial_accept_tail, enable_mtp_rotating_buffer (MTP rollback and verify buffer) Gemma 4 MTP not a snapshot path and not changed. Observed: the tail zeroing returns early for a ring with no values (a Turbo4Asym ring), and enable_speculative_buffer refuses every label but Fp16. Both as on main.
KVCache::trim, RotatingKVCache::trim (speculative rollback, pad trim), cache/prefill_rewind.rs all not changed. prefill_rewind refuses Turbo4Asym ring storage by name, as on main.
cache/detach.rs, cache/paged_detach.rs (dense and paged KV entries, TP and disaggregated handoff) scheduler-owned dense and paged families not a model-state snapshot path and not changed, including the two paged Turbo4 refusals the maintainer's comment refers to

The four review lessons

  1. Boundary inputs. Pinned by tests: an empty cache in every mode (stores nothing, restores fresh, truncates to a no-op); one token; a restore exactly at a turbo block edge (32) and one short of it; a restore one short of, exactly at and one past a buffer growth step (255, 256, 257 tokens); a ring one short of full, exactly full (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; a live_start past 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 in TurboQuantParams::new if a restore did not refuse them first; a snapshot missing each buffer in turn and each scalar in turn.
  2. Time on large inputs. Taking and restoring a snapshot copies array handles (ffi::copy), and validate reads shapes and dtypes only, so neither depends on the token count. snapshot_and_restore_do_not_scale_with_the_cache_length runs 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.
  3. Every other caller. See the table above. The audit found one caller that this change would have broken silently (gemma4::Cache::is_populated) and three places with the same "no keys means empty" rule.
  4. cargo fmt --check before 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), and cargo fmt --all -- --check passes 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 0700 TMPDIR. Base 944dbfc2ddd6ccab2b051dadc995e99d9d796c83. Tested tree cee95a8165e2c38ea37d83a9bb6250bf7294499f, 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 of mlxcel-core; see "Mutations"). What ran where:

  • On the commit's tree cee95a81: fmt, clippy, the six CI scripts, all of mlxcel-core cache::, the 13 mlxcel-core mutations, the focused mlxcel sets (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 --ignored sets, and make verify-test-cuda.

  • On 9076ab58, one amend earlier: the wider module runs (server::prompt_cache, server::routes, server::batch, and the other families), the 9 mlxcel mutations, and every server run. The gate on the commit's tree runs those module sets again. mlxcel-server rebuilt 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 -- --check

  • cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings

  • python3 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.py

  • The 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_snapshot 60 passed; --lib server::prompt_cache 254 passed; --lib server::routes 643 passed, 1 ignored (includes server::routes::cache, 21); --lib server::batch 641 passed, 10 ignored (includes the scheduler tests); --lib models::gemma3 70 passed, 16 ignored.

  • The families around it: models::hybrid_snapshot 8, models::kv_ring_checkpoint 11, gemma4_quantized_snapshot_tests 3, models::gemma4 141 (16 ignored), models::lfm2 46, models::bailing_moe_linear 39, models::qwen3_next 19, models::qwen4_exp 197, models::llama4 22 (6 ignored), models::afmoe 32, models::kolibri1 20, models::muse_glimmer 27, models::qwen3_5 58 (22 ignored), models::model_owned_kv_mode_tests 23. 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_cache 17, gemma4_ring_checkpoint_tests 1, models::gemma3 16, models::gemma4 16, models::llama4 6, models::qwen3_5 22. 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 in raon1_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 unmodified main (next item).

  • make verify-test-cuda with a private 0700 TMPDIR: 17,481 passed, 5 failed, 517 ignored over 199 test result lines, 38 minutes, the tree cee95a81 before and after and a clean git status. All 75 new tests ran inside the gate and passed. The five failures are all in the mlxcel library target and all Raon: the four raon1_mini::speculative tests above and models::raon_mhc::tests::compiled_site_equals_the_eager_site_bit_for_bit (panics at raon1_mini_speculative_tests.rs:116, :116, :155, :204 and raon_mhc_tests.rs:273). On unmodified main (944dbfc2d) the same five fail when models::raon1_mini (34 passed, 4 failed) and models::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 the mlxcel library target failed; the mlxcel-xla PLaMo 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 is main plus those files and the mod lines 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 on main.

New tests that compile on main main this PR
models::kv_snapshot::quantized_tests (25) 4 passed, 21 failed 25 passed
models::hybrid_snapshot::tests (8) 1 passed, 7 failed 8 passed
models::kv_ring_checkpoint::quantized_tests (4) 0 passed, 4 failed 4 passed
gemma3_tests::quantized_snapshot (6) 2 passed, 4 failed 6 passed
gemma4_quantized_snapshot_tests (3) 0 passed, 3 failed 3 passed

The failures on main carry 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 on main are the ones that must hold on both sides: an empty quantized cache stores nothing, an FP16 snapshot keeps its tensor names, Turbo4Delegated and Turbo3Asym are refused by name (three tests), and two checks of the fixtures themselves. The existing models::kv_snapshot::tests (25) and models::kv_ring_checkpoint::tests (7) pass on main.

New files:

  • src/lib/mlxcel-core/src/cache/snapshot_parts_tests.rs (13). Every stored buffer of a restored KVCache and RotatingKVCache equals 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 misaligned Turbo4Asym window) is refused before anything is assigned; a quantized MLA latent under Int8 is 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 on main. 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 an Int8, Turbo4, Turbo4Delegated or Turbo3Asym label round-trips before, at and after the wrap and stores exactly what an FP16 ring stores apart from the mode scalar; a Turbo4Asym ring 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 in lfm2_tests.rs and bailing_moe_linear_tests.rs. The hybrid attention arm in Int8, Turbo4Asym and Turbo4, 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) under Int8, Turbo4 and Turbo4Asym tables 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-Turbo4 full layer that is_populated used 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 under Int8, Turbo4Asym or Turbo4 donates a snapshot that holds the mode's sidecars, the next turn resumes from the stored boundary (cached_tokens equals the history length) and decodes what a cold run decodes; a mode that is not carried is warned about exactly once and counted as kv_mode_not_snapshotable, not empty_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_mode and non_fp16_mode_is_rejected, the two the issue names. No other test in that file changed; one comment in an FP16 test now names restore_snapshot_state.
  • cache.rs (rotating_truncation_tests): non_fp16_storage_is_refused.
  • gemma4.rs (inline gemma4_unified_mask_tests): turbo4_snapshot_donation_names_the_mode. qwen3_next.rs (inline cache_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 its Turbo4Delegated and Turbo3Asym refusal case.

Extended: routes/cache_tests.rs (the reject_kv_mode_not_snapshotable key in /v1/cache/stats). Four call sites in first_fill_tests.rs and rotating_ring_tests.rs follow 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-core ran one at a time. The 9 in the mlxcel crate 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.

Mutation Detected by
ring truncation decided by the label again rotating_truncation_tests::the_label_does_not_decide_truncation_the_ring_does
restored ring loses its label (mode = Fp16) a_restored_ring_holds_the_source_buffers_byte_for_byte
restored cache keeps its own seed the_restored_cache_takes_the_snapshot_seed_and_its_parameters
live_start not restored an_int8_front_trim_survives_the_round_trip
key_scales and val_scales swapped on restore a_restored_cache_holds_the_source_buffers_byte_for_byte
truncate_standard skips a cache with no keys/values a_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)
ring's packed V not stored the Turbo4Asym ring tests (a Turbo4Asym cache needs v_packed)
donation gate removed an_uncarried_kv_mode_is_counted_under_its_own_reason
standard_truncatable_to reads "no keys" as "nothing stored" quantized_truncation_is_refused_past_the_stored_length (Turbo4: a target past the stored length is refused)
Gemma 4 is_populated reads keys alone a_truncated_gemma4_restore_cuts_every_populated_layer (Turbo4, 40 tokens cut to 25: layer1)
startup warning ignores whether a prompt cache exists a_carried_kv_mode_and_a_server_without_a_prompt_cache_are_not_warned_about
a front-trimmed snapshot called truncatable a_front_trimmed_int8_snapshot_truncates_only_to_its_own_length
check_kv_tensors FP16-shaped for every mode the Gemma 3 model tests (Gemma 3 layer1: no keys or values behind an offset of 1) and the scheduler multi-turn test
hybrid donor cut requires keys and values in every mode a_quantized_attention_layer_is_cut_back_from_a_longer_donor
layout check: live-length guard removed a_malformed_set_is_refused_before_anything_is_assigned (an offset past the buffers)
layout check: packed-width guard removed a_malformed_set_is_refused_before_anything_is_assigned and a_malformed_ring_set_is_refused_before_anything_is_assigned (the mutated restore panics in TurboQuantParams::new, which is what the guard is there to prevent)
layout check: dtype guard removed the same two tests
layout check: batch/heads/length agreement removed a_malformed_set_is_refused_before_anything_is_assigned
layout check: last-axis guard removed a_malformed_set_is_refused_before_anything_is_assigned
layout check: K and V packed-width agreement removed a_malformed_set_is_refused_before_anything_is_assigned
layout check: rank guard removed a_malformed_set_is_refused_before_anything_is_assigned
ring layout check: agreement between the ring's buffers removed a_malformed_ring_set_is_refused_before_anything_is_assigned

One mutation survived the first run, and two things came out of that. Removing the packed-width guard (the one that keeps TurboQuantParams::new from 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 13 mlxcel-core mutations 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_holds on the test fixture (2 heads, head dim 64). The snapshot's nbytes() equals the cache's nbytes() plus its 4-byte scalars, which is the number ModelSnapshotEntry::size_bytes and the store's byte budget use.

Mode Bytes per stored row 4,096 tokens 32,768 tokens
Fp16 256 2,097,152 16,777,216
Int8 132 (int8 K and V, one FP16 scale each) 1,081,344 8,650,752
Turbo4Asym 164 (FP16 K, nibble-packed V, V norm and rescale) 1,343,488 10,747,904
Turbo4 70 (nibble-packed K and V, three FP16 sidecars) 573,440 4,587,520

A ring under an Int8, Turbo4, Turbo4Delegated or Turbo3Asym label 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 --nocapture on 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, main against this commit

mlxcel-server on loopback, GB10, one server process at a time. Each server ran under a watchdog that stops it if host MemAvailable drops 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, lowest MemAvailable 95.9 GiB. Binaries: main 944dbfc2d (sha256 239425c9…) and tree 9076ab58 (sha256 70f56e67…; see the note on trees above), both cargo 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. temperature 0, max_tokens 48, 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):

Turn Prompt tokens cached_tokens main cached_tokens this PR TTFT main (s) TTFT this PR (s)
1 5785 0 0 5.017 5.042
2 5820 0 5799 4.756 0.342
3 5852 0 5835 4.777 0.260
4 5882 0 5866 4.807 0.256
After turn 4 main this PR
snapshot_inserts 0 8
snapshot_lookups / snapshot_hits 4 / 0 4 / 3
last_reject_reason empty_set none
reject_empty_set 4 0
log 4 x Gemma4 snapshot prompt-cache donation skipped error="Gemma 4 snapshot layer0: rotating cache mode Int8 is not supported by model-state snapshots" none

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_tokens 0 / 5799 / 5835 / 5866 on both, TTFT 4.414 / 0.336 / 0.249 / 0.249 s on main and 4.402 / 0.341 / 0.252 / 0.250 s on this PR, snapshot_inserts 8 and snapshot_hits 3 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 inserted log 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 through state_snapshot.rs. kv_cache_mode_applied_layers=4 of 26.

Turn Prompt tokens cached_tokens main cached_tokens this PR TTFT main (s) TTFT this PR (s)
1 5777 0 0 0.746 0.750
2 5846 0 5829 0.442 0.106
3 5888 0 5875 0.446 0.044
4 5918 0 5906 0.446 0.049

main: snapshot_inserts 0, empty_set. This PR: snapshot_inserts 8, snapshot_hits 3, no reject. Reply text identical between main and 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=44 of 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.

Turn cached_tokens main cached_tokens this PR TTFT main (s) TTFT this PR (s)
1 0 0 14.52 14.44
2 0 5799 14.59 0.522
3 0 5835 14.69 0.449
4 0 5866 14.75 0.425

main logs Gemma 4 snapshot layer2: rotating cache mode Turbo4Asym is not supported by model-state snapshots and reports empty_set. This PR: snapshot_inserts 8, snapshot_hits 3, first entry 647,097,368 bytes. Reply text identical across main, 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):

main this PR
cached_tokens 0, 0 0, 0
startup log none one WARN ... 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 on
per-request log WARN ... Gemma 4 snapshot layer2: rotating cache mode Turbo4Delegated is not supported by model-state snapshots none
last_reject_reason empty_set kv_mode_not_snapshotable
reject_empty_set / reject_kv_mode_not_snapshotable 2 / field absent 0 / 2
/metrics mlxcel_prompt_cache_reject_total{reason="empty_set"} 2 mlxcel_prompt_cache_reject_total{reason="kv_mode_not_snapshotable"} 2

A cache-on and a cache-off server do not always agree, on main either

On Gemma 3 with Int8, the replies of this PR with the prompt cache differ from the replies of the same binary with --no-prompt-cache on turns 1 to 3. Turn 1 restores nothing in either arm, so I ran the same pair on main:

Gemma 3 1B, Int8, reply hash per turn 1 2 3 4
main, prompt cache on (every turn cold) 7a8a00a3 9a921e7f 2130b927 4d0f59ed
this PR, prompt cache on (turns 2 to 4 restored) 7a8a00a3 9a921e7f 2130b927 4d0f59ed
main, --no-prompt-cache 7ce43e5c 3817bf86 002f2fe0 4d0f59ed
this PR, --no-prompt-cache 7ce43e5c 3817bf86 002f2fe0 4d0f59ed

The two configurations already differ on unmodified main, and this PR equals main in 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, on main and 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-cache where that comparison is meaningful (Gemma 4 Int8 and fp16+turbo4, identical on all four turns) and against main everywhere.

Verification limits

  • One backend. Everything ran on CUDA (GB10, aarch64 Linux). Metal and ROCm were not built or run.
  • Two real checkpoints. Server runs used gemma-4-12B-it-4bit and gemma-3-1b-it-4bit only. 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.
  • Real-server modes. int8, fp16+turbo4, turbo4-delegated and fp16 were run on a server. Symmetric turbo4 and turbo3-asym were not; Turbo4 is covered at unit level only.
  • Turbo3Asym is not exercised through a forward pass. TurboQuantParams3 needs 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 as kv_mode_not_snapshotable runs under Turbo4Delegated.
  • Raon-1 mini under Int8 still gets no reuse, and is still counted as empty_set. Its MLA latent is refused by name inside the snapshot encoder, after the donation gate; the gate reads kv_cache_storage_modes(), which reports Int8 for it, a mode the gate treats as carried. No startup warning is printed for it either.
  • The MTP verify buffer still refuses every label but Fp16 (enable_speculative_buffer), as on main. Gemma 4 MTP with a quantized KV cache was not run.
  • Cache-on against cache-off text is identical on Gemma 4 (Int8 and fp16+turbo4) and differs on Gemma 3 Int8 turns 1 to 3, where it differs on unmodified main in 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.
  • A fixed-history conversation cannot hit. With a scripted assistant line the continuation diverges from the stored reply after the ring has wrapped, which the issue lists as out of scope and which misses on main in fp16 too. Reuse was therefore measured only on the natural conversation, where each turn appends the model's own reply.
  • TTFT numbers come from 2 to 4 fresh server processes per arm on one host, with the first process of each arm left out of the median because it compiles CUDA kernels. They show the size of the effect, not a benchmark.
  • The 9 mlxcel mutations ran in groups of three, not one at a time, and on the tree one amend before the commit's (the two trees have identical mlxcel sources).
  • The startup warning depends on builder order. It is emitted from 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.
  • Placement of one test. The issue asks for the multi-turn scheduler test in 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.
  • File size. src/models/kv_snapshot.rs is 1,075 lines after this change (838 on main); the tests moved to their own files, the encoder did not.
  • Scope. The reading of the maintainer's comment in "Scope" is mine and was not confirmed.

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
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:high High priority area:models Model architectures, weights, loading, metadata area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Nov 28, 2026
inureyes pushed a commit that referenced this pull request Nov 28, 2026
#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
@inureyes

Copy link
Copy Markdown
Member

Hardening review

Reviewed against #3250. Restores validate the whole layout before assigning anything (KVCacheSnapshotParts::validate), the packed-width guard prevents the TurboQuantParams::new panic on malformed input, inplace_marker is cleared on restore so shared buffers are not written in place, and the donation gate costs one storage-mode table read. No code findings.

Pushed (8e0cbc05)

Merge of main into the branch. The only conflict was CHANGELOG.md: main had released v0.9.0-beta.3, so the old [Unreleased] list became that release section. Main's section is kept verbatim and the #3250 entry moved unchanged into a new [Unreleased] / Added section. The prompt-cache and KV snapshot sources on this tree are identical to the composed main + #3492 + #3498 tree that was validated.

Validation

  • cargo fmt --check, check_used_by.py, license headers, check_env_var_docs.py, check_cross_repo_refs.py: pass.
  • CUDA lib tests (--profile test-fast, --test-threads=1): mlxcel snapshot, model and server filters 2241 passed, 0 failed; mlxcel-core cache:: 646 passed. Composed with fix: keep the boundary snapshot when a prompt-cache warm-up extends it #3492: 1853 passed, clippy -D warnings clean for mlxcel and mlxcel-core lib and tests.
  • Real models on GB10, composed with fix: keep the boundary snapshot when a prompt-cache warm-up extends it #3492: Gemma 3 1B with int8 K/V gives cached_tokens 0/2712 and an identical retry hits (2726); Gemma 4 12B with fp16+turbo4 (44 of 48 layers, packed-V rings) gives 0/2704 and retry 2718. Every reply matches a cold fresh-server run byte for byte, with no rejects.

Not run: the full make verify-test-cuda gate, Metal, ROCm, and symmetric turbo4 / turbo3-asym on a real server.

@inureyes
inureyes merged commit 1e86aad into lablup:main Nov 28, 2026
35 checks passed
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 28, 2026
inureyes added a commit to Jaeyeong-CHOI/mlxcel that referenced this pull request Nov 30, 2026
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.
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata priority:high High priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: support quantized KV cache modes in model-state snapshots for prompt-cache reuse

2 participants