Skip to content

[muse_glimmer] Compile the residual sites and the attention output gate - #5931

Draft
felipemello1 wants to merge 3 commits into
mainfrom
felipemello1/muse-followups/5-glimmer-residual-norm
Draft

felipemello1 wants to merge 3 commits into
mainfrom
felipemello1/muse-followups/5-glimmer-residual-norm

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: Muse Glimmer's block glue now runs as 3 compiled kernels instead of 10 eager ones: each residual site (post-norm, residual add and, after attention, the FFN pre-norm) and the attention output gate. Two new regions, on by default for the trainer and the generator. Glimmer-30B decode is 4.1-6.3% faster at 1-256 tokens; prefill and the trainer step stay within noise.

main:    attn_out -> [w+1] [rms_norm] [x + .] [w+1] [rms_norm] -> h, ffn input   (5 kernels)
         ffn_out  -> [w+1] [rms_norm] [h + .]                  -> block output   (3 kernels)
         heads    -> view -> [sigmoid(gate)] [out * .]         -> wo             (2 kernels; backward 5)
this PR: attn_out -> [post-norm + add + ffn_norm]              -> h, ffn input   (1 kernel)
         ffn_out  -> [post-norm + add]                         -> block output   (1 kernel)
         heads    -> [view + sigmoid + multiply]               -> wo             (1 kernel; backward 4)

Based on main; no dependency on other open PRs.

Problem

  1. Glimmer's block is post-norm: h = x + post_attention_norm(attn_out), then ffn_norm(h), and at the end h + post_ffn_norm(ffn_out).
  2. Each norm is an RMSGainCenterNorm: one eager kernel adds weight + gain_center, one runs the norm. The adds and the output gate (out * sigmoid(gate)) are eager too.
  3. So a layer runs 10 small kernels that each read or write a [T, 6656] tensor.
  4. Cost at decode 64, one GB300, one sliding-window layer: 23.0 µs of a 226.9 µs layer.

Solution

  1. muse_glimmer_residual_norm: two block methods, _attention_residual(x, attn_out) and _ffn_residual(h, ffn_out), with one decorator. They call the same norm modules as before.
  2. muse_glimmer_attention_output: a module-level _flatten_attention_output(output, gate), the name Muse Spark uses for the same step. It is pointwise, so batch_invariant=True.
  3. emulate_precision_casts on both: the compiled kernels round the post-norm output and the sigmoid to bf16 where eager does.
  4. Remat: the end-of-block recompute=False region now wraps _ffn_residual, so Full remat skips the post-FFN norm and the add on replay, region on or off. The norm keeps only its [T] rstd; replay rebuilds its input, ffn_out, with the FFN. REMAT.md is updated.
  5. Both regions are in MuseGlimmerModel.Config's default list, so trainer and generator run the same regions.

Results

Numerics (forwards run in both roles, grads only in the trainer):

residual sites, width 6656, 2048/37/1 tokens   outputs differ from eager in <= 3.7e-5 of elements,
                                               no_grad vs grad mode in <= 6.5e-6; error vs fp64 1.00x eager's
output gate, 32 heads x 128, 2048/64/1 tokens  forward and grad of the attention output: bitwise equal to eager
                                               grad of the gate: 30-32% of elements differ, error vs fp64 0.85x eager's
2-layer unit, regions off vs on                decode 1-8, 32, 128 tokens bitwise; other no_grad rows rel. L2 <= 2.8e-3
                                               fwd+bwd 4096: output 2.1e-3, grads <= 9.6e-3
Full remat                                     grads equal the no-remat grads bit for bit, region on and off
goldens, 10 steps, from this PR's CI run       fake_pg a10g: step 1 loss bitwise, grad_norm -7.2e-5 rel.; max |d loss| 0.0030
                                               real_pg a10g: step 1 loss bitwise, grad_norm +6.8e-5 rel.; max |d loss| 0.0195
                                               real_pg mi350x: step 1 loss -1.7e-5 rel.; max |d loss| 0.0166
  • Residual sites: at width 6656 the norm is a looped reduction. Inductor picks the loop's block size per kernel, so a few rows sum in another order.
  • Gate grad: the compiled backward keeps the sigmoid's derivative in fp32. Eager rounds it to bf16.
  • Without emulate_precision_casts, 34-47% of the residual-site outputs and 26% of the gate outputs differ from eager.
  • Goldens: the last commit regenerates the three muse_glimmer.txt files from this PR's CI logs. Earlier numerics-only PRs moved the same files by as much (e.g. compiling ComplexRoPE in real arithmetic: max |d loss| 0.0281 on real_pg a10g, 0.0136 on mi350x).

Memory under Full remat, torch_remat's saved-tensor report after the forward (Glimmer-30B layers 2-3, 4096 tokens, GB300). Main keeps 0 B per layer. This PR keeps 16 KiB per layer with the regions on: the post-FFN norm's [4096, 1] fp32 rstd. With the regions off it keeps 29 KiB: the rstd plus the [6656] effective weight. Replay rebuilds ffn_out in both.

Kernel time per sliding-window layer at decode 64, Glimmer-30B, one GB300, CUDA-graph replay profile, µs (kernels). block = each block under torch.compile.

                   main         this PR      block
attention site      11.1 (5)     5.4 (1)      4.8 (1)
FFN site             7.0 (3)     4.5 (1)      5.4 (1)
gate                 4.9 (2)     2.0 (1)      2.0 (1)

Step time, Glimmer-30B layers 2 (sliding window) and 3 (global), µs: this PR's tree with the two regions off vs on. Generator rows compile as vLLM calls the model (2048 tokens static, then 1536 symbolic, then each size). Trainer rows use Full remat.

                 off      on
decode 1           435     407 (-6.3%)
decode 8           440     422 (-4.1%)
decode 32          462     442 (-4.5%)
decode 64          451     428 (-5.1%)
decode 128         474     451 (-4.8%)
decode 256         551     526 (-4.6%)
decode 512         754     751 (-0.4%)
prefill 2048      2631    2656 (+0.9%)
prefill 8192     10147   10151 (+0.0%)
fwd+bwd 4096     20931   20970 (+0.2%)   interleaved A/B: 0.994x (5 rounds, 0.972-1.006)
fwd+bwd 16384    84776   83159 (-1.9%)

Measured with the Glimmer qkv_norm_rope PR's change in both arms; it touches other kernels. Peak memory is equal. Graphs: an RL trainer sequence (fwd+bwd at 4096 and 3072 tokens, then no_grad at both) compiles 3 graphs per region function, under the default limit of 8.

NOTE: the Glimmer qkv_norm_rope PR edits the lines above in Attention.forward. Whichever of the two lands second drops num_tokens = x_TD.shape[0] (a one-line conflict).
NOTE: Glimmer's RL recipes run TP=2 in both roles; speed at TP=2 was not measured. The TP+SP integration tests (muse_glimmer_mm_fsdp+tp+sp, muse_glimmer_mm_tp+cp+pp+sp) keep the default regions and run in this PR's CI.

