Skip to content

[Metal] Use the split SDPA kernel from 9 rows before M3 - #4973

Merged
zcbenz merged 2 commits into
ml-explore:mainfrom
YingjieHe:sdpa-split-pre-m3
Nov 29, 2026
Merged

zcbenz merged 2 commits into
ml-explore:mainfrom
YingjieHe:sdpa-split-pre-m3

Conversation

@YingjieHe

Copy link
Copy Markdown
Contributor

On M1 and M2 the vector kernels slow down as the query rows per KV head grow past 8, while the split kernel stays flat. Take the split kernel above 8 rows there instead of 32. M3 and newer are unchanged.

Why (measured, M2 Max)

  • Vector kernels: time grows with rows.
  • Split kernel: time flat across 2–32 rows (reads K/V once).
  • Crossover on M2 Max: split faster above 8 rows; at ≤ 8 rows vector is equal or faster.

Kernel numbers (M2 Max, bf16, head dim 128, 8 KV heads, causal, 28 calls, min of 7×20)

Rows 900 keys: vector → split 4000 keys: vector → split
2–6 split slower (0.43–0.86x) split slower
8 1.26x 0.97x
10 1.32x 1.16x
12 1.38x 1.39x
16 2.43x 1.80x
32 4.21x 3.38x

8 query tokens, 16 q heads / 8 KV heads (16 rows), on upstream main:
300 keys 1.86 → 1.12 ms, 900 keys 4.33 → 1.85 ms, 4000 keys 7.57 → 4.26 ms.

Normal decoding with high GQA (also changes on M1/M2)

1 token × 9–32 q heads per KV head now uses split. 60 cases (GQA 12–32, head dim 64/128, 1–2 tokens, 900–16000 keys): all faster, 1.12x–6.5x, none slower. Already >32 rows: 1.00x.

Head dim KV heads × q heads per KV 900 keys 4000 keys 16000 keys
128 4 × 16 2.46 → 1.20 ms 3.92 → 2.73 12.93 → 7.79
128 4 × 32 4.16 → 1.30 7.15 → 2.85 23.27 → 7.85
64 8 × 16 2.29 → 1.06 5.30 → 1.85 17.26 → 5.39

Unchanged (checked)

  • ≤ 8 rows: same time (±3%), bit-identical error vs fp32 reference.

  • Head dim 192: same time, identical error.

  • Plain decoding (1 token, 2 q heads per KV): end-to-end outputs identical, 392/392 clips.

  • ☑️ I understand it is strictly prohibited to use AI to write PR description

  • AI usage disclosure: benchmarks runs with agent, all other written by myself

@zcbenz zcbenz added the await verification This pull request is non-trivial and requires a human expert to verify its correctness. label Nov 27, 2026
On M1 and M2 the vector kernels slow down as the query rows per KV head
grow past 8, while the split kernel stays flat. Take the split kernel above
8 rows there instead of 32. M3 and newer are unchanged.
@zcbenz zcbenz removed the await verification This pull request is non-trivial and requires a human expert to verify its correctness. label Nov 29, 2026
@zcbenz
zcbenz merged commit 9ef1889 into ml-explore:main Nov 29, 2026
24 checks passed
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.

2 participants