Skip to content

perf: Restore decode lookahead for Gemma 3 via a ring-aware teardown rewind #2159

Closed

Description

@inureyes

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-416 lookahead_params: line 385 returns None whenever self.model.sequence_state_layout().backend == SequenceStateBackend::ModelOwned.
  • decode_tick.rs:450-480 apply_lookahead_trim(ids, positions): trims only pool KVCaches. Call sites at lines 323, 497, 558, 596 pass lookahead_teardown_positions(false) = 1; line 707 passes lookahead_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) added LanguageModel::trim_sequence_state(seq_id, excess) (src/lib/mlxcel-core/src/generate.rs:654-675), implemented by Gemma 3 at src/models/gemma3.rs:1645 through Cache::rewind_padded_prefill (gemma3.rs:923) and RotatingKVCache::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 rewinds offset/idx. update_in_place (cache.rs:4990-5160) overwrites slot idx once offset >= max_size, destroying the K/V of position offset - 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

  1. Ring undo log in RotatingKVCache (new file src/lib/mlxcel-core/src/cache/decode_undo.rs, an impl RotatingKVCache block like prefill_rewind.rs). Add a field decode_undo: Option<DecodeUndoLog> holding up to depth entries { slot: i32, keys: UniquePtr<MlxArray>, values: UniquePtr<MlxArray> }, plus pub fn set_decode_undo_depth(&mut self, depth: usize) and pub fn rewind_decode_writes(&mut self, n: i32) -> Result<(), String>. In update_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 a contiguous copy before the slice_update, keeping the newest depth entries. Warmup writes (offset < max_size) record nothing: the slot was never valid and plain trim is exact there. rewind_decode_writes(n) restores the recorded rows newest first with slice_update, then calls trim(n), clears inplace_marker (as rewind_padded_prefill does), and drops the used entries. Any multi-token update, trim, trim_front, snapshot restore, enable_speculative_buffer, or detach clears the log.
  2. Rejected alternative: retaining the pre-write keys/values handles 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.
  3. Model hooks in LanguageModel (generate.rs, next to trim_sequence_state): fn supports_decode_lookahead_rewind(&self) -> bool { false } and fn rewind_decode_appends(&self, seq_id: SequenceId, n: i32) -> Result<(), String> defaulting to Err. Delegate both in src/loaded_model.rs (next to line 550) and src/vision/mod.rs (next to line 379); PR feat(scheduler): sequence-aware pad trim for model-owned families #2140 found LoadedModel had silently dropped a hook delegation, so the delegation is part of the fix.
  4. Gemma 3 implementation (gemma3.rs): make_configured_caches enables depth 2 (lookahead_teardown_positions(true)) on every Cache::Rotating layer. rewind_decode_appends calls with_existing_sequence_state(seq_id, ..) and per layer runs KVCache::trim(n) for Cache::Standard (must return exactly n) and rewind_decode_writes(n) for Cache::Rotating, naming the layer in any Err. supports_decode_lookahead_rewind returns true only when every sliding layer's mode is KVCacheMode::Fp16 (Int8 and Turbo4Asym carry sidecars the log does not cover, mirroring how supports_padded_prefill declines Turbo4Asym).
  5. Scheduler wiring (decode_tick.rs): line 385 returns None only 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 as DenseKvCache, or PagedKvCache under the paged override). apply_lookahead_trim calls self.model.rewind_decode_appends(seq_id, want) for each id when the natural backend is model-owned, after the pool trim and before sync_sequence_storage. On Err, log at error with seq_id and finish that request with an error the same way the pad-trim Err path does at its call sites (scheduler/pad_trim.rs callers); 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, the RotatingKVCache::trim cursor 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), and rewind_decode_writes returns Err there.
  • Edge cases: n == 0 is a no-op; n larger than the recorded entries for writes past warmup is Err with the cache untouched; a rewind spanning the warmup/wrap boundary (one recorded write, one warmup write) restores exactly; n > offset is Err.
  • Error handling: every refusal leaves the cache untouched and returns a message naming the layer, n, offset, idx, and recorded depth.

Acceptance Criteria

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 --check

Manual (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

  1. added
    type:performance
    priority:medium
    area:inference
    area:core
    status:ready
    status:in-progress
    and removed
    status:ready
    on Oct 6, 2026
  2. added
    status:done
    and removed
    status:in-progress
    on Oct 6, 2026
  3. added a commit that references this issue on Oct 14, 2026
    ffbc9c6
  4. added this to the 0.8 milestone on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:corearea:inferencepriority:mediumstatus:donetype:performance

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions