Skip to content

Fix missing YaRN mscale softmax-scale correction in DeepSeek MLA - #548

Merged
justinchuby merged 2 commits into
mainfrom
fix/deepseek-mla-yarn-softmax-scale
Aug 22, 2026
Merged

justinchuby merged 2 commits into
mainfrom
fix/deepseek-mla-yarn-softmax-scale

Conversation

@justinchuby

Copy link
Copy Markdown
Member

Root cause

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 inside DeepseekV2Attention.__init__ (HF's 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 portions alike).

src/mobius/components/_deepseek_mla.py implemented (1) but not (2), on the mistaken assumption (captured in the removed code comment) that (1) alone reproduces the needed effect. That's false whenever mscale == mscale_all_dim (as in deepseek-ai/DeepSeek-V2-Lite, both 0.707): (1)'s ratio-based attention_factor collapses to exactly 1.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

DeepSeekMLA reproduced 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 both DeepSeek-V2-Lite and a real DeepSeek-V3 config — 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() in src/mobius/components/_rotary_embedding.py, mirroring HF's helper of the same name exactly (same guards: no-op when rope_type == "default", no-op when mscale_all_dim is falsy). DeepSeekMLA.__init__ now calls it to compute self.scaling whenever no explicit scale= override is passed.

Before / after evidence

Using real HF configs (random weights, single dense MLA layer / full 4-layer model):

Config Before (max abs diff, position ≥ 1) After
deepseek-ai/DeepSeek-V2-Lite (factor=40, mscale=mscale_all_dim=0.707) up to ~0.9 ~5e-6 (FP noise)
deepseek-ai/DeepSeek-V3 config (factor=40, mscale=mscale_all_dim=1.0) missing ~1.87x scale (confirmed via config inspection) corrected

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 at prefill positions ≥ 1; now PASS at rtol=atol=1e-3.
  • src/mobius/components/_deepseek_mla_test.py — 4 new unit tests: exact mscale^2 correction value (mirroring DeepSeek-V2-Lite's real rope_scaling), the rope_type == "default" no-op guard, the mscale_all_dim == 0 no-op guard, and that an explicit scale= override still wins.
  • tests/synthetic_parity_test.py: removed the deepseek_v3 atol override of 0.04 (previously attributed to "MoE dispatch FP accumulation" — actually this same bug being masked) and replaced it with an empirically measured 0.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.0025 keeps ~2x headroom over the higher measurement while being 16x tighter than the old 0.04.

Commands run

python3 -m pytest src/mobius/components/_deepseek_mla_test.py src/mobius/components/_rotary_embedding_test.py -q
python3 -m pytest tests/integration_test.py -k "deepseek_v2_lite_prefill_logits_match or deepseek_non_mla_decoder_prefill_logits_match" -q
python3 -m pytest "tests/synthetic_parity_test.py::test_synthetic_parity" -k "deepseek or dots1 or glm4" -q
python3 -m pytest tests/synthetic_parity_test.py -q   # full suite: only pre-existing, unrelated `modernbert-decoder` failure (confirmed present on origin/main too)
ruff check src/mobius/components/_deepseek_mla.py src/mobius/components/_deepseek_mla_test.py src/mobius/components/_rotary_embedding.py tests/synthetic_parity_test.py
ruff format --check <same files>

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-decoder failure).

Out of scope (not included in this PR)

  • GLM-5.2 (glm_moe_dsa) registration/export — separate, unrelated follow-up (tracked via PR Add GLM-5.2 IndexShare DSA, MTP, and GGUF export support #404).
  • The deepseek_v4 synthetic-parity config-override bug in tests/_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]

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]>
@justinchuby
justinchuby requested review from a team and a lite review from Copilot August 22, 2026 19:53
@github-actions

github-actions Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

Performance Comparison

Comparing b9c9043 → 6c635c9

