Skip to content

refactor: move per-layer sequence state from models to the scheduler - #3305

Merged
inureyes merged 14 commits into
mainfrom
refactor/issue-3254-scheduler-owned-state
Nov 23, 2026
Merged

inureyes merged 14 commits into
mainfrom
refactor/issue-3254-scheduler-owned-state

Conversation

@inureyes

@inureyes inureyes commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

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 feat: Support --ctx-checkpoints and --checkpoint-min-step for sliding-window families #3255 hooks, which call the same kv_ring_checkpoint functions.
  • Carried from the feat: support --ctx-checkpoints and --checkpoint-min-step #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

Test plan

  • 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.
  • Byte compatibility: generic path against the model-owned encoders, tensor for tensor, with the names pinned.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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

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
@inureyes inureyes added status:review Under review type:refactor Code restructuring without changing functionality priority:high High priority area:architecture Architecture and code structure changes area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Nov 23, 2026
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
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Move Gemma 3 and Qwen 3.5 text per-sequence state into the scheduler's pool entry behind one LayerState abstraction, with snapshot, restore, truncation and checkpoints written once, plus a per-branch checkpoint cap.

Findings Addressed (f3caea8)

  • Gemma3Wrapper did not override forward_batched_with_ids, so the trait default dropped the ids and ran every row on the shared fallback slot. It now refuses ids like the single-row entries (Qwen 3.5 already did), with a test. Not reachable from the engine, which routes layer-state rows first (HIGH)
  • Pooled::prepare_sequence_state called the model release hook, deleting Qwen 3.5 MRoPE positions installed before prepare, so issue_2572_qwen35_mixed_mrope_and_text_rows_match_solo_decode lost its multimodal row. Prepare now drops only the pool entry (MEDIUM)
  • The Qwen 3.5 MTP slice step now fails the request when the pool entry has no layer state, matching slice 0, instead of panicking in the adapter (LOW, defensive)

Remaining Items

  • Gemma 3 decode at B=4 is below main in all five benchmark cells (1.9% to 4.1%, nulls 1.0% to 2.5%). The batched decode path matches main's (forward_batched_decode_with_caches plus the undo flush), so no cause was found in code. Needs a quiet-host rerun before the acceptance line is met (MEDIUM)
  • Follow-up issues are drafted, not filed (orchestrator) (MEDIUM)
  • The PR body still marks the benchmark as running and engine-parity as not run (LOW)
  • The checkpoint restore path skips check_kv_tensors, which whole and truncated restores run (LOW)

Verification

  • All stated requirements implemented (Gemma 3 B=4 decode cell not shown, follow-ups not filed)
  • No placeholder/mock code remaining
  • Integrated into project code flow (engine step, prefill, cohort, verify, prompt cache, MTP bursts and slices, VLM wrappers)
  • Project conventions followed
  • Existing modules reused where applicable (kv_snapshot, kv_ring_checkpoint, hybrid encoders match main's names and order)
  • No unintended structural changes
  • Tests pass (clippy -D warnings lib and tests; models::gemma3 64 passed, models::qwen3_5 45 passed)

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
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

Scope: 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.

Fixed in 9a274d0 and 00940c5:

  • MEDIUM, checkpoint restore skipped tensor validation (state_snapshot.rs). Whole and truncated restores ran check_kv_tensors; restore_from_checkpoint did not, in either arm. The hybrid arm (Qwen 3.5) matters: hybrid_snapshot::restore_attention assigns keys, values and offset unchecked. Every restore now validates each layer before install, and full layers must also hold at least offset rows. Test: every_restore_refuses_attention_tensors_that_do_not_fit (mismatched pair and too few rows, whole and checkpoint).
  • LOW, Qwen 3.5 per-step allocations (qwen3_5_layer_state.rs). LentCaches rebuilt a RecurrentState (one heap Vec) per linear layer, per row, per forward. The slot table now stays in place and the tensors are moved out and back.

Checked, no change needed:

  • Isolation: pool rows come from batch_layer_state_mut (duplicates rejected), Gemma 3 refuses ids on every KVCache-slice entry, the VLM wrappers forward the whole layer-state surface, the MTP adapter refuses a sequence with no pool state instead of using the fallback slot, and DFlash runs on its own fresh caches.
  • Resource bounds: layer state lives in the pool entry and is freed with it; the engine calls release_sequence_state_by_id on every release, which drops the Qwen 3.5 MRoPE entry. Snapshot and checkpoint bytes stay under the existing store budgets.
  • Decode hot path: Gemma 3 B=4 runs the same per-layer row Vec, attention dispatch, undo flush and paged-shadow sync as main, with one pool lookup instead of a pool lookup plus a model-map lookup. I found no extra MLX op or eval, and host-side allocation differences cannot account for 2-4%. I found no code cause.

Remaining (LOW, not fixed):

  • state_snapshot_dispatch::policy_of allocates the layer-kind Vec on every snapshot-candidate check. This is per request, not per token.
  • The per-branch cap loop in enforce_conversation_checkpoint_rules is O(k^2) prefix comparisons over the lineage. That is the same class as the existing spacing loop, and the byte budget bounds k.

Validation: server::prompt_cache::state_snapshot and the Qwen 3.5 layer-state, checkpoint and MTP-adapter tests pass locally, and clippy passes with -D warnings.

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
@inureyes

Copy link
Copy Markdown
Member Author

Follow-up to the review above. One more fix, plus details on two of the checks.

  • 4a879e9: a restored full layer with no keys and values must now be at offset 0. The hybrid decoder set the offset to the snapshot length even with no attention rows, and the validator accepted an absent pair. This is covered by the same test.
  • By-id entries: every engine forward (step, prefill, score, batched prefill, verify) tries the layer-state route first, so the Gemma 3 refusal panics and the MTP Missing panic are not reachable from the server for an open sequence. full_model_drafter passes no id and runs on the drafter's own model instance.
  • Byte accounting: on main a model-owned entry reported 0 bytes (empty placeholder caches), and the paged shadow counted blocks through sync_paged_state_with_lengths. The branch keeps both behaviours. layer_state_nbytes has no caller yet, so no admission or stats path counts live layer-state bytes, before or after this PR.
  • Gemma 3 B=4: I diffed the engine step, batch_layer_state_mut, the generic forward_batched_decode chain, attend_batched_rows dispatch, cache construction (undo depth and modes), flush_decode_undo, the paged-shadow sync and can_unwind_lookahead against main. They match apart from generics and one fewer map lookup per row.

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
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 23, 2026
@inureyes
inureyes marked this pull request as ready for review November 23, 2026 08:28
@inureyes
inureyes merged commit 061f544 into main Nov 23, 2026
2 of 16 checks passed
@inureyes
inureyes deleted the refactor/issue-3254-scheduler-owned-state branch November 23, 2026 08:28
@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:architecture Architecture and code structure changes area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:high High priority status:done Completed type:refactor Code restructuring without changing functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor: Generalize prompt-cache state ownership from models to the scheduler

1 participant