Skip to content

Skip left-padded keys in Metal vector attention - #8

Open
ronaldmannak wants to merge 10 commits into
mainfrom
claude/metal-sdpa-left-padding-skip
Open

ronaldmannak wants to merge 10 commits into
mainfrom
claude/metal-sdpa-left-padding-skip

Conversation

@ronaldmannak

@ronaldmannak ronaldmannak commented Nov 13, 2026 •

Copy link
Copy Markdown
Owner

Batched decode keeps rows of different lengths in one key/value buffer, left-padded to the longest row. Batched generation in mlx-swift-lm (mlx-swift-lm issue 771) and mlx-lm's batch cache both work this way. Today the padded keys are hidden with a mask, so the attention kernel still visits every slot and reads the mask.

This adds an optional left_padding count per row to scaled_dot_product_attention. When the call reaches a Metal vector kernel (up to 8 queries, at most 32 query rows per key/value head), the kernel starts each row at its first valid key and reads no mask. It combines with mask="causal", which batched speculative verification needs.

This is the attention part of #6 made general, as a speed change only. The guarantee is narrow: a padded row reproduces the row run alone only when both use the same kernel and block count. Exact solo results are a separate, opt-in topic: #9 (stacked on this one) for attention, and MLX issue 4819 for quantized matmul.

What changed

  • mx.fast.scaled_dot_product_attention and the C++ function take left_padding, an int32 [B] array. Each count must satisfy 0 <= count < T_kv; with causal also count <= T_kv - T_q. Counts are not checked, and results outside that range are unspecified. It cannot be combined with an array mask, a window or sinks.
  • With mask="causal", padding hides keys on the left and causality hides later queries' keys on the right. On the vector path the kernels apply their existing causal check; there is no shader change for this.
  • The single-pass and two-pass Metal vector kernels skip the padded keys of each row. The kernel choice is the stock one.
  • On the vector path the primitive takes the counts as its only mask operand, and its fallback rebuilds the boolean mask from them for graph transforms such as vmap.
  • Everything else gets a boolean mask built from the counts: the CPU and CUDA backends, more than 8 queries, more than 32 query rows per key/value head (for example 64/8 heads with 8 queries), and the shapes stock MLX keeps off the vector kernels with an array mask (head dimension 512, and 192 with matching values).
  • Calls without left_padding compile the same kernels as before: the new input is behind a function constant, and no kernel functions are added.
  • benchmarks/python/sdpa_left_padding_bench.py compares a stock build with this branch (see below).

Evidence

Stock is fc344c98. Head is 89849a85; everything after 40c4d406 is formatting and the benchmark script.

Tests on M5 Max (applegpu_g17s), at 40c4d406:

$ MLX_ENABLE_TF32=0 python -m pytest -q python/tests/test_fast_sdpa.py
42 passed, 2 skipped

$ python python/tests/run.py      # full Python suite
990 passed, 57 skipped

CPU-only build (-DMLX_BUILD_METAL=OFF), test_fast_sdpa.py: 18 passed, 26 skipped (the GPU-only tests). The left-padding mask-fallback and causal CPU tests pass. Formatters (clang-format, ruff) are clean.

Tests on M1 Max (applegpu_g13s), run by Codex on the same code: test_fast_sdpa.py, checks near the 1,024-thread limit with the padded specialization, and the CPU-only build all pass.

The left-padding tests:

  • test_sdpa_vector_left_padding_shapes: 9 shapes, 1, 3 and 8 queries, 40 to 5,000 keys, three data types. It forces the fused kernel and checks that the default dispatch gives the same bits, so a silent fallback to the mask fails it.
  • test_sdpa_left_padding_mask_fallback_shapes: head dimensions 192/192 and 512, and 16 queries, must match an explicit mask bit for bit.
  • test_sdpa_causal_left_padding_cpu and _gpu: causal padding against an explicit combined mask, including a row whose earliest query sees one key, for 1, 2, 8 and 9 queries on both kernels.
  • test_sdpa_left_padding_vmap: vmap through the fallback that rebuilds the mask, with and without causal.
  • test_sdpa_vector_left_padding_preserves_logical_block_order: the narrow solo guarantee, with the kernel and block count held fixed.

Speed

python benchmarks/python/sdpa_left_padding_bench.py \
    --base /path/to/stock-env/bin/python --pr /path/to/branch-env/bin/python

Bfloat16, batch 4. Each sample chains calls in one evaluation, as stacked layers do. Processes run in the order stock, branch, branch, stock, and each build's two processes are pooled. "Ragged" rows hold all, a half, a quarter and a sixteenth of the keys (about 52% padding); "equal" rows have none. One query runs without a mask; 4 and 8 queries use mask="causal". Stock is called with a boolean mask built once per step and shared by every chained call, as a caller would.

