Skip to content

[rope][perf] Compile ComplexRoPE in real arithmetic (rope region) - #5196

Merged
felipemello1 merged 13 commits into
mainfrom
felipemello1/lcp/dsv4-2-complex-rope
Oct 20, 2026
Merged

felipemello1 merged 13 commits into
mainfrom
felipemello1/lcp/dsv4-2-complex-rope

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

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).
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

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.
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).

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Oct 9, 2026
@felipemello1
felipemello1 added this pull request to stack #5202 October 9, 2026 05:09
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 9, 2026
@felipemello1
felipemello1 force-pushed the felipemello1/lcp/dsv4-2-complex-rope branch from 9de565a to 5caf6d0 Compare October 9, 2026 17:18
@felipemello1
felipemello1 removed this pull request from stack #5202 October 16, 2026 20:19
@felipemello1
felipemello1 changed the base branch from felipemello1/lcp/dsv4-1-mhc to main October 16, 2026 20:19
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.
@felipemello1
felipemello1 added this pull request to stack #5499 October 18, 2026 05:31
@felipemello1
felipemello1 marked this pull request as ready for review October 18, 2026 05:51
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 18, 2026
…k and Muse Glimmer; test bf16/fp32 and a strided query
Comment thread torchtitan/models/common/rope.py Outdated
return query_out, key_out

