Repository navigation
update(models): use MLX causal mode for purely causal hybrid prefill - #3056
Conversation
M5 verification request (blocks merge)Issue #3051 requires a run on an M5-generation GPU. The host this PR was built on is an M3 Ultra, so this PR is ready but must not merge until the M5 numbers below are recorded in On M5 the choice depends on MLX's own verdict, so the cells after the first piece are where M5 differs from the M3 Ultra: if MLX fuses causal mode there with Build1. Interleaved A/B, same binary, causal mode off vs onBoth arms use one binary; the switch is Models: 2. Op probe, causal mode against the array mask at the issue's shape3. Unit testsWhat to check
|
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.
The generic Engine::verify forward runs a [1, k+1] block with no caller mask, so it qualified for causal mode in every family this change wires. The decision now also requires that no DecodeLookaheadAppendScope is active, which keeps the verify dispatch it had before. The decision is split into a pure function so the tests do not depend on MLXCEL_PREFILL_CAUSAL_MODE in the environment, and a bf16 head_dim 256 equivalence case behind a cache is added.
…al mode On pre-M5 Metal, MLX falls back for causal SDPA at head_dim 256 over q_len != k_len, which is every prefill piece after the first. There causal_attention ran its per-layer chunked causal fallback, which peaked 2.6% (qwen3.5-4b) and 4% (qwen3.8-27b) above the shared array mask at 28K tokens with 2048-token chunks. prefill_causal_mask now takes the full-attention geometry and the activation dtype and asks MLX's own verdict (sdpa_mode_is_fused, memoized per shape) whether causal mode fuses; where it does not, the model keeps building its one array mask for every layer, the pre-change dispatch. Non-Metal backends report no fused kernel and so keep the array mask too. The bench harness now honors SERVER_MODELS="" as documented.
COOLDOWN (seconds, default 0) sleeps before every CLI and server run, so a thermally limited host such as the M5 Max keeps the two arms comparable instead of throttling the later runs of a back-to-back sweep. Refs #3051
a25ed39 to
a53e1c9
Compare
Main build against this branch on an M5 Max (MLX 9f806b36), with a 75 s cooldown and A/B then B/A order. MLX fuses the head_dim 256 array mask here too, so main logs no gated calls at 28K, but causal mode still cuts the single-pass peak from 14.53 to 8.76 GB (qwen3.5-4b-4bit) and from 31.83 to 26.03 GB (qwen3.8-27b-4bit), and prefill by 20.6% and 22.6%. The later 2048-token pieces take causal mode as well, lowering the 28K chunked peak by 6.0% and 1.7%. At 4.6K the short last piece keeps the shared array mask because MLX reports causal mode unfused there. Greedy output is byte-identical in every cell and repetition. The CHANGELOG entry and the technical report now carry the M5 numbers; the M3 Ultra data is unchanged. Refs #3051
…#3097) ## Summary Extends #3051's `prefill_causal_mask` to the remaining models that built a dense f32 prefill mask once per forward, adds its sliding-window counterpart, and covers the two update items (Gemma 2's per-layer softcap mask, maskless padded prefill opt-ins). - `prefill_causal_mask`: FalconH1, Plamo2, LFM2 (and its speculative prefill), Bailing-MoE-Linear, Llama 4 global layers, Mistral 4, MiniCPM3, Nemotron-NAS, GLM4V, GLM4V-MoE, HunyuanVL, PaddleOCR-VL, ERNIE 4.5 MoE VL, the TP Qwen 3.5 runtime. FalconH1, Plamo2, Nemotron-NAS, Mistral 4, MiniCPM3 and the GLM4V family now route a mask-less multi-token forward through `maskless_prefill_attention` instead of an unmasked SDPA. - `prefill_sliding_window_mask` (new): Cohere2, Cohere2-MoE, Cohere Compass, OLMo 3, Ministral 3, EXAONE 4, EXAONE-MoE, Mellum, Step 3.5, AFMoE, Gemma 3n. Inside the window it asks for causal mode, past it for MLX's native `window_size` entry, each only where MLX fuses the call; otherwise the one shared band stays. - Jamba and Nemotron-H pipeline stages and the TP Gemma 3 runtime now match their single-process models. - Gemma 2 shares one softcapped causal mask per forward (`softcap_prefill_causal_mask`). - `PrefillAttention` carries a value head dim, so the MLA-style concatenated heads ask MLX the right question. - Cohere2, OLMo 3, MiniCPM3, Gemma 3n and Mistral 4 opt into `supports_maskless_padded_prefill`. Padded, batched, caller-masked and speculative forwards keep the array mask, as in #3056. Out of scope and unchanged: sink SDPA (gpt_oss, falcon_ocr, laguna, mimo_v2_flash, DeepSeek V4) and the MLA paths that add the mask to scores (KimiLinear, GLM4-MoE-Lite and its pipeline stage, KimiK3, LongCat). ## Measurements (M5 Max, main vs branch, two interleaved repetitions) | Model | Prompt | Path | Peak, main to branch | Prefill, main to branch | |---|---|---|---|---| | lfm2-8b-a1b-4bit | 19717 | single pass | 13.50 to 11.63 GB | 4.06 to 2.06 s | | llama-4-scout-17b-16e-instruct-4bit | 19717 | single pass | 72.88 to 73.00 GB | 27.50 to 26.07 s | | exaone-4.0-1.2b-4bit | 28706 | single pass | 9.82 to 4.05 GB | 6.07 to 2.87 s | | c4ai-command-r7b-12-2024-4bit | 7508 | single pass | 8.57 to 7.99 GB | 2.30 to 2.06 s | | glm-4.1v-9b-thinking-4bit | 22755 | 2048 chunks | 8.91 to 8.40 GB | 11.94 to 11.16 s | | gemma-3n-e2b-it-4bit | 28706 | single pass | 23.05 to 13.05 GB | 10.48 to 4.53 s | Chunked cells, Gemma 2 and the remaining rows are in `docs/benchmark_results/prefill-causal-mode-remaining-m5max-2026-11-15.md`. Greedy output is byte-identical to main in every cell. Teacher-forced traces (3 x 2048-token forwards behind 2048, `MLXCEL_PREFILL_CAUSAL_MODE=0` vs default) show 0 disagreements at decided positions and max logit delta 0.0000 on all six traced models. ## Test plan - [x] `utils::prefill_sliding_mask_tests` (new, one test per helper branch plus window and softcap equivalence), `utils::prefill_causal_mode_tests`, `window_sdpa_tests`, roster count test - [x] 714 unit tests of the touched model and TP modules - [x] `tests/maskless_padded_prefill_parity.rs` on cohere2, olmo3, minicpm3, gemma3n and mistral4 checkpoints (relative RMS 0) - [x] fmt, narrow clippy for both crates, env-var docs, benchmark raw-log check, kernel dtype keys Closes #3072
The sink SDPA bridge took only an explicit array mask, so GPT-OSS, Laguna, Falcon-OCR, MiMo v2 Flash and DeepSeek-V4 built a dense f32 prefill band that #3056 and #3097 had removed everywhere else. MLX already accepts mask_mode "causal" and window_size together with sinks. Add fast_scaled_dot_product_attention_with_sinks_causal (a cxx Result, so MLX validation errors do not abort) and let the fused-kernel probe ask with sinks. prefill_sdpa::causal_prefill_attention takes the maskless call where prefill_uses_causal_mode allows it and MLX fuses it, else builds the same band. PrefillAttention gains a sinks flag so prefill_causal_mask and prefill_sliding_window_mask decide with sink geometry. GPT-OSS (single model and pipeline stage), Falcon-OCR, MiMo v2 Flash and all-local DeepSeek-V4 stacks use the shared helpers; Laguna's layers call causal_prefill_attention. The OpenAI privacy filter's symmetric band is unchanged. M5 Max, main vs branch: gpt-oss-20b-mxfp4-q4 at 19,773 tokens peaks 17.86 GB instead of 22.54 GB single pass (prefill 6.63 to 3.62 s) and 13.16 instead of 13.42 GB in 2048-token chunks; laguna-xs.2-4bit at 28,747 tokens 29.25 instead of 35.84 GB; falcon-ocr 4.70 instead of 5.11 GB. Greedy output is byte-identical in every cell. New unit tests compare the causal sink entry and the routed helper with the explicit-mask call and an f64 host reference. Closes #3098
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)returnsNone(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 equalscreate_causal_mask(seq_len, offset)at any cache offset.MLXCEL_PREFILL_CAUSAL_MODE=0restores it everywhere (documented indocs/environment-variables.md).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.rsandqwen2_vl.rs. Position ids feed only RoPE, so the Qwen-VL MRoPE paths qualify as well; their attentionforwardgained the causal-mode branch for a mask-less multi-token call.scripts/bench/prefill_peak/ab_prefill.shgainedBASE_ENV/NEW_ENVper-arm environment and agated_callscolumn, and honorsSERVER_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.prefill_causal_modetests 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, 610server::batchand 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, MLX9f806b36, A/B then B/A with a 75 s cooldown before each run (newCOOLDOWNknob inab_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.[1,24,28000,256]fp16: array mask 5.51 GB / 557 ms, causal mode 3.94 GB / 245 ms, both fused.prefill_causal_modeand 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. Thecreate_causal_maskroster count drops from 50 to 45 caller files.Closes #3051