Repository navigation
update(models): extend MLX causal mode to the remaining prefill masks - #3097
Merged
Merged
Conversation
The plain-causal hybrids (FalconH1, Plamo2, LFM2, Bailing-MoE-Linear), the full-attention decoders (Llama 4 global layers, Mistral 4, MiniCPM3, Nemotron-NAS), the GLM4V family and the tensor-parallel Qwen 3.5 runtime now build their prefill mask through prefill_causal_mask. The sliding-window families (Cohere2, Cohere2-MoE, Cohere Compass, OLMo 3, Ministral 3, EXAONE 4, EXAONE-MoE, Mellum, Step 3.5, AFMoE, Gemma 3n) use the new prefill_sliding_window_mask, which leaves the band to MLX's causal mode inside the window and to the native window_size entry past it wherever MLX fuses the call; maskless_prefill_attention is the attention side of both. Padded, batched, caller-masked and speculative forwards keep the shared array. The Jamba and Nemotron-H pipeline stages and the tensor-parallel Gemma 3 runtime now use their single-process models' masks. Gemma 2 shares one softcapped causal mask per forward instead of one per layer. Cohere2, OLMo 3, MiniCPM3, Gemma 3n and Mistral 4 opt into maskless padded prefill. PrefillAttention gains a value head dim for the MLA-style concatenated heads. On M5 Max, greedy output is byte-identical to main on lfm2, llama-4-scout, exaone-4.0, command-r7b, glm-4.1v, gemma-3n and gemma-2, and teacher-forced traces agree at every position. A 28K single pass drops from 9.82 to 4.05 GB on exaone-4.0-1.2b and from 23.05 to 13.05 GB on gemma-3n-e2b. Sink SDPA and the MLA paths that add the mask to scores (KimiLinear, GLM4-MoE-Lite, KimiK3, LongCat, DeepSeek V4) are unchanged. Closes #3072
5 tasks done
inureyes
marked this pull request as ready for review
November 15, 2026 21:31
This was referenced Nov 15, 2026
inureyes
added a commit
that referenced
this pull request
Nov 16, 2026
…#3103) ## Summary Opts GLM4V, GLM4V-MoE, Nemotron-NAS, Cohere2-MoE and EXAONE-MoE into `supports_maskless_padded_prefill`, so a tile-aligned padded prefill piece of these families skips `create_padded_prefill_mask`. Follows the five opt-ins of #3097. - Cohere2-MoE and EXAONE-MoE already built their own causal and sliding masks and handled a mask-less multi-token forward, so they only needed the opt-in. - GLM4V and GLM4V-MoE (text backbones and the VLM wrappers) opt in. Their MRoPE positions did not depend on the mask, but a padded embedding prefill was wrong: the stored image positions cover only the real prompt, so the padded piece fell back to `index + rope_deltas` for every row, giving the real rows after an image the wrong positions. `padded_tail_positions` now keeps the stored rows for the real tokens and continues from them for the pad rows. - Nemotron-NAS keeps its caches inside the model, out of the engine's reach, which is why it declined padding. It now implements `trim_state` over those caches and enables both padded and maskless padded prefill. - EXAONE-MoE finding: `create_padded_prefill_mask` is plain causal, so the masked arm ignores the sliding window past it (relative RMS 2.9e-3 from the unpadded forward on the tiny model). The maskless arm matches the unpadded forward exactly, so the opt-in is also the more accurate path there. ## Parity gates Each gate prefills unpadded, padded without a mask, and padded with the padding mask, trims the pad, decodes one token, and compares both rows. | Family | Model | Maskless vs masked (prefill / decode) | Maskless vs unpadded | |---|---|---|---| | GLM4V, GLM4V-MoE (text, image positions on and off, ids and embeddings) | tiny random weights | 0 / 0 | 0 / 0 | | Nemotron-NAS | tiny random weights | 0 / 0 | 0 / 0 | | Cohere2-MoE (sigmoid, softmax; 20 tokens past a 16-token window) | tiny random weights | 0 / 0 | 6e-8 / 8e-8 | | EXAONE-MoE | tiny random weights | 0 / 0 inside the window | 0 / 0 | | glm-4.1v-9b-thinking-4bit | checkpoint | 0 / 0 | 0 / 0 | | llama-3_3-nemotron-super-49b-4bit | checkpoint | 0 / 0 | 0 / 0 | | glm-4.5v-4bit (glm4v_moe) | checkpoint | 0 / 0 | 2.5e-2 / 2.2e-2 on both arms alike (MoE padded-width kernel difference) | No benchmark was run: the change drops one `[1, 1, L, L]` mask per padded piece and moves no arithmetic. ## Test plan - [x] `models::padded_prefill_parity_tests`, the Cohere2-MoE and EXAONE-MoE gates, the Nemotron-NAS engine test - [x] `tests/maskless_padded_prefill_parity.rs` on the three local checkpoints, lock-wrapped - [x] fmt, narrow clippy, env-var docs, benchmark raw-log check, kernel dtype keys, causal-mask roster test Closes #3101
inureyes
added a commit
that referenced
this pull request
Nov 16, 2026
…3104) ## Summary Llama 4's MoE (chunked-attention) layers built one dense f32 `[L, S]` chunk mask per prefill forward and ran the masked SDPA over every visible key, which set Llama 4's single-pass peak after #3097. A one-row prefill now passes no mask to those layers: `Llama4Cache::attend` splits the step at chunk boundaries and runs MLX's causal-mode SDPA per piece over that piece's own keys (`chunked_causal_attention` in `llama4_helpers.rs`). A piece that starts mid-chunk behind a cache attends to the cached keys of its chunk plus its own, through causal mode's bottom-right alignment; the key range starts at the chunk start or the cache's `start_position`, whichever is later. The dense mask stays where `prefill_uses_causal_mode` says no (batched rows, speculative verify blocks, `MLXCEL_PREFILL_CAUSAL_MODE=0`), so the kill switch restores main's dispatch. A decode row and a caller mask keep `ChunkedKVCache::attend`. The legacy `Llama4CxxModel::forward` (plain `KVCache`) does not use the chunk mask and is unchanged. ## Measurements (M5 Max, llama-4-scout-17b-16e-instruct-4bit, 19717 tokens, two alternated repetitions) | Path | Peak, main to branch | Prefill, main to branch (rep 1, rep 2) | |---|---|---| | single pass | 72.88 to 68.41 GB | 37.92 / 27.31 s to 38.50 / 27.73 s | | 2048-token chunks | 65.86 to 65.70 GB | 22.25 / 27.48 s to 21.29 / 17.84 s | Greedy output is byte-identical in both cells and both repetitions. Prefill timing is within the shared host's load noise (load 1.6 to 30), so no prefill change is claimed. Teacher-forced logit trace, dense mask (`MLXCEL_PREFILL_CAUSAL_MODE=0`) against the branch default, three 2048-token forwards behind 7168 tokens of context (each crosses the 8192 boundary mid-forward): 0 / 6144 top-1 disagreement, 0 / 756 on decided positions, max logit delta 0.0000, perplexity 11.4503 in both. A width-10000 single-pass trace ran out of memory in both arms (full-vocabulary logits per row), so the single pass is covered by the CLI identity and the unit tests. Details in `docs/benchmark_results/llama4-chunked-attention-m5max-2026-11-15.md`. ## Test plan - [x] New unit tests compare the maskless path with the dense mask at offset 0 (inside one chunk and across chunks), mid-chunk, mid-chunk across a boundary, behind a trimmed front, on a chunk boundary, and in f16; a synthetic-weight model test checks a 5 + 15 split prefill against the single pass (`models::llama4`, 18 passed). - [x] `create_causal_mask_roster_count_matches_repo`, `cargo fmt --check`, clippy for `mlxcel` lib and tests, `check_env_var_docs.py`, `check_benchmark_raw_logs.py`, `make verify-kernel-dtype-keys`. ## Not changed Decode (`q_len == 1`) still attends unmasked over the cache's visible window, which after the front trim holds the last `chunk_size` keys and so can include the previous chunk's keys once a context passes 8192 tokens; mlx-lm's `chunk_mask` excludes them. That predates this PR and is left for a separate issue. Closes #3100
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
This was referenced Nov 17, 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.
Summary
Extends #3051's
prefill_causal_maskto 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 throughmaskless_prefill_attentioninstead 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 nativewindow_sizeentry, each only where MLX fuses the call; otherwise the one shared band stays.softcap_prefill_causal_mask).PrefillAttentioncarries a value head dim, so the MLA-style concatenated heads ask MLX the right question.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)
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=0vs default) show 0 disagreements at decided positions and max logit delta 0.0000 on all six traced models.Test plan
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 testtests/maskless_padded_prefill_parity.rson cohere2, olmo3, minicpm3, gemma3n and mistral4 checkpoints (relative RMS 0)Closes #3072