Skip to content

fix(models): make the internlm3, hunyuan and gemma2 prefills causal - #1001

Merged
inureyes merged 1 commit into
mainfrom
fix/issue-999-causal-prefill-four-models
Aug 2, 2026
Merged

inureyes merged 1 commit into
mainfrom
fix/issue-999-causal-prefill-four-models

Conversation

@inureyes

@inureyes inureyes commented Aug 2, 2026

Copy link
Copy Markdown
Member

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 through mlxcel_core::causal_attention in internlm3.rs, hunyuan_v1_dense.rs, hunyuan_moe.rs and gemma2.rs, matching the llama3.rs convention, and adds a real-checkpoint regression gate.

The contract is documented on pad_tokens_for_prefill in src/lib/mlxcel-core/src/generate.rs (line 162): every generation path (CLI text prefill, VLM embeddings prefill, chunked prefill) calls LanguageModel::forward with mask == None and 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 was if l > 1 { masked_call } else { causal_attention }, so the one case that needed a causal mask never got one and the l == 1 decode side got causality it does not need. Now if l > 1 && mask.is_some(), so a maskless multi-token prefill falls to causal_attention and an explicit mask still takes the masked call. Decode is unchanged: causal_attention takes its single-query maskless fast path at l == 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 sets attn_logit_softcapping, so the null mask reached compiled_softcap_sdpa in attention_dispatch, which applies no causality of its own. The fix routes the maskless case through causal_attention carrying self.softcapping rather than bypassing the softcap to reach a causal path, since causal_attention builds the additive causal mask and hands it to the same softcap composite.
  • tests/causal_prefill_greedy_parity.rs (new): seven gates in the style of tests/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"

checkpoint before after
models/gemma2-2b-4bit the rise of factories, which transformed the way people worked and lived. \n\n **Please provide me with the rise of factories, which transformed the nature of work and labor. \n\nHere's a breakdown of the key
models/internlm3-8b-4bit ,<|im_end|> repeated for all 24 tokens the emergence of a new class of industrial capitalists. These were the owners of the means of production. They
models/hunyuan-1.8b-4bit was 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 ... byte-identical

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

family reference-id gate causality gate pre-fix deviation post-fix bound
internlm3 yes, mlx-lm 0.31.3, 56 prompt ids yes 1.02e0 1.2e-3 2e-2
gemma2 yes, mlx-lm 0.31.3, 44 prompt ids yes 1.72e-1 5.2e-4 2e-2
hunyuan_v1_dense yes, mlx-lm 0.31.3, 36 prompt ids yes 1.50e-1 1.49e-2 5e-2
hunyuan_moe no yes, opt-in 6.44e-1 2.12e-2 1e-1

On the pre-fix code all seven gates fail.

hunyuan_moe is fixed by code inspection plus the reference-free causality gate only. The only 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 no end-to-end generation comparison exists. Its gate is opt-in behind MLXCEL_TEST_HUNYUAN_MOE=1 so a 42 GB load stays off the default cargo test run.

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:

InternLM3        position-0 deviation by prefill length: 2:0.000e0 14:6.710e-4 28:6.355e-4 56:1.179e-3
Gemma 2          position-0 deviation by prefill length: 2:0.000e0 11:0.000e0  22:5.021e-4 44:5.240e-4
Hunyuan V1 dense position-0 deviation by prefill length: 2:0.000e0  9:0.000e0  18:1.431e-2 36:1.487e-2
Hunyuan MoE      position-0 deviation by prefill length: 2:0.000e0 10:0.000e0  20:2.253e-2 41:2.123e-2

Every ladder is flat or falling at its last rung, hunyuan_moe included (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

  • internlm3 end-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 a tokenizer.json whose byte-fallback splitting disagrees with its own tokenizer.model, mlxcel prefers tokenizer.json, and 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 predates this change and is out of scope.
  • PaliGemma 2 was never affected. It reaches gemma2.rs through src/loading/vlm_siglip.rs, but prepare_inputs_for_multimodal in src/vision/merge.rs supplies 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.rs deliberately untouched. It has the same leaf shape but MiniCPM3Model::forward overrides with create_causal_mask(seq_len, offset) whenever seq_len > 1.

Test plan

  • cargo fmt --all -- --check
  • cargo clippy --release --all-targets --features metal,accelerate -- -D warnings (release form; make verify-clippy uses 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 binaries
  • MLXCEL_TEST_HUNYUAN_MOE=1 cargo test --release --features metal,accelerate --test causal_prefill_greedy_parity
  • Pre-fix control: all seven gates fail with the deviations tabulated above
  • Real-checkpoint generation on gemma2-2b-4bit, internlm3-8b-4bit, hunyuan-1.8b-4bit and paligemma2-3b-6bit

Closes #999

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
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority area:models Model architectures, weights, loading, metadata labels Aug 2, 2026
@inureyes
inureyes merged commit 83af464 into main Aug 2, 2026
4 checks passed
@inureyes
inureyes deleted the fix/issue-999-causal-prefill-four-models branch August 2, 2026 11:26
@inureyes inureyes self-assigned this Aug 31, 2026
@inureyes inureyes added status:done Completed and removed status:review Under review labels Sep 6, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata priority:high High priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(models): internlm3, hunyuan dense/moe and gemma2 run a fully bidirectional prefill

1 participant