Repository navigation
fix(metal): bound the materializing prefill SDPA on Metal - #3049
Conversation
The query-axis chunking that keeps MLX's SDPA fallback score matrix within MLXCEL_ATTENTION_CHUNK_BUDGET_MB returned early on every non-CUDA build, so on Metal an unfused prefill attention call allocated all [B, heads, L, L] scores at once and a ~26K-token prompt aborted with metal::malloc on an M4 Pro. The chunk gate now resolves a backend at runtime: CUDA keeps its cuDNN mirrors unchanged, and 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. A softcap composite always counts as materializing. The budget is checked first, so the probe runs only for over-budget calls, and the verdict is memoized per shape in window_sdpa. Both gates in attention and causal_attention now run ahead of the M5 route, which issues the same SDPA, and fire only on a fallback, so fused kernels keep their route on every GPU generation. MLXCEL_METAL_ATTENTION_CHUNK=0 restores the single-call fallback. New tests pin the per-mode verdict (causal head_dim 256 q == k stays unchunked, a later prefill chunk is chunked), the kill switch parse, and chunked-vs-single parity at head_dim 256 fp16 with causal, array-mask and softcap calls. The existing CUDA gate test passes its backend explicitly and keeps its expectations. Refs #3033
MLX keeps up to ten command buffers in flight and frees a chunk's scores only when its buffer completes, so on Metal about that many chunks are live at once and the transient is a multiple of the budget, not the budget. For one [1, 24, 28000, 256] fp16 array-mask call on an M3 Ultra the single call peaked at 43.5 GB of MLX memory, chunked at 1024 MiB at 26.0 GB and at 256 MiB at 9.8 GB, all chunked variants faster than the single call. MLXCEL_ATTENTION_CHUNK_BUDGET_MB therefore defaults to 256 on Metal and stays 1024 on CUDA; an explicit value overrides both. Adds an ignored op-level probe test (MLX peak memory and output difference of the gated call against the single call), the benchmark doc with the M3 Ultra results (CSV raw data), and rerunnable verify scripts for the CLI and server paths under scripts/bench/metal_sdpa_chunk/. The probe shape variables are allowlisted as test-only. On qwen3.5-4b and qwen3.8-27b a 28K single-pass prefill drops from 66.5 to 44.4 GB and 114.0 to 78.5 GB peak footprint with identical greedy output and unchanged prefill time; Gemma 4, whose calls MLX fuses, is untouched. An M5+ section is left pending. Refs #3033
M5 Max verification request (blocks merge)The gate asks MLX per call whether the SDPA it is about to issue would fall back, and MLX's answer depends on the GPU generation (#2646: on M5 and later the array-mask call at head_dim 256 fuses). The M3 Ultra results in this PR cover the pre-M5 side only. Please run the same harness on the M5 Max before this PR is merged and post the results here. Setup gh pr checkout 3049 --repo lablup/mlxcel
cargo build --release --bin mlxcel
pgrep -x mlxcel || pgrep -x mlxcel-server # must print nothing; keep the GPU idle during the runsModels (same checkpoints as the M3 Ultra run, in one directory): Runs # CLI matrix: 28K single-pass and 2048-chunk prefill on all three models, plus the forced 4.6K cells
MODELS_DIR=/path/to/models scripts/bench/metal_sdpa_chunk/verify.sh /tmp/verify-3033-m5
# Server path, 4B at 28K (port 8110)
MODELS_DIR=/path/to/models scripts/bench/metal_sdpa_chunk/server_verify.sh /tmp/verify-3033-m5 qwen3.5-4b-4bit 28000
# Op-level probe at the default and two other budgets
for b in 256 1024 16; do
MLXCEL_ATTENTION_CHUNK_BUDGET_MB=$b MLXCEL_SDPA_PROBE_LEN=28000 RUST_MIN_STACK=16777216 \
cargo test --profile test-fast -p mlxcel-core --lib metal_chunk_tests::sdpa_chunk_peak_memory_probe -- --ignored --nocapture
doneWhat to check
Report back Chip, GPU core count, memory, macOS version, MLX pin, and |
The gate's verdict comes from MLX and MLX fuses more on M5, so the M3 Ultra results did not cover that generation. On an M5 Max (40-core GPU, 128 GB, macOS 27.2.1, MLX 9f806b36) every 28K cell, single pass and 2048-token chunked prefill on qwen3.5-4b, qwen3.8-27b and gemma-4-12b, logged 0 gated calls with unchanged peak footprint, and every cell's greedy output matched its MLXCEL_METAL_ATTENTION_CHUNK=0 baseline. The forced 16 MiB cells chunked only the last, sub-2048-row prefill chunk. verify.sh runs the two arms back to back, and on this GPU the second arm read up to 14% slower with the gate never firing. An order-reversed repeat with a 90 s pause before each run put both arms within 2.2%, so the benchmark doc reports that control and says to use one. The op-level probe takes MLXCEL_SDPA_PROBE_DIM and MLXCEL_SDPA_PROBE_KV_HEADS, because its default shape is fused on M5. At head_dim 512 with an array mask, 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; its output differs from the single call by 3.05e-5 (1 to 2 fp16 ulp), while 512 MiB and above give 0. Refs #3033
M5 Max verification resultsApple M5 Max, 40-core GPU, 128 GB, macOS 27.2.1 (26B131), MLX Checks requested in the comment above:
One new observation: at 256 MiB that head_dim 512 call differs from the single call by 3.05e-5 (1 to 2 fp16 ulp) on every repetition, while 512 MiB and above, and the M3 Ultra, give 0. The text was still identical in every model run. I did not trace the cause. It does not look like a merge blocker to me, but it should be on record next to the "diff 0" claims. No regression found on M5: no fused call was chunked, prefill time did not change, and no output text changed. |
…3083) ## Summary DeepSeek V3-family (Kimi-VL, Kimi-K2, Youtu) and DeepSeek V3.2 multi-token MLA steps no longer build the dense `[B, H, L, S]` rope-score tensor. `mla::rope_folded_attention` concatenates `[q_nope | q_pe]` and `[k | k_pe]` along the head dim, as mlx-lm's `deepseek_v2.py` does, and applies MLX causal mode, the caller's mask, or V3.2's top-k mask (now `[B, 1, L, S]`, shared by every head). MLX does not fuse a query width (192, or 576 absorbed) that differs from the value width (128 / 512), so the call takes the fallback that the #3049 gate query-chunks to 256 MiB. The shared `absorbed_attention` uses the same call for a multi-token step (DeepSeek V2 with `MLXCEL_MLA_ABSORBED=1`). Single-token decode keeps the rope-mask form, unchanged. DeepSeek V2's default path already concatenated, and its attention is already chunked since #3049, so it does not move: main reproduces the issue's 27.98 / 54.44 GB with every attention call bounded. That remainder is something other than the score tensor and is not addressed here. ## Measurements (M5 Max, 28K-token prompt, greedy 48 tokens, cooled, order reversed between reps) | model | prefill | peak main | peak branch | prefill main / branch (rep 2) | output | |---|---|---|---|---|---| | kimi-vl-a3b-thinking-4bit (19723 tok) | 2048 chunks | 19.99 GB | 14.43 GB | 28.07 / 25.78 s | identical | | kimi-vl-a3b-thinking-4bit | single pass | 76.31 GB | 32.03 GB | 35.37 / 30.88 s | differs | | deepseek-v2-lite-chat-4bit-mlx (28705 tok) | 2048 chunks | 27.98 GB | 27.98 GB | 42.84 / 42.81 s | identical | | deepseek-v2-lite-chat-4bit-mlx | single pass | 54.32 GB | 54.32 GB | 52.70 / 52.85 s | identical | | deepseek-v2-lite, `MLXCEL_MLA_ABSORBED=1` | 2048 chunks | 15.13 GB | 15.13 GB | 42.73 / 42.64 s | identical | The Kimi-VL single-pass output diverges at a near-tie phrasing in the first reasoning sentence. Here is the teacher-forced `logit_trace` of main vs branch with `--decided 2`. At width 2048 from a cold start, 1 of 2627 decided positions disagrees (0.038%, largest gap 2.18). At width 2048 behind 2048 context, 0 of 2731 do. 90 to 93% of all disagreements land on the reference's rank 2, and perplexity is 0.04 to 0.06% lower. Full tables: `docs/benchmark_results/mla-prefill-rope-fold-m5max-2026-11-15.md`. ## Test plan - [x] `mlxcel-core` `mla::` (53, including 5 new `prefill_tests` against the host f64 MLA reference: causal mode behind a cache, array mask, f16, absorbed latent shape, and the chunked causal fallback on the folded latent shape) - [x] `mlxcel` `models::deepseek_v3`, `deepseek_v32`, `deepseek_v2`, `youtu_vl_lm`, `mla_batched` - [x] fmt, narrow clippy for both crates, `check_env_var_docs.py`, `check_benchmark_raw_logs.py`, `make verify-kernel-dtype-keys` - [x] Real checkpoints above. No V3.2 checkpoint fits the host, so its path is covered by unit tests only. Closes #3071
The full-attention layers of the hybrid and Qwen-VL models built an explicit causal array mask for every prefill, which MLX does not fuse on pre-M5 Metal and which forced the bounded query-chunked fallback from #3049. prefill_causal_mask returns None when the mask would be purely causal (more than one query row, batch 1, no caller mask), so the layer's SDPA runs through causal_attention with MLX's bottom-right alignment, which matches create_causal_mask at any cache offset. Batched or caller-masked prefill and speculative verify keep the array mask. MLXCEL_PREFILL_CAUSAL_MODE=0 restores the array mask. Wired into qwen3_5, qwen3_next, granitemoehybrid, qwen3_vl, qwen3_vl_moe and qwen2_vl.
…3056) ## Summary Full-attention layers of the hybrid and Qwen-VL models built an explicit f32 causal array mask for every prefill. Before M5, MLX fuses SDPA in causal mode at head_dim 256 but not with an array mask, so a single-pass prefill took the query-chunked fallback from #3049 and kept a 3.65 GiB mask alive at 28K tokens. This PR routes prefill through MLX's causal mode where that is equivalent and MLX actually fuses it. - `mlxcel_core::utils::prefill_causal_mask(seq_len, offset, batch, attention, activation_dtype)` returns `None` (causal mode) when the forward has more than one query, batch 1, no caller mask, is not a speculative verify block (`DecodeLookaheadAppendScope`), and MLX's own verdict (`window_sdpa::sdpa_mode_is_fused`, memoized per shape) says causal SDPA fuses at that shape. MLX aligns causal mode bottom-right (`kL - qL`), which equals `create_causal_mask(seq_len, offset)` at any cache offset. - Where causal mode would fall back too (pre-M5, every prefill piece after the first at head_dim 256), the model keeps its one array mask shared by every full-attention layer, which is the earlier dispatch. Two alternatives that put causal mode everywhere raised the chunked peak by 4% and 11% on qwen3.8-27b; both are measured in the benchmark doc. - Batched or caller-masked prefill, decode, speculative verify and non-Metal backends keep the array mask. `MLXCEL_PREFILL_CAUSAL_MODE=0` restores it everywhere (documented in `docs/environment-variables.md`). - Wired into the real forward paths: `qwen3_5.rs` (prefill, capture-layer and last-hidden prefill, pipeline stage), `qwen3_next.rs` (sequence forward and stage), `granitemoehybrid.rs`, `qwen3_vl.rs`, `qwen3_vl_moe.rs` and `qwen2_vl.rs`. Position ids feed only RoPE, so the Qwen-VL MRoPE paths qualify as well; their attention `forward` gained the causal-mode branch for a mask-less multi-token call. - `scripts/bench/prefill_peak/ab_prefill.sh` gained `BASE_ENV`/`NEW_ENV` per-arm environment and a `gated_calls` column, and honors `SERVER_MODELS=""`. ## Verification (M3 Ultra) Same binary, `MLXCEL_PREFILL_CAUSAL_MODE=0` (base) against the default, interleaved A/B/B/A in one GPU lock hold, load average 0.3 to 5.4. Full tables and CSVs for both hosts: `docs/benchmark_results/qwen35-prefill-causal-mode-m3ultra-2026-11-15.md`. | 28K tokens | qwen3.5-4b-4bit | qwen3.8-27b-4bit | |---|---|---| | CLI single pass peak | 30.13 to 19.82 GB | 64.20 to 53.96 GB | | CLI single pass prefill | 16.89 to 13.38 s (-20.8%) | 86.09 to 73.33 s (-14.8%) | | CLI single pass gated calls | 8 to 0 | 16 to 0 | | CLI 2048 chunks peak / prefill | 8.97 GB, 13.87 to 13.85 s | 25.80 GB, 74.77 to 74.74 s | | server peak / TTFT | 9.10 GB, 13.90 to 13.89 s | 25.92 GB, 74.88 to 74.81 s | - 4.6K tokens with 2048-token chunks: peaks unchanged (5.34 and 19.85 GB), prefill -0.8% and -0.5%, gated calls 24 to 16 and 48 to 32. Only the first piece fuses in causal mode on this hardware; the later pieces fall back in MLX whatever mask they get, so the acceptance item "gated calls drop to 0" holds for the single-pass cells but not the chunked ones on pre-M5. - Greedy output byte-identical between arms in every cell, CLI and server, and for an image prompt on qwen3.5-4b-4bit in both repetitions. - Tests: 10 `prefill_causal_mode` tests in mlxcel-core (offset 0, offset > 0 and a bf16 head_dim 256 case numerically against the array mask, padded, batched, decode, verify block, a shape MLX does not fuse, kill switch); 96 model, 610 `server::batch` and 328 prompt-cache tests on Metal after merging main. One combined run of all three groups aborted without a panic message after 19 tests; it did not reproduce in two further model runs or in the separate groups, so it is recorded as an intermittent crash of the combined Metal test set. Clippy (mlxcel and mlxcel-core lib and tests), fmt and the five contract checks pass. ## Verification (M5 Max) Rebased onto main at `49ea6cc9`. A main build against the branch build, MLX `9f806b36`, A/B then B/A with a 75 s cooldown before each run (new `COOLDOWN` knob in `ab_prefill.sh`). On M5 MLX fuses the head_dim 256 array mask too, so main already has 0 gated calls at 28K; causal mode still drops the f32 mask and the fused kernel's larger working set, and the 2048-row pieces behind a cache take causal mode as well because MLX reports them fused. | 28K tokens | qwen3.5-4b-4bit | qwen3.8-27b-4bit | |---|---|---| | CLI single pass peak | 14.53 to 8.76 GB | 31.83 to 26.03 GB | | CLI single pass prefill | 12.71 to 10.09 s (-20.6%) | 57.65 to 44.63 s (-22.6%) | | CLI 2048 chunks peak | 6.06 to 5.70 GB | 20.69 to 20.34 GB | | CLI 2048 chunks prefill | 7.78 to 7.67 s | 40.75 to 39.95 s | - 4.6K with 2048-token chunks: peak 4.13 to 4.07 GB and 17.15 to 17.10 GB, prefill -1.0% and -2.9% (27B rerun with four repetitions after a one-off slow branch reading; both passes are in the CSVs). Gated calls stay 8 and 16: they are the short last piece (452 and 494 rows), where MLX reports causal mode unfused too, so the shared array mask is kept as on main. - Greedy output byte-identical between main and branch in every cell and every repetition, so no logit trace was needed. Server cells were not rerun on M5. - Op probe at `[1,24,28000,256]` fp16: array mask 5.51 GB / 557 ms, causal mode 3.94 GB / 245 ms, both fused. - 11 `prefill_causal_mode` and roster tests, 96 model tests (qwen3_5, qwen3_next, granitemoehybrid, qwen2_vl, qwen3_vl), narrow clippy for mlxcel and mlxcel-core, fmt, env-var docs, raw-logs and kernel dtype-key checks pass. The `create_causal_mask` roster count drops from 50 to 45 caller files. Closes #3051
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 withmetal::mallocon an M4 Pro. Reported in #3033 by @georgiedekker; supersedes #3034.metalCargo feature, fix: diagnose automatic QMV retry failure on M5 Ultra #1988) asks MLX's ownuse_fallbackverdict 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 inattentionandcausal_attentionrun ahead of the M5 route for the same reason.MLXCEL_ATTENTION_CHUNK_BUDGET_MBdefaults 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=0restores the single-call fallback. Both are documented indocs/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, 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.[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 fix(metal): bound materializing SDPA prefill by chunking the query axis #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).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 filesm5max-*.verify.shmatrix read the second arm up to 14% slower because the GPU was throttling, with the gate never firing.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
cargo test -p mlxcel-core --libforlayers::,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 backendcargo clippy -p mlxcel-core --lib --tests -- -D warnings,cargo fmt --check,check_env_var_docs.py,check_benchmark_raw_logs.pyCloses #3033