Repository navigation
feat(core): adopt native window SDPA for Metal prefill - #2646
Conversation
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
…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
Implementation Review SummaryIntent
Findings Addressed
Remaining Items
Verification
|
`--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
|
Follow-up to the review summary: 0abab3f covers a second form of the same finding (MEDIUM). Under |
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
Security and performance reviewFixed in cc18090:
Checked, no change needed:
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, Validation: |
Summary
mlxcel_core::window_sdparoutes a causal multi-query prefill whose keys outgrow the sliding window either through upstream MLX's nativewindow_sizewithmask_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, defaultauto) selects the route;autotakes the native entry only where MLX's ownScaledDotProductAttention::use_fallbackreports 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 runsauto.MLXCEL_LOG_WINDOW_SDPAprints per-dispatch route evidence (shapes, dtypes, window; no prompt data). Both variables are indocs/environment-variables.md.RotatingKVCache::attendcarries 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.RotatingKVCache::fetched_kv_dtype: f16 forfp16+turbo4, the input dtype otherwise) and goes native only when every sliding cache agrees (--turbo-boundary-vmixes 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.DEFAULT_PREFILL_CHUNK = 2048the 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)autoselects, 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, whichautokeeps legacy; head dim 128 0.43x to 0.06x.autodispatch counts 22/35/50 per prompt, all fused.--decided 2, widths 2048 and 4096, route lines confirmnative_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.MLXCEL_NATIVE_WINDOW_SDPA=0restores the previous route.autowould 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
fp16+turbo4on a bf16 model planned native and then declined in every sliding layer, rebuilding the mask per layer.Test plan
cargo test --workspace --profile test-fast --features metal,accelerate --no-fail-faston cc18090: 13896 passed, 0 failed over 176 binariescargo clippy --workspace --all-targets -- -D warningsandcargo fmt --checkcleanwindow_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 shapesattend_tests::batched_paged_one_row_is_one_pooled_launchfailed 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 gatesgemma-3-1b-it-4bit,gemma-4-e4b-it-4bit,gemma-4-31b-it-4bitwith route evidence fromMLXCEL_LOG_WINDOW_SDPACloses #2621