@staticmethod
def _rotate_pairs(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be a method in _RotatePairs, instead of here in ComplexRoPE.

Comment thread torchtitan/models/common/rope.py Outdated
@local_compile(
"complex_rope",
batch_invariant=True,
options={"max_pointwise_cat_inputs": 0, "max_complex_pointwise_cat_inputs": 0},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

now that we are compiling this, can we remove the Helion kernel override, entirely

felipemello1 and others added 3 commits October 19, 2026 00:46
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.
…s a Function; test a compiled call with the complex cache
@felipemello1 felipemello1 changed the title [rope][perf] Compile ComplexRoPE in real arithmetic (complex_rope region) [rope][perf] Compile ComplexRoPE in real arithmetic (rope region) Oct 19, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

message from claude:

@tianyu-l thanks for the review. The stack is updated; summary below, details in the PR bodies.

1. What we missed

  • We had compared the compiled RoPE with the Helion kernel only up to 16k tokens.
  • At 32k-64k Helion was faster, e.g. Llama 3 8B prefill 64k: 265.9 vs 231.5 us.
  • Two causes:
    • the rotation wrote its real/imag halves with stride-2 stores, which stop vectorizing at the ragged tail of a dynamic T;
    • the complex cache was gathered by positions in its own kernel, because Inductor can't load complex.

2. What changed in this PR

  • _rotate_pairs is now _RotatePairs.rotate, as you suggested.
  • bf16 pairs are written as one int32 each (and read that way when contiguous), so loads and stores stay contiguous.
  • Under compile the cache rows are gathered as floats, so the gather fuses into the rotation.
  • One region name, rope, for both classes. The cat options stay on ComplexRoPE only: they make CosSinRoPE 1.3-2.6x slower, and without them fp32 ComplexRoPE is 1.4x slower.
  • Numerics: bitwise with eager, outputs and grads, for every model below (GB300); batch invariant.

3. Results (RoPE alone, us, GB300, CUDA graphs; this PR (Helion); 128k = static T)

model               mode      16k              64k                128k
Llama 3 8B          train     118.2 (141.0)    452.7 (462.8)      801.9 (888.8)
                    prefill    63.7 ( 73.8)    224.3 (231.5)      439.8 (436.4)
Muse Glimmer 30B    train     106.7 (114.9)    381.5 (373.4)      664.5 (721.4)
                    prefill    55.1 ( 62.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     581.8 (613.8)   2262.1 (2285.9)    4499.5 (Helion fails: int32 index)
                    prefill   111.4 (108.2)    426.5 (384.9)      846.3 (Helion fails)
Kimi K2.5           train     312.0 (321.1)   1178.6 (1168.8)    2300.1 (2294.1)
                    prefill    67.2 ( 61.7)    246.5 (204.2)      486.1 (381.3)
decode, every model, 1 / 256 seqs: 6-7 us (Helion 10-25)

4. Still a gap: the DeepSeek-V3 / Kimi forward

  • Their q_pe / k_pe reach RoPE as strided slices, so prefill trails Helion by 3-27% above.
  • Fix, two new PRs on top of this stack:
    • the MLA region (the existing "[dsv3][perf] Compile MLA q/k RoPE and concat glue" PR, moved onto this stack);
    • "[dsv3][perf] MLA RoPE: rotate q's rope dims within the row, as int32 pairs": in that region, -30% to -35% vs before, bitwise with eager. Measured against Helion inside the region, it's faster at prefill 64k and train 64k for both models.
  • Can you check the approach there?

5. Removing Helion
Yes. "[rope] Remove the Helion RoPE override and the helion dependency" is the top of the stack, now that no model is slower than Helion.

6. CI
The integration goldens no longer change. Local fake-PG exports for DeepSeek-V3, Muse Glimmer, Llama 3, Qwen3 and GPT-OSS are bitwise equal to main at this PR and at the top of the stack. The earlier red was the 1-ulp loss change, now gone.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review the PR, in particular on the complex rope math change

@claude

claude Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 24s —— View job


Review: complex RoPE math change

  • Gather context (diff, rope.py, tests, callers)
  • Review the real-arithmetic rotation and int32 packing math
  • Review the backward, cache gather, region config, and callers (DSv4, vision encoders, MRoPE, Helion / fused MLA)
  • Post review

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 _RotatePairs (torchtitan/models/common/rope.py:319-365)

  1. Forward formula. real = xr*cos - xi*sin and imag = xr*sin + xi*cos are the same terms as c10::complex (a+bi)(c+di) with x on the left. Floating-point addition is commutative, so the only possible difference from eager is FMA contraction. The PR body already says this.
  2. Inverse. sin = -sin is the same as rope_cache.conj(), and it applies to both q and k, as eager does.
  3. Backward. For y = R(θ)x, the input gradient is R(θ)ᵀ g = R(-θ) g, so rotate(grad, cos, -sin) is right. With inverse=True the sign flips twice, which is also right.
    • The rounding points match eager. Eager's backward upcasts with the type_as backward, runs the complex-mul VJP in fp32, then rounds once to bf16 in the .float() backward. rotate(grad) does the same: fp32 math, then one type_as(x).
    • Returning None for cos/sin is fine, since they come from a non-persistent buffer.
  4. Reading a bf16 pair as one int32. x.view(int32) puts x[2i] in the low 16 bits.
    • pairs << 16 gives exactly the fp32 value of x[2i].
    • pairs & ~0xFFFF (Python -65536, i.e. 0xFFFF0000 as an int32) gives exactly the fp32 value of x[2i+1].
    • Both are exact because a bf16 is the top half of an fp32.
  5. Writing the pair back. int16 -> int32 sign-extends, then & 0xFFFF strips the sign bits. imag << 16 shifts the sign extension out. (low | high).view(bf16) then puts real at 2i and imag at 2i+1, which is the interleaving eager produces, and the last dim goes back from H/2 to H.
  6. Cache under compile. view_as_real(cache).flatten(-2) has shape (T, 1, dim). unflatten(-1, (-1, 2))[..., 0/1] gives cos/sin of shape (T, 1, dim/2), which broadcasts against x_real of shape (T, N, dim/2). Direct callers that pass the complex cache (Kimi / Muse Spark vision encoders, the fused-MLA test) take the is_complex() branch and broadcast the same way as eager.
  7. Callers. Every q/k slice offset is even: DSv3 q_pe at 128, k_pe at 512; DSv4 rope slice at 448. So the int32 view is valid wherever it is taken.
    • At decode, a [1, 1, 64] slice of a wider row reports is_contiguous() (strides of size-1 dims are ignored), so it takes the int32-read path. It still works because the strides and offset are even.
    • If a future caller sliced at an odd offset, view(int32) would raise; it would not give wrong numbers silently. So relying on the comment is acceptable.
  8. Region config. _LOCAL_COMPILE_CALLBACKS keeps a list per name, so two decorators with different options under "rope" is supported. There are no stale complex_rope / cos_sin_rope region names left in the repo. HelionComplexRoPE.forward overrides the compiled forward, so Muse Spark's override still wins.

Suggestions (all minor)

  1. The branch is torch.compiler.is_compiling(), not "the rope region is enabled" (rope.py:269, rope.py:289).
    • Any enclosing compile now takes the real-arithmetic path: full-model compile.components=["model"], a compiled vision encoder that calls ComplexRoPE.apply_rotary_emb, or the later q/k-norm regions that inline RoPE.
    • That is probably what you want, but it changes the code path for existing full-model-compile users of Llama 3 / DSv3 / Kimi, even with rope removed from local_compile_regions.
    • The numerics in the PR body only cover the region. Please state this in the PR body, and ideally run one full-model-compile loss comparison (Principle 5).
  2. Endianness is implicit. The comment at rope.py:345 ("x[2i] in the low half") only holds on little-endian hardware. That is true for every CUDA and ROCm target, but saying "(little-endian)" would make the bit layout self-documenting.
  3. The test does not match the bitwise claim. test_compiled_matches_eager_complex uses assert_close with default bf16 tolerances, and its comment says results "can differ from eager complex by 1 bf16 ulp in rare elements". The PR body says bitwise for every measured model.
    • Both are defensible, because FMA contraction isn't guaranteed.
    • Consider asserting rtol=0, atol=0 for the contiguous bf16 case as a regression tripwire, since that is the property the goldens depend on. Or keep it as is and align the comment with the body.
  4. Memory, no action needed. ctx.save_for_backward(cos, sin) saves strided views of the gathered (T, 1, dim) fp32 cache. Eager's complex-mul backward also saves the gathered cache, so this is not a regression. The AOT partitioner may also choose to recompute the gather from positions.

Overall, the math (forward, inverse, backward, and bit packing) is consistent with eager ComplexRoPE, and the design comments in the code explain the non-obvious choices well. The only item I'd push on before landing is suggestion 1.

Felipe Mello added 4 commits October 19, 2026 01:08
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
@felipemello1

Copy link
Copy Markdown
Contributor Author

reply from claude: Triage of the bot review:

  • Suggestion 1 (is_compiling() vs the region flag): kept, since Inductor has no complex kernels and any compile wants real arithmetic. NOTE added. The RL generator doesn't compile the whole model (CompilationMode.NONE), it runs the same regions as the trainer. Trainer vs generator max logprob diff before -> after this PR: batch-invariant mode stays exactly 0 for Llama 3 debug, DeepSeek-V3 debug (TP1) and Llama 3 8B (TP2); DeepSeek-V3 16B TP2 + EP2 isn't bitwise even before (MoE/EP path) and stays within 0.01; normal mode within 0.01.
  • Suggestion 2 (little-endian): added in [dsv3][perf] MLA RoPE: rotate q's rope dims within the row, as int32 pairs #5529, which edits that function anyway.
  • Suggestion 3 (bitwise test): bitwise depended on which Triton config autotune picked (the configs round differently, likely FMA contraction), which also made one A10G golden test nondeterministic. The region now uses one config per kernel (triton.autotune_pointwise=False, kernel time within -1.5%..+1.6%); the test keeps assert_close because A10G still isn't bitwise with eager.
  • Suggestion 4 (memory): no action.

@acisseJZhong

Copy link
Copy Markdown
Contributor

please update all the golden loss including Rocm before landing.

@acisseJZhong acisseJZhong added ciflow/rocm ciflow/8gpu ciflow/h100.8 Trigger H100.8 CI ciflow/b200 Trigger B200 CI ciflow/real-pg Run the full 8-GPU Real PG integration suite labels Oct 20, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 20, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/8gpu.
Currently recognized labels are

  • ciflow/b200
  • ciflow/docker
  • ciflow/fake-pg
  • ciflow/h100.8
  • ciflow/real-pg
  • ciflow/rl
  • ciflow/rocm

Please add the new label to .github/pytorch-probot.yml

Felipe Mello added 2 commits October 20, 2026 00:04
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: Updated the goldens of the models that compile the region (Llama 3, DeepSeek-V3, Muse Glimmer):

  • A10G: Fake PG and Real PG from this PR's CI, plus the Real PG goldens that only run on main from an export run on this branch (12 runs of the DeepSeek-V3 CP+PP test gave identical values).
  • ROCm mi350x: deepseek_v3, deepseek_v3_cp_pp, llama3, llama3_pp, muse_glimmer from the ciflow/rocm run. GPT-OSS, Qwen3 and SFT pass unchanged.
  • B200: the Kimi K3 golden failure was already failing on main and main refreshed it today; the GraphTrainer graph_trainer_dist_moe_mxfp8_fsdp_ep_pp crash ("weight must be contiguous CUDA storage") also fails on main's scheduled run.

@felipemello1
felipemello1 merged commit b95271e into main Oct 20, 2026
acisseJZhong pushed a commit that referenced this pull request Oct 21, 2026
)

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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/h100.8 Trigger H100.8 CI ciflow/real-pg Run the full 8-GPU Real PG integration suite ciflow/rl ciflow/rocm ciflow/8gpu 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.

3 participants