Skip to content

Use fused SDPA for causal head_dim 256 with 512 to 1023 query rows - #4893

Merged
zcbenz merged 2 commits into
ml-explore:mainfrom
jvmenen:sdpa-d256-short-query-v3-rebase
Nov 22, 2026
Merged

zcbenz merged 2 commits into
ml-explore:mainfrom
jvmenen:sdpa-d256-short-query-v3-rebase

Conversation

@jvmenen

@jvmenen jvmenen commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Closes #4695.

Why

On M5 chips, causal fp16/bf16 attention with head dim 256 (Qwen3.5 and similar models) only uses the fused kernel from 1024 query rows. Chunks of 512 to 1023 rows take the unfused path, although the fused kernel does the same call in 25 to 31% less time (median over key lengths of 1K to 64K). That hits the last chunk of every prompt, and every chunk when the prefill step is below 1024.

How it works, in plain terms

  • use_fallback gets one extra rule: on NAX devices, fp16 or bf16, head dim 256, causal mask, no array mask, at least 512 query rows and at least 8 heads in total (batch × query heads) go to the fused kernel.
  • Why the head count. With fewer than 8 heads the fused kernel has too little work to fill the GPU and can be slower than the unfused path (1 × 4/1 down to 0.76×, 1 × 2/1 down to 0.65×). 8 is the smallest count measured that is faster everywhere. On other chips or head layouts the break-even point may lie elsewhere, so numbers from other setups are welcome.
  • Why 512 rows. Below 512 rows the results are mixed (some configurations are slower at 448 rows), so that range stays unfused. Other chips and head layouts may give a different picture here as well; a lower threshold could be a follow-up if measurements support it.
  • No kernel changes. Float32, array masks, devices without NAX and other head dims behave as before.

Results

Unfused time divided by fused time for one SDPA call on an M5 Pro, bf16 and fp16, 512 to 1023 query rows, key lengths up to 64K:

batch, query / KV heads median range slower cells
1, 16/4 1.45× (31% less time) 1.20× to 2.04× 0 of 96
1, 24/4 1.43× (30%) 1.27× to 2.30× 0 of 96
1, 8/2 1.36× (27%) 1.10× to 1.84× 0 of 96
2, 4/1 1.34× (25%) 1.06× to 1.84× 0 of 96

Both paths ran alternately in one process; at 1024 rows, where both are already fused, the ratio is 1.00 ± 0.03. In an mlx-lm prefill of Qwen3.5-9B the gain is up to 10% (33K context, prefill step 512) and not measurable with the default step of 2048. The output differs from the unfused path by at most 2.4e-4 (bf16) and 3.8e-5 (fp16).

Tests

  • test_sdpa_head_dim_256_short_query_routing checks that 512, 700 and 1023 rows take the fused kernel (fp16 and bf16, several head layouts, keys up to 20K), and that 511 rows and 4 heads in total do not. It fails on main and passes with this change.
  • test_sdpa_head_dim_256_short_query compares the fused result with a float32 reference and with the unfused path, including sliced KV caches with stale rows behind the slice, batch 2, GQA 1:1 and 8:1, transposed inputs and few heads. The largest case (12K keys) is skipped on CI.

test_fast_sdpa passes with MLX_ENABLE_TF32=0 (39 tests, 2 skipped).

Notes

Only measured on an M5 Pro, so numbers for other configurations would be helpful. #4476 proposed the same row range without the head-count condition.

@aaishwarymishra

Copy link
Copy Markdown
Contributor

@jvmenen Hi, I was maybe thinking of testing it on my M5 macbook air, I think MLX recommends can you maybe include the benchmark script and the steps so I can check it on my own machine so our benchmark are similar :)

Causal float16/bfloat16 attention with head_dim 256 and fewer than 1024
query rows (the last chunk of a chunked prefill, or new tokens appended to
a long KV cache) went through the unfused matmul + softmax path. On NAX
devices the fused kernel is faster for 512 to 1023 rows at every key
length measured (1K to 64K), as long as batch * query heads >= 8.
Float32 and array masks are unchanged.

Add a routing test and numerics tests against a float32 reference and the
unfused path, including sliced KV caches with stale rows, batch 2, GQA 1:1
and 8:1, transposed inputs and few heads.
@zcbenz
zcbenz force-pushed the sdpa-d256-short-query-v3-rebase branch 3 times, most recently from 7e8e47d to 143d0b4 Compare November 22, 2026 02:34
@zcbenz
zcbenz force-pushed the sdpa-d256-short-query-v3-rebase branch from 143d0b4 to dd6d862 Compare November 22, 2026 07:51
@zcbenz
zcbenz merged commit 8e98fb8 into ml-explore:main Nov 22, 2026
24 checks passed
Lyxot added a commit to Lyxot/unsloth-zoo that referenced this pull request Nov 26, 2026
`fused_kernel_exists` decides whether a quantized-KV attention call is dequantized onto mlx's fused kernel. It now follows mlx 0.32.5's `has_fused_kernel` and `use_fallback`:

- 2 to 8 queries whose GQA group stacks 33 to 128 rows run on `sdpa_split` (ml-explore/mlx#4723). This applies at head dims 64, 96, 128, 192 and 256 with matching value dims, two or more KV heads (or NAX), at least 128 keys and no array mask.
- On NAX, half-precision head dim 256 fuses from 512 queries once batch x heads reaches 8 (ml-explore/mlx#4893). Head dim 512 fuses under an array mask as well as causal.

It also refuses array masks whose leading axes mlx's fused kernel, broadcasting from the right against `[B, HQ, L, S]`, would read differently from a runtime that aligns them to its own scores (a 3-D `[B, L, S]` mask). The runtime path keeps those calls.
Lyxot added a commit to Lyxot/unsloth-zoo that referenced this pull request Nov 26, 2026
`fused_kernel_exists` decides whether a quantized-KV attention call is dequantized onto mlx's fused kernel. It now follows mlx 0.32.5's `has_fused_kernel` and `use_fallback`:

- 2 to 8 queries whose GQA group stacks 33 to 128 rows run on `sdpa_split` (ml-explore/mlx#4723). This applies at head dims 64, 96, 128, 192 and 256 with matching value dims, two or more KV heads (or NAX), at least 128 keys and no array mask.
- On NAX, half-precision head dim 256 fuses from 512 queries once batch x heads reaches 8 (ml-explore/mlx#4893). Head dim 512 fuses under an array mask as well as causal.

It also refuses array masks whose leading axes mlx's fused kernel, broadcasting from the right against `[B, HQ, L, S]`, would read differently from a runtime that aligns them to its own scores (a 3-D `[B, L, S]` mask). The runtime path keeps those calls.
rcfa pushed a commit to cubiculum-ai/mlx that referenced this pull request Nov 26, 2026
…l-explore#4893)

Co-authored-by: Jeroen van Menen <[email protected]>
Co-authored-by: Cheng <[email protected]>
(cherry picked from commit 8e98fb8)
danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Nov 27, 2026
## Summary

Pins `mlx==0.32.5` and brings every zoo route that mirrors or competes
with mlx dispatch in line with it. Workarounds that 0.32.5 fixes
upstream are removed, routes that 0.32.5 makes unreachable or slower are
deleted, and two routing choices made for the pin that cost speed end to
end are corrected.

On an M5 Pro, batched decode is 1.2-2.4x faster at 4-24 rows, short
prefill is 1.1-1.9x faster, and long Gemma 4 prefill is 1.07-1.12x
faster than main on mlx 0.32.4. On an M3 Max, Gemma 4 prefill is
1.03-1.08x faster and batched decode at 8-16 rows 1.06-1.16x.
Single-stream decode and LoRA training step time are unchanged on both.

## Changes

1. **`chore(mlx): pin mlx 0.32.5`**
- Version-pinned mirrors of stock dispatch that is unchanged in 0.32.5
move to `"0.32.5"`, and their bitwise tests are re-gated.
   - Removes workarounds 0.32.5 fixes upstream:
- the row-contiguous copy before cross-entropy (ml-explore/mlx#4702);
     - M1/M2 SDPA thread-limit routing (ml-explore/mlx#4708, #4719);
     - `toks_f + 0` (ml-explore/mlx#4880).
- mlx now reads `MLX_ENABLE_TF32`, `MLX_SDPA_BLOCKS` and
`MLX_SDPA_D512_MIN_KL` through `mx.config`, which caches the first read.
Zoo reads them the same way, and tests use `mx.config.scoped_update`.
- 0.32.5's deeper stock `gelu_approx` (ml-explore/mlx#4906) exposes an
`mx.compile(shapeless=True)` bug: a cache entry first traced inside a
gradient later returns a stale batch shape. Zoo's installed
`gelu_approx` keeps the plain formula for non-fp16 dtypes, and every
trainer installs it.
- The native sliding-window route goes live on 0.32.5. Its fingerprint
of the Gemma 4 compile patch's mask builder is re-pinned.
   - Two Metal tests re-baselined for 0.32.5:
- The KV-shared checkpoint peak bound goes from 1.25x to 1.3x the
unshared peak. On 0.32.5 the unshared stack's peak falls more than the
shared one, so a correctly tied stack reads 1.20-1.28 depending on chip.
With the tie removed it read 1.68 on 0.32.4.
- The VLM stream test with a short arrival during a long prefill keeps
the short row bitwise. The long row keeps its first token exact, and its
logprob must be within 0.125. The arrival splits the long prefill into
different chunk sizes, and stock bf16 matmul is not row-count invariant
on either mlx version. The bitwise result flipped between M1 and M3 with
each mlx release, whichever zoo revision ran.
2. **`perf(mlx): mirror mlx 0.32.5's attention fusion rules`**:
`fused_kernel_exists` follows 0.32.5's `has_fused_kernel` /
`use_fallback`:
   - `sdpa_split` for 33-128 stacked query rows (ml-explore/mlx#4723);
   - NAX head dim 256 from 512 queries (ml-explore/mlx#4893);
   - head dim 512 under array masks;
- array masks whose leading axes the fused kernel would read differently
from the runtime are refused.
3. **`refactor(mlx): drop the NAX staged quantized matmul route`**:
0.32.5 runs staged NAX weight loads in stock `qmm_t`
(ml-explore/mlx#4682), so zoo's copy is unreachable under the pin. The
training qmm chooser over the one remaining dense route becomes
`dense_train_qmm_available()` / `call_dense_train_qmm()`.
4. **`refactor(mlx): drop the NAX small-row quantized matmul kernel`**:
off since the pin closed its gap. Stock 0.32.5's qmv_nax and split-K
qmm_nax (ml-explore/mlx#4712, #4781) are faster than the kernel in most
cells. The NAX scope keeps int8 prefill, sorted gather and dense
prefill.
5. **`perf(mlx): recover small-batch decode and NAX prefill on mlx
0.32.5`**: fixes two losses that came from re-pinning in (1). Each was
isolated by running the zoo revision before the pin and this branch,
both on mlx 0.32.5.
- **SIMD small-row route.** It had been narrowed to rows 17-24 from
per-op timings, which cost about 8% at 3-4 rows end to end on an M3 Max.
Now:
     - rows back to 3-24;
- a 3-4 row entry for 4-bit heads of at least 2^24 weights at any width;
- a `SIMD_QMM_STOCK_ROWS = (5, 16)` band where stock qmv_mma
(ml-explore/mlx#4787) wins and the call stays native.
- **Dense prefill.** Re-pinned to 0.32.5, it went live on NAX GPUs,
where stock's staged `qmm_t_nax` beats dequantize-once (-6-7% long
prefill on an M5 Pro). It now stays off where stock runs its NAX
kernels.

## Performance

End-to-end through the Unsloth Studio in-process backend: main (mlx
0.32.4) vs this branch with the matching Unsloth Studio change (mlx
0.32.5). Numbers are new/base, two interleaved rounds per case, one
`--stable` scheduler slot per case; 4-bit MLX checkpoints unless noted.

| case | M3 Max | M5 Pro |
|---|---|---|
| batched decode Qwen3-4B, 4 / 8 / 16 / 24 rows | 1.02 / 1.06 / 1.07 /
1.02 | 1.20 / 1.39 / 1.55 / 1.82 |
| batched decode Llama 3.2 3B, 4 / 8 / 16 / 24 rows | 1.01 / 1.08 / 1.16
/ 1.07 | 1.21 / 1.42 / 1.51 / 2.44 |
| batched decode Qwen3.6-35B-A3B, 8 / 16 rows | 0.94 (CI to 1.05) / 1.00
| 1.05 / 1.10 |
| short prefill Llama 3.2 3B, 32 / 64 / 512 tokens | 0.99 / 0.98 / 1.02
| 1.92 / 1.89 / 1.09 |
| Gemma 4 E4B prefill, 2k / 8k / 16k | 1.07 / 1.08 / 1.08 | 1.11 / 1.12
/ 1.11 |
| Gemma 4 12B (8-bit) prefill, 2k / 8k | 1.03 / 1.05 | 1.07 / 1.08 |
| Gemma 4 E4B speculative decode, 128 / 2k context | 1.44 / 1.36 | 1.40
/ 1.34 |
| single-stream decode, all models | 0.99-1.01 | 1.00 |
| LoRA training step (Qwen3-4B, Llama 3.2 3B, Qwen3.5 2B, Gemma 4 E2B) |
0.99-1.00 | 0.97-1.01 |

The two zoo-caused losses, before and after (5):

| case | before | after |
|---|---|---|
| M3 Max batched decode at 3-4 rows, Qwen3-4B | 0.93 | 1.035 |
| M3 Max batched decode at 3-4 rows, Llama 3.2 3B | 0.93 | 1.027 |
| M5 Pro prefill, 2k-8k | 0.93-0.94 | 1.00 |

Known losses that are not from zoo; each shows the same with main's zoo
running on mlx 0.32.5:

- Qwen3.6-35B-A3B single-stream decode at 128 tokens on an M5 Pro: 0.95.
- Qwen3.6-35B-A3B speculative decode: noisy, 0.69-1.08 across runs, on
both chips.
- Qwen3.8-27B at 8k tokens on an M3 Max: about 0.95. Isolated over three
interleaved rounds:
  - main's zoo on 0.32.4: 21.7 tok/s decode, 227 tok/s prefill;
  - main's zoo on 0.32.5: 21.3 / 206;
  - this branch on 0.32.5: 21.1 / 220.

So this branch is neutral on decode and +7% on prefill against the same
mlx. The rest comes from mlx and thermal drift within the run.

## Risks

- The removed M1/M2 workaround is upstream-fixed. The gating M1 CI leg
runs the Metal suites without it and passes, but it has not been
benchmarked on M1/M2.
- fp16 `gelu_approx` stays exposed to the shapeless-compile bug: no fp16
body tried satisfies both the stale-shape check and
ml-explore/mlx#4906's finite-gradient contract. This exposure predates
the bump.
- The SIMD row band is measured on an M3 Max and used for every non-NAX
GPU.

## Validation

Targeted Metal suites on an M3 Max and an M5 Pro, mlx 0.32.5:

```bash
python -m pytest -q tests/test_mlx_nax_metal.py tests/test_mlx_generate_metal.py tests/test_mlx_decode_metal.py tests/test_mlx_moe_metal.py tests/test_mlx_attention_metal.py tests/test_mlx_training_e2e_metal.py
```

- M3 Max: 1573 passed. Failures, none from this change:
  - 7 FastVLM tests whose remote processor code needs `timm`;
- 2
`test_verify_moe_qwen4_takes_fast_verify_blocks_unless_lanes_hold_them`
cases, which fail on main as well;
  - 8 training e2e tests whose models were not in the offline cache.
- M5 Pro: 926 passed. The only failures are the 7 `timm` FastVLM tests.
- New and changed tests were mutation-checked: reverting each production
change fails its test.
- The bf16-vs-fp32 gradient error is equal on main and on this branch.
- The gating M1 CI leg (`MLX install + import smoke (Apple Silicon,
pinned)`) passes on this head.

Pairs with the Unsloth Studio change that pins mlx 0.32.5.

---------

Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use fused attention for head dim 256 from 512 query rows with enough heads

3 participants