Test plan

  • tests/unit_tests/gpu/models/muse_glimmer/test_compile_regions.py (fails on main: no _attention_residual, no _flatten_attention_output):
    • test_residual_norm_region_matches_eager, widths 256 and 6656 (looped reduction), 2048/37/1 tokens in one binding: under 1e-4 of output elements differ from eager, and between no_grad and grad mode; outputs and grads within 1.05x of eager's error vs fp64.
    • test_attention_output_region_matches_eager, 64/37/1 tokens: the same checks plus batch invariance.
  • At this head (on main f548851), GB300: gpu/models/muse_glimmer and test_remat.py 23 passed; CPU cpu/models/muse_glimmer 132 passed, 1 skipped (a tokenizer test, skipped on main too). pre-commit passes (pyrefly prints only the notes it prints on main).
  • NOTE: the core CPU and GPU unit-test workflows skip draft PRs, so these GPU tests have not run in CI yet (the thresholds were measured on GB300; CI's GPU runners are A10G).

@felipemello1
felipemello1 added this pull request to stack #5499 November 7, 2026 05:58
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 7, 2026
@felipemello1 felipemello1 added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/real-pg Run the full 8-GPU Real PG integration suite ciflow/rocm labels Nov 7, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 3m 10s —— View job


Approve -- please address the items before merging (empty human summary, regenerate Glimmer goldens, REMAT.md wording): review

@claude claude Bot left a comment

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.

Verdict: Approve -- please address the items below before merging. The change is model-local, the regions are registered and off when local_compile.regions is empty (graph_trainer clears them), and the measured decode win is about 4-6% with no trainer regression. What remains is the description, the goldens, and one doc paragraph. A maintainer still needs to review.

What this PR does. Glimmer's two post-norm residual sites become two compiled block methods under one region, muse_glimmer_residual_norm (not batch-invariant). The head flatten plus sigmoid gate becomes a batch-invariant method under a second region, muse_glimmer_attention_output. Both regions are added to MuseGlimmerModel.Config's default local_compile.regions, so the trainer and the vLLM generator use them. The trailing recompute=False remat region now wraps the post-FFN norm together with the add.

Example. One layer at decode, region on:

before: h = x + post_attention_norm(attn_out)   # [w+1] [rms_norm] [add]
        ffn_in = ffn_norm(h)                     # [w+1] [rms_norm]
        out = h + post_ffn_norm(ffn_out)         # [w+1] [rms_norm] [add]   -> 8 kernels
after:  h, ffn_in = _attention_residual(x, attn_out)   # 1 kernel
        out = _ffn_residual(h, ffn_out)                 # 1 kernel, still a recompute=False region

Numerics: bf16 outputs differ from eager in fewer than 1e-4 of the elements, because the summation order changes. So loss and grad_norm move by a few ulps, and the Glimmer goldens shift.

Must fix

  1. The "Summary (human-written)" section is empty. Only the agent section is filled in.
  2. The goldens are not in the diff. tests/assets/losses/{fake_pg,real_pg}/a10g/muse_glimmer.txt and real_pg/mi350x/muse_glimmer.txt must be regenerated in this PR (as the NOTE says) before merging. Please also confirm in the PR that the only change is the expected one, a few ulps from the different summation order, and not a larger shift.
  3. torchtitan/distributed/REMAT.md:250-255: the paragraph now contradicts itself and describes a "trailing bare norm" pattern that no model uses any more (inline, with a suggestion).

Should consider

  • torchtitan/models/muse_glimmer/model.py:196-200: the attention-output region turns off pointwise autotuning so its results don't change from run to run, but the reduction region, where the kernel config actually changes the summation order, does not pin anything. This could widen the gap between trainer and generator results in non-deterministic RL runs (inline, unverified).
  • tests/unit_tests/gpu/models/muse_glimmer/test_compile_regions.py:109: _compare_region_to_eager is a general version of the fp64/bf16 comparison loop in test_qkv_norm_rope_region_matches_forward_math (lines 50-89 of the same file). Having that test use the helper removes about 25 duplicated lines and keeps one set of tolerances.
Details
  • Gate. The problem is real and measured: 10 small eager kernels per layer, 23 us of 227 us at decode 64. The code stays in the model folder and nothing shared changes except the REMAT.md doc. It is the same pattern as Muse Spark's muse_spark_attention_output and muse_spark_residual. Trainer and generator use it equally, so the design is not one-sided.
  • Recompile/remat. Every pre/post block norm has gain_center=1.0 (flavors.py:264-278), so all layers share one graph per method. That avoids the hazard described in MuseSparkRMSNorm (a float baked into layer 0's graph and replayed for another layer). Each region method has a single call site, so the default limit of 8 graphs per method applies; the author measured 3.
  • Batch-invariant mode. It already rejects Glimmer's defaults, because "loss" is batch_invariant=False. Adding muse_glimmer_residual_norm (False) does not newly break a working config.
  • Memory under Full remat. ffn_out was already kept alive for the bare post-norm on replay (by the removed marker). Now the saved region keeps it for backward instead, so peak memory should be unchanged, as the PR reports.

Not verified: GPU numerics and perf numbers; graph counts at TP=2 + SP (not measured, per the description; covered only by the CI TP+SP integration entries).

Comment thread torchtitan/distributed/REMAT.md Outdated
Comment on lines +250 to +255
add (`moe.shared_add`) are fixed `recompute=False` regions: they save nothing
for backward, so a saved add keeps nothing resident, its inputs need no
marker, and replay skips it. Only the adds are wrapped; a trailing norm, such
as Muse Glimmer's post-norm, stays a bare operation with a marker on its input.
marker, and replay skips it. Usually only the adds are wrapped, and a trailing
norm stays a bare operation with a marker on its input. Muse Glimmer's
`ffn_residual` also holds its post-FFN norm: the norm keeps only its input and a
`[T]` rstd for backward, so replay skips both.

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.

This paragraph now contradicts itself. Line 251 still says the ffn_residual regions "save nothing for backward", and two lines later Glimmer's region saves ffn_out and the rstd. "Usually ... a trailing norm stays a bare operation with a marker on its input" also matches no model any more: Glimmer was the only trailing-norm example, and every other ffn_residual (llama3, qwen3, qwen3_5, deepseek_v3, gpt_oss, kimi_k3, vision_encoder) wraps a bare torch.add. The doc should describe what the code does today. Suggested rewording:

Suggested change
add (`moe.shared_add`) are fixed `recompute=False` regions: they save nothing
for backward, so a saved add keeps nothing resident, its inputs need no
marker, and replay skips it. Only the adds are wrapped; a trailing norm, such
as Muse Glimmer's post-norm, stays a bare operation with a marker on its input.
marker, and replay skips it. Usually only the adds are wrapped, and a trailing
norm stays a bare operation with a marker on its input. Muse Glimmer's
`ffn_residual` also holds its post-FFN norm: the norm keeps only its input and a
`[T]` rstd for backward, so replay skips both.
add (`moe.shared_add`) are fixed `recompute=False` regions, so replay skips
them. A bare add saves nothing for backward, so its inputs need no marker and
stay resident only as long as the forward needs them. Muse Glimmer's
`ffn_residual` also holds its post-FFN norm, which saves only its input and a
`[T]` rstd for backward, the same tensors the norm would save anywhere else.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Rewritten in 7020d9e and 021ec57, close to your suggestion. The last sentence now says what a GPU saved-tensor report shows under Full remat at Glimmer-30B width: the norm keeps only its [T] rstd (16 KiB per layer), and replay rebuilds ffn_out.

Comment on lines +196 to +200
_compile_residual_norm = local_compile(
"muse_glimmer_residual_norm",
batch_invariant=False,
options={"emulate_precision_casts": True},
)

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.

Unverified, a question. muse_glimmer_attention_output turns off pointwise autotuning because "kernel configs picked by timing can round differently from run to run". This region holds the looped reductions, and there the kernel config really does decide the summation order. Your own test comment says Inductor picks a different loop block size per kernel at width 6656. If Inductor benchmarks several reduction configs at the first call (in non-deterministic mode), the RL trainer and generator processes could pick different configs. Then the same [T, 6656] input would give different post-norm outputs in the two roles, and the trainer-vs-generator logprob gap grows compared with eager, where each shape gets the same kernel every time. Deterministic CI probably doesn't show this. Can you confirm that the reduction config is chosen without timing, or pin it here (e.g. with a comment on which Inductor option does it)? If it is already deterministic, a one-line comment on why this region doesn't need the option the sibling region has would help the next reader.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: They are not pinned. Outside deterministic mode, Inductor may time a few reduction configs at the first call, so two processes can pick different block sizes. Another pick moves under 1e-4 of the outputs by one bf16 ulp: at width 6656 the no_grad and grad kernels differ in at most 6.5e-6 of elements. Deterministic and batch-invariant runs already filter to one config. Muse Spark's norm regions don't pin it either. I added a comment on the residual-norm region saying this. On the gate region, the pointwise-autotuning option and its comment are gone: a pointwise config can't change values.

Felipe Mello added 2 commits November 6, 2026 22:07
Two regions, on by default: muse_glimmer_residual_norm runs each residual site
(post-norm, residual add and, after attention, the FFN pre-norm) as one kernel;
muse_glimmer_attention_output runs the head flatten and the sigmoid output gate as
one kernel. The end-of-block save region now wraps the compiled post-FFN norm and add.
@felipemello1
felipemello1 removed this pull request from stack #5499 November 7, 2026 06:12
@felipemello1
felipemello1 force-pushed the felipemello1/muse-followups/4-glimmer-qkv-norm-rope branch from dd0f420 to 5839e16 Compare November 7, 2026 06:13
@felipemello1
felipemello1 force-pushed the felipemello1/muse-followups/5-glimmer-residual-norm branch from c7defc3 to 021ec57 Compare November 7, 2026 06:13
@felipemello1
felipemello1 changed the base branch from felipemello1/muse-followups/4-glimmer-qkv-norm-rope to main November 7, 2026 06:13
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review. Since your review: rebased on main f548851 as a standalone PR (no longer stacked on the Glimmer qkv_norm_rope PR). The gate is a free function, and its pointwise-autotune option is gone. The REMAT.md and comment wording now say the norm keeps only its [T] rstd and replay rebuilds ffn_out (GPU saved-tensor report under Full remat: 16 KiB per layer vs 0 B on main). The last commit regenerates the three muse_glimmer goldens from this PR's CI logs (step-1 loss bitwise on both a10g files; deltas in the body). The other red ROCm models tests (llama3_fsdp+tp+pp, deepseek_v3_fsdp+cp+pp+ep, gpt_oss_pp+fsdp+cp+ep+sacop) fail on main's run at the same base with the same values.

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 44s —— View job


Approve -- please address the items before merging (empty human summary; the new GPU unit test hasn't run on A10G CI yet because the PR is a draft): review

@claude claude Bot left a comment

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.

Verdict: Approve -- please address the items below before merging. Since the last review, the goldens, the REMAT.md paragraph and the reduction-config question are resolved. Two items remain: the human summary is still empty, and the new GPU tests have not run in CI. A maintainer still needs to review.

Since the last review (at 7c50f0d).

  • Goldens regenerated: resolved. All three muse_glimmer.txt files are in the diff. Step-1 loss is bitwise on fake_pg and real_pg a10g, and moves -1.7e-5 relative on mi350x. The largest later shift is 0.0195 (real_pg a10g, step 4). That is the size you get from a few ulps compounding over 10 steps in bf16, and it is in line with earlier numerics-only Glimmer changes. The old mi350x step-9 grad_norm spike (4.16) is gone, so nothing points to a larger regression.
  • REMAT.md:249-254: resolved. The paragraph now separates the bare-add case from Glimmer's norm-plus-add region and no longer describes a pattern that no model uses.
  • Reduction-config pinning (model.py, _compile_residual_norm): resolved by the new comment. Dropping triton.autotune_pointwise from the gate region is correct: a pointwise kernel config can't change values.
  • Test-helper duplication with the qkv_norm_rope test: no longer applies now that the PR is standalone.

Example. One layer, regions on (unchanged from the last review):

before: h = x + post_attention_norm(attn_out); ffn_in = ffn_norm(h)   # 5 kernels
        out = h + post_ffn_norm(ffn_out)                               # 3 kernels
        wo(view(out_heads) * sigmoid(gate))                            # 2 kernels
after:  h, ffn_in = _attention_residual(x, attn_out)                   # 1 kernel
        out = _ffn_residual(h, ffn_out)   # 1 kernel, still the recompute=False ffn_residual region
        wo(_flatten_attention_output(out_heads, gate))                 # 1 kernel

Must fix

  1. The "Summary (human-written)" section is still empty. The author must write it; an agent can't.
  2. The PR is still a draft, so "1 GPU Unit Tests" is skipped and tests/unit_tests/gpu/models/muse_glimmer/test_compile_regions.py has never run in CI. Its thresholds (< 1e-4 of elements differ, <= 1.05x eager's fp64 error) were measured on GB300. CI runs on A10G, where Inductor can pick different reduction configs at width 6656. Mark the PR ready (or trigger the workflow) and confirm the test passes on A10G before merging. Don't loosen the thresholds if it fails; find out which check fails first.
Details
  • Remat markers. recompute_needs_tensor(output) and (gate) still sit right before _flatten_attention_output, and (attn_out) before _attention_residual. Compiled region or not, both are bare (non-remat.region) consumers, so the markers are still needed. This matches Muse Spark (muse_spark/model.py:139-142). The comments that say "bare ops" are still accurate.
  • Recompiles. All three block norms use gain_center=1.0 (flavors.py:264-278), and o_gate is set uniformly (flavors.py:233). So the gate is None guard does not split graphs across layers, and every layer shares the same graphs per region function. The author measured 3 graphs per function, under the default limit of 8.
  • Removing num_tokens. _flatten_attention_output uses output.shape[0]. That equals the post-gather x_TD.shape[0] under SP, because inner_attention returns [T, H, K] for the gathered T.
  • Test placement and value. The test is in the GPU suite with the usual skipif(cuda) guard. It guards the batch_invariant=True claim on the gate region, which the goldens don't cover.

Not verified: GPU numerics and perf numbers; the A10G result of the new unit test; graph counts at TP=2 + SP.

Z-Ghostshell added a commit to Z-Ghostshell/torchtitan that referenced this pull request Nov 17, 2026
…efault (pytorch#5740)

Summary:

Why:
Decoder blocks run the post-attention residual add and the following FFN norm as separate kernels. Decode is launch-latency bound, and issue pytorch#5537 reports a diagnostic hand-fusion of this seam improving decode from 3.7742 to 3.6674 ms/step (2.9%) on Qwen3-0.6B bf16, 8x MI355X, TP=4, 32 concurrent sequences, 341-token prompts, 319 output tokens, greedy decoding with ignore_eos, FULL_DECODE_ONLY graphs, Torch 2.16.0.dev+rocm10.0. That is the issue author's ROCm generator measurement, not a result of this PR.

How:
- Add `residual_norm(residual, delta, norm)` in `models/common/norm.py`, a `residual_norm` local compile region (non-batch-invariant) that returns `(residual + delta, norm(residual + delta))`. The norm module is called inside the region, so any norm (RMSNorm, OffsetRMSNorm, overrides such as `higher_precision_rms_norm`) keeps its own math and the shared norm contract is unchanged.
- Use it at the `x + attn_out -> ffn_norm` seam of llama3, qwen3, deepseek_v3 (and its MTP block), gpt_oss and qwen3_5 (qwen3.6/3.8 share its block). deepseek_v4 (hyper-connections), kimi_k3 and muse_spark (own residual modules) have no such seam. Muse Glimmer is left to pytorch#5931, which already covers its residual sites.
- Enable `residual_norm` in the default `local_compile.regions` of those models, instead of only in the RL generator recipe, so trainer and generator share one compile policy. Kimi K2 / K2.5 reuse the DeepSeek-V3 block (so they call the helper) but keep their explicitly empty region list, per the existing TODO in `kimi_k2_7/model.py`.

Numerics:
With the region off (the eager path), the helper runs `residual + delta` then `norm(h)`, the same ops in the same order as main. CI runs with compilation off, so golden losses are not expected to change; if any do, the new curves will be taken from CI. With the region compiled, results are not bitwise equal to eager (an A100 Qwen3 run differs from step 1). This is expected from the fusion: Inductor moves the add into the norm's reduction kernel, so the sum-of-squares reduction order differs from the eager CUDA kernel, and by default Inductor does not round the intermediate sum to bf16 before normalizing (`emulate_precision_casts=False`). An op-level confirmation on GPU is pending.

Follow-up: fusing block i's trailing `x + ffn_out` with block i+1's `attention_norm` needs a decoder-loop change and interacts with the `ffn_residual` remat region.

### Agent details
This description clarification was prepared with an AI assistant. The author remains responsible for reviewing the exact code and any GitHub reply or re-export.

Differential Revision: D129126504
Z-Ghostshell added a commit to Z-Ghostshell/torchtitan that referenced this pull request Nov 17, 2026
…efault (pytorch#5740)

Summary:

Why:
Decoder blocks run the post-attention residual add and the following FFN norm as separate kernels. Decode is launch-latency bound, and issue pytorch#5537 reports a diagnostic hand-fusion of this seam improving decode from 3.7742 to 3.6674 ms/step (2.9%) on Qwen3-0.6B bf16, 8x MI355X, TP=4, 32 concurrent sequences, 341-token prompts, 319 output tokens, greedy decoding with ignore_eos, FULL_DECODE_ONLY graphs, Torch 2.16.0.dev+rocm10.0. That is the issue author's ROCm generator measurement, not a result of this PR.

How:
- Add `residual_norm(residual, delta, norm)` in `models/common/norm.py`, a `residual_norm` local compile region (non-batch-invariant) that returns `(residual + delta, norm(residual + delta))`. The norm module is called inside the region, so any norm (RMSNorm, OffsetRMSNorm, overrides such as `higher_precision_rms_norm`) keeps its own math and the shared norm contract is unchanged.
- Use it at the `x + attn_out -> ffn_norm` seam of llama3, qwen3, deepseek_v3 (and its MTP block), gpt_oss and qwen3_5 (qwen3.6/3.8 share its block). deepseek_v4 (hyper-connections), kimi_k3 and muse_spark (own residual modules) have no such seam. Muse Glimmer is left to pytorch#5931, which already covers its residual sites.
- Enable `residual_norm` in the default `local_compile.regions` of those models, instead of only in the RL generator recipe, so trainer and generator share one compile policy. Kimi K2 / K2.5 reuse the DeepSeek-V3 block (so they call the helper) but keep their explicitly empty region list, per the existing TODO in `kimi_k2_7/model.py`.

Numerics:
With the region off (the eager path), the helper runs `residual + delta` then `norm(h)`, the same ops in the same order as main. CI runs with compilation off, so golden losses are not expected to change; if any do, the new curves will be taken from CI. With the region compiled, results are not bitwise equal to eager (an A100 Qwen3 run differs from step 1). This is expected from the fusion: Inductor moves the add into the norm's reduction kernel, so the sum-of-squares reduction order differs from the eager CUDA kernel, and by default Inductor does not round the intermediate sum to bf16 before normalizing (`emulate_precision_casts=False`). An op-level confirmation on GPU is pending.

Follow-up: fusing block i's trailing `x + ffn_out` with block i+1's `attention_norm` needs a decoder-loop change and interacts with the `ffn_residual` remat region.

### Agent details
This description clarification was prepared with an AI assistant. The author remains responsible for reviewing the exact code and any GitHub reply or re-export.

Differential Revision: D129126504
Z-Ghostshell added a commit to Z-Ghostshell/torchtitan that referenced this pull request Nov 18, 2026
…efault (pytorch#5740)

Summary:

Why:
Decoder blocks run the post-attention residual add and the following FFN norm as separate kernels. Decode is launch-latency bound, and issue pytorch#5537 reports a diagnostic hand-fusion of this seam improving decode from 3.7742 to 3.6674 ms/step (2.9%) on Qwen3-0.6B bf16, 8x MI355X, TP=4, 32 concurrent sequences, 341-token prompts, 319 output tokens, greedy decoding with ignore_eos, FULL_DECODE_ONLY graphs, Torch 2.16.0.dev+rocm10.0. That is the issue author's ROCm generator measurement, not a result of this PR.

How:
- Add `residual_sum_and_norm(residual, delta, norm)` in `models/common/norm.py`, a `residual_sum_and_norm` local compile region (non-batch-invariant) that returns `(residual + delta, norm(residual + delta))`. The norm module is called inside the region, so any norm (RMSNorm, OffsetRMSNorm, overrides such as `higher_precision_rms_norm`) keeps its own math and the shared norm contract is unchanged.
- Use it at the `x + attn_out -> ffn_norm` seam of llama3, qwen3, deepseek_v3 (and its MTP block), gpt_oss and qwen3_5 (qwen3.6/3.8 share its block). deepseek_v4 (hyper-connections), kimi_k3 and muse_spark (own residual modules) have no such seam. Muse Glimmer is left to pytorch#5931, which already covers its residual sites.
- Zero-bubble pipeline schedules (ZBVZeroBubble, InterleavedZeroBubble, custom schedules with W actions) split backward into an input pass that keeps the graph (`retain_graph=True`) and a weight pass. A compiled backward that donates buffers rejects that (`This backward function was compiled with non-empty donated buffers which requires create_graph=False and retain_graph=False`); the saved RMSNorm `rsqrt` makes this region the first default one in these models to hit it. `build_pipeline` now sets `torch._functorch.config.donated_buffer = False` next to the existing in-place WGRAD-accumulation opt-out when the schedule splits backward.
- Enable `residual_sum_and_norm` in the default `local_compile.regions` of those models, instead of only in the RL generator recipe, so trainer and generator share one compile policy. Kimi K2 / K2.5 reuse the DeepSeek-V3 block (so they call the helper) but keep their explicitly empty region list, per the existing TODO in `kimi_k2_7/model.py`.

Numerics:
These models now run the region compiled by default. `BaseModel.parallelize` always applies `local_compile`, and CI only clears the regions in configs that turn on SPMD typechecking (`torchtitan_recipes/tests/__init__.py`), so the golden-loss configs run it compiled and their numbers change. The compiled region is not bitwise equal to eager: Inductor moves the add into the norm's reduction kernel, so the sum-of-squares reduction order differs from the eager kernel, and it does not round the intermediate sum to the activation dtype before normalizing (`emulate_precision_casts=False`). With the region off, the helper runs `residual + delta` then `norm(h)`, the same ops in the same order as main; the llama3 SFT golden test, which turns on SPMD typechecking and so runs with the region off, still matches its existing golden. The golden files below are regenerated from this PR's CI output (fake-PG A10G job: llama3 FSDP+TP+CP with and without region AC give identical numbers, so the activation-remat invariant still holds):
- `fake_pg/a10g`: `llama3.txt`, `deepseek_v3.txt`, `qwen3.txt`, `gpt_oss.txt`
- `real_pg/a10g`: `llama3_pp.txt`, `deepseek_v3_cp_pp.txt`, `gpt_oss_pp.txt`
Not regenerated, because no PR CI job runs them: the non-PP `real_pg/a10g` files and every `real_pg/mi350x` file.

Follow-up: fusing block i's trailing `x + ffn_out` with block i+1's `attention_norm` needs a decoder-loop change and interacts with the `ffn_residual` remat region.

### Agent details
This description clarification was prepared with an AI assistant. The author remains responsible for reviewing the exact code and any GitHub reply or re-export.

Differential Revision: D129126504
Z-Ghostshell added a commit to Z-Ghostshell/torchtitan that referenced this pull request Nov 18, 2026
…efault (pytorch#5740)

Summary:

Why:
Decoder blocks run the post-attention residual add and the following FFN norm as separate kernels. Decode is launch-latency bound, and issue pytorch#5537 reports a diagnostic hand-fusion of this seam improving decode from 3.7742 to 3.6674 ms/step (2.9%) on Qwen3-0.6B bf16, 8x MI355X, TP=4, 32 concurrent sequences, 341-token prompts, 319 output tokens, greedy decoding with ignore_eos, FULL_DECODE_ONLY graphs, Torch 2.16.0.dev+rocm10.0. That is the issue author's ROCm generator measurement, not a result of this PR.

How:
- Add `residual_sum_and_norm(residual, delta, norm)` in `models/common/norm.py`, a `residual_sum_and_norm` local compile region (non-batch-invariant) that returns `(residual + delta, norm(residual + delta))`. The norm module is called inside the region, so any norm (RMSNorm, OffsetRMSNorm, overrides such as `higher_precision_rms_norm`) keeps its own math and the shared norm contract is unchanged.
- Use it at the `x + attn_out -> ffn_norm` seam of llama3, qwen3, deepseek_v3 (and its MTP block), gpt_oss and qwen3_5 (qwen3.6/3.8 share its block). deepseek_v4 (hyper-connections), kimi_k3 and muse_spark (own residual modules) have no such seam. Muse Glimmer is left to pytorch#5931, which already covers its residual sites.
- Zero-bubble pipeline schedules (ZBVZeroBubble, InterleavedZeroBubble, custom schedules with W actions) split backward into an input pass that keeps the graph (`retain_graph=True`) and a weight pass. A compiled backward that donates buffers rejects that (`This backward function was compiled with non-empty donated buffers which requires create_graph=False and retain_graph=False`); the saved RMSNorm `rsqrt` makes this region the first default one in these models to hit it. `build_pipeline` now sets `torch._functorch.config.donated_buffer = False` next to the existing in-place WGRAD-accumulation opt-out when the schedule splits backward.
- Enable `residual_sum_and_norm` in the default `local_compile.regions` of those models, instead of only in the RL generator recipe, so trainer and generator share one compile policy. Kimi K2 / K2.5 reuse the DeepSeek-V3 block (so they call the helper) but keep their explicitly empty region list, per the existing TODO in `kimi_k2_7/model.py`.

Numerics:
These models now run the region compiled by default. `BaseModel.parallelize` always applies `local_compile`, and CI only clears the regions in configs that turn on SPMD typechecking (`torchtitan_recipes/tests/__init__.py`), so the golden-loss configs run it compiled and their numbers change. The compiled region is not bitwise equal to eager: Inductor moves the add into the norm's reduction kernel, so the sum-of-squares reduction order differs from the eager kernel, and it does not round the intermediate sum to the activation dtype before normalizing (`emulate_precision_casts=False`). With the region off, the helper runs `residual + delta` then `norm(h)`, the same ops in the same order as main; the llama3 SFT golden test, which turns on SPMD typechecking and so runs with the region off, still matches its existing golden. The golden files below are regenerated from this PR's CI output (fake-PG A10G job: llama3 FSDP+TP+CP with and without region AC give identical numbers, so the activation-remat invariant still holds):
- `fake_pg/a10g`: `llama3.txt`, `deepseek_v3.txt`, `qwen3.txt`, `gpt_oss.txt`
- `real_pg/a10g`: `llama3_pp.txt`, `deepseek_v3_cp_pp.txt`, `gpt_oss_pp.txt`
Not regenerated, because no PR CI job runs them: the non-PP `real_pg/a10g` files and every `real_pg/mi350x` file.

Follow-up: fusing block i's trailing `x + ffn_out` with block i+1's `attention_norm` needs a decoder-loop change and interacts with the `ffn_residual` remat region.

### Agent details
This description clarification was prepared with an AI assistant. The author remains responsible for reviewing the exact code and any GitHub reply or re-export.

Differential Revision: D129126504

This branch has not been deployed

No deployments
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/real-pg Run the full 8-GPU Real PG integration suite ciflow/rocm 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.

1 participant