Repository navigation
Description
Problem / Background
PR #2139 (closes #1754, merged a4974fab) made lookahead_params key on the model's natural backend, so every model-owned sequence-state family (Gemma 3, Gemma 4, AFMoE, Llama 4, Muse Glimmer, and the SSM/hybrid families) now decodes synchronously. That gate was correct: apply_lookahead_trim iterates CachePool::get_caches_mut, which is empty for these families, so the speculative prime append was never unwound. Before the fix, a Gemma 3 completion snapshot held one more position than it claimed (offset 166 for 165 tokens) and lookahead output differed from MLXCEL_FORCE_SYNC=1.
The cost is throughput. On GB10 CUDA, gemma-3-4b-it-4bit (200 tokens, default flags, n=4 per arm) went from 84.1-84.5 tok/s to 74.1-75.2 tok/s, with output now byte-identical to force-sync (TECHNICAL_REPORTS/pr-2139-completion-snapshot-token-len.en.md, section 4). This issue restores the pipeline for Gemma 3 with a correct teardown rewind of its model-owned state.
Current Behavior
src/server/batch/scheduler/decode_tick.rs:367-416lookahead_params: line 385 returnsNonewheneverself.model.sequence_state_layout().backend == SequenceStateBackend::ModelOwned.decode_tick.rs:450-480apply_lookahead_trim(ids, positions): trims only poolKVCaches. Call sites at lines 323, 497, 558, 596 passlookahead_teardown_positions(false)= 1; line 707 passeslookahead_teardown_positions(next.is_some()), which is 2 on the steady-tick teardown (scheduler/mod.rs:819).- PR feat(scheduler): sequence-aware pad trim for model-owned families #2140 (closes feat(scheduler): sequence-aware cache trim hook so model-owned families can use padded prefill #1755,
1e561f1e) addedLanguageModel::trim_sequence_state(seq_id, excess)(src/lib/mlxcel-core/src/generate.rs:654-675), implemented by Gemma 3 atsrc/models/gemma3.rs:1645throughCache::rewind_padded_prefill(gemma3.rs:923) andRotatingKVCache::rewind_padded_prefill(src/lib/mlxcel-core/src/cache/prefill_rewind.rs:43). That rewind refuses a non-chronological buffer, and a single-token decode write into a wrapped ring is not chronological, so it cannot serve the lookahead teardown (TECHNICAL_REPORTS/pr-2140-model-owned-pad-trim.en.md, Follow-up). RotatingKVCache::trim(src/lib/mlxcel-core/src/cache.rs:5711) only rewindsoffset/idx.update_in_place(cache.rs:4990-5160) overwrites slotidxonceoffset >= max_size, destroying the K/V of positionoffset - max_size.
Why a plain trim is not enough after wrap: from a state holding positions N-W..N-1 (W = max_size), the steady teardown unwinds two prime writes (N into slot p, N+1 into slot p+1). After trim(2) the sync re-forward of N rewrites slot p, but slot p+1 still holds the speculative K/V of N+1 where position N-W+1 belonged, and query N attends that slot. With one write unwound the re-forward is correct, but a snapshot captured before it carries the speculative K/V in the evicted slot.
Proposed Solution
- Ring undo log in
RotatingKVCache(new filesrc/lib/mlxcel-core/src/cache/decode_undo.rs, animpl RotatingKVCacheblock likeprefill_rewind.rs). Add a fielddecode_undo: Option<DecodeUndoLog>holding up todepthentries{ slot: i32, keys: UniquePtr<MlxArray>, values: UniquePtr<MlxArray> }, pluspub fn set_decode_undo_depth(&mut self, depth: usize)andpub fn rewind_decode_writes(&mut self, n: i32) -> Result<(), String>. Inupdate_in_place, when the log is enabled and the write lands on a slot that was valid (offset >= max_size), record the overwritten[B, H, 1, D]rows of K and V as acontiguouscopy before theslice_update, keeping the newestdepthentries. Warmup writes (offset < max_size) record nothing: the slot was never valid and plaintrimis exact there.rewind_decode_writes(n)restores the recorded rows newest first withslice_update, then callstrim(n), clearsinplace_marker(asrewind_padded_prefilldoes), and drops the used entries. Any multi-token update,trim,trim_front, snapshot restore,enable_speculative_buffer, or detach clears the log. - Rejected alternative: retaining the pre-write
keys/valueshandles instead of copying rows. It adds no op per step but keeps up to two full window buffers alive per sliding layer per sequence, which does not scale with--parallel. Switch to it only if the per-step row copy measurably prevents the throughput target below, and record that measurement in the PR. - Model hooks in
LanguageModel(generate.rs, next totrim_sequence_state):fn supports_decode_lookahead_rewind(&self) -> bool { false }andfn rewind_decode_appends(&self, seq_id: SequenceId, n: i32) -> Result<(), String>defaulting toErr. Delegate both insrc/loaded_model.rs(next to line 550) andsrc/vision/mod.rs(next to line 379); PR feat(scheduler): sequence-aware pad trim for model-owned families #2140 foundLoadedModelhad silently dropped a hook delegation, so the delegation is part of the fix. - Gemma 3 implementation (
gemma3.rs):make_configured_cachesenables depth 2 (lookahead_teardown_positions(true)) on everyCache::Rotatinglayer.rewind_decode_appendscallswith_existing_sequence_state(seq_id, ..)and per layer runsKVCache::trim(n)forCache::Standard(must return exactlyn) andrewind_decode_writes(n)forCache::Rotating, naming the layer in anyErr.supports_decode_lookahead_rewindreturnstrueonly when every sliding layer's mode isKVCacheMode::Fp16(Int8 and Turbo4Asym carry sidecars the log does not cover, mirroring howsupports_padded_prefilldeclines Turbo4Asym). - Scheduler wiring (
decode_tick.rs): line 385 returnsNoneonly when the natural backend is model-owned AND!self.model.supports_decode_lookahead_rewind(). The per-sequence backend check at lines 405-414 must still admit Gemma 3 (allocated asDenseKvCache, orPagedKvCacheunder the paged override).apply_lookahead_trimcallsself.model.rewind_decode_appends(seq_id, want)for each id when the natural backend is model-owned, after the pool trim and beforesync_sequence_storage. OnErr, log aterrorwithseq_idand finish that request with an error the same way the pad-trimErrpath does at its call sites (scheduler/pad_trim.rscallers); never continue decoding from a desynchronized state.
Scope
In scope: the RotatingKVCache undo log and rewind, the two LanguageModel hooks with delegations, Gemma 3 (text, and its VLM wrapper through delegation), the lookahead_params gate and apply_lookahead_trim wiring, tests, and the GB10 measurement.
Out of scope: Gemma 4 (MTP speculative buffering interacts with the ring), Llama 4 (ChunkedKVCache needs its own rewind), AFMoE and Muse Glimmer (no checkpoint-validated rewind yet), SSM/hybrid families (recurrent state has no positional rewind), Int8/Turbo4Asym sliding storage, and the CLI path (no lookahead pipeline). Each stays synchronous through the default false capability; file per-family follow-ups once Gemma 3 lands.
Implementation Notes
- Reuse:
with_existing_sequence_state,lookahead_teardown_positions, theRotatingKVCache::trimcursor logic, and the pad-trim abort path. Do not add a second trim loop in the scheduler. - Constraints: no change to output or throughput of dense/paged families or of force-sync. The log is skipped when
buffer_size > 0(speculative buffering already keeps rollback slack), andrewind_decode_writesreturnsErrthere. - Edge cases:
n == 0is a no-op;nlarger than the recorded entries for writes past warmup isErrwith the cache untouched; a rewind spanning the warmup/wrap boundary (one recorded write, one warmup write) restores exactly;n > offsetisErr. - Error handling: every refusal leaves the cache untouched and returns a message naming the layer,
n,offset,idx, and recorded depth.
Acceptance Criteria
- Gemma 3 decodes on the lookahead pipeline in
mlxcel-serverwith default flags, and greedy output is byte-identical toMLXCEL_FORCE_SYNC=1, including a prompt longer than the checkpoint'ssliding_window(read from itsconfig.json) so the ring wraps during decode, at--parallel 1and with 4 concurrent requests. (PR perf(scheduler): restore Gemma 3 decode lookahead via ring rewind #2182: byte-identical md5 vs force-sync for short, 1906-token, and 4 concurrent requests at--parallel 4and--parallel 1) - Completion snapshot
token_lenequals the cache offset at capture (fix(prompt-cache): completion-origin snapshots claim one more token than their caches hold #1754 invariant). Insrc/server/batch/scheduler_completion_snapshot_tests.rsthelength, one-decoded-token, and EOS tests pass unchanged;model_owned_sequence_never_primes_the_decode_lookahead(lines 181-219) is replaced by a test asserting the tiny Gemma 3 getsSomeparams and a model-owned stub with the default capability still getsNone. (PR perf(scheduler): restore Gemma 3 decode lookahead via ring rewind #2182: snapshot tests pass on the pipelined path; test replaced bymodel_owned_sequence_primes_the_decode_lookahead_only_with_a_rewind, the default-capabilityNonecase is covered by an INT8-sliding Gemma 3 and a trait-default stub) - A new scheduler test on the tiny Gemma 3 fixture (
scheduler_model_owned_cache_tests.rs:75,sliding_window: 8) decodes past the window with lookahead, forces both a 1-position teardown (admission mid-generation) and the 2-position steady teardown, and asserts tokens and per-layer offsets equal a force-sync run. (PR perf(scheduler): restore Gemma 3 decode lookahead via ring rewind #2182:scheduler_model_owned_lookahead_tests, on the pad-trim fixture with one sliding and one global layer, because the named fixture'ssliding_window_pattern: 1has no sliding layer) - Unit tests in
src/lib/mlxcel-core/src/cache/decode_undo_tests.rs: after wrap, one and two decode writes followed byrewind_decode_writesleave K, V,offset, andidxbyte-identical to the pre-write cache; a rewind spanning the warmup boundary is exact; refusals (buffer_size > 0, non-Fp16 mode,nbeyond recorded depth) returnErrand leave the cache untouched. Each fails on current code. (PR perf(scheduler): restore Gemma 3 decode lookahead via ring rewind #2182) - Decode throughput on GB10 for gemma-3-4b-it-4bit (200 tokens, default flags) recovers to within 3% of the pre-fix(prompt-cache): key completion snapshots by the tokens their state holds #2139 84.1-84.5 tok/s, measured with n>=3 repeats interleaved per round against a force-sync arm and a null arm (two identical builds), with paired deltas in the PR. GB10 single-run decode is bimodal, so disjoint ranges alone are not evidence. (PR perf(scheduler): restore Gemma 3 decode lookahead via ring rewind #2182: 87.3 tok/s vs 87.6 pre-fix(prompt-cache): key completion snapshots by the tokens their state holds #2139, null arm within 1%; past the window 72.7 vs 77.1 for the unsound pre-fix(prompt-cache): key completion snapshots by the tokens their state holds #2139 pipeline, 67.3 force-sync)
- Dense-KV lookahead (Llama 3.2 1B) output and throughput unchanged. (PR perf(scheduler): restore Gemma 3 decode lookahead via ring rewind #2182: 270.4 vs 270.0 tok/s, identical output)
Verification
cargo test --release --features cuda -p mlxcel-core cache:: -- --test-threads=1
cargo test --release --features cuda server::batch::scheduler -- --test-threads=1
cargo test --release --features cuda models::gemma3 -- --test-threads=1
cargo clippy --release --features cuda --all-targets -- -D warnings
cargo fmt --checkManual (GB10, mlxcel-server run under gpu-lock run): reproduce the PR #2139 section 4 protocol on gemma-3-4b-it-4bit, once with default flags and once with MLXCEL_FORCE_SYNC=1, plus a prompt past the sliding window; diff the greedy outputs (must be identical) and report decode tok/s per arm.
Activity
fix(scheduler): skip the re-dispatch when every rewind failed
perf(scheduler): restore decode lookahead for Gemma 3 via ring rewind
perf(cache): copy undo rows only for lookahead prime writes
fix(scheduler): skip the re-dispatch when every rewind failed
perf(scheduler): restore Gemma 3 decode lookahead via ring rewind (la…