Repository navigation
[dsv3][perf] MLA RoPE: rotate q's rope dims within the row, as int32 pairs - #5529
Conversation
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.
… one store per half
# Conflicts: # torchtitan/models/muse_spark/model.py
# Conflicts: # torchtitan/models/muse_spark/model.py
…on batch_invariant=False
|
@claude check again |
|
Claude finished @tianyu-l's task in 1m 18s —— View job Re-review: MLA RoPE int32 tail rotation
I didn't run the GPU test because this runner has no GPU. I also didn't run Overall: the PR now handles both of @tianyu-l's comments. The two What I checked
One point worth addressing
Nits
Earlier review itemsEach earlier item was either fixed or answered with a reason, and I agree with the answers:
SummaryThis looks good to merge. The only change I'd suggest is the |
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
|
reply from claude: Took the gate suggestion. The fast path now requires |
…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]>
TLDR: In the
mla_qkregion, 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
_apply_rope_to_q_and_k_pesplits q[T, H, 192]intoq_nope [.., 128]andq_pe [.., 64], rotatesq_pewithk_pe, and concatenates back.q_peis 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.Solution
_apply_rope_to_q_and_k_pe(themla_qkregion) rotates through_RotateTail: it views the whole q row as int32 pairs, rotates the last 32 words with_RotatePairs.rotateand concatenates them with q_nope's 64 untouched words.k_peuses the same cos/sin rows. The backward is the same rotation by the opposite angle._RotatePairs.rotatealso accepts pairs already packed as int32 words, so both paths share one rotation formula.k_pein one RoPE call as before.k_pekeeps its existing compiled path.Results
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:
k_pethe 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.RoPE? Only MLA has this shape: q's rope dims at the tail andk_perotated whole. DeepSeek-V4's sites need other shapes (kv's tail, no key, inverse ono), and Qwen3.5 rotates the first dims. The opt-infused_mlaoverride also does its tail rotation in MLA code. The cost: MLA imports_RotatePairsand callsself.rope._reshape_cache, behind atype(self.rope) is ComplexRoPEcheck.NOTE:
ComplexRoPE: subclasses, such as the Helion RoPE override (which replacesforward), 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._RotatePairs.rotatetraces 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).mla_qk: DeepSeek-V3 and Kimi K2.x (on by default in the DeepSeek-V3 model config).F.linearon them; TP communication is an explicitspmd.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.assert_close; on GB300 it is bitwise.Test plan
pytest tests/unit_tests/gpu/models/deepseek_v3/test_mla_rope_compile.py: eager vs themla_qkregion (int32 path) vs theroperegion 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 (CosSinRoPEtest_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.