Repository navigation
perf(scheduler): restore Gemma 3 decode lookahead via ring rewind - #2182
Merged
Merged
Conversation
inureyes
added a commit
that referenced
this pull request
Oct 6, 2026
6 tasks done
PR #2139 gated the decode lookahead off for every model-owned family because the teardown trim reached only CachePool caches. Gemma 3 lost about 10 tok/s on GB10. A plain cursor trim cannot serve it either: once the sliding window wraps, each decode write overwrites the K/V of the position that just left the window. RotatingKVCache gains an opt-in undo log (cache/decode_undo.rs) of its newest single-token writes: the starting cursors, plus a copy of the overwritten [B, H, 1, D] rows once the ring has wrapped. rewind_decode_writes(n) restores those rows newest first and the exact offset and idx, and refuses (cache untouched) under speculative buffering, non-FP16 storage, a disabled log, n > offset, or writes the log no longer holds. Any other mutation clears the log. Row copies are lazy, so the model schedules them in one async_eval right after building each forward (flush_decode_undo_rows); otherwise they would pin the pre-write buffer and stop slice_update from reusing it. LanguageModel gains supports_decode_lookahead_rewind and rewind_decode_appends, delegated through LoadedModel and the VLM wrapper. Gemma 3 opts in when every sliding layer is FP16, logs depth 2 on scheduler sequence caches only (the CLI fallback slot keeps none), and rewinds global layers with KVCache::trim. The scheduler admits a model-owned family to the pipeline only with that capability, including the ModelOwned allocation used at --parallel 1, rewinds it on every teardown, and fails the request with an error when a rewind fails. Refs #2159
The undo log copied the overwritten rows of every single-token write once the window had wrapped, and the model flushed those copies with an extra async_eval per forward. Only the scheduler's prime forward makes appends a teardown can unwind, so force-sync decoding and requests the pipeline does not admit paid that cost for nothing. DecodeLookaheadAppendScope (thread-local guard) now marks the prime forward in lookahead_forward. Writes outside it log their cursors only; an overwrite made outside the scope is refused by rewind_decode_writes, which no teardown requests. Warmup writes are unaffected. GB10 measurements behind this (gemma-3-4b-it-4bit, 1906-token prompt, so every decode write overwrites a valid slot): with the row copies left unflushed the pinned pre-write buffers stop slice_update from reusing them in place and decode drops to 64.5 tok/s, below force-sync; with the flush it runs at 72.4; with no row copies at all (unsound) at 76.9. Refs #2159
When a lookahead teardown fails the model-owned rewind of every sequence in the batch, the surviving id set is empty. The stale-id and finishing teardowns now return instead of priming a zero-row batched forward, which has no empty guard on the lookahead path. Refs #2159
inureyes
force-pushed
the
update/issue-2159-gemma3-lookahead-rewind
branch
from
October 6, 2026 19:05
73eeb32 to
e1a7787
Compare
inureyes
added a commit
that referenced
this pull request
Oct 6, 2026
…2186) ## Summary The fused paged-attention kernels computed the per-token pool base in 32 bits, so a layer slab past 2^32 elements per side (131,072 blocks of `[32, 8, 128]` for Llama-3.1-8B) silently read another row of the same buffer. The base is now 64-bit in all six bodies, and the 32-bit merge kernel is guarded by size checks instead. ## What changed Kernel bodies: only the pool-base declaration changes, plus a one-line comment above it. The variable type and the casts change; template args, grid, JIT names and dtype keys are unchanged (`make verify-kernel-dtype-keys`: 9 in scope). | Backend | v1 decode | v2 partial | |---|---|---| | Metal (`ulong`) | `paged_attention.cpp:149` | `paged_attention_v2.cpp:176` | | CUDA (`uint64_t`) | `paged_attention.cpp:303` | `paged_attention_v2.cpp:372` | | HIP (`uint64_t`) | `paged_attention_hip.h:140` | `paged_attention_hip.h:302` | Each line becomes `T base = ((T)row * page + slot) * (T)stride_kv + kv_head * dim;`, with `row` widened before the multiply. The `k_pool[base + d]` / `v_pool[base + d]` reads use the 64-bit value unchanged. The same arithmetic in `fused_norm.cpp` and `fused_rope_append.cpp` already uses `ulong` (Metal) and `uint64_t` (CUDA). Sparse decode runs on v2 partial, so it gets the same fix. - Merge: `paged_attention_merge_states` throws `std::invalid_argument` (an `Err` in Rust) when `v_in` or the merged output exceeds `UINT32_MAX` elements. `PagedDecodePlan::validate` rejects such plans before launch. The batched decode panics on a launch `Err`, so with this check those batches go to gather instead. - Docs: the `MLXCEL_PAGED_SLAB_BLOCKS` row in `docs/environment-variables.md`. - Tests are in a new `cache/paged_pool_offset_tests.rs`, not `paged_batch_decode_tests.rs`, which is already 599 lines. ## Verification On gfx1151, rebased on `9c0ae2e9` (after #2181). Review follow-up `c3fef346` changes comments and docs only: - `paged_pool_past_u32_elements_matches_gather` (ignored, about 17 GiB): f16 pool of 131,073 blocks, K/V only in the last block, v1 and v2 checked against a host reference. With main's bodies it fails with max error 0.456 for both kernels. With this PR it passes (guarded runs). It also confirms the last block reads back and row 0 (where a 32-bit base lands) is zero. - Source pin test: with only the HIP v2 body reverted it fails, naming that line. - Merge refusal test (lazy broadcasts) and plan-bound test pass. - `cargo test -p mlxcel-core --features rocm --lib -- paged`: 264 passed. Clippy on lib and tests is clean, and the script gates plus `verify-rocm-overlay` pass. - Decode: Llama-3.1-8B-Instruct-4bit, server `--parallel 4 --ctx-size 131072`, 4 clients at ~16K prompt, 128 tokens, fused v2 on both arms (the log shows `fused v2 launch`). A build with main's kernel bodies (this branch with the three kernel files reverted) and this PR were run as a pair inside one `rocm_gpu_guard.sh` window, three times, and all attempts were clean. Per-request decode tok/s was 14.0/13.9/14.0 before and 14.1/14.0/14.0 after. Both medians are 14.0, so there is no regression. `examples/paged_attention_kernel_bench` was not used: it keeps the 32-block default slab, so at batch 4 / 16K it measures gather. - `make verify-rocm` on `c3fef346` (with `MLXCEL_ROCM_SMOKE_MODEL=models/mlx/Qwen3-0.6B-4bit`): script gates, workspace clippy and smoke pass. Tests: 152 suites, 11984 passed, 5 failed, 383 ignored. The 5 failures are the Gemma 3 lookahead tests in `server::batch::scheduler` (from #2182). They fail the same way with every file of this PR reverted to `origin/main` `9c0ae2e9`, pass when run alone, and are filed as #2187. Found while writing the test: on ROCm, strided MLX copies of 2^32 or more elements fail to launch. That is filed as #2184, and the test avoids it. Not verified: Metal and CUDA are not available on this host. Their v1 and v2 partial pool-base lines in the table above changed and were only reviewed, not compiled or run. Closes #2153
18 tasks
inureyes
added a commit
that referenced
this pull request
Oct 6, 2026
The B9 observability tests armed the opt-in suppression counters with `set_var("MLXCEL_LANG_BIAS_COUNTERS", "1")`. The gate caches the environment in a process-wide `OnceLock`, so once any of those tests ran, every later decode with a token bias in the same test binary (`ignore_eos` installs one) left the batched fused sampler and with it the decode lookahead. In the single-threaded ROCm gate the observability tests sort before the scheduler tests, which made the five Gemma 3 lookahead tests from #2182 fail. A binary search over the 5236 preceding tests isolated `sampling_observability_tests::byte_fragment_suppression_counter_tracks_opt_in_entries`; any test in that file arms the gate.
The gate moves to `mlxcel_core::lang_bias_counters`, which adds a thread-local `scoped_override` RAII guard that wins over the cached environment value on the calling thread only and restores the previous setting on drop. The observability tests hold that guard for their whole body instead of mutating the environment. Production is unchanged: nothing outside tests changes the variable after startup. `MLXCEL_LANG_BIAS_COUNTERS` is now documented in docs/environment-variables.md.
Validated on gfx1151: the minimal pair fails before and passes after, and `cargo test -p mlxcel --lib --profile test-fast --features rocm -- --test-threads=1` reports 8849 passed, 0 failed.
Closes #2187
inureyes
added a commit
that referenced
this pull request
Oct 6, 2026
…2188) ## Summary The five Gemma 3 lookahead tests from #2182 failed in the full single-threaded `-p mlxcel --lib` run because `sampling_observability_tests` armed the opt-in lang-bias suppression counters with `set_var("MLXCEL_LANG_BIAS_COUNTERS", "1")`. The gate caches that variable in a process-wide `OnceLock`, so from then on every decode with a token bias (the victims use `ignore_eos`, which installs one) failed `row_supports_fused_batch_except_bias`, `lookahead_params` returned `None`, and the lookahead never primed. ## How it was found A binary search over the 5236 tests that sort before the victims (each step ran a half plus `lookahead_is_gated_on_the_rewind_capability` with `--exact --test-threads=1` on the test-fast binary) ended at `sampling_observability_tests::byte_fragment_suppression_counter_tracks_opt_in_entries`. Every test in that file arms the gate through `counter_lock()`. Running a victim alone with `MLXCEL_LANG_BIAS_COUNTERS=1` reproduces the same failure, which confirms the mechanism. ## Fix - The gate moves to a new `mlxcel_core::lang_bias_counters` module with a thread-local `scoped_override(enabled)` RAII guard. A live guard wins over the cached environment value on its own thread only, guards nest, and drop restores the previous setting. - The observability tests hold that guard (together with their existing counter lock) for the whole test instead of mutating the environment. Their sampling calls run on the test thread, so the override covers them; with the variable unset they would fail if the override did not take effect. - `config_supports_fused_batch_false_for_token_bias` in mlxcel-core pins the counters off, so an exported variable no longer flips it, and now also asserts that a biased row leaves the fused path while the counters are on. - `MLXCEL_LANG_BIAS_COUNTERS` is now documented in `docs/environment-variables.md`, including that it takes biased requests off the lookahead pipeline. Production impact: none. Nothing outside the tests changes the variable after startup, so a server that serves one family and then another sees the same setting throughout, and the override is never set in production code. The leak is backend-independent (pure Rust process state), so a single-threaded Metal or CUDA lib run, or a parallel run where an observability test happened to arm the gate first, could hit it too. ## Verification On gfx1151 (`--features rocm`, test-fast profile, `--test-threads=1`): - Minimal pair (`byte_fragment_suppression_counter_tracks_opt_in_entries` plus each of `model_owned_sequence_primes_the_decode_lookahead_only_with_a_rewind` and `lookahead_is_gated_on_the_rewind_capability`): 1 failed before, 2 passed after. - `cargo test -p mlxcel --lib --profile test-fast --features rocm --no-fail-fast -- --test-threads=1`: 8849 passed, 0 failed, 156 ignored (before: 8844 passed, 5 failed). - `sampling_observability_tests`: 6 passed; new `lang_bias_counters::tests::override_is_scoped_nested_and_thread_local` passes; `config_supports_fused_batch_false_for_token_bias` passes with and without `MLXCEL_LANG_BIAS_COUNTERS=1` exported. - `make verify-rocm` with `MLXCEL_ROCM_SMOKE_MODEL=models/mlx/Qwen3-0.6B-4bit` on the final head: OK. Script gates, fmt, clippy `-D warnings` and the smoke (32 tokens) pass; the workspace test run reports 11987 passed, 0 failed, 382 ignored across 152 test binaries (`-p mlxcel --lib`: 8849 passed, 0 failed, 156 ignored). Not verified: Metal and CUDA (not available on this host). The change is backend-independent Rust; no Metal or CUDA path is touched. Closes #2187
This was referenced Oct 7, 2026
inureyes
added a commit
that referenced
this pull request
Oct 7, 2026
Closes the ADR 0008 deferral for the model-owned families (issue #2172, Stage C part 2). Gemma 3's `Cache` and Llama 4's `Llama4Cache` implement the new `KvAttention` trait by matching to the inner cache: a global or dense layer runs `KVCache::attend`, a sliding layer the new `RotatingKVCache::attend`, a chunked layer the new `ChunkedKVCache::attend`. Both new entries write through `update_and_fetch`, so the #2182 decode undo log still records every speculative single-token write and every multi-token clear; `cache::attend_batched_rows` is the per-row batched loop that replaces the `model_owned` dispatch helpers, and `attend_batched` hands its non-pooled batches to it. `rg 'is_paged_backed\(\)|is_paged_decode\(\)' src/models` returns nothing: `gemma4_verify_rows` asks `KVCache::is_dense_fp16()`, a layout question. With no model reading it, `DecodeBatchContext` and the core `DecodeStorageBackend` are removed outright: `StepBatch` loses its `context`, the scheduler no longer builds one, the trait entry is `forward_batched_with_ids(input, seq_ids, caches, mask)`, and `forward_batched_with_context` folds into `forward_batched` across the VLM wrappers, qwen3_5, qwen3_moe and muse_glimmer. Routes that change op order, recorded in ADR 0009: the dense-pointer `paged_decode_attention_dense_compat` and `_rotating_compat` kernels (per-row C++ loops of block slices, a concat and one SDPA) are no longer selected on the paged backend; a Turbo4Asym Gemma 3 global layer takes the dequant-first variant `KVCache::attend` selects; Llama 4's RoPE layers project once per batch on the dense backend too. FP16 and sliding rows run the exact ops they ran, pinned bit for bit by new tests in `cache::attend`, `models::gemma3` and `models::llama4`, plus batched-versus-single-row decode tests on the synthetic models. The dense-compat profiler example and the rollout script that compared the two routes through the removed context are deleted; the kernels stay as the `ffi_tests` reference pair. Validated with `cargo check` and `cargo clippy -D warnings` (`--features cuda --lib --tests --bins --examples`); the module test run and the Gemma 3 engine-parity comparison follow in this PR.
inureyes
added a commit
that referenced
this pull request
Oct 7, 2026
) ## Summary Epic #2166 Phase 4b ([ADR 0009](docs/adr/0009-engine-step-api.md), amending ADR 0007 and 0008). `BatchScheduler` is split into policy and execution. Execution moves into a new `mlxcel_core::engine` module, and the scheduler drives the model only through it. A single sequence is a batch of one: `Engine::step` is the only decode entry for every row count. - **Engine** (`src/lib/mlxcel-core/src/engine/`). `Engine<M>` owns the model and the `CachePool`. - `open(SequenceSpec)`, `adopt`, `adopt_paged`, `close` (the old `release_sequence_caches`). - `prefill(&PrefillStep)` runs one `PrefillPlan` piece; the shared `piece_input` builds its input and mask. `prefill_cohort` runs the padded cohort, `complete_prefill` samples the first token, `trim_padding` undoes padding. - `step(&StepBatch { seq_ids, input }, &mut [StepRow<H>]) -> StepOutput` runs the forward, then for each row: mask, draw, `try_eval`, thinking override, logprobs, matcher, `finish_step`. A batch of one always takes this per-row chain. A larger batch takes one fused `[B, vocab]` draw when `shared_fused_params` admits every row; its tokens go through `try_eval` before readback. - `submit` plus `finish_rows` are the lookahead's split form. The forward runs inside `DecodeLookaheadAppendScope`, and `unwind_appends` trims the pool or calls `rewind_decode_appends` for a model-owned family. - `StepRow` carries the row's `RowSampler`, config, history, budget and an `H: StepRowHooks` (logit mask, override, matcher, first-token stamp, `FinishHooks`). `RowOutcome` carries the token, `Option<FinishCause>` and `Option<RowError>`. `RowError` is `Structured`, `Eval` or `BatchEval`; a batch-wide failure counts once against the health limit. `EngineError` (`MissingSequence`, `Batch`, `Open`, `Trim`, `Rewind`, `Eval`) is per sequence, and one failed row never aborts a batch. - **Scheduler.** - `step_rows.rs` builds rows and applies outcomes. Decode tick (single, batched, lookahead), full, chunked, planned, embedding and cohort prefill, the prompt-cache warm-up and the handoff call the engine. - It keeps admission, tick policy, preemption, prompt-cache lookup, donate and adopt, disaggregated handoff and the MTP/DFlash burst generators. Those burst adapters still run target forwards outside the engine (ADR 0009). - `rg -n '\.forward[a-z_]*\(|sample_token_[a-z_]*\(' src/server/batch/scheduler --glob '!*_tests.rs'` returns only two `plan.forwarded_len()` accessor hits. - The legacy `--no-batch` worker is the same scheduler at `max_batch_size=1`. - **Single row equals a batch of one, decided at the engine.** `LanguageModel::forward` stays the required method. Inverting it touches more than 200 implementations, and only the engine chooses between the two forwards. At B=1 the engine runs the family's single-row forward, as the provided batched entry does at `b == 1`. `single_row_batch_parity_tests` pins one-row batched logits bit for bit against it on real Qwen3 and Llama 3 checkpoints, with and without sequence ids. - **Cache-owned attention for the families #2210 deferred.** - The `KvAttention` trait is implemented for `KVCache`, `RotatingKVCache` and `ChunkedKVCache`. For `RotatingKVCache`, `update_and_fetch` stays the write path, so the #2182 decode-undo log records every speculative write and every clear. - `attend_batched_rows` is the shared per-row loop. - Gemma 3 and Llama 4 call the entry, the `model_owned.rs` dispatch helpers are gone, and `gemma4_verify_rows` asks `is_dense_fp16()`. `rg 'is_paged_backed\(\)|is_paged_decode\(\)' src/models` returns nothing. - **`DecodeBatchContext` and the core `DecodeStorageBackend` are removed.** - The trait entry is `forward_batched_with_ids`. The context override folds into `forward_batched` across qwen3_5, qwen3_moe, muse_glimmer, `loaded_model`, the VLM wrappers, multimodal dispatch and the pipeline runtime. - The server's `--decode-storage-backend` is unchanged. - Deleted: `examples/profile_paged_decode_kernel.rs` and `scripts/benchmark_paged_decode_rollout.sh`, which compared the removed compat kernels through the context. The kernels stay in core as the `ffi_tests` reference. - **Parity tooling.** `mlxcel-engine-parity` gains a `d:engine` arm (`engine_probe::engine_direct::DirectEngine`). ## Numeric changes These are not bit-identical to `main`. ADR 0009 lists them. 1. Gemma 3 and Llama 4 on the paged backend run per-row `attend` instead of the per-row C++ compat kernels. It is the same attention without the block concat. 2. The same applies to a Gemma 3 global layer in any Turbo mode with a dequant-first or compressed variant (Turbo4Asym, Turbo4Delegated, and sparse-V behind its env gates), and to a Turbo-mode Llama 4 dense layer. They take the variant `KVCache::attend` selects, as Qwen3 already did. 3. Llama 4's RoPE layers (3 of every 4) run the whole block batched on the dense backend too, MoE feed-forward included. FP16 and Int8 global layers and every sliding or chunked layer run the same ops as before. Tests pin them bit for bit. ## Changes during review - **Review, HIGH (36be06c).** The first version let a one-row batch take the fused draw, whose readback cannot report an MLX error. A throw at B=1 would then have aborted the process instead of failing the request (#822). A batch of one now always runs the per-row chain (pinned by a test), and the B>1 fused draw also goes through `try_eval`. - **Review, MEDIUM (36be06c).** - The fused-eligibility rule is now one function, called by both the lookahead gate and the sync step. - Row eval failures carry `main`'s `inference backend error: X` wording again. - The first-token stamp runs after the matcher, and a successful prime clears the failure counter. - **Review, model families (900e8ac, daf5dac).** - Added Int8 and Turbo4Delegated route tests. - Added a real-checkpoint B=2 vs B=1 scheduler test. - Corrected the op-order list. - Removed the dead `gemma3::Attention::window_size`. - Split the engine prefill half into `engine/prefill.rs`, made `get_rows_mut` single-pass, and cleaned up stale comments. - **Security, HIGH (4266bfc).** One throw in the fused draw used to count as B eval failures, so a single transient error on a batch of 8 or more drained every request and shut the scheduler down. It is now one `RowError::BatchEval`, counted once. - `step` refuses a row count that differs from `seq_ids`. - A short fused readback or pipelined token count fails every row instead of silently dropping rows. - **Finalizer (bf50f8e, 7e536b3).** A test for the short-readback path, plus ADR 0009 and comment alignment. - **Merge from `main` (dc60407).** Clean. ## Open follow-ups - **Paged backend for Gemma 3 and Llama 4.** Both still report `supports_paged_decode_backend() == true`, so `auto` picks paged and they pay pool allocation and per-step sync, but no attention path reads the pool any more. To be decided by the epic's end-of-run measurement. - **Compat kernels.** Removing the now reference-only kernels and their bridge entries is a separate cleanup. ## Test plan All on GB10 under `gpu-lock`, after merging `main`, each CUDA test with `-- --test-threads=1`. - [x] `cargo fmt --all -- --check`; `cargo clippy --profile test-fast --features cuda --lib --tests --bins --examples -- -D warnings` and `-p mlxcel-core --lib --tests`; `scripts/insert_apache_header.py --check`; `--test vlm_wrapper_capability_delegation`, `dead_doc_pointers`, `model_loader_stdout_guard` - [x] mlxcel-core: `engine::`, `cache::attend`, `mla::`, `cache::paged_batch_decode`, `cache::decode_undo`, `cache::paged_detach`, `sampling`, `generate::`, `prefill`, `decode_finish`, `ffi_tests::test_paged_decode` - [x] Root crate, one module at a time: `models::{qwen3, llama3, helium, deepseek_v2, gemma3, llama4, gemma4, muse_glimmer, afmoe}`, `multimodal::`, `server::batch::scheduler` (187), `server::batch::{active, sequence}`, `finish_step_tests`, `speculative_burst_tests`, `distributed::{disaggregated, pipeline}`, `prefill_span_coverage`, `cli_input`, `engine_probe`, `memory_estimate` - [x] Real checkpoints, `MLXCEL_REQUIRE_MODELS=1 MLXCEL_SDPA_DETERMINISTIC=1`: `single_row_batch_parity` (Qwen3-1.7B and Llama-3.2-1B 4-bit, one-row batched logits bitwise equal to the single-row forward, with and without sequence ids); `scheduler_real_batch_parity` (Gemma-3-1B 4-bit, two concurrent greedy requests at B=2 give the same 48-token streams as each alone, paged and dense) - [x] Release `mlxcel-engine-parity -n 400` under `MLXCEL_SDPA_DETERMINISTIC=1`: CLI = server dense = server paged = direct engine for greedy and seeded-penalties-DRY on Qwen3-1.7B (10 of 12 pairs identical), Llama-3.2-1B (11 of 12) and Gemma-3-1B (11 of 12); the divergent pairs are the documented prompt-cache rows, unchanged from the Phase 0 baseline (Qwen3 greedy at token 0, 4792 vs 785, and seeded at 11; Llama seeded at 25; Gemma 3 seeded dense vs cache miss at 51, the same before and after the Gemma 3 migration) - [ ] Throughput against the 1.0 percent threshold, plus the paged-backend question for Gemma 3 and Llama 4: the epic's end-of-run measurement on a quiet host Closes #2172
5 tasks
6 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
Gemma 3 decodes on the lookahead pipeline again, now with a teardown that rewinds its model-owned state exactly, including a sliding window the decode has wrapped. On GB10 the issue's protocol (gemma-3-4b-it-4bit, 200 tokens, default flags) runs at 87.3 tok/s, against 87.6 for the pre-#2139 binary and 76.2 for force-sync, with greedy output byte-identical to
MLXCEL_FORCE_SYNC=1.RotatingKVCachegets an opt-in undo log (cache/decode_undo.rs): per single-token write the starting cursors, plus a copy of the overwritten[B, H, 1, D]rows when the write lands on a valid slot inside aDecodeLookaheadAppendScope(the scheduler's prime forward).rewind_decode_writes(n)restores rows newest first and the exactoffset/idx, and refuses with the cache untouched under speculative buffering, non-FP16 storage, a disabled log,n > offset, or a write the log does not cover. Any other mutation clears the log.LanguageModel::supports_decode_lookahead_rewind/rewind_decode_appends, delegated inLoadedModeland the VLM wrapper. Gemma 3 opts in when every sliding layer is FP16, logs depth 2 on scheduler sequences only (the CLI slot keeps none), and trims global layers withKVCache::trim.lookahead_paramsadmits a model-owned family only with that capability, including theModelOwnedallocation at--parallel 1.apply_lookahead_trimcalls the rewind beforesync_sequence_storage; onErrit logs, finishes the request with an error (overriding a same-ticklength/stopso nothing is donated), and drops the id from the re-dispatch.The row copies are lazy MLX nodes reading the pre-write buffer. Left unevaluated they pin that buffer, so the write's
slice_updatecannot reuse it in place and copies the whole window every step. Measured on a 1906-token prompt (every write overwrites a valid slot): unflushed 64.5 tok/s, below force-sync; flushed in oneasync_evalper forward 72.4; no copies at all (unsound) 76.9. This also rules out the issue's rejected alternative of retaining pre-write handles: it pins the same buffers. Copies are taken only inside the prime forward, so force-sync and requests the pipeline does not admit pay nothing.Measurements (GB10, CUDA,
mlxcel-server, default flags)Interleaved rounds, rotated order, fresh server per arm and round, median of 3 requests per arm, host-idle gate before each arm (CPU busy < 12%; an ungated first pass on a loaded host showed 40-60 tok/s outliers in both lookahead arms).
nullis a byte-identical copy of thenewbinary,refis12601f86(pre-#2139),baseis0ee13dfe.The issue's bar (within 3% of 84.1-84.5) is met with margin, and the null arm puts the method's floor under 1%. Past the window the restored pipeline costs 5.7% against the pre-#2139 binary: that is the price of the row copies plus their extra
async_eval, which the unsoundrefnever paid (its output differs there). It is still 8% faster than sync.Llama 3.2 1B (dense KV, gated, n=4): new 270.4, null 268.0, base 270.0, sync 210.0 tok/s; paired new vs base -0.3 to +0.5%; identical output in every arm.
Correctness
--parallel 4(default) and at--parallel 1.refdiffers on the long and concurrent requests (the fix(prompt-cache): completion-origin snapshots claim one more token than their caches hold #1754 desync). Concurrent requests are queued behind a long blocker prefill so both arms see the same batch history; without that, force-sync alone produced two different outputs across runs.scheduler_model_owned_lookahead_tests(new) uses the pad-trim fixture (one sliding, one global layer), not thescheduler_model_owned_cache_tests.rs:75fixture the issue names: that fixture'ssliding_window_pattern: 1makes its only layer aCache::Standard, so it cannot wrap. A real Gemma 3 with a window of 8 runs pipelined and force-sync in lockstep, single sequence (ModelOwnedallocation) and four concurrent (paged override), with an admission teardown and two-position finish teardowns after the wrap. At every tick without a live lookahead the offsets, cursor, whole sliding buffer and live global K/V are bit-equal, and tokens match. With the row restore removed both tests fail. Also: the capability gate (INT8 sliding layer stays sync), the trait default, and the error path.cache::decode_undo_tests: rewinds of one and two writes after the wrap, across the cursor rollover, after an over-window prefill, across the warmup boundary, refusals untouched, scope behaviour.model_owned_sequence_never_primes_the_decode_lookaheadis replaced bymodel_owned_sequence_primes_the_decode_lookahead_only_with_a_rewind; the fix(prompt-cache): completion-origin snapshots claim one more token than their caches hold #1754length, one-token and EOS snapshot tests pass unchanged on the pipelined path.Test plan
mlxcel-corecache::(556),server::batch(495),models::gemma3,vision::pass with--test-threads=1undergpu-lockcargo clippy --release --features cuda --lib --tests -- -D warnings(both crates) andcargo fmt --checkNot verified on this host
0ee13dfe;e466f511(fix(cuda): add MLXCEL_SDPA_DETERMINISTIC for reproducible decode #2162, CUDA SDPA switch) landed after and was not rebuilt here.Closes #2159