Skip to content

fix(models): apply YaRN RoPE in DeepSeek V3.2 attention and indexer - #3279

Merged
inureyes merged 6 commits into
mainfrom
fix/issue-3178-deepseek-v32-yarn
Nov 23, 2026
Merged

inureyes merged 6 commits into
mainfrom
fix/issue-3178-deepseek-v32-yarn

Conversation

@inureyes

@inureyes inureyes commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Root cause

deepseek_v32 rotated the MLA q_pe / k_pe (single-sequence and batched decode) and the DSA indexer queries and keys with plain RoPE. Its RopeScaling parsed only type, factor and mscale_all_dim, which fed the softmax-scale correction and nothing else. Upstream builds both RoPEs with initialize_rope(..., scaling_config=args.rope_scaling), which for DeepSeek-V3.2 (yarn, factor 40, original_max_position_embeddings 4096, betas 32 / 1) is YarnRoPE. Plain RoPE agrees with that table only on the high-frequency pairs the correction ramp leaves alone (pairs 0-10 of 32); the low-frequency pairs rotated up to 40 times too fast, which is harmless within the 4096 positions the model was pre-trained on and breaks past them, matching the 7.3 / 1403 / 2080 perplexity cliff in the issue.

Change

  • rope_scaling is now the shared RopeScalingSpec (the whole block), and a new DsaRope (src/models/deepseek_v32_rope.rs) resolves it once per model through RopeScalingKind::resolve / yarn_rope_setup, then hands a duplicate to every MLA block and indexer. All six call sites use it with their existing traditional flag. It applies upstream's YaRN magnitude multiplier to the rotated dims only (1.0 for the shipped config, since mscale == mscale_all_dim); the softmax-scale correction is unchanged. deepseek_yarn is accepted as an alias, as upstream does.
  • No block, or a default one, keeps the exact plain fast_rope(.., base, 1.0, offset) call (pinned bit-exact by a test).
  • glm_moe_dsa maps its whole rope_parameters block (upstream sets rope_scaling = rope_parameters), so a GLM-5 YaRN block would also take effect; a default one is unchanged.
  • DsaRope::from_args refuses a qk_rope_head_dim that is zero, odd, or wider than the head it rotates (min(index_head_dim, qk_nope_head_dim + qk_rope_head_dim)) before the YaRN table is built, so a malformed config fails at load with an error instead of allocating an unbounded table.
  • Because the table now comes from the shared resolver, --rope-* / --yarn-* overrides reach these families; docs/llama-server-compat.md is updated accordingly.

Tests

src/models/deepseek_v32_rope_tests.rs: prefill and decode across original_max_position_embeddings, and batched decode with one row on each side of it, must leave YaRN-rotated k_pe and indexer keys in the cache, checked against a reference built from yarn_rope_setup + fast_rope_with_freqs and against plain RoPE; indexer queries and keys likewise; the checkpoint-geometry table is pinned to values computed independently from upstream's YarnRoPE formula in Python; the magnitude multiplier touches only the rotated dims; a YaRN model's batched decode matches sequential decode; MLA queries rotate with the key table past the original context (a two-token prefill at positions 0,1 and 128,129, and a batched decode with rows 128 positions apart, must attend identically by RoPE's relative-position property; each q_pe site reverted alone fails it at 1.45e-3 against a 1e-4 tolerance); a malformed rope width (0, 7, 14) is refused.

With the six RoPE sites reverted to main (tests kept), prefill_and_decode_cache_yarn_rotated_keys_past_the_original_context, batched_decode_caches_yarn_rotated_keys_per_row and indexer_queries_and_keys_rotate_with_yarn fail (cached k_pe off by up to 2.04, indexer queries by 11.4). With the fix, cargo test --lib --profile test-fast --features rocm -- deepseek_v32 glm_moe_dsa rope_utils rope_overrides passes (99 tests, run twice), and cargo clippy --lib --tests --features rocm -- -D warnings, cargo fmt --check and scripts/ci/check_used_by.py are clean, on ROCm gfx1151. Workspace-wide tests and clippy were not run locally.

Pending on M3 Ultra

This host (ROCm gfx1151, 30 GB) cannot load DeepSeek-V3.2-4bit, so the perplexity criteria behind 8192 and 16384, the #3163 top-k overlap re-run and the update to docs/benchmark_results/mla-quantized-latent-dsa-m3ultra-2026-11-19.md are not done here:

MLXCEL_TRACE_PREFILL_CHUNK=2048 logit_trace models/deepseek-v3.2-4bit corpus.txt 64 8 8 8192 > fp16-8k.tsv

Out of scope

src/models/deepseek_v3.rs has the same defect on current main: DeepSeekV3Attention calls plain fast_rope / fast_rope_batched for q_pe / k_pe and reads rope_scaling only for the softmax scale, while DeepSeek-V3 checkpoints carry the same YaRN block. That needs its own issue.

Closes #3178

DeepSeek V3.2 rotated the MLA q_pe / k_pe and the DSA indexer queries and keys with plain RoPE, reading rope_scaling only for the softmax-scale correction. The checkpoints ship YaRN (factor 40 over 4096 original positions), so past 4096 tokens the low-frequency pairs rotated up to 40 times too fast and fp16 perplexity rose from 7.3 to over 1400.

rope_scaling is now the shared RopeScalingSpec, and a per-model DsaRope resolves it through RopeScalingKind::resolve once, handing a duplicate to every MLA block and indexer, at all six call sites including batched decode. It applies upstream's YaRN magnitude multiplier to the rotated dims only (1.0 for the shipped config). An absent or default block keeps the exact plain fast_rope call. glm_moe_dsa maps its whole rope_parameters block, as upstream does, and the --rope-* overrides now reach both families.

Regression tests in deepseek_v32_rope_tests.rs check the cached k_pe and indexer keys, and the indexer queries, against a yarn_rope_setup + fast_rope_with_freqs reference across original_max_position_embeddings; three of them fail with the fix reverted. Long-context perplexity on DeepSeek-V3.2-4bit is pending on an M3 Ultra.

Closes #3178
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority area:models Model architectures, weights, loading, metadata labels Nov 22, 2026
The #3178 tests observed the cached k_pe and the indexer queries and keys, but not the MLA q_pe, which is never cached: reverting both q_pe sites (single-sequence forward and batched decode) to plain RoPE left every deepseek_v32 and glm_moe_dsa test green.

The new test observes the query through RoPE's relative-position property. With q_pe and k_pe on one table, two tokens attend identically at positions 0, 1 and at 128, 129 (eight times the tiny config's original context); a query on a different table than its keys breaks that. It checks a two-token prefill and a batched decode with the two rows 128 positions apart. On the fix the drift is below 1e-5; with either q_pe site reverted to plain RoPE it is 1.45e-3, against a 1e-4 tolerance.

