Skip to content

Commit c97035c

Browse files
justinchubyCopilotCopilot
authored
Fix missing YaRN mscale softmax-scale correction in DeepSeek MLA (#548)
## 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 #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]> --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: Copilot Autofix powered by AI <[email protected]>
1 parent b9c9043 commit c97035c

4 files changed

Lines changed: 115 additions & 10 deletions

File tree

‎src/mobius/components/_deepseek_mla.py‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from mobius.components._rms_norm import RMSNorm
2121
from mobius.components._rotary_embedding import (
2222
apply_rotary_pos_emb,
23+
yarn_apply_mscale,
2324
)
2425

2526
if TYPE_CHECKING:
@@ -94,12 +95,18 @@ def __init__(
9495
bias=False,
9596
)
9697

97-
# Attention scale: 1/sqrt(qk_head_dim).
98-
# YaRN mscale is handled by the cos/sin cache (attention_factor
99-
# is applied to cos/sin in YarnRope), so no additional scaling
100-
# is needed here. The cos/sin scaling produces attention_factor^2
101-
# effect on the attention logits automatically.
102-
self.scaling = scale if scale is not None else self.qk_head_dim**-0.5
98+
# Attention scale: 1/sqrt(qk_head_dim), with an additional YaRN
99+
# mscale^2 softmax-scale correction when YaRN is active (see
100+
# ``yarn_apply_mscale``). This is separate from the RoPE cos/sin
101+
# ``attention_factor`` applied inside YarnRope, which only rescales
102+
# the rope portion of Q/K, not the full attention logit.
103+
self.scaling = (
104+
scale
105+
if scale is not None
106+
else yarn_apply_mscale(
107+
config.rope_type, config.rope_scaling, self.qk_head_dim**-0.5
108+
)
109+
)
103110

104111
# Whether RoPE uses interleaved layout (DeepSeek-V3 uses this)
105112
self._rope_interleave = config.rope_interleave

‎src/mobius/components/_deepseek_mla_test.py‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55

66
from __future__ import annotations
77

8+
import math
9+
810
import pytest
911

1012
from mobius._testing import (
@@ -106,6 +108,66 @@ def test_custom_scale(self):
106108
mla = DeepSeekMLA(config, scale=0.25)
107109
assert mla.scaling == pytest.approx(0.25)
108110

111+
def test_yarn_mscale_softmax_scale_correction(self):
112+
"""YaRN-active configs apply an extra mscale^2 softmax-scale factor.
113+
114+
Regression test for the missing DeepSeek-V2/V3 YaRN attention
115+
softmax-scale correction (HF's ``yarn_apply_mscale``): the RoPE
116+
cos/sin ``attention_factor`` only rescales the rope portion of Q/K,
117+
not the full attention logit, so a separate ``mscale_all_dim``-based
118+
correction must also be applied to ``self.scaling``. Values mirror
119+
the real ``deepseek-ai/DeepSeek-V2-Lite`` config.
120+
"""
121+
config = _mla_config(
122+
rope_type="yarn",
123+
rope_scaling={
124+
"factor": 40,
125+
"mscale": 0.707,
126+
"mscale_all_dim": 0.707,
127+
"original_max_position_embeddings": 4096,
128+
},
129+
)
130+
mla = DeepSeekMLA(config)
131+
qk_head_dim = 12 + 4 # 16
132+
mscale = 0.1 * 0.707 * math.log(40) + 1.0
133+
expected = qk_head_dim**-0.5 * mscale * mscale
134+
assert mla.scaling == pytest.approx(expected)
135+
# Sanity: the correction is non-trivial (not silently a no-op).
136+
assert mla.scaling != pytest.approx(qk_head_dim**-0.5)
137+
138+
def test_yarn_mscale_correction_skipped_when_rope_type_default(self):
139+
"""No mscale correction is applied outside of YaRN.
140+
141+
Matches HF's ``rope_parameters.get("rope_type", "default") !=
142+
"default"`` guard.
143+
"""
144+
config = _mla_config(
145+
rope_type="default",
146+
rope_scaling={"factor": 40, "mscale_all_dim": 0.707},
147+
)
148+
mla = DeepSeekMLA(config)
149+
qk_head_dim = 12 + 4 # 16
150+
assert mla.scaling == pytest.approx(qk_head_dim**-0.5)
151+
152+
def test_yarn_mscale_correction_skipped_when_mscale_all_dim_zero(self):
153+
"""No correction when ``mscale_all_dim`` is unset/zero, matching HF."""
154+
config = _mla_config(
155+
rope_type="yarn",
156+
rope_scaling={"factor": 40, "mscale_all_dim": 0.0},
157+
)
158+
mla = DeepSeekMLA(config)
159+
qk_head_dim = 12 + 4 # 16
160+
assert mla.scaling == pytest.approx(qk_head_dim**-0.5)
161+
162+
def test_custom_scale_overrides_yarn_correction(self):
163+
"""An explicit ``scale=`` always wins over the YaRN correction."""
164+
config = _mla_config(
165+
rope_type="yarn",
166+
rope_scaling={"factor": 40, "mscale_all_dim": 0.707},
167+
)
168+
mla = DeepSeekMLA(config, scale=0.25)
169+
assert mla.scaling == pytest.approx(0.25)
170+
109171
def test_head_dim_composition(self):
110172
"""qk_head_dim = qk_nope_head_dim + qk_rope_head_dim."""
111173
config = _mla_config(qk_nope_head_dim=20, qk_rope_head_dim=6)

‎src/mobius/components/_rotary_embedding.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,33 @@ def forward(self, op: OpBuilder, position_ids: ir.Value):
313313
return self._cast_embeddings(op, cos, sin)
314314

315315

316+
def yarn_apply_mscale(rope_type: str | None, rope_scaling: dict | None, scaling: float) -> float:
317+
"""Apply the DeepSeek-V2/V3 YaRN attention-softmax scale correction.
318+
319+
This mirrors HuggingFace's ``yarn_apply_mscale`` in
320+
``modeling_deepseek_v2.py``: DeepSeek's MLA attention modules multiply
321+
the softmax scale (``qk_head_dim**-0.5``) by ``mscale(factor,
322+
mscale_all_dim) ** 2`` whenever YaRN is active. This is *independent*
323+
of — and in addition to — the ``attention_factor`` that :class:`YarnRope`
324+
applies to the RoPE cos/sin cache: that factor only rescales the
325+
rotated (rope) portion of Q/K, while this correction rescales the whole
326+
attention logit (rope + nope portions alike). Omitting it reproduces
327+
exactly at position 0 (single-key softmax is scale-invariant) but
328+
diverges sharply at position >= 1 for any real YaRN-scaled checkpoint
329+
where ``mscale_all_dim`` is non-zero (e.g. DeepSeek-V2-Lite, DeepSeek-V3).
330+
"""
331+
if rope_type == "default" or not rope_scaling:
332+
return scaling
333+
mscale_all_dim = rope_scaling.get("mscale_all_dim") or 0.0
334+
if not mscale_all_dim:
335+
return scaling
336+
factor = rope_scaling.get("factor") or 1.0
337+
if factor <= 1:
338+
return scaling
339+
mscale = 0.1 * mscale_all_dim * math.log(factor) + 1.0
340+
return scaling * mscale * mscale
341+
342+
316343
class YarnRope(BaseRope):
317344
"""YaRN (Yet another RoPE extensioN) rotary embeddings.
318345

‎tests/synthetic_parity_test.py‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -160,10 +160,19 @@
160160
# Gemma3 VL: same QK-norm FP accumulation as gemma3_text (~0.045 max diff).
161161
# argmax_match=True (near-tie), cosine=0.996 — functionally correct.
162162
"gemma3": 0.05,
163-
# DeepSeek-V3: sigmoid-gated MoE with fused expert weights. Sequential vs batched
164-
# expert dispatch produces FP accumulation differences → ~0.034 max diff.
165-
# Near-tie argmax, cosine=0.996 — functionally correct.
166-
"deepseek_v3": 0.04,
163+
# DeepSeek-V3: previously carried a 0.04 override attributed to "MoE
164+
# dispatch FP accumulation", but that was masking a real bug: the
165+
# DeepSeek-V2/V3 MLA softmax scale was missing the YaRN
166+
# mscale_all_dim^2 correction HF applies (see
167+
# ``mobius.components._rotary_embedding.yarn_apply_mscale``). Fixed in
168+
# ``_deepseek_mla.py``. Post-fix, remaining diff is genuine FP-order
169+
# noise from parallel MoE dispatch: ~3.5e-5 measured via a standalone
170+
# interpreter, ~1.2e-3 measured under this pytest process (both
171+
# reproducible in their own harness — the residual gap is ORT
172+
# intra-op thread-schedule dependent, not seed-dependent). 0.0025
173+
# keeps ~2x headroom over the higher measurement while staying 16x
174+
# tighter than the old 0.04.
175+
"deepseek_v3": 0.0025,
167176
# dots1: same DeepSeek V3 architecture (sigmoid routing + shared experts).
168177
# MoE dispatch accumulation differences → similar tolerance needed.
169178
"dots1": 0.04,

0 commit comments

Comments
 (0)