Skip to content

fix(cache): bound the turbo4 sliding append to visible_len - #2330

Merged
inureyes merged 2 commits into
mainfrom
fix/issue-1793-turbo4-sliding-visible-len
Oct 15, 2026
Merged

inureyes merged 2 commits into
mainfrom
fix/issue-1793-turbo4-sliding-visible-len

Conversation

@inureyes

@inureyes inureyes commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Summary

With --kv-cache-mode fp16+turbo4, update_turbo4_concat concatenated the whole physical key buffer onto a multi-token append, while every mask is sized from visible_len(). After a decode step grew the buffer or a speculative trim rewound it, a Gemma 4 MTP verify block attended zero-filled growth slots and rolled-back draft keys. After a wrap, prior keys came back in physical order, and an over-window return was clamped to max_size (#678).

  • visible_fp16_prefix_for_concat becomes RotatingKVCache::visible_window(arrays, max_keep). It returns the newest visible slots in chronological order, sliced the same way from any set of per-token buffers. update_concat, update_turbo4_concat (keys plus v_packed, v_norms, v_rescale) and enable_speculative_buffer all call it, so turbo keeps the same max_size - 1 prior keys as FP16, then returns and stores every new key.
  • Both single-token pre-trims (update_in_place, update_turbo4_in_place) cut an over-window buffer down to the newest max_size slots before idx (over_window_keep_range). The turbo path had no pre-trim, so a first install longer than the window kept returning its surplus slots, and the new over-window store needs one too. Using idx rather than the physical end matters after a rollback: when a trim follows an over-window append, the rolled-back draft keys would otherwise survive, which was also true for FP16 unbuffered caches. The turbo append now requires v_rescale to stay in lockstep with v_norms.
  • The first_cache_live_len doc comment is corrected.
  • examples/logit_trace gains two settings. MLXCEL_TRACE_KV_CACHE_MODE injects the resolved per-layer modes into model-owned caches. MLXCEL_TRACE_DECODE_STEP=1 ends the context pass with a single-token step. Runtime warnings now go to stderr. Both settings are documented in docs/benchmarks.md.

Tests (each fails with the fix reverted)

  • cache::rotating_turbo_window_tests (6 tests) asserts that turbo returns the same keys as FP16 and a matching V after decode growth, a trim rollback, a wrap, an over-window append, and an over-window install. With the fix reverted, all 5 fail; for example, "turbo returned 64 keys where FP16 returned 10". With only the pre-trim reverted, 3 fail. decode_after_over_window_append_and_trim_drops_rolled_back_keys checks append, trim, then decode against a cache that never saw the rolled-back keys, in both modes, and fails when the pre-trim keeps the physical end.
  • first_cache_live_len_sliding_matches_returned_keys_turbo4 (Gemma 4, append, trim, append) fails with "mask with 11 key columns, but the turbo append returned 266 keys". The Gemma 3 tests turbo_live_len_matches_the_keys_a_multi_token_append_returns and turbo_live_len_matches_the_keys_after_a_trim_rollback also fail.
  • On the rebased tree, the cache filter in mlxcel-core passes 638 tests. In the main lib, the models::gemma4, models::gemma3, turbo, live_len, gemma4_mtp, speculative, rotating, models::laguna, models::muse and models::afmoe filters all pass. Clippy (-p mlxcel-core --lib --tests, and --lib --tests --example logit_trace), fmt and the scripts/ci checks are clean.

Real checkpoint (GB10, gemma-4-26b-a4b-it-4bit, drafter mlx-community/gemma-4-26B-A4B-it-assistant-bf16 downloaded)

These runs used the first commit. The review follow-up changes only the pre-trim of buffers longer than the 1024-token window, and none of these runs reaches such a buffer.

  • Teacher-forced trace. Run with MLXCEL_SDPA_DETERMINISTIC=1 MLXCEL_TRACE_START_TOKEN=512 MLXCEL_TRACE_DECODE_STEP=1 MLXCEL_TRACE_KV_CACHE_MODE=fp16+turbo4 logit_trace MODEL docs/architecture.md 8 40 8 512, with the fix and with it reverted. Decided positions change: 23 of 180 positions (gap ≥ 2) flip between the two arms. Against the FP16 arm, 22 of 181 decided positions disagree when reverted and 19 of 181 with the fix. The largest disagreeing gap falls from 11.9 to 7.0, and the perplexity shift falls from -41.9% to -13.5%. With no decode step the two arms are byte-identical, so the difference comes from the growth slots. The FP16 arm is self-parity identical.
  • MTP server run. mlxcel-server --kv-cache-mode fp16+turbo4 --model-draft ... --draft-kind mtp with MLXCEL_MTP_ALLOW_INEXACT=1, two 400-token greedy chats. Neither arm logs a mask/key mismatch warning. Below the 1024-token sliding window these verify blocks run maskless, so the reverted arm attends the extra keys without a warning. Its output text differs from the fixed arm, and acceptance rises with the fix (0.55 to 0.65, and 0.80 to 0.92).
  • Not demonstrated. The warning branch needs a context past the window. On this host, Gemma 4 26B with fp16+turbo4 aborts at that point on main and with this change: [scaled_dot_product_attention] Mask type must promote to output type float32, thrown from gemma4::Attention::attend. It reproduces without a drafter on a 1.7k-token prompt, and FP16 KV does not abort. It is a separate pre-existing defect.

Closes #1793

With --kv-cache-mode fp16+turbo4 the multi-token append of a sliding RotatingKVCache concatenated the whole physical key buffer: decode-growth zero slots, keys a speculative trim had rolled back, physical rather than chronological order after a wrap, and a return clamped to max_size against the #678 rule. Masks are sized from visible_len(), so a Gemma 4 MTP verify block attended keys outside the window it was meant to see.

The FP16 prefix helper is generalized into RotatingKVCache::visible_window, which slices the newest visible slots in chronological order identically from any set of per-token buffers. update_concat, update_turbo4_concat (keys plus v_packed, v_norms, v_rescale) and enable_speculative_buffer share it, so turbo keeps exactly the max_size - 1 prior keys FP16 keeps and returns every new key. The turbo decode path now pre-trims an over-window buffer as the FP16 one does; without it a first install longer than the window kept returning the surplus slots on every decode step. The first_cache_live_len doc comment is corrected.

examples/logit_trace gains MLXCEL_TRACE_KV_CACHE_MODE (injects the per-layer modes into model-owned caches) and MLXCEL_TRACE_DECODE_STEP (ends the context pass with a single-token step), and logs runtime warnings to stderr.

Tests: an FP16-versus-turbo key-identity suite in mlxcel-core (decode growth, trim rollback, wrap, over-window append, over-window install) and turbo variants of the Gemma 3 and Gemma 4 live-length tests including a trim rollback; all fail with the fix reverted.

Closes #1793
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Oct 15, 2026
The single-token pre-trim of an over-window rotating buffer kept the newest max_size physical slots and set idx to max_size. A trim after the over-window append had rewound idx past rolled-back draft keys, so the next decode step kept those keys and then overwrote the oldest live slot. Turbo4Asym reaches this now that its multi-token append stores the oversized buffer like FP16 does; FP16 unbuffered caches had the same flaw.

Both pre-trims (update_in_place and update_turbo4_in_place) now keep the newest max_size slots before idx through over_window_keep_range. The turbo append also requires v_rescale in lockstep with v_norms instead of storing a v_rescale shorter than the keys.

decode_after_over_window_append_and_trim_drops_rolled_back_keys compares the decode step after append, trim and decode against a cache that never saw the rolled-back keys, in both modes; it fails with the physical-end pre-trim.

Refs #1793
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 15, 2026
@inureyes
inureyes merged commit 86e34ff into main Oct 15, 2026
52 of 53 checks passed
@inureyes
inureyes deleted the fix/issue-1793-turbo4-sliding-visible-len branch October 15, 2026 21:28
inureyes added a commit that referenced this pull request Oct 16, 2026
## Cause

The issue's hypothesis (a float32 q/k/v) was wrong. Logging the SDPA call on the crashing layer showed `q` bf16 `[1,16,1980,256]`, `k`/`v` fp16 `[1,8,1980,256]`, mask f32 `[1980,1980]`. TurboQuant caches always return fp16 K/V, so a bf16 model hands SDPA a bf16 query over fp16 K/V. SDPA attends in `result_type(q, k, v)`, which is float32 for bf16 + fp16. The bridge cast the additive mask to the query's dtype (bf16), and the CUDA overlay's patched promotion table keeps bf16 + float32 at bf16, so the mask no longer promoted into the float32 output and SDPA threw. Below the window Gemma 4 attends maskless, which is why only prompts past 1024 tokens crashed. Metal's unpatched table promotes bf16 + float32 to float32, so it was CUDA-only.

## Fix and why at this boundary

The bridge (`fast_scaled_dot_product_attention`, the sinks variant, the Metal 4 bridge) is the one place that already adapts mask dtypes to MLX's contract, and its stated purpose was to satisfy "must promote to output type". It picked the wrong target. A shared `sdpa_mask_for_inputs` now casts floating masks to `result_type(q, k, v)`. The sinks bridge passes attention sinks through the same helper, because SDPA applies the same promotion rule to them (review finding; GPT-OSS greedy output on `gpt-oss-20b-mxfp4-q4` is byte-identical before and after). When q/k/v share a dtype this is the same cast as before. `mask_in_score_dtype` on the chunked path now casts to the query dtype only when K and V share it.

Rejected: casting K/V back to bf16 in Gemma 4 (fixes one model, adds a per-layer K/V copy, and changes turbo4 numerics everywhere), and making turbo caches return the input dtype (changes the cache's fp16 contract that fused turbo kernels rely on).

## Validation

- New tests `layers::tests::additive_mask_with_bf16_query_over_fp16_kv_is_accepted` and `gemma4_unified_mask_tests::turbo4_past_window_sliding_mask_is_accepted_by_sdpa` (Turbo4Asym `RotatingKVCache` with bf16 K/V, past-window `create_sliding_window_prefill_mask`, `trim_mask_to_keys`, `attention_from_ptr`, compared with float32 attention). With the bridge change reverted both abort with `Mask type must promote to output type float32`. With it, they pass.
- `layers::tests` (100) and `models::gemma4` (120) pass. Clippy (`-p mlxcel-core --lib --tests`, root `--lib --tests`) and fmt are clean, and so are the `scripts/ci` checks.
- GB10, `~/models/mlx/gemma-4-26b-a4b-it-4bit`, `mlxcel-server`, 1987-token prompt, 300 tokens at temperature 0, `MLXCEL_SDPA_DETERMINISTIC=1`. On main, `--kv-cache-mode fp16+turbo4` aborts. With the fix it completes, both with no drafter and with `--model-draft ~/models/mlx/gemma-4-26b-a4b-it-assistant-bf16 --draft-kind mtp` (`MLXCEL_MTP_ALLOW_INEXACT=1`). The turbo4 output is coherent and matches the FP16 KV arm for the first 287 characters, then diverges on wording, as expected from 4-bit V quantization.
- Follow-ups from review, not in this PR: the CUDA chunk gate (`cuda_sdpa_materializes_scores`, `materializing_sdpa_query_chunk`) judges flash eligibility and score bytes from q's dtype, which understates mixed bf16/fp16 attention that runs in float32. The softcap composite still casts its mask to q's dtype and returns v's dtype. The CUDA `dtype.cpp` overlay header says bf16 + fp16 gives bf16, while its table gives float32.
- A `CHANGELOG.md` entry is added under Fixed.
- Acceptance criterion 4 (#1793) was re-checked with a reverted-#2330 build. Results are on #1793.

Closes #2336
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:medium Medium priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(cache): bound the turbo4 sliding append to visible_len

1 participant