Skip to content

[dsv3][perf] MLA RoPE: rotate q's rope dims within the row, as int32 pairs - #5529

Merged
felipemello1 merged 144 commits into
mainfrom
felipemello1/rope-helion/2-mla-int32-rope
Oct 20, 2026
Merged

felipemello1 merged 144 commits into
mainfrom
felipemello1/rope-helion/2-mla-int32-rope

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

TLDR: In the mla_qk region, q's rope dims are rotated within the contiguous q row, read and written as int32 pairs, instead of being split off as a strided view. DeepSeek-V3 and Kimi K2.5 q/k RoPE glue: -30% to -32% prefill, -34% to -36% train, at 89-99.6% of the bandwidth floor, bitwise with eager on GB300.

Problem

  1. q today. _apply_rope_to_q_and_k_pe splits q [T, H, 192] into q_nope [.., 128] and q_pe [.., 64], rotates q_pe with k_pe, and concatenates back.
  2. A strided view. q_pe is a slice of each row, so the compiled rotation can't view it as int32 pairs: Inductor would copy it first. It reads the two halves with stride-2 loads instead.
  3. Cost. The region runs at 59-69% of the bandwidth floor: DeepSeek-V3 prefill 64k 1380.0 us (floor 945.7). Helion's kernel in the same place is faster (1326.5 us).

Solution

  1. Rotate within the row. Under compile, for ComplexRoPE and a contiguous bf16 q, _apply_rope_to_q_and_k_pe (the mla_qk region) rotates through _RotateTail: it views the whole q row as int32 pairs, rotates the last 32 words with _RotatePairs.rotate and concatenates them with q_nope's 64 untouched words. k_pe uses the same cos/sin rows. The backward is the same rotation by the opposite angle.
  2. _RotatePairs.rotate also accepts pairs already packed as int32 words, so both paths share one rotation formula.
  3. Unchanged. Eager, fp32 and non-contiguous q take the split / rotate / cat path, with q's tail and k_pe in one RoPE call as before. k_pe keeps its existing compiled path.
before:  q [T,H,192] -> split -> q_pe (strided) -> rotate (stride-2 loads, int32 stores) -> cat
after:   q [T,H,192] -> view int32 [T,H,96] -> rotate the last 32 words, copy the first 64 -> view bf16

Results

Numerics (GB300): bitwise identical to eager (outputs and grads of q and k_pe), DeepSeek-V3 (128 heads) and
                  Kimi K2.5 (64 heads), odd T. Not guaranteed by construction: Inductor may contract the real
                  arithmetic into FMAs.

mla_qk region (_apply_rope_to_q_and_k_pe), real module path, GB300, CUDA graphs, fresh Inductor caches, one
process per tree, us. Each mode's largest shape (train 64k, prefill 128k) is its first, static compile; the
others run with dynamic T. floor = bytes read + written / measured HBM bandwidth.
model            mode      T       before    after    delta    floor
DeepSeek-V3 671B train    16k      761.3    492.8   -35.3%    472.8
                          64k     2985.5   1926.6   -35.5%   1891.3
                 prefill  16k      352.8    242.7   -31.2%    236.4
                          64k     1380.0    953.5   -30.9%    945.7
                          128k    2748.1   1899.5   -30.9%   1891.3
                 decode   1          8.2      6.2
                          256       12.3     10.3
Kimi K2.5        train    16k      403.3    266.3   -34.0%    237.7
                          64k     1518.6    989.7   -34.8%    950.6
                 prefill  16k      189.0    131.5   -30.4%    118.8
                          64k      721.1    495.0   -31.4%    475.3
                          128k    1429.8    977.9   -31.6%    950.6
                 decode   1          8.3      6.2
                          256       12.3      8.2

End to end (estimate): -0.27 ms per DeepSeek-V3 layer at 16k train, ~0.3% of a 2-layer fwd+bwd step
                       (178.58 ms, from the mla_qk PR's run).
graphs: _apply_rope_to_q_and_k_pe 4 of 8 (train static T, train dynamic T, no_grad dynamic T, no_grad T=1),
        same as before. The rope region alone (mla_qk off): 5 graphs on a 5-call sequence, same as before.

cat options in mla_qk, kept (same bench, after this PR, us):     with      without
DeepSeek-V3  prefill 64k / train 16k                            953.5 / 492.8   1052.9 / 547.1
Kimi K2.5    prefill 64k / train 16k                            495.0 / 266.3    600.5 / 291.3
             (they cost 1-2 us at decode 256: 10.3 vs 8.3, 8.2 vs 7.2)

Helion RoPE in the same place (measured earlier with a bench closure, same shapes; "before" matched within 0.3%):
DeepSeek-V3  prefill 64k 1326.5   train 64k 2673.0   prefill 128k: fails (int32 index overflow)
Kimi K2.5    prefill 64k  668.9   prefill 128k 1316.0   train 64k 1360.1

Size vs gain: +58/-12 non-test lines (rope.py, attention.py) for ~0.3% end to end. On its own that is under our bar; it's here because it closes the last gap to the Helion RoPE override (26-28% faster than Helion in this region), so the next PR can delete it without any model getting slower than Helion.

You may ask:

  • Why not rotate k_pe the same way? Its output is its own [T, 1, 64] tensor, so its stores are already contiguous int32 pairs. The region gets it as a slice of the [T, 576] wkv_a output, so reading it as int32 without a copy would mean passing the whole row in. It is 0.3% (DeepSeek-V3) to 0.5% (Kimi) of the region's bytes.
  • Why in MLA, not on RoPE? Only MLA has this shape: q's rope dims at the tail and k_pe rotated whole. DeepSeek-V4's sites need other shapes (kv's tail, no key, inverse on o), and Qwen3.5 rotates the first dims. The opt-in fused_mla override also does its tail rotation in MLA code. The cost: MLA imports _RotatePairs and calls self.rope._reshape_cache, behind a type(self.rope) is ComplexRoPE check.

NOTE:

  • The fast path runs only for exact ComplexRoPE: subclasses, such as the Helion RoPE override (which replaces forward), keep split -> rope -> cat, so Helion still runs where it is enabled. Its only user is the DeepSeek-V3 MTP integration test; the next PR deletes it.
  • Other ComplexRoPE models: _RotatePairs.rotate traces the same ops for bf16 (contiguous and split), fp32 and fp16 inputs; the fake-PG goldens of DeepSeek-V3, GPT-OSS, Llama 3, Muse Glimmer and Qwen3 are unchanged (exported at the next PR).
  • Reaches every recipe that enables mla_qk: DeepSeek-V3 and Kimi K2.x (on by default in the DeepSeek-V3 model config).
  • TP/SP: not run. Activations are local tensors (Linear runs F.linear on them; TP communication is an explicit spmd.redistribute), so the int32 view sees the local [T, H/tp, 192] q, e.g. DeepSeek-V3 at TP2 has Kimi K2.5's 64 heads, measured above. SP all-gathers x before the projections.
  • Not tested: loss curve, H100. On A10G (CI) the compiled rotation is not bitwise with eager, so the test uses assert_close; on GB300 it is bitwise.

Test plan

  • pytest tests/unit_tests/gpu/models/deepseek_v3/test_mla_rope_compile.py: eager vs the mla_qk region (int32 path) vs the rope region alone (split path), outputs and grads, assert_close (bitwise on GB300).
  • pytest tests/unit_tests/{gpu,cpu}/models/deepseek_v3 tests/unit_tests/gpu/models/qwen3_5/test_rope_compile.py tests/unit_tests/cpu/models/common/test_rope.py tests/unit_tests/gpu/models/kimi_k2_7 tests/unit_tests/{gpu,cpu}/models/muse_spark: 77 passed, 1 failed, 2 skipped, 3 xfailed. The failure (CosSinRoPE test_forward_and_backward_match_eager) also fails on main on GB300.

Stack: 2 of 3 on top of the RoPE / Muse Spark stack: mla_qk region -> this PR -> remove the Helion RoPE override.

felipemello1 and others added 30 commits October 15, 2026 23:21
Inductor cannot generate code for complex mul, so a compiled ComplexRoPE kept
eager fallbacks. Under torch.compile, apply_rotary_emb now spells the rotation
in real arithmetic on view_as_real(cache), which fuses into one kernel per
tensor and matches the eager complex forward to 1 bf16 ulp. Eager is
unchanged. Register ComplexRoPE.forward as the opt-in complex_rope region.
# Conflicts:
#	torchtitan/models/muse_spark/model.py
# Conflicts:
#	torchtitan/models/muse_spark/model.py
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude check again

@claude

claude Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 18s —— View job


Re-review: MLA RoPE int32 tail rotation

  • Read the updated diff (cb97fe4, 4 files) against felipemello1/lcp/dsv3-2-dsv3-mla-qk-region
  • Check the surrounding code in rope.py, deepseek_v3/attention.py and torchtitan_recipes/overrides/helion_rope.py
  • Post the review

I didn't run the GPU test because this runner has no GPU. I also didn't run pre-commit, but I checked the new lines by eye: they're ASCII and under flake8's 120-character limit.

Overall: the PR now handles both of @tianyu-l's comments. The two rotate_tail methods are gone from rope.py, _RotateTail sits next to its only caller in deepseek_v3/attention.py, and the only shared-code change left is _RotatePairs.rotate accepting packed int32 input. I found no correctness bugs.

What I checked

  • The packed path in _RotatePairs.rotate (rope.py:353-375). For int32 input, pairs << 16 and pairs & ~0xFFFF read the same bits as the bf16 path does through x.view(torch.int32). out_dtype is bf16, so the rounding and the int32 packing are the same as before, and the result stays int32. Existing callers never pass int32, so they trace the same ops as before.
  • _RotateTail (attention.py:206-232).
    • The forward views the row as [T, H, 96] int32 and splits it 64 / 32. num_pairs = cos.shape[-1] = 32, which is qk_rope_head_dim // 2. So the rotated words are exactly q's last 64 bf16 dims.
    • The backward rotates by -sin and passes q_nope's grad words through unchanged, which is the right adjoint.
    • cos/sin get None grads, which matches _RotatePairs.
  • The cache. self.rope._reshape_cache(q, positions) takes the full [T, H, 192] q, but _reshape_for_broadcast only reads query_shape[0] (rope.py:494), so the cache it returns is the same as for q_pe. The _maybe_check_max_pos check still runs, and one gather is shared between q and k_pe, as before.
  • k_pe. k_pe.unsqueeze(1) is a strided [T, 1, 64] view of the wkv_a output, so it takes _RotatePairs' split-halves read in both branches, as before.
  • When each path runs. Under the rope region alone, _apply_rope_to_q_and_k_pe isn't compiled, so is_compiling() is False and the split -> self.rope -> cat path runs. The test covers that path too. That's correct.

One point worth addressing

isinstance(self.rope, ComplexRoPE) silently bypasses subclasses that override forward (attention.py:189)

  • HelionComplexRoPE(ComplexRoPE) (torchtitan_recipes/overrides/helion_rope.py:535) only overrides forward. With mla_qk on, the fast path goes straight to _reshape_cache + _RotatePairs. A user who enables the Helion override gets stock RoPE with no warning.
  • The PR body says this, and the next PR deletes Helion. But CLAUDE.md asks for a warning when a code path silently skips user configuration, and the same thing would happen to any future ComplexRoPE subclass.
  • A one-word fix: type(self.rope) is ComplexRoPE. A subclass with its own forward then falls back to split -> self.rope(...) -> cat, and Helion keeps working until the next PR removes it.
  • If you'd rather keep isinstance because the next PR lands right after, that's fine. In that case, saying so in the comment at attention.py:193 would help.

Fix this →

Nits

  • rope.py:359: "It needs an even element offset: every caller slices q/k at even widths." This now only applies to the bf16 branch. The packed caller has already done the int32 view, so the offset requirement is on _RotateTail, whose docstring already says so. You could leave it as is or scope it to the bf16 view.
  • The test (test_mla_rope_compile.py) uses positions. The previous commit (5eabc56) covers positions=None for the region. A [None, positions] parametrization here would cover the int32 path with the cache[:T] slice too, at little cost.

Earlier review items

Each earlier item was either fixed or answered with a reason, and I agree with the answers:

  • (1) The test uses assert_close now.
  • (2) and (4) were declined, and the reasons are fine.
  • (3) The int32 input is now documented in rotate's docstring and its only caller is named.
  • (5) TP/SP: activations are local tensors here, so the int32 view sees the local [T, H/tp, 192] q.

Summary

This looks good to merge. The only change I'd suggest is the type(...) is ComplexRoPE gate, so the Helion override isn't silently bypassed while it still exists. Everything else is optional.

Felipe Mello added 21 commits October 19, 2026 23:02
isinstance also matched ComplexRoPE subclasses that override forward
(the Helion RoPE override), which the fast path silently bypassed. They
now take split -> rope -> cat. The GPU test also covers positions=None,
which slices the cache instead of gathering it.
Main's MLA CP change refreshed real_pg/a10g/deepseek_v3_cp_pp.txt
without this PR's rope region; the combined values come from this PR's
CI, identical on all 11 PRs of the stack and in an export run. ROCm
mi350x goldens of the models that compile the region (DeepSeek-V3,
DeepSeek-V3 CP+PP, Llama 3, Llama 3 PP, Muse Glimmer) from the
ciflow/rocm run on this branch. Losses vs main: within 4.1e-4 relative
(A10G cp_pp), within 1.8e-4 (mi350x Llama 3 and DeepSeek-V3), and within
3.5e-3 for mi350x Muse Glimmer, whose first steps run at grad norm ~40.
# Conflicts:
#	tests/assets/losses/real_pg/mi350x/deepseek_v3_cp_pp.txt
@felipemello1

Copy link
Copy Markdown
Contributor Author

reply from claude: Took the gate suggestion. The fast path now requires type(self.rope) is ComplexRoPE, so ComplexRoPE subclasses that replace forward (the Helion override, until the next PR deletes it) take split -> rope -> cat instead of being bypassed. The GPU test also covers positions=None. For plain ComplexRoPE nothing changes: outputs and grads bitwise equal to the previous version in 12 GPU cases.

Base automatically changed from felipemello1/lcp/dsv3-2-dsv3-mla-qk-region to main October 20, 2026 15:54
@felipemello1
felipemello1 merged commit 2fddc6b into main Oct 20, 2026
acisseJZhong pushed a commit that referenced this pull request Oct 21, 2026
…pairs (#5529)

**TLDR:** In the `mla_qk` region, q's rope dims are rotated within the
contiguous q row, read and written as int32 pairs, instead of being
split off as a strided view. DeepSeek-V3 and Kimi K2.5 q/k RoPE glue:
-30% to -32% prefill, -34% to -36% train, at 89-99.6% of the bandwidth
floor, bitwise with eager on GB300.

**Problem**
1. **q today.** `_apply_rope_to_q_and_k_pe` splits q `[T, H, 192]` into
`q_nope [.., 128]` and `q_pe [.., 64]`, rotates `q_pe` with `k_pe`, and
concatenates back.
2. **A strided view.** `q_pe` is a slice of each row, so the compiled
rotation can't view it as int32 pairs: Inductor would copy it first. It
reads the two halves with stride-2 loads instead.
3. **Cost.** The region runs at 59-69% of the bandwidth floor:
DeepSeek-V3 prefill 64k 1380.0 us (floor 945.7). Helion's kernel in the
same place is faster (1326.5 us).

**Solution**
1. **Rotate within the row.** Under compile, for ComplexRoPE and a
contiguous bf16 q, `_apply_rope_to_q_and_k_pe` (the `mla_qk` region)
rotates through `_RotateTail`: it views the whole q row as int32 pairs,
rotates the last 32 words with `_RotatePairs.rotate` and concatenates
them with q_nope's 64 untouched words. `k_pe` uses the same cos/sin
rows. The backward is the same rotation by the opposite angle.
2. **`_RotatePairs.rotate`** also accepts pairs already packed as int32
words, so both paths share one rotation formula.
3. **Unchanged.** Eager, fp32 and non-contiguous q take the split /
rotate / cat path, with q's tail and `k_pe` in one RoPE call as before.
`k_pe` keeps its existing compiled path.

```text
before:  q [T,H,192] -> split -> q_pe (strided) -> rotate (stride-2 loads, int32 stores) -> cat
after:   q [T,H,192] -> view int32 [T,H,96] -> rotate the last 32 words, copy the first 64 -> view bf16
```

**Results**
```text
Numerics (GB300): bitwise identical to eager (outputs and grads of q and k_pe), DeepSeek-V3 (128 heads) and
                  Kimi K2.5 (64 heads), odd T. Not guaranteed by construction: Inductor may contract the real
                  arithmetic into FMAs.

mla_qk region (_apply_rope_to_q_and_k_pe), real module path, GB300, CUDA graphs, fresh Inductor caches, one
process per tree, us. Each mode's largest shape (train 64k, prefill 128k) is its first, static compile; the
others run with dynamic T. floor = bytes read + written / measured HBM bandwidth.
model            mode      T       before    after    delta    floor
DeepSeek-V3 671B train    16k      761.3    492.8   -35.3%    472.8
                          64k     2985.5   1926.6   -35.5%   1891.3
                 prefill  16k      352.8    242.7   -31.2%    236.4
                          64k     1380.0    953.5   -30.9%    945.7
                          128k    2748.1   1899.5   -30.9%   1891.3
                 decode   1          8.2      6.2
                          256       12.3     10.3
Kimi K2.5        train    16k      403.3    266.3   -34.0%    237.7
                          64k     1518.6    989.7   -34.8%    950.6
                 prefill  16k      189.0    131.5   -30.4%    118.8
                          64k      721.1    495.0   -31.4%    475.3
                          128k    1429.8    977.9   -31.6%    950.6
                 decode   1          8.3      6.2
                          256       12.3      8.2

End to end (estimate): -0.27 ms per DeepSeek-V3 layer at 16k train, ~0.3% of a 2-layer fwd+bwd step
                       (178.58 ms, from the mla_qk PR's run).
graphs: _apply_rope_to_q_and_k_pe 4 of 8 (train static T, train dynamic T, no_grad dynamic T, no_grad T=1),
        same as before. The rope region alone (mla_qk off): 5 graphs on a 5-call sequence, same as before.

cat options in mla_qk, kept (same bench, after this PR, us):     with      without
DeepSeek-V3  prefill 64k / train 16k                            953.5 / 492.8   1052.9 / 547.1
Kimi K2.5    prefill 64k / train 16k                            495.0 / 266.3    600.5 / 291.3
             (they cost 1-2 us at decode 256: 10.3 vs 8.3, 8.2 vs 7.2)

Helion RoPE in the same place (measured earlier with a bench closure, same shapes; "before" matched within 0.3%):
DeepSeek-V3  prefill 64k 1326.5   train 64k 2673.0   prefill 128k: fails (int32 index overflow)
Kimi K2.5    prefill 64k  668.9   prefill 128k 1316.0   train 64k 1360.1
```

Size vs gain: +58/-12 non-test lines (`rope.py`, `attention.py`) for
~0.3% end to end. On its own that is under our bar; it's here because it
closes the last gap to the Helion RoPE override (26-28% faster than
Helion in this region), so the next PR can delete it without any model
getting slower than Helion.

You may ask:
- Why not rotate `k_pe` the same way? Its output is its own `[T, 1, 64]`
tensor, so its stores are already contiguous int32 pairs. The region
gets it as a slice of the `[T, 576]` wkv_a output, so reading it as
int32 without a copy would mean passing the whole row in. It is 0.3%
(DeepSeek-V3) to 0.5% (Kimi) of the region's bytes.
- Why in MLA, not on `RoPE`? Only MLA has this shape: q's rope dims at
the tail and `k_pe` rotated whole. DeepSeek-V4's sites need other shapes
(kv's tail, no key, inverse on `o`), and Qwen3.5 rotates the first dims.
The opt-in `fused_mla` override also does its tail rotation in MLA code.
The cost: MLA imports `_RotatePairs` and calls
`self.rope._reshape_cache`, behind a `type(self.rope) is ComplexRoPE`
check.

NOTE:
- The fast path runs only for exact `ComplexRoPE`: subclasses, such as
the Helion RoPE override (which replaces `forward`), keep split -> rope
-> cat, so Helion still runs where it is enabled. Its only user is the
DeepSeek-V3 MTP integration test; the next PR deletes it.
- Other ComplexRoPE models: `_RotatePairs.rotate` traces the same ops
for bf16 (contiguous and split), fp32 and fp16 inputs; the fake-PG
goldens of DeepSeek-V3, GPT-OSS, Llama 3, Muse Glimmer and Qwen3 are
unchanged (exported at the next PR).
- Reaches every recipe that enables `mla_qk`: DeepSeek-V3 and Kimi K2.x
(on by default in the DeepSeek-V3 model config).
- TP/SP: not run. Activations are local tensors (Linear runs `F.linear`
on them; TP communication is an explicit `spmd.redistribute`), so the
int32 view sees the local `[T, H/tp, 192]` q, e.g. DeepSeek-V3 at TP2
has Kimi K2.5's 64 heads, measured above. SP all-gathers x before the
projections.
- Not tested: loss curve, H100. On A10G (CI) the compiled rotation is
not bitwise with eager, so the test uses `assert_close`; on GB300 it is
bitwise.

**Test plan**
- `pytest
tests/unit_tests/gpu/models/deepseek_v3/test_mla_rope_compile.py`: eager
vs the `mla_qk` region (int32 path) vs the `rope` region alone (split
path), outputs and grads, `assert_close` (bitwise on GB300).
- `pytest tests/unit_tests/{gpu,cpu}/models/deepseek_v3
tests/unit_tests/gpu/models/qwen3_5/test_rope_compile.py
tests/unit_tests/cpu/models/common/test_rope.py
tests/unit_tests/gpu/models/kimi_k2_7
tests/unit_tests/{gpu,cpu}/models/muse_spark`: 77 passed, 1 failed, 2
skipped, 3 xfailed. The failure (CosSinRoPE
`test_forward_and_backward_match_eager`) also fails on main on GB300.

Stack: 2 of 3 on top of the RoPE / Muse Spark stack: mla_qk region ->
this PR -> remove the Helion RoPE override.

---------

Co-authored-by: Felipe Mello <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants