Skip to content

feat(core): adopt native window SDPA for Metal prefill - #2646

Merged
inureyes merged 8 commits into
mainfrom
feature/issue-2621-native-window-sdpa
Oct 26, 2026
Merged

inureyes merged 8 commits into
mainfrom
feature/issue-2621-native-window-sdpa

Conversation

@inureyes

@inureyes inureyes commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Summary

  • mlxcel_core::window_sdpa routes a causal multi-query prefill whose keys outgrow the sliding window either through upstream MLX's native window_size with mask_mode = "causal" (Adding sliding window attention ml-explore/mlx#4734) or through the explicit full-width windowed mask of before (kept byte for byte). Softcap, sinks, extra mask arrays, q_len <= 8, queries longer than keys, empty batches, head dims outside the full-kernel set and every non-Metal backend keep the legacy route by construction.
  • MLXCEL_NATIVE_WINDOW_SDPA (0, 1, auto, default auto) selects the route; auto takes the native entry only where MLX's own ScaledDotProductAttention::use_fallback reports a fused kernel. That verdict comes from a shape probe that is memoized per thread (bounded at 64 entries, keyed on shape, dtypes and arm), returns false for degenerate shapes, and catches MLX exceptions so it can never abort across the cxx boundary. An unknown env value warns once and runs auto. MLXCEL_LOG_WINDOW_SDPA prints per-dispatch route evidence (shapes, dtypes, window; no prompt data). Both variables are in docs/environment-variables.md.
  • RotatingKVCache::attend carries the ring's window for an unmasked over-window multi-token step (it ran unmasked, non-causal attention before; only Gemma 3 can reach it, and before this PR every Gemma 3 path built the mask so the branch was unreachable). Gemma 3, its stage model and VLM backbone, and Gemma 4's text-only prefill skip building the sliding mask when the plan is native, so production prefill reaches the route.
  • The model-level plan uses the K/V dtype the sliding caches actually return (RotatingKVCache::fetched_kv_dtype: f16 for fp16+turbo4, the input dtype otherwise) and goes native only when every sliding cache agrees (--turbo-boundary-v mixes modes per layer). The plan and each layer's decision therefore match, so TurboQuant modes keep one mask build per forward instead of rebuilding it per layer.
  • On the pinned MLX at pre-M5 Metal, head dim 256 (every cached sliding-window checkpoint) is fused only for a fresh f16/bf16 prefill of 2048 rows or more, so with DEFAULT_PREFILL_CHUNK = 2048 the route engages on a prompt's first chunk and continuation chunks stay legacy; head dim 128 is fused at any width.

Measurements (M1 Ultra, docs/benchmark_results/native-window-sdpa-m1ultra-2026-10-26.md)

  • Enablement criterion, fixed before timing: (a) correctness suite at stated tolerances, (b) 0 logit-trace disagreements on decided positions, (c) a repeatable full-model prefill gain of at least 3% with non-overlapping ranges on at least one eligible shape and no eligible shape slower than its noise band. All three hold; (c) rests on one shape (Gemma 4 E4B, 2327 to 2257 ms median, 3.0%), which the report states.
  • Kernel level: on the shapes auto selects, 0.50x to 0.11x of the legacy time at W=512 and 0.89x to 0.20x at W=1024, call peak memory 94 MiB to 26 MiB (Gemma 3 1B, 2048 rows) and 5376 MiB to 640 MiB (31B geometry, 8192 rows); graph-fallback shapes neutral to 4% slower, which auto keeps legacy; head dim 128 0.43x to 0.06x.
  • Full model: Gemma 4 E4B prefill -3.0% at 2105 tokens (n = 6, non-overlapping ranges), 31B -5.8% to -13.7% at 4129 and 8187 tokens (n = 2, large legacy-arm variance, direction only), Gemma 3 1B inside its 2% to 3% noise band; decode and process RSS unchanged; auto dispatch counts 22/35/50 per prompt, all fused.
  • Logit trace (--decided 2, widths 2048 and 4096, route lines confirm native_fused=true): 0 disagreements on decided positions for Gemma 3 1B (f16, 24/8192 near-tie flips, all rank 2) and Gemma 4 E4B (bf16, 0 of 3150 decided); the reverted arm against itself is byte-identical; width 512 (graph fallback on both arms) identical in effect.
  • Behavior change: greedy text on bf16 Gemma 4 differs from the previous release at near-tie positions (MLX's graph fallback rounds scores and probabilities to the activation dtype; the fused kernel keeps f32). Gemma 3 1B is byte-identical across arms. MLXCEL_NATIVE_WINDOW_SDPA=0 restores the previous route.
  • Not run: M5/NAX hosts (the pinned dispatch fuses head dim 256 at every width there, so auto would engage on more shapes and needs its own measurement), CUDA and ROCm (unchanged by construction), any head-dim 128 sliding-window checkpoint at the model level, and TurboQuant cache modes timed in either arm.

Changes during review

  • Model-level plan now accounts for the cache's K/V dtype and requires agreement across sliding caches; before, fp16+turbo4 on a bf16 model planned native and then declined in every sliding layer, rebuilding the mask per layer.
  • Fused probe memoized and made exception-safe; eligibility rejects empty batches and zero query heads.

Test plan

  • cargo test --workspace --profile test-fast --features metal,accelerate --no-fail-fast on cc18090: 13896 passed, 0 failed over 176 binaries
  • cargo clippy --workspace --all-targets -- -D warnings and cargo fmt --check clean
  • window_sdpa_tests:: (19): native vs legacy vs f64 host reference over 8 shapes at f32/f16/bf16, MHA/GQA, W=1, continuation, rotating-cache wrap, trim and decode; invisible keys bitwise inert; eligibility exclusions; cache-mode plan dtype; probe memo bounds and degenerate shapes
  • attend_tests::batched_paged_one_row_is_one_pooled_launch failed once in an earlier full run (process-global paged launch counter, code this PR does not touch) and passed on every rerun, including both later full gates
  • Real-model runs on gemma-3-1b-it-4bit, gemma-4-e4b-it-4bit, gemma-4-31b-it-4bit with route evidence from MLXCEL_LOG_WINDOW_SDPA

Closes #2621

Upstream MLX takes a `window_size` argument at `fast::scaled_dot_product_attention` since ml-explore/mlx#4734, and the pin bump in #2614 kept every mlxcel call site at `-1`. A causal multi-query prefill over a sliding window therefore still built a full-width `[q_len, k_len]` additive mask and ran the array-mask SDPA, which on Metal never reaches the steel kernel's window band skipping.

`mlxcel_core::window_sdpa` is now the one place that decides, for the over-window prefill branch of `causal_attention`, between that legacy mask route (kept byte for byte) and MLX's `window_size` with `mask_mode = "causal"`. The decision is explicit about what the call carries: a softcap, a sink, an extra mask array, a query block of 8 rows or fewer, queries longer than the keys, an unsupported head dim or dtype, or any non-Metal backend keeps the legacy route, so decode, speculative verify, padding and CUDA/ROCm are unchanged. `MLXCEL_NATIVE_WINDOW_SDPA` (`0`, `1`, `auto`) selects the route; `auto` also asks MLX's own `use_fallback` through a new shape probe and only takes the native entry where a fused kernel runs. `MLXCEL_LOG_WINDOW_SDPA` prints the dispatch evidence.

`RotatingKVCache::attend` now carries the ring's window for an unmasked over-window multi-token step instead of running unmasked attention, and Gemma 3, the Gemma 3 VLM backbone and Gemma 4's text-only prefill skip building the sliding mask when the plan is native, so the production prefill reaches the route rather than only a helper.

`window_sdpa_tests.rs` checks the eligibility matrix, the mode plan, the native entry against the legacy mask and an f64 host reference at f32/f16/bf16 over fresh, continuation, W=1 and long-block shapes, bitwise inertness of invisible keys, and the rotating cache's prefill, continuation, decode and trim sequence. `examples/window_sdpa_microbench.rs` is the kernel-level A/B harness.

Refs #2621
… auto

Report and raw artifacts for the native sliding-window SDPA route (#2621) on an Apple M1 Ultra at MLX pin `7ca40033`, with the enablement decision the code already carries (`MLXCEL_NATIVE_WINDOW_SDPA` defaults to `auto`).

Kernel level (`examples/window_sdpa_microbench`, 5 interleaved samples per arm): where the native arm reaches the fused steel kernel and the legacy mask arm does not, which on this pre-NAX GPU is every fresh head-dim 256 prefill of 2048 rows or more, the native entry runs in 0.50x to 0.11x of the legacy time at W=512 and 0.89x to 0.20x at W=1024, with 3.5x to 8x less peak memory; where both arms are the graph fallback (every head-dim 256 continuation chunk) it is neutral to 4% slower, which is why `auto` keeps the legacy route there; at head dim 128 it is 0.43x to 0.06x on every shape.

Full model (`mlxcel generate`, 64 greedy tokens, arms alternated, fresh process per run): under `auto` the route engages on the fresh 2048-token chunk of every sliding layer and MLX reports each dispatch fused; Gemma 4 E4B prefill gains 3.0% at 2105 tokens with non-overlapping ranges at n = 6, the 31B rows point the same way at n = 2, Gemma 3 1B stays inside its noise band, and decode is unchanged everywhere.

Teacher-forced logit traces at widths 2048 and 4096 (`--decided 2`) show zero disagreement on decided positions for the f16 Gemma 3 1B and the bf16 Gemma 4 E4B; every disagreement is a near-tie flip from the graph fallback's activation-dtype rounding of scores, so greedy text on bf16 Gemma 4 can differ from the previous release at those positions, as the report states. M5, CUDA and ROCm are recorded as not run.

Refs #2621
@inureyes inureyes added status:review Under review type:performance Performance improvements priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:macos macOS (Apple Silicon) specific area:benchmark Benchmark harness and performance measurement (bench_*.sh, /update-benchmarks) labels Oct 26, 2026
…ow SDPA report

The greedy-text paragraph now gives the first differing generated word per Gemma 4 pair as measured (E4B at word 24, 12 and 24; the 31B inside a repetition loop that every arm enters under the raw-document prompt), and the paged launch-counter test note no longer claims a run on `main` that was not made.

Refs #2621
The report now says that windows at or above the visible keys were not timed (both arms are plain causal there), that quantized KV modes decline the native plan at the layer and rebuild the mask per layer unmeasured, that on an M5 host the native entry sits outside the `MLXCEL_LOG_NA_ATTENTION` and `MLXCEL_METAL4_ATTENTION` coverage so `MLXCEL_NATIVE_WINDOW_SDPA=0` is the switch there, and that the paged launch-counter failure is consistent with a shared-counter race rather than shown on `main`. The `metal4_attention` and `causal_window_attention` comments name the route the unmasked over-window prefill now takes.

Refs #2621
Gemma 3 and Gemma 4 decide once per forward whether to skip the sliding mask, planning the native window route from the activation dtype. A `fp16+turbo4` rotating cache returns FP16 K/V, so under bf16 activations MLX promotes the call to float32 and serves head dim 256 from its graph fallback: the model planned native, every sliding layer declined, and the mask was rebuilt per layer instead of once per forward.

`RotatingKVCache::fetched_kv_dtype` states the dtype each mode returns, `WindowSdpaShape::with_kv_dtype` carries it, and the four model-level plan sites (Gemma3Model, Gemma3StageModel, Gemma3Backbone, Gemma4TextModel) read it, so that combination now plans legacy up front. A new test checks, for every KV cache mode and activation dtype, that the planned shape equals the one read off the arrays the ring returns; it fails with the Turbo4Asym mapping reverted.

Also links the MLX dispatch source as a GitHub URL in the report, records that criterion (c) is met at its margin, and adds Gemma 3's CacheInterface impl to the `Used by` of `RotatingKVCache::attend`.

Validated with window_sdpa_tests (14), models::gemma3 and the Gemma 4 mask tests, clippy -D warnings on mlxcel-core and mlxcel lib and tests, and fmt.

Refs #2621
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Route causal multi-query sliding-window prefill on Metal through MLX's native window_size where it is eligible and measured to help, keeping the explicit-mask route for every other case and as an A/B arm.

Findings Addressed

  • With fp16+turbo4 on a bf16 model (Gemma 4), the model-level plan read the activation dtype while the ring returns FP16 K/V. MLX promotes that call to float32, which at head dim 256 runs the graph fallback, so every sliding layer declined and rebuilt the mask (one build per sliding layer instead of one per forward). The plan now reads RotatingKVCache::fetched_kv_dtype, and a test checks the planned shape against the arrays every cache mode returns (12d8b8d) (HIGH)
  • Report cited the MLX dispatch source as a bare repository path; now a GitHub URL (12d8b8d) (LOW)
  • RotatingKVCache::attend Used by: omitted Gemma 3's CacheInterface impl (12d8b8d) (LOW)

Remaining Items

  • TurboQuant cache modes are not timed under either arm. The plan now matches the layer by construction, but there is no speed measurement for them (LOW)
  • The default-on decision rests on one shape (Gemma 4 E4B at 2105 tokens, 3.0% against a 3% bar, n = 6, ranges do not overlap). The 31B rows (n = 2) only show direction. The report now says this (LOW, informational)

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (window_sdpa_tests 14, models::gemma3, Gemma 4 mask tests, clippy and fmt; the orchestrator re-runs the workspace gate)

`--turbo-boundary-v` keeps the outer layers' caches at FP16 while the rest run `fp16+turbo4`, so under bf16 activations the sliding rings return two K/V dtypes. The model-level plan read only the first sliding cache (an FP16 boundary layer), planned native, and every Turbo4Asym sliding layer then declined and rebuilt the mask.

`window_sdpa::sliding_caches_kv_dtype` returns the one dtype all sliding caches return, or `None` when they disagree, and Gemma 3 (model, stage model, backbone) and Gemma 4 plan the native route only on agreement. A test covers the empty, uniform and mixed cases under bf16 and f16 activations.

Validated with window_sdpa_tests (15), models::gemma (164), clippy -D warnings on mlxcel-core and mlxcel lib and tests, and fmt.

Refs #2621
@inureyes

Copy link
Copy Markdown
Member Author

Follow-up to the review summary: 0abab3f covers a second form of the same finding (MEDIUM). Under --turbo-boundary-v N with fp16+turbo4, the boundary layers keep FP16 caches while the other sliding layers return FP16 K/V from Turbo4Asym. With bf16 activations that means two different K/V dtypes. The plan read only the first sliding cache, which is a boundary layer, so it planned native and every Turbo sliding layer then declined. The plan now goes native only when all sliding caches return the same dtype (window_sdpa::sliding_caches_kv_dtype), and a test covers this case.

Under the default auto mode every over-window sliding prefill asked MLX for its fused-kernel verdict: once in the model's plan and again in every sliding layer, so a Gemma 3 27B chunk ran about 53 probes. Each probe builds three lazy zero arrays (three scalar fill buffers through the allocator plus a dozen graph nodes) and drops them. The verdict depends only on shape, dtype, window and process constants, so it is now memoized per thread, keyed on the full shape and the probed arm, with a 64-entry bound that clears rather than growing across a long-running server as k_len moves per chunk.

The probe also had no exception boundary. cxx declares it infallible, so a negative dimension (zeros throws) would terminate the process, and zero KV heads reached an integer division in MLX's has_fused_kernel. It now answers false for any non-positive dimension and for any MLX exception, which keeps the legacy mask route. Eligibility rejects an empty batch and non-positive query heads before probing, an unknown MLXCEL_NATIVE_WINDOW_SDPA value is reported once on stderr instead of silently selecting auto, and the comments no longer claim the probe allocates nothing.

Validated with the window_sdpa_tests module (19 pass, four new: degenerate probe shapes, memo parity and bound, eligibility guards, known mode values) and clippy on mlxcel-core lib and tests.

Refs #2621
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

Fixed in cc18090:

  • MEDIUM (perf): under the default auto mode the fused-kernel probe ran once in the model plan and again in every sliding layer (about 53 per Gemma 3 27B prefill chunk), each building three lazy zero arrays with scalar fill buffers. The verdict is now memoized per thread, keyed on full shape, dtype and arm, bounded at 64 entries.
  • MEDIUM (FFI abort): sdpa_uses_fused_kernel is infallible on the cxx side, so a negative dimension would terminate the process and zero KV heads reached an integer division in MLX. It now answers false for non-positive dimensions and any MLX exception (legacy route). Eligibility also rejects an empty batch and non-positive query heads.
  • LOW: an unknown MLXCEL_NATIVE_WINDOW_SDPA value is reported once on stderr; comments no longer claim the probe allocates nothing.

Checked, no change needed:

  • Both env vars are read once through OnceLock; with logging off a dispatch costs one relaxed atomic. The log line carries shapes, dtypes and the route only, no token or prompt data.
  • The legacy arm builds the same create_causal_mask_with_window_full mask and layers::attention call as the pre-PR over-window branch, so legacy mode stays byte-identical.
  • Softcap, sinks, caller masks (padding, VLM external masks), non-Metal backends and q_len > k_len cannot reach the native entry.

Left as is: the native SDPA entry is also declared infallible across cxx, like every other SDPA entry in the bridge; eligibility guarantees the inputs MLX validates (positive window, rank 4, float dtype, GQA ratio, q_len <= k_len).

Validation: window_sdpa_tests:: (19 pass, 4 new) and clippy on mlxcel-core lib and tests.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:benchmark Benchmark harness and performance measurement (bench_*.sh, /update-benchmarks) area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:macos macOS (Apple Silicon) specific priority:medium Medium priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

update(perf): adopt native window SDPA for Metal prefill

1 participant