Model Metric Baseline Current Delta
bert (feature-extraction) model_size_bytes 359 KB 359 KB +0.0% ⚪
bert (feature-extraction) num_nodes 68 68 +0.0% ⚪
falcon model_size_bytes 364 KB 364 KB +0.0% ⚪
falcon num_nodes 66 66 +0.0% ⚪
gemma2 model_size_bytes 428 KB 428 KB +0.0% ⚪
gemma2 num_nodes 105 105 +0.0% ⚪
gpt2 model_size_bytes 388 KB 388 KB +0.0% ⚪
gpt2 num_nodes 54 54 +0.0% ⚪
llama model_size_bytes 425 KB 425 KB +0.0% ⚪
llama num_nodes 60 60 +0.0% ⚪
llama (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
llama (static-cache) num_nodes 56 56 +0.0% ⚪
mamba (ssm-text-generation) model_size_bytes 296 KB 296 KB +0.0% ⚪
mamba (ssm-text-generation) num_nodes 94 94 +0.0% ⚪
phi3 model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 num_nodes 58 58 +0.0% ⚪
phi3 (static-cache) model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 (static-cache) num_nodes 54 54 +0.0% ⚪
qwen2 model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 num_nodes 60 60 +0.0% ⚪
qwen2 (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 (static-cache) num_nodes 56 56 +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) model_size_bytes 506 KB 506 KB +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) num_nodes 264 264 +0.0% ⚪
qwen3_5_text (hybrid-text-generation) model_size_bytes 458 KB 458 KB +0.0% ⚪
qwen3_5_text (hybrid-text-generation) num_nodes 126 126 +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) model_size_bytes 977 KB 977 KB +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) num_nodes 428 428 +0.0% ⚪
t5 (seq2seq) model_size_bytes 836 KB 836 KB +0.0% ⚪
t5 (seq2seq) num_nodes 176 176 +0.0% ⚪
whisper (speech-to-text) model_size_bytes 1008 KB 1008 KB +0.0% ⚪
whisper (speech-to-text) num_nodes 128 128 +0.0% ⚪

No performance regressions.

@github-actions

github-actions Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing b9c9043 → 6c635c9

Model Sub-model Changes Status
bert (feature-extraction) model 0 ⚪
falcon model 0 ⚪
gemma2 model 0 ⚪
gemma4 (gemma4) decoder 0 ⚪
gemma4 (gemma4) embedding 0 ⚪
gemma4 (gemma4) vision_encoder 0 ⚪
gemma4_text model 0 ⚪
gpt2 model 0 ⚪
llama model 0 ⚪
llama (static-cache) model 0 ⚪
mamba (ssm-text-generation) model 0 ⚪
phi3 model 0 ⚪
phi3 (static-cache) model 0 ⚪
qwen model 0 ⚪
qwen (static-cache) model 0 ⚪
qwen2 model 0 ⚪
qwen2 (static-cache) model 0 ⚪
qwen2_moe model 0 ⚪
qwen2_moe (static-cache) model 0 ⚪
qwen3 model 0 ⚪
qwen3 (static-cache) model 0 ⚪
qwen3_5_moe (hybrid-text-generation) model 0 ⚪
qwen3_5_text (hybrid-text-generation) model 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) decoder 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) embedding 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) vision_encoder 0 ⚪
qwen3_moe model 0 ⚪
qwen3_moe (static-cache) model 0 ⚪
qwen3_next (hybrid-text-generation) model 0 ⚪
t5 (seq2seq) decoder 0 ⚪
t5 (seq2seq) encoder 0 ⚪
whisper (speech-to-text) decoder 0 ⚪
whisper (speech-to-text) encoder 0 ⚪

No architecture changes detected. ✅


Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed)

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@justinchuby
justinchuby merged commit c97035c into main Aug 22, 2026
18 of 22 checks passed
@justinchuby
justinchuby deleted the fix/deepseek-mla-yarn-softmax-scale branch August 22, 2026 20:06
@justinchuby

