Repository navigation
[rope][perf] Compile ComplexRoPE in real arithmetic (rope region) - #5196
Conversation
9de565a to
5caf6d0
Compare
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.
5caf6d0 to
0f2486b
Compare
…k and Muse Glimmer; test bf16/fp32 and a strided query
| return query_out, key_out | ||
|
|
||
| @staticmethod | ||
| def _rotate_pairs( |
There was a problem hiding this comment.
Should this be a method in _RotatePairs, instead of here in ComplexRoPE.
| @local_compile( | ||
| "complex_rope", | ||
| batch_invariant=True, | ||
| options={"max_pointwise_cat_inputs": 0, "max_complex_pointwise_cat_inputs": 0}, |
There was a problem hiding this comment.
I wonder if we just need one compile region "rope" for both complex and cos-sin, and potentially others.
I don't know if these options apply to cos-sin rope https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/rope.py#L283
|
|
||
| # Cat options: _rotate_pairs writes its real/imag halves with one store each, not one masked | ||
| # kernel over both: 1.08-1.20x faster fwd+bwd on GB300 (needs the per-half cast there). | ||
| @local_compile( |
There was a problem hiding this comment.
now that we are compiling this, can we remove the Helion kernel override, entirely
ComplexRoPE and CosSinRoPE register under one "rope" region; ComplexRoPE keeps its cat options for the stack path. The rotation moves onto _RotatePairs, and contiguous bf16 pairs are read and written as int32 so loads and stores stay contiguous.
…irs as int32 for split views too
…s a Function; test a compiled call with the complex cache
|
message from claude: @tianyu-l thanks for the review. The stack is updated; summary below, details in the PR bodies. 1. What we missed
2. What changed in this PR
3. Results (RoPE alone, us, GB300, CUDA graphs; this PR (Helion); 128k = static T) 4. Still a gap: the DeepSeek-V3 / Kimi forward
5. Removing Helion 6. CI |
|
@claude review the PR, in particular on the complex rope math change |
|
Claude finished @tianyu-l's task in 3m 24s —— View job Review: complex RoPE math change
Verdict: I found no correctness problems in the math. Below is what I checked, then a few small suggestions. I could only read the code: this runner has no permission to run Python, so I ran nothing on CPU or GPU. What I checked in
|
On A10G the compiled rotation rounds differently from eager complex multiply, so Llama 3 and DeepSeek-V3 losses move by up to 1.5e-4 relative over 10 steps. Values from this PR's CI: Fake PG (llama3_fsdp+tp+cp, deepseek_v3_fsdp+ep) and Real PG (llama3_fsdp+tp+pp, deepseek_v3_fsdp+cp+pp+ep).
Inductor autotunes a pointwise kernel by timing when it has more than one candidate config, and for the rotation the configs can round differently (likely FMA contraction): on GB300 the k_pe kernel's first config is bitwise eager and its second differs in 2 of 65536 elements. When the timings are close the pick can flip between runs. This is the likely cause of A10G CI's deepseek_v3_fsdp+cp+pp+ep numerics changing run to run (13 runs, 9 distinct step-1 losses; inferred, not reproduced on A10G). With one config per kernel the numerics are fixed (bitwise eager in the probed GB300 case). Kernel time stays within -1.5% to +1.6%: summed CUDA kernel time per call on GB300, autotune on -> off, Llama 3 8B, DeepSeek-V3 and Kimi K2.5 shapes at 16k and 64k: train -1.5% to 0%, prefill 0% to +1.6%. Inductor's deterministic=True still autotunes pointwise kernels, and emulate_precision_casts=True makes the configs agree but differs from eager in 12 elements.
…autotuning With one Triton config per kernel, deepseek_v3_fsdp+cp+pp+ep is deterministic again: 12 runs give identical losses (11 PR runs and one export run), where autotuned runs gave 9 distinct step-1 losses in 13. Values from those runs: deepseek_v3_cp_pp.txt (PR CI) and the goldens that only run on main, deepseek_v3.txt, llama3.txt and muse_glimmer.txt (export run on this PR's branch). Losses vs main: Llama 3 and DeepSeek-V3 within 1.3e-4 relative; Muse Glimmer within 5.9e-3, whose first steps run at grad norm ~40 and amplify the first-step change (1.4e-5).
# Conflicts: # tests/assets/losses/real_pg/a10g/deepseek_v3_cp_pp.txt
|
reply from claude: Triage of the bot review:
|
|
please update all the golden loss including Rocm before landing. |
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
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: Updated the goldens of the models that compile the region (Llama 3, DeepSeek-V3, Muse Glimmer):
|
) NOTE: - This PR makes `ComplexRoPE` compilable and turns the `rope` region on by default for Llama 3, DeepSeek-V3 (Kimi K2.x inherits it), Muse Spark and Muse Glimmer. - `rope` replaces the `complex_rope` and `cos_sin_rope` region names. `ComplexRoPE` and `CosSinRoPE` share the name, each with its own compile options, so Qwen3 and GPT-OSS keep their behavior. Configs that list `complex_rope` or `cos_sin_rope` must switch to `rope`; an unknown name raises. - The overrides are untouched. Muse Spark keeps its Helion RoPE kernel until "[muse_spark][perf] Compile RoPE with the q/k norms; drop the Helion RoPE override" (later in this stack). DeepSeek-V3's fused MLA override keeps doing its own RoPE. - DeepSeek-V4 turns the region on in "[dsv4][perf] Compile the attention's q norm + RoPE glue (q_norm_rope, partial_rope)". **TLDR:** Under compile, `ComplexRoPE` rotates in real arithmetic instead of a complex multiply, as the `rope` region, now on by default. The cache rows are gathered as floats, so the gather fuses into the rotation, and bf16 pairs are written as one int32 each, so stores are contiguous. RoPE prefill at 64k vs eager: Llama 3 8B 1126.5 -> 224.3 us, DeepSeek-V3 2589.9 -> 426.5 us. For contiguous q/k it is on par with or faster than the Helion RoPE kernel at 16k-64k. Outputs and grads are bitwise equal to eager for every model measured (GB300). **Problem** 1. **ComplexRoPE.** `apply_rotary_emb` rotates q/k with `view_as_complex` and a complex multiply. 2. **No complex codegen.** Inductor can't generate kernels for complex tensors. 3. **Fallbacks.** So a compiled `ComplexRoPE` still runs those ops as separate eager kernels. 4. **Cost.** Llama 3 8B's RoPE at 64k tokens (q `[64k, 32, 128]`, k `[64k, 8, 128]`) in eager: 2223.4 us fwd+bwd, 1126.5 us prefill. **Solution** 1. **Real arithmetic under compile.** Rotate each `(x[2i], x[2i+1])` pair in fp32 with `cos`/`sin`, instead of `view_as_complex` and a complex multiply. 2. **One int32 per bf16 pair.** Write each rotated bf16 pair as one int32, so stores are contiguous. - Contiguous inputs are also read that way: a bf16 shifted into the high 16 bits is its exact fp32. - Split views, such as DeepSeek-V3's `q_pe`, read their two halves, since an int32 view of a strided tensor is copied first. - fp32 and fp16 inputs rotate in fp32, cast each half to the input dtype, and stack. 3. **Float cache gather.** Under compile, `_reshape_cache` gathers rows of the cache's real view `(T, 1, dim)`. A complex gather ran as its own kernel; the float gather fuses into the rotation. 4. **Custom backward.** `_RotatePairs` rotates the grad by the opposite angle, in one kernel. It is required: the int32 bit views have no autograd. 5. **On by default.** `rope` joins the default `local_compile_regions` of Llama 3, DeepSeek-V3, Muse Spark and Muse Glimmer, and replaces `cos_sin_rope` in Qwen3 and GPT-OSS. 6. **Unchanged:** eager, and the overrides that replace RoPE (Helion, fused MLA). ```text eager: x -> view_as_complex -> * cache[positions] (complex) -> view_as_real (unchanged) compiled: x, cache[positions] as floats -> rotate in fp32 -> bf16: one int32 per pair (one kernel) backward: the same rotation by -angle ``` **Results** ```text Numerics (GB300): bitwise identical to eager, outputs and q/k grads, train and no_grad, bf16, for every model below (Llama 3 8B, Muse Glimmer 30B, Muse Spark 816B shapes, DeepSeek-V3 671B with strided q_pe / k_pe, Kimi K2.5). Not guaranteed by construction: Inductor may contract the real arithmetic into FMAs, and how depends on the kernel config, so the region uses one config per kernel (pointwise autotuning off). fp32: within assert_close defaults of eager (test_compiled_matches_eager_complex). Batch invariant: a full batch and its uneven chunks match bitwise, outputs and grads (3 head layouts, T up to 8192), and test_compiled_is_batch_invariant passes. The earlier version's break with a real-view gather does not reproduce on this code. ``` ```text RoPE alone, GB300, CUDA graphs, us: eager -> this PR (Helion RoPE kernel) 16k and 64k: dynamic T. 128k: the first compile of its mode (static T). model mode 16k 64k 128k (static) Llama 3 8B train 575.5 -> 118.2 (141.0) 2223.4 -> 452.7 (462.8) 801.9 (888.8) prefill 294.0 -> 63.7 ( 73.8) 1126.5 -> 224.3 (231.5) 439.8 (436.4) Muse Glimmer 30B train 496.2 -> 106.7 (114.9) 1897.9 -> 381.5 (373.4) 664.5 (721.4) prefill 256.3 -> 55.1 ( 62.9) 965.9 -> 192.3 (194.8) 375.1 (364.8) Muse Spark shapes train 182.5 (258.7) 692.0 (854.5) 1381.7 (1638.5) prefill 92.4 (118.1) 346.2 (419.3) 689.4 (790.2) DeepSeek-V3 671B train 1492.2 -> 581.8 (613.8) 5836.6 -> 2262.1 (2285.9) 4499.5 (Helion fails: int32 index) prefill 665.4 -> 111.4 (108.2) 2589.9 -> 426.5 ( 384.9) 846.3 (Helion fails) Kimi K2.5 train 780.9 -> 312.0 (321.1) 2985.8 -> 1178.6 (1168.8) 2300.1 (2294.1) prefill 350.9 -> 67.2 ( 61.7) 1335.3 -> 246.5 ( 204.2) 486.1 (381.3) decode, every model, 1 / 256 seqs: eager 16-27 us -> 6-7 us (Helion 10-25) Llama 3 8B prefill with dynamic T (warmed at 32768): 64k 228.3, 128k 447.0 (Helion 231.5 / 436.4) eager columns from an earlier run (eager code unchanged); 128k eager not measured ``` - Contiguous q/k (Llama 3, Glimmer, Muse Spark shapes): at 16k-64k (dynamic T), on par with or faster than Helion, at most +2.2% (Glimmer train 64k). At 128k, at most +2.8% (Glimmer prefill, static); Llama prefill 128k with dynamic T is 447.0 (+2.4%). - Split views (DeepSeek-V3, Kimi `q_pe` / `k_pe`): training on par with Helion; prefill +3% to +11% (DeepSeek-V3) and +9% to +27% (Kimi), from the stride-2 loads of the split view. - Muse Spark shapes go through the region; Muse Spark itself keeps the Helion override until later in this stack. Graphs: `rope` uses 4 per model on this code (train, dynamic T, T=1 and T=8 no_grad; recounted), under the default limit of 8. Inside Muse Spark's q/k region (later in this stack), the nested region is inlined: bitwise the same as without it. You may ask: why not stack per half for bf16 too? With dynamic T the stride-2 stores stop vectorizing at the ragged row tail. Writing each pair as one int32 keeps the stores contiguous for every bf16 input; only contiguous inputs can also be read that way. You may ask: the int32 view ends the fusion with whatever produced x. Inside the norm + RoPE regions, the normed q/k are written out first. Net it still wins: Muse Spark's q/k region is faster than Helion at every size in the PR that uses it. You may ask: why keep the cat options (`max_pointwise_cat_inputs=0`, `max_complex_pointwise_cat_inputs=0`) on ComplexRoPE? Only fp32/fp16 inputs still stack, and without the options fp32 prefill is 1.4x slower (Llama 3 shapes, 16k: 122.9 vs 172.4 us). They make CosSinRoPE 1.3-2.6x slower (Qwen3 shapes, 16k-64k), so each class keeps its own decorator under the shared name. You may ask: why not DeepSeek-V4 here? Turned on alone it goes past the graph limit; its glue PR enables it together with the glue regions. NOTE: who takes the compiled branch: - It keys on `torch.compiler.is_compiling()`, not on the `rope` flag: any compile that traces ComplexRoPE rotates in real arithmetic. Today that means the regions that inline RoPE (`mla_qk`, Muse Spark's q/k region later in this stack). - The RL vLLM generator runs the same local regions as the trainer (`CompilationMode.NONE`, no whole-model compile). - Trainer vs generator max logprob diff, before -> after this PR: batch-invariant mode stays exactly 0 for Llama 3 debug and DeepSeek-V3 debug (TP1) and Llama 3 8B (TP2); DeepSeek-V3 16B TP2 + EP2 is not bitwise even before (its MoE/EP path) and stays within 0.01; normal mode within 0.01 everywhere. NOTE: not tested: GraphTrainer (it traces the eager branch), H100. NOTE: golden losses: on A10G the compiled rotation is not bitwise equal to eager (on GB300 it is), so this PR refreshes the A10G goldens of the models that compile it: - From this PR's CI: Fake PG `llama3.txt`, `deepseek_v3.txt`; Real PG `llama3_pp.txt`, `deepseek_v3_cp_pp.txt`. From an export run on this branch, the Real PG goldens that run only on main: `llama3.txt`, `deepseek_v3.txt`, `muse_glimmer.txt`. - Losses vs main: Llama 3 and DeepSeek-V3 within 4.1e-4 relative over 10 steps, no drift (Llama 3 Fake PG bitwise through step 5). Muse Glimmer within 5.9e-3: its first steps run at grad norm ~40, which amplifies the 1.4e-5 first-step change. - The region turns off pointwise autotuning. With it on, Inductor picked between kernel configs that round differently by timing: deepseek_v3_fsdp+cp+pp+ep gave 9 distinct step-1 losses in 13 runs of the same code. With one config, 12 runs are identical. Kernel time (GB300, Llama 3 8B / DeepSeek-V3 / Kimi K2.5 shapes, 16k and 64k): train -1.5% to 0%, prefill 0 to +1.6%. - On A10G, compiled still matches eager within `assert_close` (`test_compiled_matches_eager_complex` passes there). - Every PR above this one printed the same values, so none of them moves these goldens. - ROCm mi350x: `deepseek_v3.txt`, `deepseek_v3_cp_pp.txt`, `llama3.txt`, `llama3_pp.txt`, `muse_glimmer.txt` from this PR's `ciflow/rocm` run. Losses vs main within 1.8e-4 relative; Muse Glimmer within 3.5e-3, as on A10G. GPT-OSS, Qwen3 and SFT goldens pass unchanged. **Test plan** - `pytest tests/unit_tests/gpu/models/qwen3_5/test_rope_compile.py`: the ComplexRoPE tests pass (bf16 and fp32, a contiguous and a strided query, forward and inverse, batch invariance, a direct call with the complex cache). - Also run: `tests/unit_tests/cpu/models/common/test_rope.py`, `tests/unit_tests/gpu/recipes/test_helion_rope.py`, `tests/unit_tests/cpu/recipes/test_fused_mla_override.py`, `torchtitan/experiments/graph_trainer/tests/test_trace_module.py`, `tests/unit_tests/cpu/models/qwen3_5/test_qwen3_5_mrope_positions.py`: 110 passed, 9 failed. All 9 fail the same way on main on this host: - `TestRoPELocalCompile::test_forward_and_backward_match_eager` (CosSinRoPE); - `TestFusedMLANumerics` bf16 and fp32; - `TestTraceFSDP` llama3 / deepseek_v3 / qwen3; - `TestQwen35MRoPEPositions` x3. - A bitwise probe over each model's RoPE call site (table above). --------- Co-authored-by: Felipe Mello <[email protected]>
NOTE:
ComplexRoPEcompilable and turns theroperegion on by default for Llama 3, DeepSeek-V3 (Kimi K2.x inherits it), Muse Spark and Muse Glimmer.ropereplaces thecomplex_ropeandcos_sin_roperegion names.ComplexRoPEandCosSinRoPEshare the name, each with its own compile options, so Qwen3 and GPT-OSS keep their behavior. Configs that listcomplex_ropeorcos_sin_ropemust switch torope; an unknown name raises.TLDR: Under compile,
ComplexRoPErotates in real arithmetic instead of a complex multiply, as theroperegion, now on by default. The cache rows are gathered as floats, so the gather fuses into the rotation, and bf16 pairs are written as one int32 each, so stores are contiguous. RoPE prefill at 64k vs eager: Llama 3 8B 1126.5 -> 224.3 us, DeepSeek-V3 2589.9 -> 426.5 us. For contiguous q/k it is on par with or faster than the Helion RoPE kernel at 16k-64k. Outputs and grads are bitwise equal to eager for every model measured (GB300).Problem
apply_rotary_embrotates q/k withview_as_complexand a complex multiply.ComplexRoPEstill runs those ops as separate eager kernels.[64k, 32, 128], k[64k, 8, 128]) in eager: 2223.4 us fwd+bwd, 1126.5 us prefill.Solution
(x[2i], x[2i+1])pair in fp32 withcos/sin, instead ofview_as_complexand a complex multiply.q_pe, read their two halves, since an int32 view of a strided tensor is copied first._reshape_cachegathers rows of the cache's real view(T, 1, dim). A complex gather ran as its own kernel; the float gather fuses into the rotation._RotatePairsrotates the grad by the opposite angle, in one kernel. It is required: the int32 bit views have no autograd.ropejoins the defaultlocal_compile_regionsof Llama 3, DeepSeek-V3, Muse Spark and Muse Glimmer, and replacescos_sin_ropein Qwen3 and GPT-OSS.Results
q_pe/k_pe): training on par with Helion; prefill +3% to +11% (DeepSeek-V3) and +9% to +27% (Kimi), from the stride-2 loads of the split view.Graphs:
ropeuses 4 per model on this code (train, dynamic T, T=1 and T=8 no_grad; recounted), under the default limit of 8. Inside Muse Spark's q/k region (later in this stack), the nested region is inlined: bitwise the same as without it.You may ask: why not stack per half for bf16 too? With dynamic T the stride-2 stores stop vectorizing at the ragged row tail. Writing each pair as one int32 keeps the stores contiguous for every bf16 input; only contiguous inputs can also be read that way.
You may ask: the int32 view ends the fusion with whatever produced x. Inside the norm + RoPE regions, the normed q/k are written out first. Net it still wins: Muse Spark's q/k region is faster than Helion at every size in the PR that uses it.
You may ask: why keep the cat options (
max_pointwise_cat_inputs=0,max_complex_pointwise_cat_inputs=0) on ComplexRoPE? Only fp32/fp16 inputs still stack, and without the options fp32 prefill is 1.4x slower (Llama 3 shapes, 16k: 122.9 vs 172.4 us). They make CosSinRoPE 1.3-2.6x slower (Qwen3 shapes, 16k-64k), so each class keeps its own decorator under the shared name.You may ask: why not DeepSeek-V4 here? Turned on alone it goes past the graph limit; its glue PR enables it together with the glue regions.
NOTE: who takes the compiled branch:
torch.compiler.is_compiling(), not on theropeflag: any compile that traces ComplexRoPE rotates in real arithmetic. Today that means the regions that inline RoPE (mla_qk, Muse Spark's q/k region later in this stack).CompilationMode.NONE, no whole-model compile).NOTE: not tested: GraphTrainer (it traces the eager branch), H100.
NOTE: golden losses: on A10G the compiled rotation is not bitwise equal to eager (on GB300 it is), so this PR refreshes the A10G goldens of the models that compile it:
llama3.txt,deepseek_v3.txt; Real PGllama3_pp.txt,deepseek_v3_cp_pp.txt. From an export run on this branch, the Real PG goldens that run only on main:llama3.txt,deepseek_v3.txt,muse_glimmer.txt.assert_close(test_compiled_matches_eager_complexpasses there).deepseek_v3.txt,deepseek_v3_cp_pp.txt,llama3.txt,llama3_pp.txt,muse_glimmer.txtfrom this PR'sciflow/rocmrun. Losses vs main within 1.8e-4 relative; Muse Glimmer within 3.5e-3, as on A10G. GPT-OSS, Qwen3 and SFT goldens pass unchanged.Test plan
pytest tests/unit_tests/gpu/models/qwen3_5/test_rope_compile.py: the ComplexRoPE tests pass (bf16 and fp32, a contiguous and a strided query, forward and inverse, batch invariance, a direct call with the complex cache).tests/unit_tests/cpu/models/common/test_rope.py,tests/unit_tests/gpu/recipes/test_helion_rope.py,tests/unit_tests/cpu/recipes/test_fused_mla_override.py,torchtitan/experiments/graph_trainer/tests/test_trace_module.py,tests/unit_tests/cpu/models/qwen3_5/test_qwen3_5_mrope_positions.py: 110 passed, 9 failed. All 9 fail the same way on main on this host:TestRoPELocalCompile::test_forward_and_backward_match_eager(CosSinRoPE);TestFusedMLANumericsbf16 and fp32;TestTraceFSDPllama3 / deepseek_v3 / qwen3;TestQwen35MRoPEPositionsx3.