Repository navigation
fix(models): make the deepseek_v2 prefill causal - #998
Merged
Merged
Conversation
`deepseek_v2` emitted token id 64279 (`}'_`) for every generated token on `models/deepseek-v2-lite-4bit` while mlx-lm decoded the same weights correctly. A per-stage numerical diff against the mlx-lm 0.31.3 reference on identical prompt ids localized it in one pass: in layer 0 every tensor feeding attention matched bit for bit (`compressed_kv`, the `kv_a_layernorm` latent, `kv_b_proj` output, `k_nope`, `values`, the RoPE'd `q_pe` and `k_pe`, and the concatenated `queries` and `keys`, all at 0.0 relative RMS), and the first stage to leave the noise floor was the SDPA output itself at 6.0e-1. Broken down per query position, the last prompt position matched to 1.9e-6 while position 0 was off by 8.5e-1, which is the signature of a missing causal mask rather than a wrong projection or a bad weight. Root cause: `MLAAttention::forward` had the mask policy inverted. The `l == 1` decode branch called `causal_attention`, where causality is vacuous, while the `l > 1` prefill branch handed the caller's mask straight to the unmasked `attention_from_ptr`. Every generation path (CLI text prefill, the VLM embeddings prefill, chunked prefill) calls the model with `mask == None` and expects the model to build its own causal mask, as documented on `padded_prompt_and_mask` in `src/lib/mlxcel-core/src/generate.rs` and as `llama3.rs`, `deepseek.rs` and `dots1.rs` implement it. So the one branch that needed a causal mask never got one: prefill ran fully bidirectional, every layer wrote future-contaminated K/V into the cache, and the first sampled token was already wrong. `deepseek_v3.rs` carries a comment describing the identical defect being fixed there under issue #525; `deepseek_v2.rs` never got the same treatment. Route a maskless multi-token prefill through `causal_attention` in both the decompressed path and the matrix-absorbed prefill added by #995. An explicit mask (the padded-prefill case) still goes to the masked call, and decode is unchanged because `causal_attention` takes its single-query maskless fast path at `l == 1`. After the fix every dumped stage sits inside f16 noise (1.3e-6 at the layer-0 SDPA, rising to 1.7e-3 at the logits after 27 layers of accumulation) and the 20-token greedy continuation matches the reference id for id. `tests/deepseek_v2_greedy_parity.rs` closes the coverage gap that let this ship: nothing in the tree ever generated from a real `deepseek_v2` text checkpoint. It has two gates, the reference ids, and a reference-free assertion that adding five later prompt tokens does not move the first position's logits. The old code failed the second by 1.35 relative RMS against a 2e-2 threshold, so the gate has a 67x margin and stays meaningful for any checkpoint of this family. `docs/supported-models.md` now names the validation checkpoint and states the maskless-prefill contract for all four DeepSeek text families, including that V3 and V3.2 have no local checkpoint and carry code inspection rather than a real-checkpoint gate. Closes #991
6 tasks done
inureyes
added a commit
that referenced
this pull request
Aug 2, 2026
…1001) 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
6 tasks done
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
`deepseek_v2` emitted token id 64279 (`}'_`) for every generated token on `models/deepseek-v2-lite-4bit` while mlx-lm decoded the same weights correctly. A per-stage numerical diff against the mlx-lm 0.31.3 reference on identical prompt ids localized it in one pass: in layer 0 every tensor feeding attention matched bit for bit (`compressed_kv`, the `kv_a_layernorm` latent, `kv_b_proj` output, `k_nope`, `values`, the RoPE'd `q_pe` and `k_pe`, and the concatenated `queries` and `keys`, all at 0.0 relative RMS), and the first stage to leave the noise floor was the SDPA output itself at 6.0e-1. Broken down per query position, the last prompt position matched to 1.9e-6 while position 0 was off by 8.5e-1, which is the signature of a missing causal mask rather than a wrong projection or a bad weight. Root cause: `MLAAttention::forward` had the mask policy inverted. The `l == 1` decode branch called `causal_attention`, where causality is vacuous, while the `l > 1` prefill branch handed the caller's mask straight to the unmasked `attention_from_ptr`. Every generation path (CLI text prefill, the VLM embeddings prefill, chunked prefill) calls the model with `mask == None` and expects the model to build 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. So the one branch that needed a causal mask never got one: prefill ran fully bidirectional, every layer wrote future-contaminated K/V into the cache, and the first sampled token was already wrong. `deepseek_v3.rs` carries a comment describing the identical defect being fixed there under issue lablup#525; `deepseek_v2.rs` never got the same treatment. Route a maskless multi-token prefill through `causal_attention` in both the decompressed path and the matrix-absorbed prefill added by lablup#995. An explicit mask (the padded-prefill case) still goes to the masked call, and decode is unchanged because `causal_attention` takes its single-query maskless fast path at `l == 1`. After the fix every dumped stage sits inside f16 noise (1.3e-6 at the layer-0 SDPA, rising to 1.7e-3 at the logits after 27 layers of accumulation) and the 20-token greedy continuation matches the reference id for id. `tests/deepseek_v2_greedy_parity.rs` closes the coverage gap that let this ship: nothing in the tree ever generated from a real `deepseek_v2` text checkpoint. It has two gates, the reference ids, and a reference-free assertion that adding five later prompt tokens does not move the first position's logits. The old code failed the second by 1.35 relative RMS against a 2e-2 threshold, so the gate has a 67x margin and stays meaningful for any checkpoint of this family. `docs/supported-models.md` now names the validation checkpoint and states the maskless-prefill contract for all four DeepSeek text families, including that V3 and V3.2 have no local checkpoint and carry code inspection rather than a real-checkpoint gate. Closes lablup#991
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
deepseek_v2ran a fully bidirectional prefill. Thel == 1decode branch ofMLAAttention::forwardcalledcausal_attention, where causality is vacuous, while thel > 1prefill branch handed the caller's mask straight to the unmaskedattention_from_ptr. Since every generation path calls the model withmask == Noneand expects the model to build its own causal mask, the one branch that needed a causal mask never got one.Root cause and how it was localized
A per-stage numerical diff against the mlx-lm 0.31.3 reference, on the identical prompt ids
[100000, 549, 6077, 280, 7239, 317], localized it in one pass. In layer 0 every tensor feeding attention matched bit for bit:input_ids,embed,in_lnq_raw,q_nope,q_pe(post-RoPE)compressed_kv,ckv(postkv_a_layernorm)kv_up(kv_b_proj),k_nope,values,k_pequeries,keys(concatenated)attn_out(the SDPA output)So tokenization, weight loading, the 4-bit expert planes, the MLA rope/nope split, the YaRN rotation and the concatenation order were all cleared, and the fault was inside the attention call itself. Breaking that same tensor down per query position named the mechanism:
The last prompt position matched to the noise floor because it attends to all six keys either way. Only the earlier positions moved. That is the signature of a missing causal mask, not a wrong projection or a bad weight. Those contaminated positions were then written into the KV cache by every layer, so by layer 1 the last position was contaminated too and the first sampled token was already wrong.
The contract that was violated is documented on
pad_tokens_for_prefillinsrc/lib/mlxcel-core/src/generate.rs(line 162): aNonemask means "the forward pass will use its built-in causal mask".llama3.rs,deepseek.rsanddots1.rsall implement it asl > 1 && mask.is_none()routing tocausal_attention.deepseek_v3.rscarries a comment describing this exact defect being fixed there under #525, with the same reasoning about future-contaminated K/V.deepseek_v2.rsnever got the same treatment.MLXCEL_MLA_ABSORBED=1(#995) reproduced the symptom unchanged with27/27 layersfolded, which is consistent: the absorbed path up-projects the live latent window throughkv_b_projand runs the same prefill SDPA, so it carried the same inverted mask policy.Before / after
}'_}'_}'_...(id 64279, 20 times)Paris.\nThe official language of France is French.\nThe currency of France is the Euro (Paris.\nThe official language of France is French.\nThe currency of France is the Euro (All 20 ids now match the reference:
8913, 13, 185, 549, 6269, 4706, 280, 7239, 317, 6016, 13, 185, 549, 19305, 280, 7239, 317, 254, 28071, 334.Re-running the stage diff after the fix puts every stage inside f16 noise: 1.2986e-06 at the layer-0 SDPA, rising to 2.0113e-03 at
final_normand 1.7319e-03 at the logits after 27 layers of accumulation.What changed
src/models/deepseek_v2.rs,MLAAttention::forward: a multi-token prefill with no caller-supplied mask now goes throughmlxcel_core::causal_attention. An explicit mask (the padded-prefill case) still goes toattention_from_ptr, and decode is unchanged becausecausal_attentiontakes its single-query maskless fast path atl == 1.src/models/deepseek_v2.rs,MLAAttention::forward_absorbed: the same fallback in the absorbed prefill branch, so the two paths stay comparable rather than one being causal and the other not.tests/deepseek_v2_greedy_parity.rs(new): the real-checkpoint gate.docs/supported-models.md: the DeepSeek bullet now names the validation checkpoint and states the maskless-prefill contract, instead of being a bare- DeepSeek v1 / v2 / v3 / v3.2.The regression gate
Nothing in the tree ever generated from a real
deepseek_v2text checkpoint, which is why a documented, supported architecture could sit fully broken while every unit test and every CI job reported success. The new test file has two independent gates, both self-skipping whenmodels/deepseek-v2-lite-4bitis absent:deepseek_v2_greedy_parity_matches_mlx_lmpins all 20 generated ids against the mlx-lm reference.deepseek_v2_prefill_is_causalpins the property the bug violated, with no dependence on reference ids: the first prompt position's logits must not move when five later prompt tokens are added. Measured against the pre-fix code that assertion fails at 1.35 relative RMS versus a 2e-2 threshold, a 67x margin, so it stays meaningful for any checkpoint of this family rather than being tuned to one continuation.Blast radius
The fix is confined to
deepseek_v2.rs. Per the consumer map, DeepSeek-VL2 is the only other module that reaches it, anddeepseek_v3.rs/deepseek_v32.rscontain nodeepseek_v2::import, so V3 and V3.2 cannot be affected by this change at all.Reach of the original defect across the DeepSeek family, by inspection of the deciding lines:
deepseek(v1)if l > 1 && mask.is_none() { causal_attention(...) }deepseek_v2attention_from_ptrdeepseek_v3else if l > 1 { let causal = create_causal_mask(l, live_before); add(&pe_scores, &causal) }deepseek_v32effective_maskbuildscreate_causal_mask(l, live_before)whenl > 1and no mask was passedminicpm3MiniCPM3Model::forwardalways overrides withcreate_causal_mask(seq_len, offset)forseq_len > 1dots1if l > 1 && mask.is_none() { causal_attention(...) }Accepted validation limit. No DeepSeek V3 or V3.2 checkpoint fits the development machine, so those two families are covered by the code inspection above and by unit tests, not by a real-checkpoint run. Since the fix does not touch any code they execute (separate files, no shared MLA helper), the inspection is the whole of the exposure rather than a partial substitute for a run that would have told us more.
Checkpoints re-verified locally after the fix:
models/deepseek-v2-lite-4bit: token-exact against mlx-lm, was fully degenerate.models/deepseek-vl2-small-4bit, text-only:Paris, which is also the most populous city in the country. It is located in the north-, unchanged from the pre-fix control run. Its prefill was also maskless (verified by instrumenting the shared module: it reachesDeepSeekV2Model::forwardwithmask == Noneand a 6-token prefill), so the fix corrects its prefill too; it simply had not been degrading visibly on this prompt.models/deepseek-vl2-small-4bit, image path:The image is a solid orange color.ontests/fixtures/test_image.png, still correct.Out of scope, filed separately
The same inverted policy exists in four unrelated files. Confirmed by inspection and, where a checkpoint was available, by running them:
src/models/internlm3.rsmodels/internlm3-8b-4bitdegenerates towaswaswaswas...src/models/hunyuan_v1_dense.rsmodels/hunyuan-1.8b-4bitdegenerates towas was was was...src/models/gemma2.rsmodels/gemma2-2b-4bitdiverges from the mlx-lm reference at the first generated token on a 36-token prompt (fluent but different); the file has no causal-mask machinery at allsrc/models/hunyuan_moe.rsThese are deliberately not in this PR, which is scoped to one logical change.
Test plan
cargo fmt --all -- --checkcargo clippy --release --all-targets --features metal,accelerate -- -D warnings(release form on purpose: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 -- --test-threads=1: 75 test binaries, 0 failures. A first pass had one failure ingranite4_vision_parity::text_only_forward_produces_finite_logits, which passes in isolation and is a memory-contention flake unrelated to this change (Granite 4 Vision runs agranitemoehybridtext tower, notdeepseek_v2)../target/release/mlxcel generate -m models/deepseek-v2-lite-4bit -p "The capital of France is" -n 20 --no-chat-templatematches the mlx-lm reference id for id.models/deepseek-vl2-small-4bitre-verified on both the text-only and the image path.Closes #991