Repository navigation
refactor: move per-layer sequence state from models to the scheduler - #3305
Conversation
The per-conversation state-checkpoint cap (--ctx-checkpoints N) counted every branch below a re-inserted common ancestor together. Regenerating an earlier turn after a fork (edit at k+1, then regenerate at k) could therefore evict a sibling branch's checkpoints, a behaviour the #3283 review recorded and pinned as over-eviction. The cap now counts one root-to-leaf line at a time: a checkpoint is dropped when some line through the inserted checkpoint holds N longer checkpoints above it. A fork keeps up to N per branch, a single line behaves as before, and the result does not depend on insertion order. The checkpoint byte budget stays the bound on what all branches hold together. The fork test now asserts that a regenerated ancestor leaves both branches intact, and a new test inserts a two-branch conversation in five orders and expects the same N per branch each time. state_checkpoints tests pass (20). Docs for --ctx-checkpoints describe the per-branch rule. Refs #3254
Prompt-cache reuse was written once for scheduler-owned dense and paged KV and again per family for every model that keeps its caches in its wrapper, so each capability (restore, truncation, checkpoints, pad trim, decode rewind) had to be repeated per family. This adds one scheduler-owned state abstraction with a per-layer-kind policy and migrates Gemma 3 and Qwen 3.5 text onto it (ADR 0010). - mlxcel-core: LayerStateKind replaces models::model_owned::LayerKv. LayerState (Kv, Rotating, Chunked, Recurrent, Empty) implements KvAttention by matching to the inner cache. SequenceStateBackend::SchedulerOwned is the layout of a family that reports LanguageModel::layer_state_kinds(), and the pool entry holds its Vec<LayerState>, also under the paged decode override. - The engine forwards a scheduler-owned sequence through LanguageModel::forward_layer_state over the pool's rows, and runs the pad trim, the decode rewind and the paged length mirror over the layers itself. - server::prompt_cache::state_snapshot implements snapshot, restore, truncation, state checkpoints and checkpoint restore once over [LayerState], with the kv_snapshot, kv_ring_checkpoint and hybrid encoders the model-owned families use, so stored snapshots keep their tensor names, shapes and scalars. Gemma 4 and AFMoE keep their ring-checkpoint hooks, which call the same kv_ring_checkpoint functions. - Gemma 3 and Qwen 3.5 keep no per-sequence map. Their VLM wrappers forward the layer-state surface, and the Qwen 3.5 MTP adapter carries the borrowed layer state instead of a sequence id. - Model-level tests drive the two families through models::pooled_test_model::Pooled, a real CachePool behind the by-id calls the tests were written against. Families with layer_state_kinds() == None keep their code paths. Refs #3254
Adds the Qwen 3.5 whole-snapshot round trip (prefill in two pieces, snapshot through the generic path, restore into a fresh pool sequence, 16 decode steps bit for bit against a cold run with the same partition) and the scheduler-owned assertions for its table, pool state and refusal of a sequence id on the KVCache-slice entry. The generic snapshot tests compare live rows after a cut, since a cut cache keeps its physical buffer, and pin the windowed tensor names. The paged-override scheduler test now expects Gemma 3's natural backend to be SchedulerOwned and its layer state to be present on a PagedKvCache entry. The batched decode harness and the coverage scan accept a scheduler-owned family behind the pooled driver. Docs: CONTINUOUS_BATCHING and architecture describe the scheduler-owned state and the per-branch checkpoint cap. Refs #3254
…tate A scheduler-owned family refuses a sequence id on its KVCache-slice entries, so callers that drive a model by id without an engine would have panicked for Gemma 3 and Qwen 3.5: the logit-trace example and two parity tests. models::pooled_model::Pooled is now a public driver that owns the model and a CachePool, serves the by-id LanguageModel calls over pool sequences, and passes every other family through. Those callers wrap the model in it. The Qwen 3.5 MTP adapter took Option<layer state> and silently ran on the shared fallback slot when the pool held none. It now has two constructors: fallback() for the offline CLI, and for_sequence(), which refuses a sequence without pool state at the first call instead of running one request on another's state. A unit test drives prefill, verify and rollback over a pool sequence and compares every step with the fallback adapter. Also: a source scan requires the VLM wrappers around a scheduler-owned backbone to forward the four layer-state methods, and the new files are split to stay under 500 lines. Verified with cargo check over lib, tests, bins, examples and benches, clippy -D warnings on core and lib, and the changed-area test groups. Refs #3254
Decode tok/s for gemma-3-1b-it-4bit and qwen3.5-0.8b-4bit at 256 and 8192 prompt tokens, B=1 and B=4, main (bd931f7) against the branch (c98af10) with a second main arm as the null, on GB10. The first run's B=1 gaps of 4% to 6% came from three samples per arm and do not reappear with two to four times the samples; no cell shows a change that survives a repeat. The host was shared, its null is about 2%, and the record says a smaller difference is not ruled out. Also records the real-checkpoint prompt-cache comparison: identical replies and /v1/cache/stats between main and the branch over a three-turn chat, an edit and a replay with --ctx-checkpoints 4. Refs #3254
…ut pool state The image arm of the logit-trace example wrapped the model in a pooled driver twice, once in trace and once in the batched continuation, so a scheduler-owned VLM would have continued row 0 from an empty sequence. The continuation now takes the caller's driver. A Qwen 3.5 sequence the pool holds no layer state for is declined at the MTP slice start, like an unsupported family, and fails the B=1 burst with an error instead of reaching the adapter's panic. Refs #3254
…aves open A fourth run with twelve samples per arm puts Gemma 3 at 256 tokens and B=1 at -0.1% under a 1.4% null. At B=4 the branch median is below main in all five Gemma 3 cells measured (1.9% to 4.1%, nulls 1.0% to 2.5%). The record now says the acceptance line is met for B=1 and for Qwen 3.5 at B=4 and not shown for Gemma 3 at B=4, and that a quiet host is needed to tell a 2% to 3% cost from noise. Refs #3254
Gemma3Wrapper did not override forward_batched_with_ids, so the trait default dropped the sequence ids and forwarded every row through the one id-less fallback slot. A caller that bypassed the pool would have run several sequences on shared state without an error, which is the hazard the single-row entries already refuse. The batched entry now refuses ids the same way (Qwen 3.5 already did), and a test pins it. Pooled::prepare_sequence_state called the model's release hook, which for Qwen 3.5 deletes the sequence's MRoPE positions. The mixed MRoPE and text decode parity test installs those positions before preparing, so its multimodal row silently became a text row. Prepare now drops only the pool entry, as the model-owned prepare did. The MTP slice step for Qwen 3.5 now fails the request when the pool entry holds no layer state, matching slice 0, instead of letting the adapter panic in the scheduler. Validated with clippy -D warnings on lib and tests, and the models::gemma3 and models::qwen3_5 test groups. Refs #3254
Implementation Review SummaryIntent
Findings Addressed (f3caea8)
Remaining Items
Verification
|
Whole and truncated restores ran check_kv_tensors on each layer, but restore_from_checkpoint did not, in either arm, although ADR 0010 says every restore validates the key and value tensors. The hybrid arm (Qwen 3.5) relied on hybrid_snapshot::restore_attention, which assigns keys, values and offset unchecked, so a donor whose keys and values disagree, or hold fewer rows than the restored offset, would have been installed into the sequence. Every restore now checks each layer before the state is installed. A full layer must also hold at least offset rows, since attention reads its first offset rows. The new test covers a mismatched pair and too few rows for whole and checkpoint restores, and fails on the previous code. Refs #3254
LentCaches moved every layer out of the pool's vector and, on drop, rebuilt a RecurrentState for each linear layer, one heap allocation per linear layer, row and forward on the decode path. A recurrent layer now keeps its slot table in place: its tensors are moved out for the forward and put back on drop. Attention layers are still moved out and back, which allocates nothing. Qwen 3.5 layer-state, checkpoint, batched-decode and MTP-adapter tests pass. Refs #3254
Security and performance reviewScope: the four open items from the implementation review. Prompt-cache snapshots and checkpoints are in-memory only (no disk or network deserialization; the KV handoff declines scheduler-owned sequences), so a malformed snapshot can come only from an encoder bug or a config mismatch. No CRITICAL or HIGH findings.
Checked, no change needed:
Remaining (LOW, not fixed):
Validation: |
The Qwen 3.5 attention decoder sets the offset to the snapshot's token length whether or not the snapshot holds attention rows, and check_kv_tensors accepted an absent pair unconditionally. A snapshot with no attention tensors would therefore install a full layer claiming tokens it has no rows for. A full layer with no keys and values must now be at offset 0. Windowed and KV-shared layers already restore absent tensors at offset 0, so they are unaffected. Prompt-cache, Gemma 3, Qwen 3.5 and scheduler snapshot tests pass; clippy is clean. Refs #3254
|
Follow-up to the review above. One more fix, plus details on two of the checks.
Tests: prompt-cache, Gemma 3, Qwen 3.5 and scheduler snapshot modules (353 pass). Clippy is clean. |
…a 3 rerun Add a scheduler test that installs an in-flight MTP slice job for a Qwen 3.5 sequence the pool holds no layer state for and checks that the round drops the job and sends one client-visible error instead of panicking in the target adapter. The slice-job fixture is shared from the slice test module. Record run 5 of the decode benchmark: Gemma 3 at B = 4 on a quiet host with the branch rebuilt at 4a879e9. The branch is at +6.4% (P = 256) and +3.1% (P = 8192) against main, so the earlier negative gap came from host load. The Reading section now states that no cell shows a decode regression. ADR 0010 now says every restore (whole, truncated and checkpoint) validates attention tensors, and that the Gemma 3 batched entry with ids is refused like the single-row entries. CHANGELOG gets a Changed entry for the move of Gemma 3 and Qwen 3.5 state into the pool entry. No Korean counterparts exist for these docs. Validation: scheduler_qwen35_slice_guard_tests passes (1 test), cargo fmt --check, cargo clippy --profile test-fast --features cuda --lib --tests -D warnings, make verify-env-var-docs verify-used-by all clean. Refs #3254
…cheduler-owned-state # Conflicts: # src/models/afmoe.rs # src/models/kolibri1_lm.rs
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::LayerStateKindreplacesLayerKv;LanguageModel::layer_state_kinds()returns one kind per layer, orNoneto keep a family on its current path.LayerState { Kv, Rotating, Chunked, Recurrent, Empty }implementsKvAttentionby matching to the inner cache.SequenceStateBackend::SchedulerOwned: the pool entry holdsVec<LayerState>, also when the paged decode override allocates the entry asPagedKvCache.&mut [KVCache], so the engine calls a newLanguageModel::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_snapshotis the single snapshot, restore, truncation and checkpoint implementation, using the existingkv_snapshot,kv_ring_checkpointand hybrid encoders, so stored snapshots keep their tensor names, shapes and scalars.kv_ring_checkpointfunctions.--ctx-checkpoints Ncap 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 toNper branch; the byte budget bounds all branches.Changes after review
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_statedrops 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.check_restored_layerbefore installing it. The checkpoint path skipped the check before. A full layer must hold at leastoffsetrows, and a full layer with no rows must be at offset 0.Vecper linear layer and row.Deviations from the issue
gemma3_tests,scheduler_model_owned_lookahead_testsand the Qwen 3.5 model tests drove a sequence by id on the bare wrapper, which no longer holds one. Their fixtures now returnmodels::pooled_model::Pooled(the model over a realCachePool), and four scheduler tests read the snapshot throughstate_snapshot::snapshot_sequence_state.Qwen3NextCache, shared with the unmigrated Qwen3-Next and Qwen4-Exp, and borrows the pool's layer state for each forward (moves, no copies).exaone_moeandbaichuan_m1are not model-owned; the ADR corrects the table.Test plan
mlxcel-coretests (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.cli_help_consistency,llama_compat_manifest,qwen38_mtp_chain_parity,make verify-env-var-docs verify-used-by, clippy-D warningson lib, tests and examples,cargo fmt --check.b:denseagainstb:dense+pc:missdivergence that main atbd931f76reproduces at the same index with the same tokens, so it predates this PR.--ctx-checkpoints 4: identical replies and/v1/cache/statsover a three-turn chat, an edit and a replay on gemma-3-1b-it-4bit and qwen3.5-0.8b-4bit.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 fromqwen3_5.rson main as well.Closes #3254