Qwen3-8B / Llama 3.1 8B shape (32 query heads, 8 key/value heads, head dimension 128). M5 Max: two runs of 10 rounds × 50 calls, pooled. M1 Max: two runs of 15 rounds × 100 calls, shown separately.

Queries Keys Ragged: stock → left_padding µs (M5 Max) Ragged M5 Max Ragged M1 Max Equal M5 Max Equal M1 Max
1 1,024 38.9 → 28.9 −25.5% −18.7 / −19.7% −8.8% +2.9 / −9.1%
1 2,048 55.3 → 40.4 −26.8% −32.9 / −38.5% −11.1% −8.6 / −20.4%
1 4,096 104.9 → 59.0 −43.7% −38.3 / −43.8% −9.3% −14.4 / −29.6%
1 16,384 439.2 → 266.9 −39.2% −46.8 / −48.8% −9.5% −0.6 / +16.9%*
4, causal 1,024 98.3 → 78.4 −20.2% −16.1 / −22.9% −8.2% −0.8 / −10.4%
4, causal 2,048 171.9 → 134.5 −21.7% −20.2 / −26.5% −10.7% −4.6 / −7.1%
4, causal 4,096 280.7 → 201.9 −28.1% −37.2 / −32.8% −11.1% −18.6 / −11.5%
4, causal 16,384 936.7 → 616.8 −34.1% −43.0 / −45.3% −13.3% −16.3 / −22.2%
8, causal 1,024 180.5 → 144.8 −19.8% −12.7 / −22.0% −11.5% +1.9 / −9.9%
8, causal 2,048 329.6 → 257.5 −21.9% −18.6 / −23.3% −9.2% −3.7 / −10.7%
8, causal 4,096 519.5 → 377.8 −27.3% −38.0 / −32.4% −10.1% −14.3 / −15.2%
8, causal 16,384 1795.7 → 1231.7 −31.4% −40.8 / −45.9% −11.5% −16.6 / −20.0%

* One branch process throttled during this case. The M1 Max is a laptop that was charging during both runs; stock and this branch's mask path (identical code) differ by more than 3% in 13 and 15 of 24 cases, so equal-row differences below about 15% are within its noise. The ragged-row gains are consistent across both runs.

Other shapes, M5 Max (range across 1,024–16,384 keys):

Heads (query / key-value), head dim Example 1 query, ragged 4–8 causal queries, ragged Equal rows
64 / 8, D128 Llama 3.1 70B, Qwen3-32B −27% to −39% −21% to −31% (4 queries) −8% to −21% (1–4 queries)
32 / 8, D64 Llama 3.2 1B −14% to −52% −16% to −39% −7% to −34%
16 / 8, D256 Gemma 2 9B −25% to −43% −16% to −36% +1% to −10%
32 / 32, D128 Llama 2 7B (no grouped queries) −34% to −43% −25% to −39% +1% to −10%
64 / 8, D128, 8 queries 70B-class verification mask path −1% to +1% −1% to +1%
16 / 2, D512 — mask path −1% to +5% −1% to +5%

This branch called with an ordinary mask stays within noise of stock. Below 2,048 keys (30–100 µs per call) the two processes of one build can differ by 5–50% even on the M5 Max; pooling two runs damps this.

Memory

Peak above the inputs for one call, mask construction included, 32/8 D128, ragged rows. Identical on M5 Max and M1 Max.

Queries Keys Stock, mask left_padding
1 1,024 2.2 MiB 2.1 MiB
1 4,096 2.6 MiB 2.1 MiB
1 16,384 4.2 MiB 2.1 MiB
4, causal 1,024 8.9 MiB 8.4 MiB
4, causal 4,096 18.8 MiB 16.6 MiB
4, causal 16,384 41.6 MiB 33.1 MiB
8, causal 1,024 17.8 MiB 16.8 MiB
8, causal 4,096 37.5 MiB 33.2 MiB
8, causal 16,384 83.1 MiB 66.2 MiB

The key/value cache is unchanged. Called with an ordinary mask, this branch uses exactly the same memory as stock.

Correctness in the benchmark

In every case on both chips, the left_padding output was bit-identical to the mask output (bfloat16).

Cost on the mask path

On shapes that fall back, left_padding rebuilds its mask on every call, while a caller builds one per step. Measured on M5 Max in one process with the modes interleaved (20 rounds × 50 calls): a mask rebuilt before every call costs the same as left_padding, a few µs per call. That is at most 3% at 1,024 keys and under 1% from 4,096 keys, for 16/2 D512 (1, 4 and 8 queries) and 64/8 D128 with 8 queries.

