Repository navigation
Fix missing YaRN mscale softmax-scale correction in DeepSeek MLA - #548
Conversation
DeepSeek-V2/V3's MLA attention applies two independent YaRN corrections in HuggingFace's reference implementation (modeling_deepseek_v2.py): 1. `attention_scaling` on the RoPE cos/sin cache — rescales only the rope portion of Q/K. Mobius's YarnRope already implements this correctly. 2. A separate softmax-scale multiplier applied in DeepseekV2Attention (`yarn_apply_mscale`): `scaling = qk_head_dim**-0.5 * mscale**2`, where `mscale = 0.1 * mscale_all_dim * log(factor) + 1.0`. This rescales the *entire* attention logit (rope + nope), and was entirely missing from `DeepSeekMLA` — the code assumed (1) alone was sufficient, which is false whenever mscale != mscale_all_dim's ratio effect cancels out (e.g. DeepSeek-V2-Lite: mscale == mscale_all_dim == 0.707, giving attention_factor == 1.0 for (1) while (2) is still ~1.59x). Symptom: `DeepSeekMLA` reproduced HF logits almost exactly at position 0 (a single-key softmax is scale-invariant) but diverged by up to ~0.9 absolute / 93% of elements at position >= 1, for both DeepSeek-V2-Lite and a real DeepSeek-V3 config, even in a single dense (non-MoE) layer — isolating the bug to attention/RoPE scaling, not MoE routing. Fix: add `yarn_apply_mscale()` in `_rotary_embedding.py` mirroring HF's helper exactly, and use it in `DeepSeekMLA.__init__` to compute `self.scaling` when no explicit `scale` override is given. Verified against real HF configs: - `deepseek-ai/DeepSeek-V2-Lite` (rope_scaling: factor=40, mscale=mscale_all_dim=0.707): logits matched HF to ~5e-6 post-fix at every position (previously up to ~0.9 abs diff at position >= 1). - `deepseek-ai/DeepSeek-V3` (factor=40, mscale=mscale_all_dim=1.0): same missing ~1.87x scale correction confirmed via config inspection. Tests: - `tests/integration_test.py::test_deepseek_v2_lite_prefill_logits_match` and `::test_deepseek_non_mla_decoder_prefill_logits_match` — both previously FAILED with large divergence, now PASS (rtol/atol=1e-3). - `src/mobius/components/_deepseek_mla_test.py` — 4 new unit tests pinning the exact mscale^2 correction, the rope_type=="default" and mscale_all_dim==0 no-op guards (matching HF), and that an explicit `scale=` override still wins. - `tests/synthetic_parity_test.py`: removed the `deepseek_v3` 0.04 atol override (previously mis-attributed to "MoE dispatch FP accumulation" — actually this same bug) and replaced it with an empirically measured 0.0025 (residual FP-order noise from parallel MoE dispatch is ~3.5e-5 in a bare interpreter, ~1.2e-3 reproducibly under this pytest process; 0.0025 keeps ~2x headroom while staying 16x tighter than the old 0.04). Out of scope (tracked separately, not included here): GLM-5.2 (`glm_moe_dsa`) registration, the `deepseek_v4` synthetic-parity config-override bug. Co-authored-by: Copilot <[email protected]>
Performance Comparison
|
🏗️ Architecture Diff
No architecture changes detected. ✅ Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed) |
There was a problem hiding this comment.
Pull request overview
Fixes the missing YaRN mscale² softmax correction for DeepSeek MLA attention and adds regression coverage.
Changes:
- Adds and integrates the HF-compatible YaRN mscale correction.
- Preserves explicit scale overrides.
- Adds scaling guard tests and tightens DeepSeek-V3 parity tolerance.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.
| File | Summary | Review note |
|---|---|---|
tests/synthetic_parity_test.py |
Updates DeepSeek-V3 parity tolerance. | No final comments. |
src/mobius/components/_rotary_embedding.py |
Adds the YaRN softmax-scale correction helper. | Moderate: accept the nullable rope_type type. |
src/mobius/components/_deepseek_mla.py |
Applies corrected attention scaling. | No final comments. |
src/mobius/components/_deepseek_mla_test.py |
Adds correction, guard, and override tests. | No final comments. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Co-authored-by: Copilot Autofix powered by AI <[email protected]> Signed-off-by: Justin Chu <[email protected]>
Independent Lead review — VERDICT: APPROVEReviewed read-only (no local edits/pushes): full diff vs ScopeDiff against Correctness vs HF referenceHF's One minor, non-blocking divergence: HF reads API surface —
|
Replaces the dense 256-expert MatMulNBits/mask Python loop with one fused com.microsoft::QMoE node per layer via MoELayer, preserving DeepSeekV4Gate hash-routing math unchanged. Structural reduction at 256 experts: 1554->18 MatMulNBits, 7508->633 total nodes, 2 QMoE nodes. 88/88 targeted tests pass (CPU EP numeric parity, hash-routing identity, structural fusion, duplicate-expert-index validation). Independent review addressed: CUDA router_weights gap documented (pre-existing, shared with merged V3 code, tracked upstream at microsoft/onnxruntime#31570); hash-table duplicate-index validation added; multi-block quantization test coverage added. Local gates (pytest, ruff check/format) and independent review pass; admin-merged per repo precedent (PR #548) without waiting on long-running L4/L5/Integration jobs.
## Root cause `_DeepSeekMoEFFN.__init__` (src/mobius/models/deepseek.py) accepted `linear_class` but only forwarded it to `_SharedExpertMLP`, not to the `MoELayer` that builds the routed-expert dense loop-over-experts fallback: ```python self.moe = MoELayer(config, gate=gate) # linear_class silently dropped ``` Consequence: a quantized config correctly quantized attention, dense FFN, and the shared expert, but every routed MoE expert's gate/up/down projections stayed plain float `MatMul`. This both loses quantization for the routed experts and breaks the `fuse_dense_moe_to_qmoe` post-hoc rewrite, which only pattern-matches a quantized `MatMulNBits` dense-fallback shape — so a quantized DeepSeek-V2/V3 config would silently fail to fuse into QMoE for its routed experts. DeepSeek-V4 is unaffected: its `DeepSeekV4MoE` uses `expert_factory` to build `_DeepSeekV4Expert`, which independently recomputes its quantized class from `config.quantization` per-expert rather than relying on `MoELayer`'s `linear_class` forwarding — verified via review, no matching fix needed there. ## Fix One line: thread `linear_class` through to the routed-expert `MoELayer`: ```python self.moe = MoELayer(config, gate=gate, linear_class=linear_class) ``` ## Tests Added `test_deepseek_moe_ffn_linear_class_reaches_routed_experts` in `deepseek_test.py`, which isolates the assertion on `module.moe.experts` (routed) separately from `module.shared_experts` (already worked before this fix), rather than relying on an aggregate creation count — so it can't pass for the wrong reason. - Verified the new test **fails** on pre-fix code (`assert False` at the routed-experts isinstance check) and **passes** post-fix. - Full suite: `PYTHONPATH=src python3 -m pytest src/` → **3249 passed, 9 skipped**, no failures. - `ruff check` / `ruff format --check` on changed files: clean. - Independently reviewed (separate reviewer pass over the diff); verdict: **Approve**, no findings. ## Scope Deliberately minimal and focused: does not touch GLM-5.2 registration, DeepSeek-V4 QMoE export, YaRN, or any other follow-up — those are tracked/ landed separately (#548, #550, #555, #559, #560). Co-authored-by: Copilot <[email protected]> Co-authored-by: Copilot <[email protected]>
Root cause
DeepSeek-V2/V3's MLA attention applies two independent YaRN corrections in HuggingFace's reference implementation (
modeling_deepseek_v2.py):attention_scalingon the RoPE cos/sin cache — rescales only the rope portion of Q/K. Mobius'sYarnRopealready implements this correctly.DeepseekV2Attention.__init__(HF'syarn_apply_mscale):scaling = qk_head_dim**-0.5 * mscale**2, wheremscale = 0.1 * mscale_all_dim * log(factor) + 1.0. This rescales the entire attention logit (rope + nope portions alike).src/mobius/components/_deepseek_mla.pyimplemented (1) but not (2), on the mistaken assumption (captured in the removed code comment) that (1) alone reproduces the needed effect. That's false whenevermscale == mscale_all_dim(as indeepseek-ai/DeepSeek-V2-Lite, both 0.707): (1)'s ratio-basedattention_factorcollapses to exactly1.0(a no-op), while (2) is still a real ~1.59x correction that HF applies.deepseek-ai/DeepSeek-V3's official config (mscale=mscale_all_dim=1.0) has the same gap (missing ~1.87x correction).Symptom
DeepSeekMLAreproduced HF logits almost exactly at position 0 (a single-key softmax is scale-invariant to any positive multiplier) but diverged by up to ~0.9 absolute / 93% of elements at position ≥ 1, for bothDeepSeek-V2-Liteand a realDeepSeek-V3config — reproducible even in a single dense (non-MoE) layer, which isolated the bug to attention/RoPE scaling rather than MoE routing.Fix
Added
yarn_apply_mscale()insrc/mobius/components/_rotary_embedding.py, mirroring HF's helper of the same name exactly (same guards: no-op whenrope_type == "default", no-op whenmscale_all_dimis falsy).DeepSeekMLA.__init__now calls it to computeself.scalingwhenever no explicitscale=override is passed.Before / after evidence
Using real HF configs (random weights, single dense MLA layer / full 4-layer model):
deepseek-ai/DeepSeek-V2-Lite(factor=40, mscale=mscale_all_dim=0.707)deepseek-ai/DeepSeek-V3config (factor=40, mscale=mscale_all_dim=1.0)Tests
tests/integration_test.py::test_deepseek_v2_lite_prefill_logits_matchand::test_deepseek_non_mla_decoder_prefill_logits_match— both previously FAILED with large divergence at prefill positions ≥ 1; now PASS atrtol=atol=1e-3.src/mobius/components/_deepseek_mla_test.py— 4 new unit tests: exactmscale^2correction value (mirroringDeepSeek-V2-Lite's real rope_scaling), therope_type == "default"no-op guard, themscale_all_dim == 0no-op guard, and that an explicitscale=override still wins.tests/synthetic_parity_test.py: removed thedeepseek_v3atol override of0.04(previously attributed to "MoE dispatch FP accumulation" — actually this same bug being masked) and replaced it with an empirically measured0.0025. Residual FP-order noise from parallel MoE dispatch measured at ~3.5e-5 in a bare interpreter and a reproducible ~1.2e-3 under this repo's pytest process (ORT intra-op thread-schedule dependent, not seed-dependent);0.0025keeps ~2x headroom over the higher measurement while being 16x tighter than the old0.04.Commands run
All pass (25/25 MLA unit tests incl. 4 new, 63/63 combined MLA+rotary unit tests, 2/2 target integration tests, full synthetic-parity suite green aside from the pre-existing unrelated
modernbert-decoderfailure).Out of scope (not included in this PR)
glm_moe_dsa) registration/export — separate, unrelated follow-up (tracked via PR Add GLM-5.2 IndexShare DSA, MTP, and GGUF export support #404).deepseek_v4synthetic-parity config-override bug intests/_test_configs.py(Weight shape mismatch for model.layers.0.self_attn.q_b_proj.weight) — separate, unrelated fast-follow.Working as Sapper (Systems Dev for Models & Preprocess).
Co-authored-by: Copilot [email protected]