Skip to content

update(models): use MLX causal mode for purely causal hybrid prefill - #3056

Merged
inureyes merged 8 commits into
mainfrom
fix/issue-3051-causal-mode
Nov 15, 2026
Merged

inureyes merged 8 commits into
mainfrom
fix/issue-3051-causal-mode

Conversation

@inureyes

@inureyes inureyes commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

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

@inureyes inureyes added status:in-progress Currently being worked on type:performance Performance improvements priority:high High priority area:models Model architectures, weights, loading, metadata area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:macos macOS (Apple Silicon) specific arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) labels Nov 14, 2026
inureyes added a commit that referenced this pull request Nov 15, 2026
@inureyes
inureyes marked this pull request as ready for review November 15, 2026 00:58
@inureyes

Copy link
Copy Markdown
Member Author

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 docs/benchmark_results/qwen35-prefill-causal-mode-m3ultra-2026-11-15.md (add an M5 section, or a sibling -m5max- doc with its CSVs).

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 q_len != k_len, every piece takes causal mode; if not, they keep the shared array mask as on M3 Ultra.

Build

git fetch origin fix/issue-3051-causal-mode && git checkout fix/issue-3051-causal-mode
cargo build --release --features metal,accelerate --bin mlxcel

1. Interleaved A/B, same binary, causal mode off vs on

Both arms use one binary; the switch is MLXCEL_PREFILL_CAUSAL_MODE (0 restores the pre-change array mask everywhere).

export BASE_BIN=target/release/mlxcel NEW_BIN=target/release/mlxcel MODELS_DIR=<models dir> \
  BASE_ENV=MLXCEL_PREFILL_CAUSAL_MODE=0 NEW_ENV=MLXCEL_PREFILL_CAUSAL_MODE=1
TOKENS=28000 scripts/bench/prefill_peak/ab_prefill.sh <out>/m5_28k
TOKENS=4600 CLI_CELLS="qwen3.5-4b-4bit:2048 qwen3.8-27b-4bit:2048" SERVER_MODELS="" \
  EXTRA_ENV=MLXCEL_ATTENTION_CHUNK_BUDGET_MB=16 scripts/bench/prefill_peak/ab_prefill.sh <out>/m5_4600

Models: mlx-community qwen3.5-4b-4bit and qwen3.8-27b-4bit (the 28K run covers CLI single pass, CLI 2048-token chunks and the server with --parallel 1 for both).

2. Op probe, causal mode against the array mask at the issue's shape

MLXCEL_SDPA_PROBE_LEN=28000 MLXCEL_SDPA_PROBE_HEADS=24 MLXCEL_SDPA_PROBE_KV_HEADS=4 MLXCEL_SDPA_PROBE_DIM=256 \
  RUST_MIN_STACK=16777216 cargo test --release --features metal,accelerate -p mlxcel-core --lib -- --ignored --nocapture sdpa_chunk_peak_memory_probe

3. Unit tests

RUST_MIN_STACK=16777216 cargo test --profile test-fast --features metal,accelerate -p mlxcel-core --lib prefill_causal_mode

What to check

  • identical for every cell in the harness output (greedy output byte-identical between the arms, CLI and server).
  • gated_calls in summary.csv: 0 for the new arm in the 28K single-pass cells; in the chunked cells, record whether it drops to 0 (MLX fuses causal mode for later pieces on M5) or matches the base arm (the shared array mask is kept).
  • Peak (peak_bytes) and prefill time / TTFT per arm, with the spread between the two repetitions and the load average from the CSV; the new arm should not peak above the base arm in any cell.
  • The op probe's causal mode: mlx_fused=... single_call peak=... line against its array-mask line, time and peak (the issue's earlier M5 Max reading was 545 to 668 ms and 5.51 GB for the array mask, 241 to 377 ms and 3.94 GB for causal mode).
  • The 10 prefill_causal_mode unit tests pass.

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.
Main gained the roster count test (#3086) after this branch moved Qwen3Next, GraniteMoeHybrid, Qwen2VL, Qwen3VL and Qwen3VLMoe to prefill_causal_mask. The count drops from 50 to 45 caller files and the group lists drop those names, with a note pointing at prefill_causal_mask.

Refs #3051
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
@inureyes
inureyes force-pushed the fix/issue-3051-causal-mode branch from a25ed39 to a53e1c9 Compare November 15, 2026 19:29
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
@inureyes
inureyes merged commit f6bec18 into main Nov 15, 2026
31 checks passed
@inureyes
inureyes deleted the fix/issue-3051-causal-mode branch November 15, 2026 19:31
inureyes added a commit that referenced this pull request Nov 15, 2026
…#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
inureyes added a commit that referenced this pull request Nov 16, 2026
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
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata platform:macos macOS (Apple Silicon) specific priority:high High priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: Use MLX causal mode instead of a causal array mask in hybrid prefill

1 participant