Repository navigation
Skip left-padded keys in Metal vector attention - #8
Open
ronaldmannak wants to merge 10 commits into
Open
ronaldmannak wants to merge 10 commits into
ronaldmannak wants to merge 10 commits into
Conversation
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]>
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
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]>
Owner
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
This was referenced Nov 14, 2026
This was referenced Nov 15, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_paddingcount per row toscaled_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 withmask="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_attentionand the C++ function takeleft_padding, an int32[B]array. Each count must satisfy0 <= count < T_kv; with causal alsocount <= 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.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.vmap.left_paddingcompile 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.pycompares a stock build with this branch (see below).Evidence
Stock is
fc344c98. Head is89849a85; everything after40c4d406is formatting and the benchmark script.Tests on M5 Max (
applegpu_g17s), at40c4d406: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_cpuand_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:vmapthrough 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
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.
left_paddingµs (M5 Max)* 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):
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.
left_paddingThe 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_paddingoutput was bit-identical to the mask output (bfloat16).Cost on the mask path
On shapes that fall back,
left_paddingrebuilds 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 asleft_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
cd744c7left_paddingwith 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.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_paddingMetal fast path fails. The fix is tracked in #11.Not verified
Not done on purpose
left_paddingis 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.left_paddingin a follow-up.🤖 Generated with Claude Code