Earlier evidence, at cd744c7

  • A standalone script compared left_padding with the boolean-mask call and the CPU path for 11 shapes, three data types, 40 to 5,000 keys and 1 to 16 queries: 1078 checks, 0 failures. With an off-by-one planted in both kernels: 1036 checks, 588 failures.
  • Qwen3-8B-4bit in mlx-swift-lm, four rows with prompts of 1,024 to 16,384 tokens, 512 tokens each, six rounds: +26.3% tokens/s while four rows decode and +12.0% over the whole replay. With an ordinary mask the branch matched stock and its logits were bit-identical.
  • Batched speculative decoding on a prototype of the causal change (Qwen3-0.6B drafting for Qwen3-8B, four requests, copy-free rollback): 27–58% faster than the same requests run one at a time, and 30–36% faster than the same batch with a boolean mask.

Graph export

Graph export works when MLX traces the attention call and uses the boolean-mask fallback. Exporting an already-built, unevaluated graph that took the left_padding Metal fast path fails. The fix is tracked in #11.

Not verified

  • The end-to-end numbers predate the causal and mask commits.
  • CUDA was not compiled.
  • Base and Pro chips keep the single-pass kernel up to 4,096 keys with grouped queries; neither has been timed. A base M5 and an M3 Ultra run of the benchmark script are pending.

Not done on purpose

  • Per-row kernel choice for exact solo results across the two-pass cutoff: Pick the decode kernel from each row's unpadded length #9, stacked on this one. Full-model solo parity also depends on quantized matmul (MLX issue 4819).
  • More than 32 query rows per key/value head: the split kernel (MLX PR 4723) refuses array masks, so these calls use the unfused path on stock and here. Teaching it left_padding is a follow-up; 64/8 D128 with 8 queries takes 7.3 ms per call at 16,384 keys against 1.8 ms with 4 queries.
  • Head dimension 512 and 192 with matching values stay on the mask path, following the existing rules for array masks. The single-query D512 vector kernel could take left_padding in a follow-up.
  • No C or Swift bindings.

🤖 Generated with Claude Code

scaled_dot_product_attention takes an optional int32 [B] left_padding array with the number of leading padded keys in each row. On Metal, for queries of up to 8 tokens, the single-pass and two-pass vector kernels start each row at its first valid key and no mask is read. Every other path and backend uses a boolean mask built from the counts. The kernel choice and the calls without left_padding are unchanged.

This is the attention part of 84b6f9a (#6) made general: it covers every head dimension, data type and grouped-query layout the vector kernels have, and adds the single-pass kernel. It does not promise that a padded row matches the row decoded alone.

Apple M5 Max, single-token queries, time per call against a boolean mask: with ragged rows 17% less at 2,048 keys and 30% less at 16,384; with equal-length rows 2% to 5% less at 2,048 keys and up. Equal-length rows at 512 keys are up to 11% slower for head dimension 256. A four-row Qwen3-8B-4bit replay decodes 26% faster than fc344c9, and with an ordinary mask it matches fc344c9 in speed and in logit bits.

python/tests/test_fast_sdpa.py has not been run for this commit. The same assertions pass from a standalone script.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T01:09:48.507467Z dbec7cf New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

ronaldmannak and others added 5 commits November 13, 2026 15:16
The vector-kernel test now forces the fused path and checks that the default dispatch picks the same kernel, so a silent fallback to the mask fails. It covers 1, 3 and 8 queries at 1,000, 1,500 and 5,000 keys, on both sides of the two-pass cutoff. Shapes that use the mask built from the counts (head dimension 192 with matching values, 512, and more than 8 queries) move to their own test, which requires an exact match with an explicit mask. The block-order test now states the narrow guarantee it checks: same kernel and block count as the solo row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each count must satisfy 0 <= count < key length. Counts are not checked on the device, so results outside that range are unspecified. The fast path is described as applying to eligible Metal shapes, since some shapes use the mask built from the counts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Batched speculative verification needs both: padding hides keys on the left, and causality hides later draft tokens on the right. On the Metal vector path the kernels skip the padded prefix and apply their existing causal check, with no shader change. Other paths combine the padding mask with a lower-right causal mask. Each row must keep at least as many keys as queries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
On the Metal vector path the primitive now takes the int32 counts as its only mask operand, and its fallback rebuilds the boolean mask from them for graph transforms such as vmap. Other paths still receive the mask built from the counts.

Chained single-token attention calls on an M5 Max (B=4, 32/8 heads, head dimension 128, bfloat16, medians of three runs in ABBA order): -1.6% to -4.3% per call at 2,048 and 4,096 keys, within noise at 512 and 16,384 keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ronaldmannak

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: d94e146f79

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

ronaldmannak and others added 3 commits November 13, 2026 18:13
Runs main and the branch in separate processes (base, PR, PR, base) and
reports time and peak memory per attention call for ragged and equal rows,
1 query and 4 or 8 causal queries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Adds --shape and --keys, defaults to six attention shapes (including two
that stay on the mask path on both builds), and lists cases where the two
processes of one build disagree by more than 5%. Lowers the defaults to
10 rounds of 50 chained calls so all shapes finish in about 8 minutes on
an M5 Max.

Co-Authored-By: Claude Opus 5.5 <[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.

1 participant