Refs #3178
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Rotate the DeepSeek V3.2 (and GLM-5) MLA q_pe / k_pe and DSA indexer queries and keys with the checkpoint's YaRN table, matching mlx-lm YarnRoPE, while leaving absent or default rope_scaling byte-identical.

Findings Addressed

  • The MLA q_pe sites (single-sequence forward and batched decode) had no test: reverting both to plain RoPE left every deepseek_v32 / glm_moe_dsa test green. Added a relative-position invariance test (6528813); with either site reverted it fails (drift 1.45e-3 against a 1e-4 tolerance, under 1e-5 on the fix). (HIGH)

Remaining Items

  • --yarn-orig-ctx docs say the sentinel falls back to max_position_embeddings; DsaRope passes no training context, so these families fall back to 4096 as upstream YarnRoPE does. Correct for parity, undocumented. (LOW)
  • The shared YaRN helper ignores upstream's truncate key; no shipped DeepSeek-V3.2 or GLM-5 config sets it. Pre-existing. (LOW)
  • deepseek_v32.rs keeps a private yarn_get_mscale that duplicates rope_utils::yarn_get_mscale. Pre-existing. (LOW)

Verification

  • All stated requirements implemented (perplexity criteria pending on M3 Ultra, as the PR body states)
  • No placeholder/mock code remaining
  • Integrated into project code flow (full model and pipeline stage model both share one DsaRope)
  • Project conventions followed
  • Existing modules reused where applicable (RopeScalingSpec, RopeScalingKind::resolve, yarn_rope_setup)
  • No unintended structural changes
  • Tests pass (98 narrow tests, clippy --lib --tests -D warnings, fmt, on ROCm gfx1151)

Checked against upstream main mlx_lm/layers/rope.py: table values at checkpoint geometry and the magnitude ratio match an independent float64 computation, the multiplier hits only the rotated dims, and the softmax-scale correction is not applied twice. The public GLM-5 configs (zai-org/GLM-5, mlx-community/GLM-5-4bit) carry rope_parameters {rope_theta: 1000000, rope_type: default}, which still resolves to the plain rotation.

@inureyes

Copy link
Copy Markdown
Member Author

Security and Performance Review

No CRITICAL or HIGH findings, so no fix commits. Branch head stays at 6528813.

Config parsing (untrusted rope_scaling / rope_parameters)

  • YarnParams::resolve rejects a missing, zero, negative or non-finite factor, original_max_position_embeddings, beta_fast and beta_slow, and a negative or non-finite mscale / mscale_all_dim. A JSON value too large for f32 casts to inf and is caught. A rejected block warns once and falls back to the plain rotation, so nothing panics.
  • The magnitude ratio cannot divide by zero: the denominator 0.1 * mscale_all_dim * ln(factor) + 1 is at least 1 for every value that passes the screen.
  • The correction ramp only runs high - low inside low <= i <= high, so the usize subtraction cannot underflow. Float to int casts in yarn_find_correction_range saturate on NaN or inf instead of panicking.
  • A non-object rope_scaling still fails config parsing with a named error, as it did before.

Hot path

  • The table is built once per model (from_weights and the pipeline stage loader each call DsaRope::from_args once) and each attention block and indexer takes a lazy copy of a 32-element array. Loading does not re-run the powf loop per layer.
  • At the shipped config (mscale == mscale_all_dim == 1.0) the multiplier is x / x, which is exactly 1.0 in IEEE arithmetic. magnitude returns early, so decode adds no multiply, slice or concat. yarn_table_matches_the_upstream_formula_at_checkpoint_geometry asserts the exact 1.0. Decode keeps one rope kernel per tensor, fast_rope_with_freqs in place of fast_rope.

Remaining items (not fixed, below the auto-fix threshold)

  • MEDIUM: DsaRope::from_args runs before any layer weight is checked against the config, and yarn_rope_setup allocates and loops over qk_rope_head_dim / 2 entries with no upper bound. A malformed config with a very large qk_rope_head_dim and a YaRN block makes the loader allocate gigabytes (or abort) instead of failing with a shape error. Other RopeScalingKind::resolve callers have the same unbounded table pattern. Suggested fix: reject a qk_rope_head_dim that is zero, odd or larger than q_head_dim before building the table.
  • LOW (pre-existing, shared helper): values that pass the per-field screen can still overflow in combination. A factor near f32::MAX sends factor * fe to inf and the table entry to NaN, and an extreme mscale makes the ratio inf / inf. Checking that the finished table and multiplier are finite and positive, and returning Err otherwise, would close this.
  • LOW (pre-existing): the softmax-scale correction in load_mla_attention_with_rope reads factor and mscale_all_dim straight from the block with no finite check. An inf factor leaves the YaRN table on its fallback but still makes the softmax scale inf. It also ignores a --rope-scaling override that replaces the table.

Verification

  • cargo test --lib --profile test-fast --features rocm -- deepseek_v32 glm_moe_dsa rope_utils rope_overrides: 98 passed on ROCm gfx1151.
  • cargo clippy --lib --tests --features rocm -- -D warnings: clean.

… RoPE

DsaRope::from_args built the YaRN table from qk_rope_head_dim without checking it, so a zero, odd, or over-wide value in a config reached the table builder and the rope kernel. It now returns an error naming the field when the width is zero, odd, or larger than the head it rotates (the narrower of index_head_dim and qk_nope_head_dim + qk_rope_head_dim), and the model, indexer and GLM loaders propagate it. Adds a focused test for the three cases and sets index_head_dim in the checkpoint-geometry test so it stays valid.

Validation: cargo test --lib (deepseek_v32 glm_moe_dsa rope_utils rope_overrides) 100 passed; clippy --lib --tests -D warnings and fmt clean.

Refs #3178
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 22, 2026
…ek-v32-yarn

# Conflicts:
#	CHANGELOG.md
#	src/models/rope_overrides.rs
…d tests

The RoPE forward tests ran decode steps without the shared MLX test lock, so under parallel test threads they bumped the process-wide MLA decode-path counters while a_forced_int4_slot_keeps_the_indexer_key_at_eight_bits measured them as a delta, which failed it once. The five forward tests now take mlx_test_guard like the other DeepSeek V3.2 test files.

Refs #3178
Records the YaRN RoPE fix for the DeepSeek V3.2 attention and indexer, the review outcomes, and the long-context perplexity re-run still pending on M3 Ultra.
@inureyes
inureyes merged commit a9860ec into main Nov 23, 2026
33 checks passed
@inureyes
inureyes deleted the fix/issue-3178-deepseek-v32-yarn branch November 23, 2026 00:17
inureyes added a commit that referenced this pull request Nov 23, 2026
Main gained the shared `DsaRope` for the DeepSeek-V3.2 attention and indexer (#3279), which replaced the `rope_base` field the Hy4 attention read. Hy4 now rotates through the same helper, built once per model from its own `rope_parameters`: the shipped `rope_type: default` resolves to plain RoPE with no frequency table, so V3.2's YaRN cannot leak in, and the interleaved or half-split pairing stays Hy4's choice. A new test pins that bit for bit against `fast_rope` at the config's `rope_theta`.

Conflicts kept both sides: CHANGELOG.md, the latent-family notes and doc list (`hy_v4` beside `longcat_flash_sparse`), and `kv_arch`, where the LongCat sparse indexer group is appended to the Hy4-aware latent group. `MLA_LATENT_CACHE_FAMILIES` is now 19 entries.

The validation script records peak memory per run with `/usr/bin/time -l`.

Refs #2354
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata priority:high High priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: DeepSeek-V3.2 fp16 output degrades past 4096 tokens of context

1 participant