Repository navigation
Description
Problem / Background
deepseek_v2 produces completely degenerate output on models/deepseek-v2-lite-4bit (mlx-community/DeepSeek-V2-Lite-Chat-4bit-mlx), while mlx-lm decodes the same weights correctly. Every generated token is the single token id 64279 (}'_).
$ ./target/release/mlxcel generate -m models/deepseek-v2-lite-4bit -p "The capital of France is" -n 20 --no-chat-template
Runtime device: Apple GPU (Metal)
The capital of France is}'_}'_}'_}'_}'_}'_}'_}'_}'_}'_}'_}'_}'_}'_}'_}'_}'_}'_}'_}'_
[Generated 20 tokens in 0.19s = 104.80 tok/s]
The checkpoint ships a chat template, and the templated path is equally broken: -p "What is the capital of France?" without --no-chat-template gives }'_'_\'_\'_\'_\'_\....
Nothing surfaces as a failure. The model loads without error and throughput is normal (77 to 110 tok/s), so every automated signal we have reports success while the output is unusable.
The reference is correct on the same weights
This is what makes it an mlxcel defect and not a bad checkpoint. mlx-lm on the same directory and the same raw prompt, greedy:
TEXT: 'Paris.\nThe official language of France is French.\nThe currency of France is the Euro ('
TOKEN IDS: [8913, 13, 185, 549, 6269, 4706, 280, 7239, 317, 6016, 13, 185, 549, 19305, 280, 7239, 317, 254, 28071, 334]
It diverges at the first generated token
mlxcel emits 64279 where the reference emits 8913 (Paris), and never recovers. The fault is therefore in prefill or weight loading, not in the decode loop or the KV cache. That is the primary narrowing fact and should drive the search.
Pre-existing, not caused by the quantization-bounds work
The output is byte-identical on main at 30f1ca82f (2026-07-31 10:15, the last commit before #972 landed) and on the branch for #972 (issue #958). #972 routes the shared quantized-linear path in src/lib/mlxcel-core/src/layers.rs through the reconciler, and its own PR body names deepseek-v2-lite-4bit as "the shared QuantizedMultiLinear MLA path" validation target, which is why this checkpoint was run and how the symptom was found. The A/B establishes the symptom predates that change.
Reproduction
Build and run environment
Facts about this machine that are needed to build and run at all, so nobody rediscovers them.
- Every cargo invocation needs
DEVELOPER_DIR=/Applications/Xcode-26.6.0.app/Contents/Developer.xcode-select -ppoints at/Library/Developer/CommandLineTools, wherexcrun -f metalfails withxcrun: error: unable to find utility "metal", not a developer tool or in PATH, and the cmake step of themlxcel-corebuild script fails with it. - Only the release profile is warm.
target/releaseis populated;target/debugdoes not exist, so a plaincargo checkorcargo testwithout--releasetriggers a cold MLX C++ build that takes many minutes. Stay on--release --features metal,accelerate. - A test that trips an MLX C++ precondition aborts the whole test binary with SIGABRT rather than failing cleanly. Most
cxxbridge functions are declared to returnUniquePtr<T>rather thanResult<T>(381 versus 7 insrc/lib/mlxcel-core/src/lib.rs, 6 versus 0 inops.rs), and cxx only converts a C++ throw into a Rust error for theResultshape; otherwise it reachesstd::terminate. Expect an abort, not a readable assertion, when probing shapes or dtypes that MLX rejects.
mlxcel
cargo build --release --features metal,accelerate
./target/release/mlxcel generate -m models/deepseek-v2-lite-4bit -p "The capital of France is" -n 20 --no-chat-templateDownload the checkpoint with ./target/release/mlxcel download mlx-community/DeepSeek-V2-Lite-Chat-4bit-mlx if it is not already under models/.
mlx-lm reference
The reference harness is the bisect tool, not just the oracle. A per-stage numerical diff against it is how the gemma4 E-series audio divergence and the Idefics2 stacked-bug case were both localized, and the same method applies here: dump per-layer or per-op activations from both sides on identical inputs and walk forward until the first stage whose RMS diff leaves the noise floor.
python3 -m venv /tmp/mlxlm-venv
/tmp/mlxlm-venv/bin/pip install mlx-lm
cat > /tmp/ref_gen.py <<'PY'
import sys
from mlx_lm import load
from mlx_lm.generate import stream_generate
from mlx_lm.sample_utils import make_sampler
path, prompt, n = sys.argv[1], sys.argv[2], int(sys.argv[3])
model, tokenizer = load(path)
print("PROMPT IDS:", tokenizer.encode(prompt))
out_ids, text = [], ""
for r in stream_generate(model, tokenizer, prompt, max_tokens=n, sampler=make_sampler(temp=0.0)):
out_ids.append(r.token)
text += r.text
print("TEXT:", repr(text))
print("TOKEN IDS:", out_ids)
PY
# Pass the model directory as an ABSOLUTE path. See the note below.
/tmp/mlxlm-venv/bin/python /tmp/ref_gen.py /absolute/path/to/mlxcel/models/deepseek-v2-lite-4bit "The capital of France is" 20Feed the raw prompt on both sides. mlxcel needs --no-chat-template for a token-exact comparison because this checkpoint does ship a template while the reference harness does not apply one.
Pass an absolute model path. mlx_lm.utils._download does Path(path_or_hf_repo).exists() against the process working directory and, when that misses, falls straight through to snapshot_download(path_or_hf_repo), treating the string as a HuggingFace repo id. A relative models/deepseek-v2-lite-4bit therefore works only when the Python process happens to start in the repository root, and from anywhere else it becomes a Hub lookup that fails with huggingface_hub.errors.LocalEntryNotFoundError (or, without HF_HUB_OFFLINE=1, a download attempt). Absolute paths remove the failure mode entirely.
Verified output, mlx-lm 0.31.3, absolute path, greedy:
PROMPT IDS: [100000, 549, 6077, 280, 7239, 317]
TEXT: 'Paris.\nThe official language of France is French.\nThe currency of France is the Euro ('
TOKEN IDS: [8913, 13, 185, 549, 6269, 4706, 280, 7239, 317, 6016, 13, 185, 549, 19305, 280, 7239, 317, 254, 28071, 334]
The PROMPT IDS line is the first thing to compare, before any activation dump. mlx-lm feeds prefill exactly those six ids, BOS 100000 included. If mlxcel's tokenization of the same raw prompt under --no-chat-template differs by even the BOS, the divergence is upstream of every model-code candidate listed below and nothing else needs investigating first.
Decoding the two diverging ids against models/deepseek-v2-lite-4bit/tokenizer.json confirms the symptom is a real token choice and not a detokenizer artifact: 64279 is }'_ and 8913 is ĠParis.
Measurements already taken, do not repeat them
Every row below has been reproduced independently on 649f0a520 with the stock checkpoint. Treat them as settled and start after them.
| Condition | Result |
|---|---|
| Metal, repeated fresh greedy runs | Byte-identical degenerate output every time. Deterministic, so this is a numerical error rather than a memory-safety class defect. |
MLXCEL_FUSED_MOE=0 |
Unchanged, but see the correction below: this is a no-op for this model and is therefore not evidence of anything. |
rope_scaling removed from a copied config (plain RoPE, mscale multiply disabled) |
Still degenerate. The YaRN path is ruled out as the sole cause. |
models/deepseek-vl2-small-4bit, same prompt |
Coherent: Paris, which is also the most populous city in the country. It is located in the north-. |
Correction on the MLXCEL_FUSED_MOE=0 row. That result is vacuous. deepseek_v2.rs defines its own local SwitchGLU at line 545 and never calls crate::models::switch_layers::fused_moe_enabled(), unlike qwen3_moe, gemma4, olmoe, mixtral, dots1, minimax, phimoe, qwen2_moe, qwen3_next, cohere2_moe, lfm2, bailing_moe, and mellum, which all gate on it. The env var cannot change this model's MoE path, so the unchanged output rules nothing out and the fused decode-MoE kernel was never in play to begin with. Do not read it as having cleared the MoE path.
On the rope_scaling row. Independently confirmed by pointing mlxcel generate at a directory holding the same weights with rope_scaling deleted from config.json: byte-identical degenerate output. The mechanism is src/models/deepseek_v2.rs:838, where scale *= ms * ms is gated on args.mscale_all_dim() > 0.0 and mscale_all_dim() defaults to 0.0 when rope_scaling is absent, so both the YaRN rotation and the attention-scale multiply are genuinely off in that run. Note also that the working sibling deepseek-vl2-small-4bit has no rope_scaling in its language_config at all, so it never exercised the YaRN path in the first place; it is a control for the MLA and MoE structure, not for the rotation.
That last row is the sharpest fact available. src/loading/vlm_deepseek_vl2.rs:144 builds its text decoder with models::deepseek_v2::DeepSeekV2Model::from_weights, so DeepSeek-VL2-small runs the same module, the same q_lora_rank.is_none() MLA branch, the same 27 layers / 2048 hidden / 16 heads, the same 64 routed plus 2 shared experts with 6 active and first_k_dense_replace: 1, the same MLA head dims (its language_config omits them and the serde defaults are exactly the Lite values: kv_lora_rank 512, qk_nope_head_dim 128, qk_rope_head_dim 64, v_head_dim 128), the same 4-bit / group-size-64 quantization, the same float16 plus uint32 tensor dtypes, and the same weight key layout modulo a language_model. prefix (both use pre-stacked mlp.switch_mlp.*, both carry self_attn.{q_proj, kv_a_proj_with_mqa, kv_a_layernorm, kv_b_proj, o_proj}). One works and one does not.
So do not treat the presence of the args.q_lora_rank.is_none() branch at src/models/deepseek_v2.rs:801 as the root cause. That branch is exercised and correct on a locally working sibling. Check whether it is correct rather than merely present, and give equal weight to the other candidates: the MLA rope/nope split and its concatenation order, the MoE router at first_k_dense_replace: 1, the 4-bit expert plane loading, and the text weight-loading path (load_and_sanitize_weights()) versus the VLM path (load_vlm_weights_common()), which is one of the few remaining structural differences between the working and broken cases.
Coverage gap
The reason a documented, supported architecture could sit in this state is that nothing in the tree ever generates from a real deepseek_v2 text checkpoint.
docs/supported-models.md:26is a bare bullet,- DeepSeek v1 / v2 / v3 / v3.2, with no validation checkpoint named. Every neighboring entry (dots1,bailing_moe,mistral4,granitemoehybrid,bitnet) names the checkpoint it was validated against.src/models/deepseek_v2_tests.rscontains exactly one test,deepseek_v2_switch_linear_rejects_quantization_params_that_would_abort_gather_qmm, which asserts on a load-time bound with a syntheticWeightMap. It never runs a forward pass, by design.tests/hasdeepseek_vl_v2_parity.rs,deepseekocr_encoder_parity.rsanddeepseekocr_2_resampler.rs, and nothing that generates from a realdeepseek_v2text checkpoint.
This is the same shape as qwen3_next in #584: a family that passed unit tests and CI while never having been run against a real checkpoint, where the first real-model run then found four bugs at once. The fix must therefore include a real-checkpoint gate. More unit tests would not have caught this and will not prevent the next one.
Acceptance Criteria
-
./target/release/mlxcel generate -m models/deepseek-v2-lite-4bit -p "The capital of France is" -n 20 --no-chat-templatematches themlx-lmreference token for token (8913, 13, 185, 549, 6269, 4706, 280, 7239, 317, 6016, 13, 185, 549, 19305, 280, 7239, 317, 254, 28071, 334). - The root cause is identified and stated, not worked around. If the divergence is localized by a per-stage numerical diff against the reference, record which stage diverges.
- A real-checkpoint gate exists for
deepseek_v2text generation, so this cannot silently regress again. A load-and-forward test that asserts on generated token ids, skipped when the checkpoint is absent, in the style of the existing real-model integration tests undertests/. -
docs/supported-models.mdnames the validation checkpoint for the DeepSeek text families the way the neighboring entries do, rather than leaving line 26 as a bare bullet. - The reach of the defect into the other DeepSeek family members is checked and the finding recorded, including for the members that could not be run locally.
-
models/deepseek-vl2-small-4bitstill generates coherently after the fix, since it shares the module.
Technical Considerations
What the family actually shares, precisely. src/models/deepseek.rs, deepseek_v2.rs, deepseek_v3.rs and deepseek_v32.rs are separate files, and the coupling between them is narrower than "the family shares code widely" suggests. Verified consumer map:
deepseek_v2.rsis imported bysrc/loading/vlm_deepseek_vl2.rs(line 144,DeepSeekV2Model::from_weights) andsrc/vision/deepseek_vl2.rs. DeepSeek-VL2 is the only other consumer.deepseek.rsis imported bysrc/loading/vlm_deepseekocr.rs(three call sites) and bysrc/vision/deepseekocr.rs,src/vision/deepseekocr_2.rs, and the Unlimited-OCR path.deepseek_v3.rsanddeepseek_v32.rscontain nodeepseek_v2::import. They are independent implementations that overlap only through the generic core library (mlxcel_core::layers::{KVCache, MultiLinear, RMSNorm, UnifiedEmbedding, UnifiedLinear}) andcrate::models::switch_layers::validate_expert_quantization_params.
The practical consequence: a fix confined to deepseek_v2.rs reaches DeepSeek-VL2 and nothing else, and cannot regress V3 or V3.2 at all. A fix that lands in mlxcel-core layers or in switch_layers reaches every family member plus a long tail of unrelated models, and that is the case that needs the wider check. Establish which of the two the fix is before reasoning about blast radius, and do not regress the OCR and VL2 checkpoints that currently work.
Validation is limited by what is available locally, and this is a known hard limit. Present: deepseek-v2-lite-4bit, deepseek-vl2-small-4bit, deepseek-ocr-4bit (model_type: deepseekocr), deepseek-ocr-2-4bit (model_type: deepseekocr_2). Absent: any DeepSeek V3 or V3.2 checkpoint, which are too large for the development machine. If the root cause turns out to sit in shared core code rather than in deepseek_v2.rs, there is no local way to demonstrate that the fix is safe for V3 and V3.2. State that in the PR as an accepted limitation with the reasoning that supports it, rather than implying coverage that does not exist. The two other DeepSeek-named checkpoints under models/ are decoys: deepseek-coder-1.3b-4bit is model_type: llama and deepseek-r1-distill-7b-4bit is model_type: qwen2, so neither touches this code.
Relationship to the CUDA instance. #817 and #824 reported the identical }'_ symptom for the same checkpoint on GB10 CUDA. That was root-caused to an upstream MLX CUDA RMSNorm small-axis regression hitting kv_a_layernorm (axis 512) and fixed in #829 by overlaying mlx/backend/cuda/rms_norm.cu, with the upstream report tracked in #830. That fix is CUDA-specific and cannot apply to the Metal path, so this is not a duplicate. It is worth noting that both instances hit the same model with the same visible gram, and that kv_a_layernorm is a narrow-axis RMSNorm in the MLA path on both backends, which makes the corresponding Metal RMSNorm dispatch worth checking as one candidate among the others.
Config for reference. models/deepseek-v2-lite-4bit, model_type: deepseek_v2, q_lora_rank: null (the V2-Lite distinction: no query compression, unlike full V2), kv_lora_rank: 512, qk_nope_head_dim: 128, qk_rope_head_dim: 64, v_head_dim: 128, num_attention_heads: 16, num_key_value_heads: 16, n_routed_experts: 64, n_shared_experts: 2, num_experts_per_tok: 6, n_group: 1, topk_group: 1, scoring_func: softmax, first_k_dense_replace: 1, moe_layer_freq: 1, num_hidden_layers: 27, hidden_size: 2048, vocab_size: 102400, max_position_embeddings: 163840, rope_theta: 10000, rope_scaling: {type: yarn, factor: 40, mscale: 0.707, mscale_all_dim: 0.707, beta_fast: 32, beta_slow: 1, original_max_position_embeddings: 4096}, quantization: {group_size: 64, bits: 4}. Converted with mlx-lm 0.16.0.
Activity
inureyes commentedon Aug 2, 2026
Root-caused and fixed in #998.
Diverging stage. 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 the reference bit for bit at 0.0 relative RMS:q_raw,q_nope,q_pe(post-RoPE),compressed_kv,ckv(postkv_a_layernorm),kv_up,k_nope,values,k_pe, and the concatenatedqueriesandkeys. The first stage to leave the noise floor was the SDPA output itself,attn_out, at 5.9983e-01. That clears tokenization, weight loading, the 4-bit expert planes, the MLA rope/nope split, the YaRN rotation and the concatenation order in one shot.Breaking that same tensor down per query position named the mechanism:
Only the last prompt position matched, because it attends to all six keys either way. That is the signature of a missing causal mask, not a wrong projection or a bad weight.
Root cause.
MLAAttention::forwardinsrc/models/deepseek_v2.rshad the mask policy inverted. Thel == 1decode branch calledcausal_attention, where causality is vacuous, while thel > 1prefill branch handed the caller's mask straight to the unmaskedattention_from_ptr. Every generation path calls the model withmask == Noneand expects the model to build its own causal mask, as documented onpadded_prompt_and_maskinsrc/lib/mlxcel-core/src/generate.rsand asllama3.rs,deepseek.rsanddots1.rsimplement 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.rscarries a comment describing this exact defect being fixed there under #525;deepseek_v2.rsnever got the same treatment.Notes on the two levers the issue and the handoff suggested.
MLXCEL_MLA_ABSORBED=1reproduced the symptom unchanged with27/27 layersfolded. That is consistent rather than exculpatory: 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. Both paths are fixed.The
q_lora_rank.is_none()branch was, as the issue predicted, correct rather than merely present. It diffed at 0.0 against the reference.Before / after.
}'_}'_}'_...Paris.\nThe official language of France is French.\nThe currency of France is the Euro (All 20 ids now match:
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, 1.7319e-03 at the logits after 27 layers of accumulation.Family reach.
deepseek,deepseek_v3,deepseek_v32,minicpm3anddots1were each checked at the deciding lines and are all clear; the per-file evidence is in the PR. V3 and V3.2 have no local checkpoint, and since the fix touches no code they execute (separate files, no shared MLA helper), that inspection is the whole of the exposure rather than a partial substitute for a run.models/deepseek-vl2-small-4bitwas also running a maskless prefill through this same module, verified by instrumenting it, so the fix corrects its prefill too. It had simply not been degrading visibly: its text-only continuation is unchanged from the control run in the issue, and its image path still answers correctly ontests/fixtures/test_image.png.Out of scope, filed as #999. The same inverted policy exists in
src/models/internlm3.rs,src/models/hunyuan_v1_dense.rs,src/models/gemma2.rsandsrc/models/hunyuan_moe.rs. Three were reproduced locally: internlm3 and hunyuan_v1_dense degenerate to repeated tokens, and gemma2 diverges from the reference at the first generated token on a long prompt while staying fluent.fix(models): make the deepseek_v2 prefill causal (#998)
fix(models): make the deepseek_v2 prefill causal (lablup#998)
perf(mla): absorb DeepSeek V2 decode by default where the fused kerne…