Copy link
Copy Markdown
Member Author

Independent Lead review — VERDICT: APPROVE

Reviewed read-only (no local edits/pushes): full diff vs origin/main (via a throwaway git worktree, since discarded), HF transformers modeling_deepseek_v2.py reference (fetched live), and independent re-execution of the test suite pre- and post-patch.

Scope

Diff against origin/main is exactly the 4 files reported by the PR (+115/-10): _deepseek_mla.py, _rotary_embedding.py, _deepseek_mla_test.py, tests/synthetic_parity_test.py. No unrelated changes.

Correctness vs HF reference

HF's yarn_get_mscale/yarn_apply_mscale + DeepseekV2Attention.__init__'s self.scaling = yarn_apply_mscale(...) were compared line-by-line against the new yarn_apply_mscale(rope_type, rope_scaling, scaling) in _rotary_embedding.py. Formula and all three guards (rope_type == "default" no-op, mscale_all_dim falsy no-op, factor <= 1 no-op) match exactly in intent and numerics. Confirms the PR's core claim: the softmax-scale mscale² correction is independent of, and in addition to, YarnRope's existing attention_factor on cos/sin.

One minor, non-blocking divergence: HF reads rope_parameters["factor"] unconditionally (crashes KeyError on a malformed config), Mobius does .get("factor") or 1.0 (fails gracefully). Not reachable for any real DeepSeek checkpoint — defensible.

API surface — config.rope_type never None for real DeepSeek configs

Traced _configs/_base.py's RoPEConfig construction: rope_type always resolves through _first_not_none(..., default="default"), so it is only ever the field None when the whole RoPEConfig is None (model has no RoPE at all — not the DeepSeek case, since DeepSeek always sets rope_theta). yarn_apply_mscale's guard (rope_type == "default" or not rope_scaling) is also safe even in a hypothetical None state, since rope_scaling is sourced from the same object. Confirmed further by deepseek_v4_flash_test.py asserting config.rope_type == "yarn" on a real-shaped config. No live bug here.

Independent re-execution (this is the substantive verification)

  • Checked out the PR head via a temporary worktree, ran pytest src/mobius/components/_deepseek_mla_test.py: 25/25 pass post-patch (6 repeat runs, no flakiness).
  • Reverted only the two source files to origin/main (keeping the new tests): test_yarn_mscale_softmax_scale_correction fails (0.25 vs expected 0.397...), the other 3 new guard tests pass either way (expected — they test no-op paths). This directly and independently confirms the PR's fail-before/pass-after claim.
  • Ran tests/synthetic_parity_test.py -k deepseek_v3 8 times: deterministic max_abs_diff=0.001224 every run (fully seeded, not flaky) — matches the PR's own cited "~1.2e-3 under pytest" almost exactly. 0.0025 gives ~2.04x headroom over this measured, reproducible number, and is 16x tighter than the old 0.04. Did not independently reproduce the cited "~3.5e-5 bare interpreter" figure (different harness), but the more conservative pytest-measured number alone already justifies the chosen tolerance — verdict: evidence-backed, not arbitrary.
  • Confirmed the synthetic deepseek_v3 test config genuinely exercises the YaRN path (rope_type="yarn", mscale_all_dim=1.0, factor=4.0 — a real ~30% scale change, not a near-1 no-op).

CI / numerical risk

ruff check and ruff format --check both clean on all 4 changed files. dict | None syntax is fine under requires-python = ">=3.10" with from __future__ import annotations present. self.scaling is a scalar Python float (not a tensor op) — no dtype/broadcast risk.

Conclusion

No high-confidence blocking issues found. Fix is correct, minimal, well-tested, and its two headline claims (fail-before/pass-after, tolerance justification) were independently reproduced rather than taken on faith. APPROVE.

justinchuby added a commit that referenced this pull request Aug 22, 2026
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.
justinchuby added a commit that referenced this pull request Aug 23, 2026
## 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants