Repository navigation
fix(cache): bound the turbo4 sliding append to visible_len - #2330
Merged
Merged
Conversation
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
2 of 3 tasks
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
This was referenced Oct 15, 2026
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
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
With
--kv-cache-mode fp16+turbo4,update_turbo4_concatconcatenated the whole physical key buffer onto a multi-token append, while every mask is sized fromvisible_len(). After a decode step grew the buffer or a speculativetrimrewound 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 tomax_size(#678).visible_fp16_prefix_for_concatbecomesRotatingKVCache::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 plusv_packed,v_norms,v_rescale) andenable_speculative_bufferall call it, so turbo keeps the samemax_size - 1prior keys as FP16, then returns and stores every new key.update_in_place,update_turbo4_in_place) cut an over-window buffer down to the newestmax_sizeslots beforeidx(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. Usingidxrather than the physical end matters after a rollback: when atrimfollows an over-window append, the rolled-back draft keys would otherwise survive, which was also true for FP16 unbuffered caches. The turbo append now requiresv_rescaleto stay in lockstep withv_norms.first_cache_live_lendoc comment is corrected.examples/logit_tracegains two settings.MLXCEL_TRACE_KV_CACHE_MODEinjects the resolved per-layer modes into model-owned caches.MLXCEL_TRACE_DECODE_STEP=1ends the context pass with a single-token step. Runtime warnings now go to stderr. Both settings are documented indocs/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_keyschecks 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 teststurbo_live_len_matches_the_keys_a_multi_token_append_returnsandturbo_live_len_matches_the_keys_after_a_trim_rollbackalso fail.cachefilter in mlxcel-core passes 638 tests. In the main lib, themodels::gemma4,models::gemma3,turbo,live_len,gemma4_mtp,speculative,rotating,models::laguna,models::museandmodels::afmoefilters all pass. Clippy (-p mlxcel-core --lib --tests, and--lib --tests --example logit_trace), fmt and thescripts/cichecks are clean.Real checkpoint (GB10,
gemma-4-26b-a4b-it-4bit, draftermlx-community/gemma-4-26B-A4B-it-assistant-bf16downloaded)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.
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.mlxcel-server --kv-cache-mode fp16+turbo4 --model-draft ... --draft-kind mtpwithMLXCEL_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).fp16+turbo4aborts at that point onmainand with this change:[scaled_dot_product_attention] Mask type must promote to output type float32, thrown fromgemma4::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