Repository navigation
fix(models): make the internlm3, hunyuan and gemma2 prefills causal - #1001
Merged
Merged
Conversation
Four more model implementations carried the inverted attention-mask policy that #998 fixed in `deepseek_v2`. Every generation path (CLI text prefill, the VLM embeddings prefill, chunked prefill) calls `LanguageModel::forward` with `mask == None` and expects the model to apply its own causal mask, as documented on `pad_tokens_for_prefill` in `src/lib/mlxcel-core/src/generate.rs` (line 162) and as `llama3.rs`, `deepseek.rs` and `dots1.rs` implement it. `internlm3.rs`, `hunyuan_v1_dense.rs` and `hunyuan_moe.rs` handed that `None` straight to the unmasked `attention_from_ptr` on the `l > 1` branch and called `causal_attention` only at `l == 1`, where causality is vacuous. `gemma2.rs` had no causal-mask machinery at all: one unconditional masked call for both prefill and decode. The symptom scaled with how much the family tolerates future context. On a 44-word prompt `models/internlm3-8b-4bit` emitted `,<|im_end|>` repeated for every token and `models/hunyuan-1.8b-4bit` emitted `was was was was`, while `models/gemma2-2b-4bit` stayed fluent and merely diverged from the mlx-lm 0.31.3 greedy reference partway through the continuation. That last form is why this went unnoticed: for the LAST query position a causal and a bidirectional mask select the same keys, so a six-token prompt answers correctly on all four families while the prefill is fully bidirectional. Route a maskless multi-token prefill through `mlxcel_core::causal_attention` in all four, matching the `llama3.rs` convention. An explicit mask (the padded-prefill case) still takes the masked call, and decode is unchanged because `causal_attention` takes its single-query maskless fast path at `l == 1`. `gemma2.rs` needed more than a branch flip. Gemma 2 sets `attn_logit_softcapping`, so its null mask reached `compiled_softcap_sdpa` in `attention_dispatch`, which applies no causality of its own; bypassing the softcap to reach a causal path would have changed the scores instead of fixing the mask. `causal_attention` already takes a `softcap` argument and threads it into the same composite alongside the additive causal mask, so the fix routes through it with `self.softcapping` rather than around it. `tests/causal_prefill_greedy_parity.rs` closes the coverage gap. `internlm3`, `hunyuan_v1_dense` and `gemma2` get both a greedy-parity gate against mlx-lm 0.31.3 on identical prompt ids and a reference-free gate asserting that the first prompt position's logits do not move when later prompt tokens are added. On the pre-fix code every one of the seven gates fails, the position-0 deviation measuring 1.02e0 for `internlm3`, 1.72e-1 for `gemma2`, 1.50e-1 for `hunyuan_v1_dense` and 6.44e-1 for `hunyuan_moe`; after the fix the same measurements read 1.2e-3, 5.2e-4, 1.49e-2 and 2.12e-2, so each family carries a bound placed between the two (2e-2 for the first two, 5e-2 for the dense Hunyuan, 1e-1 for the MoE). A causal prefill does not drive that deviation to zero, because the two runs reach position 0 through different kernels (single-query maskless SDPA versus masked multi-query, and a 1-row versus an N-row quantized matmul, compounded per layer), and how much that costs varies by family. The assertion therefore also prints the deviation at a ladder of prefill lengths: contaminated attention climbs with the number of later tokens, kernel-path noise stays flat. Every family's ladder is flat or falling at its last rung after the fix, `hunyuan_moe` included at 2.25e-2 over 20 tokens against 2.12e-2 over 41, which is what rules out its residual being causal contamination rather than noise. `hunyuan_moe` is fixed by inspection plus the reference-free causality gate only. The one local checkpoint of that family is `mlx-community/Hunyuan-A13B-Instruct-4bit` at 42 GB and its bf16 sibling does not fit the development machine, so no reference ids are pinned for it and the gate is opt-in behind `MLXCEL_TEST_HUNYUAN_MOE=1` to keep a 42 GB load off the default test run. Two things the parity numbers do not cover, stated so they are not read as coverage. `models/internlm3-8b-4bit` is token-exact against the reference on identical prompt ids, but its end-to-end CLI text still differs, because the checkpoint ships a `tokenizer.json` whose byte-fallback splitting disagrees with its own `tokenizer.model` and mlxcel prefers `tokenizer.json` while the reference harness loads the repo's `InternLM3Tokenizer` under `trust_remote_code`; feeding mlx-lm the `tokenizer.json` ids reproduces mlxcel's CLI output exactly, so the divergence is entirely tokenization and predates this change. And PaliGemma 2 (`mlx-community/paligemma2-3b-ft-docci-448-6bit`), which reaches `gemma2.rs` through `src/loading/vlm_siglip.rs`, is byte-identical before and after at 24 and 60 tokens: `prepare_inputs_for_multimodal` supplies an additive 4D mask, so that path takes the explicit-mask branch and never saw the defect. Closes #999
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
…ablup#1001) Four more model implementations carried the inverted attention-mask policy that lablup#998 fixed in `deepseek_v2`. Every generation path (CLI text prefill, the VLM embeddings prefill, chunked prefill) calls `LanguageModel::forward` with `mask == None` and expects the model to apply its own causal mask, as documented on `pad_tokens_for_prefill` in `src/lib/mlxcel-core/src/generate.rs` (line 162) and as `llama3.rs`, `deepseek.rs` and `dots1.rs` implement it. `internlm3.rs`, `hunyuan_v1_dense.rs` and `hunyuan_moe.rs` handed that `None` straight to the unmasked `attention_from_ptr` on the `l > 1` branch and called `causal_attention` only at `l == 1`, where causality is vacuous. `gemma2.rs` had no causal-mask machinery at all: one unconditional masked call for both prefill and decode. The symptom scaled with how much the family tolerates future context. On a 44-word prompt `models/internlm3-8b-4bit` emitted `,<|im_end|>` repeated for every token and `models/hunyuan-1.8b-4bit` emitted `was was was was`, while `models/gemma2-2b-4bit` stayed fluent and merely diverged from the mlx-lm 0.31.3 greedy reference partway through the continuation. That last form is why this went unnoticed: for the LAST query position a causal and a bidirectional mask select the same keys, so a six-token prompt answers correctly on all four families while the prefill is fully bidirectional. Route a maskless multi-token prefill through `mlxcel_core::causal_attention` in all four, matching the `llama3.rs` convention. An explicit mask (the padded-prefill case) still takes the masked call, and decode is unchanged because `causal_attention` takes its single-query maskless fast path at `l == 1`. `gemma2.rs` needed more than a branch flip. Gemma 2 sets `attn_logit_softcapping`, so its null mask reached `compiled_softcap_sdpa` in `attention_dispatch`, which applies no causality of its own; bypassing the softcap to reach a causal path would have changed the scores instead of fixing the mask. `causal_attention` already takes a `softcap` argument and threads it into the same composite alongside the additive causal mask, so the fix routes through it with `self.softcapping` rather than around it. `tests/causal_prefill_greedy_parity.rs` closes the coverage gap. `internlm3`, `hunyuan_v1_dense` and `gemma2` get both a greedy-parity gate against mlx-lm 0.31.3 on identical prompt ids and a reference-free gate asserting that the first prompt position's logits do not move when later prompt tokens are added. On the pre-fix code every one of the seven gates fails, the position-0 deviation measuring 1.02e0 for `internlm3`, 1.72e-1 for `gemma2`, 1.50e-1 for `hunyuan_v1_dense` and 6.44e-1 for `hunyuan_moe`; after the fix the same measurements read 1.2e-3, 5.2e-4, 1.49e-2 and 2.12e-2, so each family carries a bound placed between the two (2e-2 for the first two, 5e-2 for the dense Hunyuan, 1e-1 for the MoE). A causal prefill does not drive that deviation to zero, because the two runs reach position 0 through different kernels (single-query maskless SDPA versus masked multi-query, and a 1-row versus an N-row quantized matmul, compounded per layer), and how much that costs varies by family. The assertion therefore also prints the deviation at a ladder of prefill lengths: contaminated attention climbs with the number of later tokens, kernel-path noise stays flat. Every family's ladder is flat or falling at its last rung after the fix, `hunyuan_moe` included at 2.25e-2 over 20 tokens against 2.12e-2 over 41, which is what rules out its residual being causal contamination rather than noise. `hunyuan_moe` is fixed by inspection plus the reference-free causality gate only. The one local checkpoint of that family is `mlx-community/Hunyuan-A13B-Instruct-4bit` at 42 GB and its bf16 sibling does not fit the development machine, so no reference ids are pinned for it and the gate is opt-in behind `MLXCEL_TEST_HUNYUAN_MOE=1` to keep a 42 GB load off the default test run. Two things the parity numbers do not cover, stated so they are not read as coverage. `models/internlm3-8b-4bit` is token-exact against the reference on identical prompt ids, but its end-to-end CLI text still differs, because the checkpoint ships a `tokenizer.json` whose byte-fallback splitting disagrees with its own `tokenizer.model` and mlxcel prefers `tokenizer.json` while the reference harness loads the repo's `InternLM3Tokenizer` under `trust_remote_code`; feeding mlx-lm the `tokenizer.json` ids reproduces mlxcel's CLI output exactly, so the divergence is entirely tokenization and predates this change. And PaliGemma 2 (`mlx-community/paligemma2-3b-ft-docci-448-6bit`), which reaches `gemma2.rs` through `src/loading/vlm_siglip.rs`, is byte-identical before and after at 24 and 60 tokens: `prepare_inputs_for_multimodal` supplies an additive 4D mask, so that path takes the explicit-mask branch and never saw the defect. Closes lablup#999
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
Four model implementations carried the same inverted attention-mask policy that #998 fixed in
deepseek_v2: a multi-token prefill with no caller-supplied mask went straight to an unmasked SDPA, so every prompt position attended to every later prompt position and every layer wrote future-contaminated K/V into the cache. This routes that case throughmlxcel_core::causal_attentionininternlm3.rs,hunyuan_v1_dense.rs,hunyuan_moe.rsandgemma2.rs, matching thellama3.rsconvention, and adds a real-checkpoint regression gate.The contract is documented on
pad_tokens_for_prefillinsrc/lib/mlxcel-core/src/generate.rs(line 162): every generation path (CLI text prefill, VLM embeddings prefill, chunked prefill) callsLanguageModel::forwardwithmask == Noneand expects the model to apply its own causal mask.What changed
src/models/internlm3.rs,src/models/hunyuan_v1_dense.rs,src/models/hunyuan_moe.rs: the leaf branch wasif l > 1 { masked_call } else { causal_attention }, so the one case that needed a causal mask never got one and thel == 1decode side got causality it does not need. Nowif l > 1 && mask.is_some(), so a maskless multi-token prefill falls tocausal_attentionand an explicit mask still takes the masked call. Decode is unchanged:causal_attentiontakes its single-query maskless fast path atl == 1.src/models/gemma2.rs: this file had no causal-mask machinery at all, just one unconditional masked call for both prefill and decode. Gemma 2 also setsattn_logit_softcapping, so the null mask reachedcompiled_softcap_sdpainattention_dispatch, which applies no causality of its own. The fix routes the maskless case throughcausal_attentioncarryingself.softcappingrather than bypassing the softcap to reach a causal path, sincecausal_attentionbuilds the additive causal mask and hands it to the same softcap composite.tests/causal_prefill_greedy_parity.rs(new): seven gates in the style oftests/deepseek_v2_greedy_parity.rs. All skip when the checkpoint is absent.src/lib/mlxcel-core/src/lib.rs:causal_attention's// Used by:list now names Gemma 2 and InternLM3, which are new callers. No code change.docs/supported-models.md: the Gemma, InternLM and Hunyuan entries now state the maskless-prefill contract, the validation checkpoint per family, and where coverage stops.Why a short prompt does not catch this
For the last query position a causal and a bidirectional mask select the same keys. A six-token prompt therefore answers correctly on all four families while the prefill is fully bidirectional. Every prompt in the new test is 36 tokens or longer, and every measurement below uses a 44-word prompt.
Per-family before/after
Greedy (
--temp 0), 24 tokens,--no-chat-template, prompt: "The Industrial Revolution began in Great Britain during the late eighteenth century and gradually spread across continental Europe and North America, reshaping agriculture, manufacturing, transportation, and the daily lives of ordinary working people. One important consequence was"models/gemma2-2b-4bitthe rise of factories, which transformed the way people worked and lived. \n\n **Please provide me withthe rise of factories, which transformed the nature of work and labor. \n\nHere's a breakdown of the keymodels/internlm3-8b-4bit,<|im_end|>repeated for all 24 tokensthe emergence of a new class of industrial capitalists. These were the owners of the means of production. Theymodels/hunyuan-1.8b-4bitwas was was was ...(24x)one one one one ...(24x)models/paligemma2-3b-6bit(image +describe en, 60 tokens)A close-up view of a bright orange surface. The surface is smooth, and along the middle ...The Gemma 2 "after" is word-exact with the mlx-lm 0.31.3 greedy reference. The Hunyuan "after" is id-exact with the reference on that raw prompt: this instruction-tuned 4-bit export degenerates on raw text completion under the reference too, and needs its chat template to produce prose, which is why the parity gate uses the chat-templated 36-token form.
Gate coverage per family
internlm3gemma2hunyuan_v1_densehunyuan_moeOn the pre-fix code all seven gates fail.
hunyuan_moeis fixed by code inspection plus the reference-free causality gate only. The only local checkpoint of that family ismlx-community/Hunyuan-A13B-Instruct-4bitat 42 GB and its bf16 sibling does not fit the development machine, so no reference ids are pinned for it and no end-to-end generation comparison exists. Its gate is opt-in behindMLXCEL_TEST_HUNYUAN_MOE=1so a 42 GB load stays off the defaultcargo testrun.A causal prefill does not drive the position-0 deviation to zero, because the two runs reach position 0 through different kernels (single-query maskless SDPA versus masked multi-query, and a 1-row versus an N-row quantized matmul, compounded per layer), and how much that costs varies by family. Each bound above therefore sits between a family's measured residual and its pre-fix figure. So that this stays checkable rather than asserted, the gate also prints the deviation at a ladder of prefill lengths, since contaminated attention grows with the number of later tokens and kernel-path noise does not:
Every ladder is flat or falling at its last rung,
hunyuan_moeincluded (2.25e-2 over 20 later tokens against 2.12e-2 over 41). That shape is what rules out its 2.12e-2 residual being causal contamination.Two things NOT covered, stated explicitly
internlm3end-to-end CLI text still differs from mlx-lm. The model is token-exact on identical prompt ids (that is what the gate asserts). The CLI difference is entirely tokenization: this checkpoint ships atokenizer.jsonwhose byte-fallback splitting disagrees with its owntokenizer.model, mlxcel preferstokenizer.json, and the reference harness loads the repo'sInternLM3Tokenizerundertrust_remote_code. Feeding mlx-lm thetokenizer.jsonids reproduces mlxcel's CLI output exactly, so the divergence predates this change and is out of scope.gemma2.rsthroughsrc/loading/vlm_siglip.rs, butprepare_inputs_for_multimodalinsrc/vision/merge.rssupplies an additive 4D mask, so that path takes the explicit-mask branch. Re-verified byte-identical before and after at 24 and 60 tokens.src/models/minicpm3.rsdeliberately untouched. It has the same leaf shape butMiniCPM3Model::forwardoverrides withcreate_causal_mask(seq_len, offset)wheneverseq_len > 1.Test plan
cargo fmt --all -- --checkcargo clippy --release --all-targets --features metal,accelerate -- -D warnings(release form;make verify-clippyuses the debug profile, which triggers a cold MLX C++ build on this machine)cargo test --release --features metal,accelerate --no-fail-fast: 5230 passed, 0 failed, 271 ignored across 75 test binariesMLXCEL_TEST_HUNYUAN_MOE=1 cargo test --release --features metal,accelerate --test causal_prefill_greedy_paritygemma2-2b-4bit,internlm3-8b-4bit,hunyuan-1.8b-4bitandpaligemma2-3b-6bitCloses #999