Skip to content

fix(metal): bound materializing SDPA prefill by chunking the query axis - #3034

Closed
georgiedekker wants to merge 3 commits into
lablup:mainfrom
georgiedekker:fix/metal-sdpa-score-materialization
Closed

georgiedekker wants to merge 3 commits into
lablup:mainfrom
georgiedekker:fix/metal-sdpa-score-materialization

Conversation

@georgiedekker

Copy link
Copy Markdown
Contributor

Problem

On Metal, any prompt above ~25k tokens fails with a single metal::malloc attempt of exactly L² × 48 bytes — the full [B, H, L, L] score matrix, which MLX's SDPA fallback materialises because an array-mask call at head_dim 256 is not fused on pre-M5 GPUs (#2621/#2646). mlxcel already has the fix (chunked_query_attention), but sdpa_query_chunk_within_budget returns early on non-CUDA builds, so it can never run on Metal.

Measured on a 48 GiB M4 Pro with a 6-bit Qwen3.5 hybrid (AREX-2, 24 query heads, head_dim 256, 21.9 GB resident): a 26,602-token prefill requests 33,967,987,392 bytes against Metal's 30,150,672,384-byte per-buffer cap. 9k tokens succeeds, so it is a cliff, not a load problem.

Change

  • sdpa_query_chunk_within_budget: keep the CUDA predicates unchanged; on Metal ask window_sdpa's memoised fused-kernel verdict (sdpa_uses_fused_kernel, which calls MLX's ScaledDotProductAttention::use_fallback) for the array-mask arm, and when MLX will fall back, return the query chunk from the existing 1 GiB budget.
  • window_sdpa::legacy_mask_uses_fused_kernel: exposes that verdict; reuses the existing per-thread memo, no new FFI, no new probe.
  • MLXCEL_METAL_ATTENTION_CHUNK=0 restores the previous route.
  • Test: the chunk math at this geometry stays inside the budget and still covers the whole query axis.

Why this is safe

chunked_query_attention already exists for the CUDA gate, slices the mask along the query axis, and has chunked-vs-unchunked parity tests (masked and broadcast-mask). Shapes MLX does fuse take the probe's true verdict and keep the current single-SDPA call; non-Metal, non-CUDA builds still return None.

Verification

  • 26,602-token prompt, 6-bit Qwen3.5 hybrid on a 48 GiB M4 Pro: fails on 0.8.1 with the 33.97 GB metal::malloc; answers correctly with this patch at the default 1 GiB budget (per-chunk scores ~1 GB; prefill ~404 s).
  • Chunked/unchunked parity tests pass; formatting, lints and the workspace test suite are green locally.
  • Model-level check: the answer uses a fact placed at token ~1 of the 26.6k prompt, so the chunking does not drop prefix context.

Fixes #3033.

