Repository navigation
feat: support --ctx-checkpoints and --checkpoint-min-step - #3283
Merged
Merged
Conversation
Gemma 3, Gemma 4 (text, VL and Unified) and AFMoE now store ring-only turn-boundary state checkpoints: every sliding layer's ring once a ring has wrapped, nothing for KV-shared layers or unwrapped rings. A restore takes the sliding layers from the checkpoint and the full-attention layers from the donor cut back with standard_truncatable_to, under the existing donor and lineage rules. --ctx-checkpoints N (N > 0) turns on keep-previous-turn and the state checkpoints the family supports and keeps at most N per conversation, dropping the oldest on insert. 0 sets the state checkpoint budget to 0 and leaves keep-previous-turn off. --checkpoint-min-step M sets the periodic checkpoint interval and the minimum spacing between state checkpoints of one conversation; 1 to 255 and negative values are refused. The flags override MLXCEL_PROMPT_CACHE_KEEP_PREVIOUS_TURN and MLXCEL_PROMPT_CACHE_CHECKPOINT_INTERVAL, and MLXCEL_DISABLE_BOUNDARY_SNAPSHOT=1 still disables everything with a warning. The state checkpoint sizing gains a ring-only estimate from kv_arch (window x sliding bytes per token). The compat manifest moves both flags to by_design and the docs describe the mapping.
gemma-4-12b-it ships with model_type gemma4_unified, which the ring checkpoint family match missed, so --ctx-checkpoints left the state checkpoint budget at 0 on the real model.
A multi-token append keeps the newest window - 1 rows plus the whole piece, so a ring captured at a history boundary holds up to window - 1 + prefill chunk rows: 3071 on gemma-4-12b-it at the default 2048 chunk, about 960 MiB instead of the 320 MiB the window alone gives. Sized at the window, the default budget held 4 checkpoints instead of 12 and evicted the rest. The estimate now takes the prefill chunk (the representative prompt length when prefill is unchunked).
Thirteen arms of scripts/bench_prompt_cache_replay.py --verify on GB10: main with nothing set and with the env switches, and this branch with the flags unset, --ctx-checkpoints 3 at four edit targets, --checkpoint-min-step 4096 and --ctx-checkpoints 8. The record also explains why the sliding-window default stays off.
6 tasks done
Ring checkpoint sizing was only tested on a Gemma 4 config. A Gemma 3 config marks its global layers with sliding_window_pattern and an AFMoE config uses layer_types, and a miss in either would leave the ring budget at zero with no error. The new test pins both: 10 of 12 Gemma 3 layers and 3 of 4 AFMoE layers are sized at window - 1 + piece rows. Refs #3255
Member
Author
Implementation Review SummaryIntent
Findings Addressed
Remaining Items
Verification
|
…eage The per-conversation cap and the minimum spacing only considered stored checkpoints that were prefixes of the one just inserted. When requests of one conversation completed out of order, a shorter checkpoint inserted after a longer one saw nothing to compare against, so the cap could be exceeded and two boundaries closer than the spacing could both survive. The rule set is now the inserted checkpoint plus every stored checkpoint of the same session bucket and session that is a prefix of it or extends it. Newer and newest keep meaning the longer boundary, not the later insertion: the spacing drops a checkpoint closer than the spacing to a longer kept one on its line, and the cap keeps the longest N. The inserted checkpoint can therefore be the one dropped. Forward-order results are unchanged. Added regression tests for reverse-order insertion of N+1 boundaries and of two boundaries closer than the spacing. Refs #3255
…E rings Setting MLXCEL_PROMPT_CACHE_STATE_CHECKPOINT_CAPACITY_BYTES to a positive value without --ctx-checkpoints now also turns on ring checkpoints for Gemma 3, Gemma 4 and AFMoE, with no per-conversation cap. Documented this next to the variable in environment-variables.md and in the llama-server compatibility note. There is no Korean translation of these pages. Refs #3255
Member
Author
Security and performance review (d1661e9)No CRITICAL or HIGH findings, so no commits were made. Checked and clean:
MEDIUM:
LOW:
Local: |
The doc comment on enforce_conversation_checkpoint_rules said one chat's checkpoints are never counted against another's. That holds for chats with no shared prefix, but when a shorter common ancestor is re-inserted after a fork (edit at k + 1, then regenerate at k), its line contains every branch below it, so the cap applies across the siblings and one branch can lose its checkpoints. The comment now states this: it over-evicts and never over-retains. The rule itself is unchanged. Add a unit test that pins the behavior (memory stays within the cap across both branches after the ancestor is re-inserted), and add the Unreleased changelog entry for --ctx-checkpoints and --checkpoint-min-step. Validation: - cargo test --profile test-fast --features cuda --lib state_checkpoints: 19 passed - cargo clippy --lib --tests --features cuda -- -D warnings: clean Refs #3255
inureyes
marked this pull request as ready for review
November 22, 2026 23:56
This was referenced Nov 23, 2026
inureyes
added a commit
that referenced
this pull request
Nov 23, 2026
…3305) ## Summary Per-sequence state moves from the model wrappers to the scheduler for Gemma 3 and Qwen 3.5 text, behind one per-layer abstraction, so snapshot, restore, truncation, turn-boundary checkpoints, pad trim and decode rewind are written once instead of once per family. Design and the family audit are in `docs/adr/0010-scheduler-owned-sequence-state.md`. - `mlxcel_core::cache::LayerStateKind` replaces `LayerKv`; `LanguageModel::layer_state_kinds()` returns one kind per layer, or `None` to keep a family on its current path. `LayerState { Kv, Rotating, Chunked, Recurrent, Empty }` implements `KvAttention` by matching to the inner cache. - `SequenceStateBackend::SchedulerOwned`: the pool entry holds `Vec<LayerState>`, also when the paged decode override allocates the entry as `PagedKvCache`. - The forward cannot receive the state through `&mut [KVCache]`, so the engine calls a new `LanguageModel::forward_layer_state(request, rows)` for a sequence that holds layer state, and runs the pad trim, decode rewind and paged length mirror over the layers itself. - `server::prompt_cache::state_snapshot` is the single snapshot, restore, truncation and checkpoint implementation, using the existing `kv_snapshot`, `kv_ring_checkpoint` and hybrid encoders, so stored snapshots keep their tensor names, shapes and scalars. - Item 4 of the issue: Gemma 3's ring checkpoint goes through the generic path and its hooks are deleted. Gemma 4 and AFMoE stay model-owned and keep their #3255 hooks, which call the same `kv_ring_checkpoint` functions. - Carried from the #3283 review: the `--ctx-checkpoints N` cap now counts one root-to-leaf line at a time, so a regenerated ancestor no longer evicts a sibling branch's checkpoints. A fork keeps up to `N` per branch; the byte budget bounds all branches. ## Changes after review - The Gemma 3 wrapper refuses `forward_batched_with_ids`. The trait default would have run every row on the one shared fallback slot. The engine always takes the layer-state route first, so server requests never reached it. - `Pooled::prepare_sequence_state` drops only the pool entry and no longer calls the model's release hook. The hook was deleting Qwen 3.5 MRoPE positions set before prepare, so a mixed MRoPE and text test had been testing two text rows. - Whole, truncated and checkpoint restores all validate every layer through `check_restored_layer` before installing it. The checkpoint path skipped the check before. A full layer must hold at least `offset` rows, and a full layer with no rows must be at offset 0. - The Qwen 3.5 MTP slice step fails the request cleanly when the pool entry has no layer state, instead of panicking in the adapter. - Qwen 3.5 keeps its recurrent slot tables in place while lent, so a forward no longer allocates one `Vec` per linear layer and row. ## Deviations from the issue - "Existing suites stay green unchanged": the assertions are unchanged, but `gemma3_tests`, `scheduler_model_owned_lookahead_tests` and the Qwen 3.5 model tests drove a sequence by id on the bare wrapper, which no longer holds one. Their fixtures now return `models::pooled_model::Pooled` (the model over a real `CachePool`), and four scheduler tests read the snapshot through `state_snapshot::snapshot_sequence_state`. - Qwen 3.5's decoder still runs over `Qwen3NextCache`, shared with the unmigrated Qwen3-Next and Qwen4-Exp, and borrows the pool's layer state for each forward (moves, no copies). - `exaone_moe` and `baichuan_m1` are not model-owned; the ADR corrects the table. - The remaining model-owned families are not migrated here. Each family group has a follow-up issue under epic #3259: #3324 (Gemma 4, AFMoE), #3325 (other sliding-window families), #3326 (Llama 4), #3327 (linear-attention hybrids), #3328 (SSM and convolution hybrids), #3329 (composite per-layer state). ## Test plan - [x] Bit-exact round trips on tiny fixtures, 16 decode steps against a cold run with the same partition: Gemma 3 ring unwrapped, ring wrapped, truncation inside the window, ring checkpoint over a longer donor; Qwen 3.5 whole snapshot and state checkpoint. - [x] Byte compatibility: generic path against the model-owned encoders, tensor for tensor, with the names pinned. - [x] Changed-area suites, serialized under the GPU lock: 2,134 lib tests (prompt cache, batch scheduler, pooled model, Qwen 3.5, Gemma 3, hybrid snapshot, ring checkpoint, vision, batched decode) and 919 `mlxcel-core` tests (cache, engine, generate, speculative). New tests: `a_sequence_id_on_the_batched_kv_slice_entry_is_refused`, `every_restore_refuses_attention_tensors_that_do_not_fit`, `scheduler_qwen35_slice_guard_tests`. - [x] `cli_help_consistency`, `llama_compat_manifest`, `qwen38_mtp_chain_parity`, `make verify-env-var-docs verify-used-by`, clippy `-D warnings` on lib, tests and examples, `cargo fmt --check`. - [x] Engine parity: qwen3.5-0.8b-4bit identical in 13 of 13 pairs. gemma-3-1b-it-4bit and gemma-4-e2b-it-4bit each have one `b:dense` against `b:dense+pc:miss` divergence that main at `bd931f76` reproduces at the same index with the same tokens, so it predates this PR. - [x] Real checkpoints, main against branch, cache on with `--ctx-checkpoints 4`: identical replies and `/v1/cache/stats` over a three-turn chat, an edit and a replay on gemma-3-1b-it-4bit and qwen3.5-0.8b-4bit. - [x] Decode rate, main against branch with a null arm (`docs/benchmark_results/scheduler-owned-state-decode-gb10-2026-11-23.md`): no cell shows a regression. Gemma 3 at B=4 read 2% to 4% low on a loaded host; on a quiet host (run 5, 12 samples per arm) the branch is 6.4% above main at 256 tokens and 3.1% above at 8192. - [ ] `rollback_speculative_cache_panics_on_ragged_batched_accepts` (ignored) fails; the message it expects is absent from `qwen3_5.rs` on main as well. Closes #3254
2 of 8 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
--ctx-checkpoints Nand--checkpoint-min-step Mnow configure the prompt cache's checkpoints instead of refusing to start, and Gemma 3, Gemma 4 (text, VL and Unified wrappers) and AFMoE gain ring-only turn-boundary state checkpoints.src/models/kv_ring_checkpoint.rs, hooks ingemma3.rs,gemma4.rs,afmoe.rs, forwarded byvision::{mod, gemma4_vl, gemma4_unified}).state_checkpoint_from_snapshotkeeps only the rotating tensors and scalars of each sliding layer. It returnsNonewhile every ring is unwrapped (the whole snapshot still truncates then), and stores nothing for KV-shared layers.restore_sequence_state_from_checkpointtakes the sliding layers from the checkpoint and the full-attention layers from the donor, cut back afterstandard_truncatable_to. A ring of the wrong length is refused. The donor rule and lineage check are unchanged. Multimodal requests never reach this path:resolve_history_boundaryclears their history boundary, so they store no Boundary-origin snapshot.--ctx-checkpoints N(src/server/prompt_cache/ctx_checkpoints.rs, resolved inserver::startup::resolve_ctx_checkpoints). Unset keeps today's defaults.N > 0turns on keep-previous-turn and the family's state checkpoints, and caps them atNper conversation:insert_state_checkpointkeeps theNlongest checkpoints of the inserted one's lineage (stored checkpoints of the same session bucket that are a prefix of it or that it is a prefix of), so the result does not depend on insertion order.N == 0setsstate_checkpoint_capacity_bytes = 0, leaves keep-previous-turn off, and logs that once at info. Negative values are refused.--checkpoint-min-step M.M > 0sets the periodic interval at absolute multiples ofM, and of two state checkpoints of one conversation closer thanMonly the longer is kept.0 < M < 256is refused at startup with a message naming the floor.0means no periodic checkpoints and no spacing rule.LLAMA_ARG_*variables through clap) overrideMLXCEL_PROMPT_CACHE_CHECKPOINT_INTERVALandMLXCEL_PROMPT_CACHE_KEEP_PREVIOUS_TURN.MLXCEL_PROMPT_CACHE_STATE_CHECKPOINT_CAPACITY_BYTESstill sets the byte budget.MLXCEL_DISABLE_BOUNDARY_SNAPSHOT=1still disables everything, and a given flag then logs a warning that it has no effect. The scheduler reads the resolved interval from the store instead of the process-wide env read.kv_arch::sliding_window_ring_bytes_from_config,snapshot_sizing::recommend_ring_checkpoint_capacity_from_config). This deviates from the issue'swindow x bytes. A multi-token append keeps the newestwindow - 1rows plus the whole piece, so a ring captured at a history boundary holds up towindow - 1 + prefill chunkrows. On gemma-4-12b-it at the 2,048 chunk that is 1,006,305,280 bytes per checkpoint (the window alone would be 320 MiB). The first build sized at the window held 4 checkpoints instead of 12.gemma4_unified(the real 12B'smodel_type) is matched as a ring family.slot_args.rsmodule doc and help text are rewritten, and the stalecapture_history_boundary_snapshottext is gone.docs/llama-server-compat.md,CONTINUOUS_BATCHING.mdandenvironment-variables.mddescribe the mapping. Both manifest entries move fromnot_applicabletoby_design, with divergences listed and issue 3255 added to the shard owners.Item 5 (default for the rotating families): not shipped
RING_FAMILY_DEFAULT_CTX_CHECKPOINTSstaysNone.Trimming the captured ring to its window (320 MiB) would change the balance. It touches the restore's exactness path, so it is left as a follow-up.
Measurements
GB10,
gemma-4-12b-it-4bit,scripts/bench_prompt_cache_replay.py --edit-target n --verify, undergpu-lock. Record:docs/benchmark_results/gemma4-ctx-checkpoints-replay-gb10-2026-11-23.md, with per-turn CSVs. "Needed" is the history boundary of turnn - 1.--ctx-checkpoints 3, target 7--ctx-checkpoints 3, target 6--ctx-checkpoints 3, target 5--ctx-checkpoints 3 --checkpoint-min-step 4096, target 5--ctx-checkpoints 8, target 3Acceptance criterion 2, read literally: at target 7 (the edited previous user message),
cached_tokensreaches the previous history boundary, but the turn is served by the keep-previous-turn whole snapshot, so that arm showsstate_checkpoint_hits = 0. The ring checkpoint is the restore point at target 6 and, with a largerN, at target 3; both arms showstate_checkpoint_inserts > 0andstate_checkpoint_hits = 1.Every arm's
--verifymismatches are plain chained whole-snapshot hits (A2 to A5, B2, B3, C2). A8 and the cold first turns never mismatch, and the same class occurs onmain, so these are the #3040 bf16 differences. On the same binary, every non-edited turn has the same TTFT with and without--ctx-checkpoints 3(within 0.1 s).Tests
models::gemma4_ring_checkpoint_tests(ignored, run with--ignored): a 4-layer fixture with a wrapped window of 8. A checkpoint at boundary 13 plus an 18-token donor restores and decodes bit-for-bit equal to the cold run. The negative control (the donor's ring under the checkpoint's scalars) changes the logits.models::kv_ring_checkpoint_tests: unwrapped ring, subset contents, family check, wrong ring length, a donor ring with no checkpoint ring.cli::slot_args_tests:N > 0andM >= 256accepted, negatives and1..=255refused, flag precedence over the env switches, stale text gone.prompt_cache::ctx_checkpoints_tests: the resolver's precedence, notices and kill switch.prompt_cache::state_checkpoints_tests: N + 1 boundaries keep the newest N; the cap counts one conversation, not the session; spacing replaces close checkpoints; the cap and the spacing also hold when checkpoints arrive longest first; re-inserting a common ancestor after a fork keeps the count within the cap.prompt_cache::snapshot_sizing_ring_tests: ring sizing by piece,gemma4_unified, Fp16 only, and Gemma 3 and AFMoE configs.Local verification (remote CI is cancelled for this epic):
cargo clippy --lib --tests --features cuda -- -D warningsis clean.cargo test --profile test-fast --features cuda --test cli_help_consistency: 27 passed.--test llama_compat_manifest: 4 passed.scripts/ci/check_llama_compat_manifest.py,check_env_var_docs.py,tests/test_check_env_var_docs.py(15 passed),check_used_by.py,check_benchmark_raw_logs.py: all OK.prompt_cache350 passed.slot_args,ctx_checkpoints,state_checkpoint,snapshot_sizing,kv_arch,runtime_settings: 129 passed.kv_ring_checkpoint7,afmoe32,models::gemma3::31,models::gemma4_tests16, all eightmodels::gemma4::submodules (74),vision::gemma4_unified19,vision::processors::gemma433. The ninedistributed::tensor_parallelgemma tests pass one per process with--exact.gemma3/gemma4filters at full or 4-thread width abort intermittently withcudaStreamEndCapture ... previous error during capture. This is the parallel CUDA-graph failure the Makefile documents for the CUDA gate (it serializes for that reason). The same filter set passed once at full width (1051 passed), and every member passes in smaller groups or alone.Changes during review
Nor keep two points closer thanM(the byte budget still bounded memory).enforce_conversation_checkpoint_rulesand pinned by a test: when a shorter common ancestor is re-inserted after a conversation forks, the cap applies across the sibling branches, so one branch can lose its checkpoints. This over-evicts and never over-retains. A per-branch rule belongs with the generic scheduler-owned path in refactor: Generalize prompt-cache state ownership from models to the scheduler #3254.docs/environment-variables.mdanddocs/llama-server-compat.mdnow note thatMLXCEL_PROMPT_CACHE_STATE_CHECKPOINT_CAPACITY_BYTESset without--ctx-checkpointsalso enables ring checkpoints for Gemma 3, Gemma 4 and AFMoE, with no per-conversation cap.CHANGELOG.mdhas an Added entry under Unreleased.Closes #3255