sdpa_query_chunk_within_budget returned early on non-CUDA builds, so the
score-matrix chunk gate could only fire on CUDA. Metal has the same
materialization: MLX's fused SDPA declines an array-mask call at head_dim
256 on pre-M5 GPUs (lablup#2621/lablup#2646), and the fallback then forms the full
[B, H, q_len, k_len] scores. Measured on a 48 GiB M4 Pro with AREX-2
(Qwen3.5 hybrid, 24 heads, head_dim 256): a 26,602-token prefill asks Metal
for 26,602^2 * 24 * 2 B = 33.97 GB in one buffer, past the 30.15 GB
per-buffer cap, and the request fails at the eval boundary. The same prompt
at 9k tokens succeeds, so it is a cliff rather than a load problem.

Ask MLX's own fused-vs-fallback verdict through the existing probe (reusing
window_sdpa's per-thread memo) and let the existing, parity-tested
chunked_query_attention bound the transient. MLXCEL_METAL_ATTENTION_CHUNK=0
restores the old route.

Verified locally on the geometry above: the 26.6k-token prompt answers
correctly through the server route with the 1 GiB default budget (per-chunk
scores ~1 GB instead of 34 GB), and the chunked-vs-unchunked parity tests
pass. Prompt still fails identically on 0.8.1 without the patch.
@cla-assistant

cla-assistant Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@cla-assistant

cla-assistant Bot commented Nov 12, 2026

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

The Metal chunk gate keyed off the optional `metal` Cargo feature, but a plain `cargo build` on macOS builds the Metal backend without it (lablup#1988), so the default build never chunked. It now keys off `target_os = "macos"`.

The gate asked MLX about the array-mask arm for every call. The maskless causal call site (`causal_attention`) issues MLX's causal mode, which a GPU can fuse where the array-mask call falls back; chunking it would replace a fused kernel with per-chunk fallbacks. The probe now asks about the arm the call actually issues (array mask, causal, or none), and a softcap call always counts as materializing, since `attention_dispatch` runs the compiled softcap composite.

Also: the contributor's geometry test did not compile (usize vs i32), the CUDA dtype test now pins its CUDA expectations off macOS, a new macOS test checks the gate against MLX's verdict per arm, and `MLXCEL_METAL_ATTENTION_CHUNK` is documented (the env-var docs check failed without it).

Validation: `cargo test -p mlxcel-core --lib -- query_chunk chunked_ window_sdpa` (31 passed on M3 Ultra), `cargo clippy --lib --tests -- -D warnings`, `scripts/ci/check_env_var_docs.py`.

Refs lablup#3033
@inureyes

Copy link
Copy Markdown
Member

Thanks for tracking this down so precisely, @georgiedekker. I reviewed it on an M3 Ultra, merged main into the branch, and pushed one follow-up commit (23bd8cc):

  • The gate checked the optional metal Cargo feature, but a plain cargo build on macOS builds Metal without it (fix: diagnose automatic QMV retry failure on M5 Ultra #1988), so the default build never chunked. It now checks target_os = "macos".
  • It probed the array-mask arm for every call. The maskless causal call site issues MLX's causal mode, and on this GPU MLX fuses that arm at head_dim 256 for a 28K prompt while the array-mask arm falls back (probe output: mask=false causal=true for [1,16,27849,256] and [1,24,27891,256]). Chunking such a call would replace the fused kernel with per-chunk fallbacks. The probe now asks about the arm the call issues, and a softcap call always counts as materializing.
  • query_chunk_len_covers_the_arex_long_prompt_geometry did not compile (usize vs i32); fixed. The CUDA dtype test now pins its CUDA expectations off macOS, and a new macOS test checks the gate against MLX's verdict per arm.
  • MLXCEL_METAL_ATTENTION_CHUNK is now in docs/environment-variables.md (the env-var docs check failed without it).

Measurements, 28K-token prompt, server with MLXCEL_PROMPT_CACHE_SYSTEM_ROOT=1 (single-pass root prefill), main vs this branch:

Model Peak footprint TTFT Answer
qwen3.5-4b-4bit 63.8 GB to 59.4 GB 18.7 s to 17.5 s same
qwen3.8-27b-4bit 109.7 GB to 93.1 GB 85.5 s to 82.4 s same

The kill switch restores the main footprint exactly. On a 4.6K-token prompt, greedy output is byte-identical with the gate off, at the default budget, and with MLXCEL_ATTENTION_CHUNK_BUDGET_MB=1, which forces chunking. cargo test -p mlxcel-core --lib -- query_chunk chunked_ window_sdpa (31 passed) and clippy are clean.

Two things block the merge: the CLA check is still pending (please sign it via the link above), and the fork CI run is waiting for maintainer approval.

@inureyes

Copy link
Copy Markdown
Member

Thank you for the report in #3033 and for this PR. The OOM you hit on the M4 Pro is real and the query-axis chunking is the right direction. We reviewed it on an M3 Ultra and found problems that make the change either inert or harmful as submitted:

  • The gate never fires in a default macOS build. It is keyed on the metal Cargo feature, but a plain cargo build on macOS builds the Metal backend without that feature (fix: diagnose automatic QMV retry failure on M5 Ultra #1988). The check needs to be on target_os = "macos" (or the runtime backend), not the feature flag.
  • It probes the wrong SDPA case. The gate asks MLX whether the array-mask call is fused for every call. MLX answers per call mode: on the M3 Ultra the causal-mode call at head_dim 256 and about 28K tokens is fused (mask=false causal=true for [1,16,27849,256] and [1,24,27891,256]), while the array-mask call is not. Probing only the array-mask case would replace a fused kernel with slower per-chunk fallbacks. The probe has to match the mask mode the call actually uses, and softcap calls should be treated as materializing.
  • The new test does not compile (usize passed where i32 is expected).
  • An existing test breaks on Metal. query_chunk_gate_sizes_mixed_half_kv... assumes no chunking outside CUDA.
  • The new environment variable is undocumented, so scripts/ci/check_env_var_docs.py fails.

We pushed fixes for these to this branch (23bd8cc) while reviewing. With them, a 28K-token prefill on the M3 Ultra dropped from 63.8 to 59.4 GB on qwen3.5-4b-4bit and from 109.7 to 93.1 GB on qwen3.8-27b-4bit, with identical output. Most of the remaining peak is not the score matrix on this host, which we are tracking separately.

Two things also keep this PR from merging: the CLA is not signed, and the fork CI run is waiting for approval. Because the fix needed a redesign of the gate rather than small corrections, we will submit a fresh implementation of #3033 as a new PR, measured on the unfused case as well, and link it here. Your report and the chunking approach are credited there. If you sign the CLA, we are happy to keep reviewing your follow-ups.

@inureyes

Copy link
Copy Markdown
Member

The fresh implementation of #3033 is up as #3049, with your report and the chunking approach credited. On the M3 Ultra it removes the single 26 to 40 GB score buffer of the reporter's call (28K-token prefill peak 66.5 to 44.4 GB on qwen3.5-4b, 114.1 to 78.5 GB on qwen3.8-27b, identical output) and leaves fused calls untouched. It is waiting on an M5 run before merge. Thanks again for tracking this down.

inureyes added a commit that referenced this pull request Nov 14, 2026
## Summary

On Metal, a prefill attention call that MLX does not fuse ran MLX's graph fallback over the whole query axis and allocated the full `[B, heads, L, L]` score matrix in one buffer, because the query-axis chunking that bounds it returned early off CUDA. A ~26.6K-token prompt on a 24-head, head_dim 256 model therefore failed with `metal::malloc` on an M4 Pro. Reported in #3033 by @georgiedekker; supersedes #3034.

- The chunk gate now picks its backend at runtime. CUDA keeps its cuDNN mirrors unchanged. Metal (the backend MLX resolved, not the `metal` Cargo feature, #1988) asks MLX's own `use_fallback` verdict for the mask mode the call actually issues (array mask, causal mode, or none), memoized per shape; a softcap composite always counts as materializing. Only a fallback that would exceed the budget is chunked, so fused kernels keep their route on every GPU generation, and the gates in `attention` and `causal_attention` run ahead of the M5 route for the same reason.
- `MLXCEL_ATTENTION_CHUNK_BUDGET_MB` defaults to 256 MiB on Metal (1024 on CUDA): MLX keeps up to ten command buffers in flight, so about that many chunks are live at once. `MLXCEL_METAL_ATTENTION_CHUNK=0` restores the single-call fallback. Both are documented in `docs/environment-variables.md`.

## Verification (M3 Ultra, pre-M5)

Baseline is the same binary with `MLXCEL_METAL_ATTENTION_CHUNK=0`, which is main's Metal dispatch. Greedy, 48 tokens, reasoning included in the comparison. Full tables, raw CSVs and rerun commands: `docs/benchmark_results/metal-sdpa-query-chunk-m3ultra-2026-11-14.md`.

1. Unfused case. On this build the Qwen 3.5 family's full-attention layers pass an explicit causal array mask, so a single-pass 28K prefill issues exactly the reporter's unfused call (`[1, 24, 28749, 256]`, a 39.7 GB score buffer on the 27B). Peak footprint before/after: qwen3.5-4b 66.46 to 44.38 GB (CLI) and 66.65 to 44.59 GB (server), qwen3.8-27b 114.05 to 78.48 GB (CLI) and 114.21 to 78.65 GB (server). Prefill/TTFT within 1.2% (18.79 to 18.61 s, 89.3 to 90.3 s CLI). Output identical. Op level, one `[1, 24, 28000, 256]` fp16 array-mask call: MLX peak 43.48 to 9.84 GB, 2.08 to 1.41 s, max abs diff 0.
2. Fused case. gemma-4-12b at 28.7K (native window and blocked D512 kernels): 0 gated calls, 23.57 vs 23.56 GB, 33.65 vs 33.56 s, identical. Causal-mode `[1, 24, 28000, 256]`: fused, not chunked, diff 0. The Qwen models have no fused prefill call on this path (item 1), so the reference numbers from the #3034 review (63.8 GB / 18.7 s, 109.7 GB / 85.5 s) are the unfused baseline, reproduced here. With the default 2048-token chunked prefill their later chunks are also unfused and get chunked: peak unchanged, prefill +3.5% (4B) and +1.9% (27B).
3. Short prompt with chunking forced (`MLXCEL_ATTENTION_CHUNK_BUDGET_MB=16`): qwen3.5-4b 4548 tokens (24 gated calls) and gemma-4-12b 4551 tokens (88, including head_dim 512 causal calls MLX does not fuse below 1024 rows): 48 greedy tokens identical.

## Verification (M5 Max)

M5 Max, 40-core GPU, 128 GB, macOS 27.2.1, MLX `9f806b36`; same harness, checkpoints and prompts. Details in the benchmark doc, section "M5+ results"; raw files `m5max-*`.

1. MLX fuses the Qwen array-mask call here, so every 28K cell (single pass and 2048-chunk prefill, all three models) logged 0 gated calls, with peak unchanged (qwen3.5-4b 39.61 GB, qwen3.8-27b 73.78 GB, gemma-4-12b 27.38 GB) and output identical. CLI and server prefill/TTFT agree within 2.2% in an order-reversed, cooled repeat. The back-to-back `verify.sh` matrix read the second arm up to 14% slower because the GPU was throttling, with the gate never firing.
2. Forced 16 MiB cells: only the last 452/455-row prefill chunk falls back on M5 (8 and 48 gated calls, against 24 and 88 on the M3 Ultra), output identical.
3. Op level: the default probe shape is fused in both modes and passes through (diff 0). At head_dim 512 with an array mask (`MLXCEL_SDPA_PROBE_DIM=512`, new probe knobs), which M5 does not fuse, 256 MiB halves the peak (16.22 to 8.23 GB) and is the fastest budget (585 to 412 ms), so the Metal default stands. At 256 MiB that output differs from the single call by 3.05e-5 (1 to 2 fp16 ulp), where the M3 Ultra gave 0. 512 MiB and above give 0. The cause was not traced.

## Test plan

- [x] `cargo test -p mlxcel-core --lib` for `layers::`, `window_sdpa`, `causal` (143 passed), including new tests for the per-mode verdict, the kill switch and head_dim 256 fp16 chunked parity; the CUDA gate test keeps its expectations with an explicit backend
- [x] `cargo clippy -p mlxcel-core --lib --tests -- -D warnings`, `cargo fmt --check`, `check_env_var_docs.py`, `check_benchmark_raw_logs.py`
- [x] Real-model runs above

Closes #3033
@inureyes inureyes closed this Nov 14, 2026
@inureyes

Copy link
Copy Markdown
Member

Closing in favor of #3049, which merged as ab45ac5 and closes #3033. It keeps the query-axis chunking from this PR and gates it per call on MLX's own fallback verdict for the mask mode in use. On the M3 Ultra a 28K-token prefill dropped from 66.5 to 44.4 GB (qwen3.5-4b-4bit) and from 114.1 to 78.5 GB (qwen3.8-27b-4bit) with identical output, and on an M5 Max, where those calls are fused, nothing changed. Thank you for the report and the approach.

@inureyes inureyes added status:done Completed type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority labels Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority:high High priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(metal): bound the materializing prefill SDPA on Metal, where query-axis chunking is gated CUDA-only and long prompts OOM

2 participants