Repository navigation
Fuse the post-attention residual add into ffn_norm and enable it by default (#5740) - #5740
Z-Ghostshell wants to merge 1 commit into
Conversation
|
@Z-Ghostshell has exported this pull request. If you are a Meta employee, you can view the originating Diff in D129126504. |
|
@claude review |
There was a problem hiding this comment.
should we only do this to qwen3?
There was a problem hiding this comment.
@Z-Ghostshell could you do this for all the model, instead of only qwen3?
There was a problem hiding this comment.
Verdict: Request changes -- turning this region on by default changes the main Qwen3 training path. That breaks an existing CPU unit test, probably changes the golden numerics with no explanation, and the region claims batch invariance without evidence.
What this PR does. It adds a local_compile region, attention_residual_norm, to qwen3/model.py. The region fuses the post-attention residual add with ffn_norm and returns both the updated residual and the FFN input. The region is added to Qwen3Model.Config's default local_compile.regions, so it runs in both training and the vLLM generator, which builds from the same model config.
Example.
# before (eager): 2+ kernels per layer
x = x + attn_out
ffn_out = self.feed_forward(self.ffn_norm(x))
# after (one Inductor graph when the region is enabled, the Qwen3 default)
x, ffn_input = _attention_residual_norm(x, attn_out, self.ffn_norm)
ffn_out = self.feed_forward(ffn_input)The forward is the same math, but RMSNorm now runs as an Inductor reduction instead of eager F.rms_norm. The bits will probably differ (the PR's own test uses assert_close, not equality).
Must fix
- PR description -- the "issue report" behind the 2.9% e2e decode number isn't linked, and the model size, decode setup and baseline aren't given. There are no numerics or training perf numbers, even though the region now runs by default in training. Please link the issue, give the setup, and add a loss/grad_norm comparison plus training TPS/memory.
tests/unit_tests/cpu/quantization/test_quantization.py:483-487-- it hardcodes the Qwen3 region list, and CPU Unit Test fails on it (test_qwen3_recipes_resolve[qwen3_8b_first_85_pct_layers_nvfp4]). Update the list. (Not in the diff, so no inline comment.)torchtitan/models/qwen3/model.py:123-- either show bitwise-identical loss, or explain the change and regenerate the Qwen3 goldens (real_pg a10g, real_pg mi350x, fake_pg a10g).torchtitan/models/qwen3/model.py:29--batch_invariant=Trueis unproven, while every other RMSNorm region declaresFalse. UseFalse; all batch-invariant recipes already disable local compile regions.tests/unit_tests/gpu/models/qwen3/test_residual_norm.py:26-- delete the file and its__init__.py. One test re-reads a config default; the parity test checks upstream Inductor at a tolerance and imports a module-private symbol. The golden-loss tests already cover model-level numerics.
Should consider
torchtitan/models/qwen3/model.py:30-36-- calling the parallelizedffn_normmodule inside afullgraphregion means Dynamo traces the SPMD redistribution wrapper (unverified under TP+SP with spmd typechecking). Also, "stream" is an overloaded term, and the file has no shape legend.
Questions
llama3/model.py:63-66has the same residual-add +ffn_normseam. Is Qwen3-only intentional, e.g. because only the Qwen3 decode path was measured?
Not verified: the golden-loss and GPU test outcomes (Integration Tests and GPU Unit Tests were still queued). A maintainer still needs to review.
| from .state_dict_adapter import Qwen3StateDictAdapter | ||
|
|
||
|
|
||
| @local_compile("attention_residual_norm", batch_invariant=True) |
There was a problem hiding this comment.
batch_invariant=True claims that the Inductor-compiled RMSNorm is batch-invariant, and nothing backs that up. Every other RMSNorm-style region in the repo declares False: offset_rmsnorm (qwen3_5/model.py:89), gated_rmsnorm (common/norm.py:35), and muse_spark_rmsnorm. In batch-invariant mode the eager reductions go through the batch_invariant_ops overrides. A compiled region lowers its own Triton reduction instead, and Inductor picks the reduction config per shape (persistent vs. looped, split reduction when there are few rows, as in decode). If someone enables this region with DebugConfig(batch_invariant=True), nothing raises, and trainer/generator logprob parity can drift without any error.
All in-repo batch-invariant recipes already set local_compile.regions = [], so declaring False costs nothing:
| @local_compile("attention_residual_norm", batch_invariant=True) | |
| @local_compile("attention_residual_norm", batch_invariant=False) |
| "loss", | ||
| "fused_binary_activation", | ||
| "rope", | ||
| "attention_residual_norm", |
There was a problem hiding this comment.
Enabling this region by default changes the main Qwen3 training path, not only decode. Two consequences:
tests/unit_tests/cpu/quantization/test_quantization.py:483-487hardcodes the Qwen3 region list. The CPU Unit Test job fails on it:test_qwen3_recipes_resolve[qwen3_8b_first_85_pct_layers_nvfp4],assert [..., 'attention_residual_norm', ...] == [...]. Update that list.- Compiled add+RMSNorm is very likely not bitwise identical to eager
F.rms_norm. The new test compares the two withassert_closetolerances, not equality. The Qwen3 goldens (tests/assets/losses/real_pg/a10g/qwen3.txt,real_pg/mi350x/qwen3.txt,fake_pg/a10g/qwen3.txt) aren't touched. Either show a bitwise-identical loss/grad_norm comparison (scripts/loss_compare.py), or explain the change and regenerate all three. Please also report training throughput/memory before and after, since this is now on by default for training.
|
|
||
| def test_qwen3_enables_region(self): | ||
| config = qwen3_debugmodel() |
There was a problem hiding this comment.
This test only re-reads a default it just set (.claude/rules/tests.md: no tests that re-read config). The parity test below checks that torch.compile of x + y; rms_norm(...) matches eager within bf16 tolerance. That is upstream Inductor's contract, and the model-level effect is already guarded by the Qwen3 golden-loss integration tests. The file also imports the module-private _attention_residual_norm. I'd delete this file and tests/unit_tests/gpu/models/qwen3/__init__.py.
| def _attention_residual_norm( | ||
| stream_TD: torch.Tensor, | ||
| attention_output_TD: torch.Tensor, | ||
| norm: nn.Module, | ||
| ) -> tuple[torch.Tensor, torch.Tensor]: | ||
| stream_TD = stream_TD + attention_output_TD | ||
| return stream_TD, norm(stream_TD) |
There was a problem hiding this comment.
Two points:
norm(stream_TD)calls a parallelizedModuleinside afullgraph=Trueregion. Once the norm has aShardingConfig, itsforwardisModule._parallelize'sforward_with_redistributionwrapper (models/base/module.py:309), so Dynamo has to trace_redistribute_inputs/_outputsandspmd.assert_type. Existing regions avoid this: they either decorate the innerforward(muse_spark_rmsnorm) or read onlynorm.weight/norm.eps(kimi_k3attention_residual). Unverified: please confirm a TP+SP Qwen3 config withdebug.spmd_typecheckingcompiles without a graph break.- "stream" is on the overloaded-terms list in CLAUDE.md, and this file has no shape-suffix legend. Consider
h_TD/attn_out_TD, plus a# T = tokens, D = model dimensionlegend.
Summary: Why: Qwen3 executes the attention residual add and the following FFN RMSNorm as separate eager kernels. Decode is launch-latency bound, and the issue report measures a 2.9% end-to-end improvement when this seam is compiled together. How: Add a batch-invariant `attention_residual_norm` local compile region that returns both the updated residual stream and its normalized FFN input. Enable it in the Qwen3 model default and cover compiled forward/backward parity with eager execution. Differential Revision: D129126504
4d3a824 to
94794bd
Compare
Summary: Why: Qwen3 executes the attention residual add and the following FFN RMSNorm as separate eager kernels. Decode is launch-latency bound, and the issue report measures a 2.9% end-to-end improvement when this seam is compiled together. How: Add a non-batch-invariant `attention_residual_norm` local compile region that returns both the updated residual and its normalized FFN input. Pass the norm weight and epsilon into functional RMSNorm so the fullgraph boundary does not trace the parallelized module wrapper. Enable the region in the Qwen3 default and compare compiled forward/backward behavior against the RMSNorm module implementation. Differential Revision: D129126504
94794bd to
484fefe
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Request changes -- the code fixes landed, but the region is still on by default in Qwen3 training. There is still no numerics or perf evidence for that, the goldens haven't been regenerated, and @tianyu-l's question is unanswered.
What changed since the last review (re-review of 484fefe). The region now takes ffn_norm.weight/eps and calls F.rms_norm directly instead of calling the parallelized module. It declares batch_invariant=False. The CPU quantization test list is updated, and the config re-read test is gone.
Example.
# main (eager): add, then RMSNorm module
x = x + attn_out
ffn_out = self.feed_forward(self.ffn_norm(x))
# HEAD (one Inductor graph; region on by default for Qwen3)
x, ffn_input_TD = _attention_residual_norm(x, attn_out_TD, self.ffn_norm.weight, self.ffn_norm.eps)
ffn_out = self.feed_forward(ffn_input_TD)With the region disabled this is bitwise the same as main (nn.RMSNorm.forward is F.rms_norm). With it enabled it is not: the PR's own test needs atol=rtol=2e-2 for the input grads.
Resolved
test_quantization.pyregion list: updated, and CPU Unit Test passes.batch_invariant=True: nowFalse.- The fullgraph region no longer traces the module's SPMD redistribution wrapper. It reads only
weight/eps, like kimi_k3'sattention_residual. - "stream" naming and the missing shape legend: fixed (
h_TD,attn_out_TD, legend added).
Must fix (still open)
- PR description -- it is unchanged. The "issue report" behind the 2.9% decode number isn't linked, and the model, decode setup and baseline aren't given. There is no loss/grad_norm comparison and no training TPS/memory before and after, even though this is now the training default. Please link the issue and add those numbers.
- @tianyu-l's question (
qwen3/model.py): "should we only do this to qwen3?" has no reply.llama3/model.py:63-66(and otherDecoderblocks) have the same residual-add +ffn_normseam. Either answer why this is Qwen3-only (e.g. only Qwen3 decode was measured), or say what the plan is for the other models. torchtitan/models/qwen3/model.py:136goldens -- compiled add+RMSNorm is not bitwise eager (see the tolerances above).tests/assets/losses/{real_pg/a10g,real_pg/mi350x,fake_pg/a10g}/qwen3.txtare still untouched. Either show bitwise-identical loss/grad_norm withscripts/loss_compare.py, or explain the change and regenerate all three. Integration Tests were still queued, so I couldn't confirm the outcome.tests/unit_tests/gpu/models/qwen3/test_residual_norm.py-- the remaining parity test comparestorch.compileofadd + F.rms_normagainst eager at a loosened bf16 tolerance. That is Inductor's contract, and the golden-loss tests cover the model-level effect. The test also imports the module-private_attention_residual_norm. Please delete this file and its__init__.py.
I found no new problems in the rewritten code.
Not verified: GPU Unit Tests and Integration Tests (golden loss) were still queued. A maintainer still needs to review.
484fefe to
5b40303
Compare
Summary: Why: Qwen3 executes the attention residual add and the following FFN RMSNorm as separate eager kernels. Decode is launch-latency bound, and the issue report measures a 2.9% end-to-end improvement when this seam is compiled together. Compiling the seam changes training numerics, so the optimization must not silently alter the default training path. How: Add a non-batch-invariant `attention_residual_norm` local compile region that returns both the updated residual and its normalized FFN input. Pass the norm weight and epsilon into functional RMSNorm so the fullgraph boundary does not trace the parallelized module wrapper. Keep the region opt-in through `LocalCompileConfig`, and compare compiled forward/backward behavior against the RMSNorm module implementation. Differential Revision: D129126504
Summary: Why: Qwen3 executes the attention residual add and the following FFN RMSNorm as separate eager kernels. Decode is launch-latency bound, and the issue report measures a 2.9% end-to-end improvement when this seam is compiled together. Compiling the seam changes training numerics, so the optimization must not silently alter the default training path. How: Add a non-batch-invariant `attention_residual_norm` local compile region that returns both the updated residual and its normalized FFN input. Pass the norm weight and epsilon into functional RMSNorm so the fullgraph boundary does not trace the parallelized module wrapper. Keep the region opt-in through `LocalCompileConfig`, and compare compiled forward/backward behavior against the RMSNorm module implementation. Differential Revision: D129126504
5b40303 to
cd4ca5a
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Request changes -- the region is now opt-in and the default training path is bitwise unchanged. But no recipe turns it on, the 2.9% claim still has no source or setup, @tianyu-l's question is unanswered, and the change now bypasses ffn_norm.forward on every path.
What changed since the last review (re-review of cd4ca5a). attention_residual_norm was removed from Qwen3Model.Config's default local_compile.regions, so it now runs only if a config lists it. The description now says "opt-in". The config re-read test is still gone.
Example.
# main
x = x + attn_out
ffn_out = self.feed_forward(self.ffn_norm(x))
# HEAD, region off (all in-repo configs): same bits, but ffn_norm.forward is skipped
x, ffn_in = _attention_residual_norm(x, attn_out, self.ffn_norm.weight, self.ffn_norm.eps)
# -> eager: x + attn_out; F.rms_norm(x, (D,), weight, eps)
# HEAD, region on: one Inductor graph (not bitwise eager)Resolved
- Qwen3 goldens and default-path numerics: no longer affected, because the region is off by default and the eager path is the same
F.rms_normcall. - The training throughput/memory request no longer applies, for the same reason.
Must fix
- No consumer, no evidence. No recipe in the repo lists
attention_residual_norm(grepovertorchtitan_recipes/andtorchtitan/experiments/), so the region is dead code at HEAD. The description still cites "the issue report" for a 2.9% e2e decode gain with no link, model, batch/sequence setup, or baseline. Please enable it in the recipe that motivates it (e.g. the Qwen3 RL generator config, wherebatch_invariant=Falseis acceptable), and link the issue with the measurement setup. Otherwise drop the region. - @tianyu-l's question ("should we only do this to qwen3?") is still unanswered.
llama3/model.pyand the otherDecoderblocks have the same residual-add +ffn_normseam. Please reply on the thread. tests/unit_tests/gpu/models/qwen3/test_residual_norm.py(still open). It tests Inductor's add+rms_normagainst eager at a loosened bf16 tolerance, and it imports the module-private_attention_residual_norm. Delete it and its__init__.py.
Should consider
torchtitan/models/qwen3/model.py:83-89--ffn_norm.forwardis now bypassed even when the region is off. This changes GraphTrainer's per-module FQN tagging and may change MoE FSDP bucketing (unverified; see the inline comment).
Not verified: GPU unit tests and GraphTrainer runs. A maintainer still needs to review.
| assert self.ffn_norm.eps is not None | ||
| x, ffn_input_TD = _attention_residual_norm( | ||
| x, | ||
| attn_out_TD, | ||
| self.ffn_norm.weight, | ||
| self.ffn_norm.eps, | ||
| ) |
There was a problem hiding this comment.
This change applies even when the region is disabled, which is now every in-repo config: ffn_norm.forward is never called again. The math is bitwise the same (nn.RMSNorm.forward is F.rms_norm), and norm_sharding_config has no out_dst_shardings, so skipping forward_with_redistribution drops no redistribution.
What does change is anything keyed on the module call. GraphTrainer's annotate_module_fqns (experiments/graph_trainer/common_utils.py:363-365) wraps every submodule's forward to tag FX nodes with module_fqn. The ffn_norm.weight access and the rms_norm ops are now tagged layers.N instead of layers.N.ffn_norm. For Qwen3 MoE with edp_shard > 1, get_default_transformer_block_buckets(split_moe_expert_buckets=True) (common_utils.py:499-511) lists layers.N.ffn_norm but not layers.N, so that weight's FSDP all-gather may fall outside its bucket. Profiler kernel annotations lose the ffn_norm label too. Unverified -- please run a GraphTrainer Qwen3 MoE config with edp_shard > 1, or check the bucket assignment.
Smallest fix: call the module on the eager path and the functional form only inside the region. For example, keep x = x + attn_out_TD; ffn_input_TD = self.ffn_norm(x) when the region is off, or tell the maintainers why bypassing the module boundary is acceptable for Qwen3 only (kimi_k3's attention_residual is its own module, so it doesn't bypass a sibling's forward).
Summary: Why: Qwen3 executes the attention residual add and the following FFN RMSNorm as separate eager kernels. Decode is launch-latency bound, and the issue report measures a 2.9% end-to-end improvement when this seam is compiled together. Compiling the seam changes training numerics, so the optimization must not silently alter the default training path or bypass module-call metadata when disabled. How: Add a non-batch-invariant `attention_residual_norm` local compile region that returns both the updated residual and its normalized FFN input. When enabled, pass the norm weight and epsilon into functional RMSNorm so the fullgraph boundary does not trace the parallelized module wrapper. When disabled, retain the original residual add and `self.ffn_norm(x)` module call so GraphTrainer FQN tagging, profiler annotations, and sharding buckets remain unchanged. Keep the region opt-in through `LocalCompileConfig`. Differential Revision: D129126504
| remat.recompute_needs_tensor(attn_out) | ||
| x = x + attn_out | ||
| remat.recompute_needs_tensor(attn_out_TD) | ||
| if is_local_compile_enabled("attention_residual_norm"): |
There was a problem hiding this comment.
@Z-Ghostshell could you simplify the PR by not considering graph trainer? Once we merge it, @SherlockNoMad can unblock graph trainer, if that's easier coordination.
| # Trailing add, always saved: it saves nothing for backward, so replay skips | ||
| # it and its inputs need no persisting, matching checkpoint early stop. | ||
| return remat.region( | ||
| torch.add, self.remat_region_name("ffn_residual"), recompute=False |
There was a problem hiding this comment.
I think what this PR proposes is fine, but it seems we are still missing the opportunity of fusing
- transformer block i: x = x + ffn_out
- transformer block i+1: norm(x)
There was a problem hiding this comment.
@felipemello1 what's the benefit of making intrusive changes into RMSNorm by adding residual arg? I imagine we have to change contract and let every norm support it. Plus it won't bring more perf gain.
There was a problem hiding this comment.
@Z-Ghostshell could you do this for all the model, instead of only qwen3?
cef4e0d to
43b4fdc
Compare
…ytorch#5740) Summary: Why: Decoder blocks run the post-attention residual add and the following FFN RMSNorm as two eager 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_rms_norm(residual, delta, norm)` in `models/common/norm.py`. It returns `(residual + delta, norm(residual + delta))`. For a plain `RMSNorm` the add and `F.rms_norm` form one `residual_rmsnorm` local compile region (non-batch-invariant), so enabling the region fuses them; with the region off it is the same eager math and bits as before. Any other norm (a subclass or a config override such as `higher_precision_rms_norm`) keeps its own `forward`, so the shared `RMSNorm` contract is unchanged. - Use it at the `x + attn_out -> ffn_norm` seam of every decoder block that has one: llama3, qwen3, deepseek_v3 (and its MTP block), gpt_oss. Blocks without this seam are unchanged: deepseek_v4 (hyper-connections), kimi_k3 and muse_spark (their own residual modules), qwen3_5 and muse_glimmer (custom norms, which would fall back unfused anyway). - Per review, the block always calls the helper, with no `is_local_compile_enabled` branch; the plain-RMSNorm fused path reads `weight`/`eps` directly, so GraphTrainer module tagging of `ffn_norm` will be handled on the GraphTrainer side after this lands. - The region is off by default for every model, so default training numerics and golden losses are unchanged. `rl_grpo_qwen3_0_6b_varlen` enables it on the generator only (the decode path the issue measured); the compiled region is not bitwise-identical to eager, so the trainer keeps its default numerics. 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, so it is left for a separate PR. ### 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
|
@claude review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging -- the shared helper answers @tianyu-l's comments: it covers every model with this seam, has no GraphTrainer branch, and adds no residual argument to RMSNorm. With the region off, the default path is unchanged. The one remaining issue is that the recipe enables the region on the generator only.
What this PR does. It adds residual_rms_norm(residual, delta, norm) in models/common/norm.py. For an exact RMSNorm (checked with type(...) is), the add and F.rms_norm run in one residual_rmsnorm local compile region. That region is off by default and declares batch_invariant=False. Any other norm, such as HigherPrecisionRMSNorm or a subclass, keeps its own forward. llama3, qwen3, deepseek_v3 (plus MTP, and kimi_k2_7 through its block) and gpt_oss use the helper at their x + attn_out -> ffn_norm seam. rl_grpo_qwen3_0_6b_varlen turns the region on for its generator.
Example.
# main
h = x + attn_out
ffn_out = self.feed_forward(self.ffn_norm(h))
# HEAD
h, ffn_input = residual_rms_norm(x, attn_out, self.ffn_norm)
ffn_out = self.feed_forward(ffn_input)
# region off: x + attn_out; F.rms_norm(h, (D,), weight, eps), same bits as main
# region on: one Inductor graph (not bitwise eager)Resolved since the last review
- @tianyu-l "do this for all the model": done. Each block that is left out is explained: deepseek_v4, kimi_k3, muse_spark, qwen3_5 and muse_glimmer have different seams or custom norms.
- @tianyu-l "don't consider graph trainer" / the if-else: the helper is called unconditionally, and @SherlockNoMad will handle tagging on the GraphTrainer side.
- @tianyu-l's concern about adding a
residualarg toRMSNorm: a free helper was used instead, so theRMSNormcontract is unchanged. - No consumer / unsourced 2.9%: the recipe now enables the region, and the number links to #5537 with its full setup.
- The GPU Inductor-vs-eager parity test is gone. The new CPU test for the
type(...) isdispatch guards a real invariant: if it becameisinstance,HigherPrecisionRMSNorm's math would be dropped silently.
Must fix
torchtitan_recipes/rl/alphabet_sort.py:134-- the region is on for the generator only, so trainer and generator numerics diverge. That conflicts withmodels.md("keep trainer and generator numerics consistent"). Enable it on both roles, or post thebit_wise/logprob_diffcost (see inline).
Should consider
- The 2.9% comes from the #5537 author's hand-fusion on ROCm. A decode ms/step for this recipe with the region on vs. off would confirm that this implementation gets the gain on the configuration it enables.
Details
- FSDP wraps whole transformer blocks (
distributed/fsdp.py), so skippingffn_norm.forwarddoes not skip any FSDP hook.norm_sharding_confighas onlyin_src/out_src(no redistribution), so the bypass skips only the boundaryassert_type.feed_forward's input boundary still type-checksffn_input. rl_grpo_qwen3_0_6b_varlen_batch_invariantbuilds its own configs and clearsregions, so thebatch_invariant=Falseregion cannot reach a batch-invariant run.build_rl_model_configscallsbuild_model_configonce per role, andlocal_compileuses adefault_factory, so theappenddoesn't leak into the trainer's list.
Not verified: GPU unit and integration tests were still queued. This PR touches core model code, so a maintainer still needs to review.
| # Decode is launch-latency bound (#5537). Generator only: the fused region is | ||
| # not bitwise-identical to eager, so the trainer keeps its default numerics. | ||
| generator_model.local_compile.regions.append("residual_rmsnorm") |
There was a problem hiding this comment.
This turns the region on for the generator only, so the trainer and generator now run different add+RMSNorm numerics. The comment says that is deliberate. But .claude/rules/models.md ("Training and Inference Share Modules") asks to keep trainer and generator numerics consistent, and every other region in this recipe runs on both roles. The sibling recipes also treat the two roles together: _no_compile and _batch_invariant both loop over (trainer_model, generator_model).
"The trainer keeps its default numerics" doesn't protect anything here. No golden-loss test runs rl_grpo_qwen3_0_6b_varlen (only test_policy_loss_configs.py builds it, on CPU). What the change does affect is bit_wise/logprob_diff, which now grows by a mismatch between compiled and eager norms in every layer.
Smallest fix is to enable the region on both roles:
| # Decode is launch-latency bound (#5537). Generator only: the fused region is | |
| # not bitwise-identical to eager, so the trainer keeps its default numerics. | |
| generator_model.local_compile.regions.append("residual_rmsnorm") | |
| # Decode is launch-latency bound (#5537). Enabled on both roles so the | |
| # trainer and generator run the same add + RMSNorm numerics. | |
| for model_config in (trainer_model, generator_model): | |
| model_config.local_compile.regions.append("residual_rmsnorm") |
If you need generator-only, please post bit_wise/logprob_diff/{mean,max} for this recipe with the generator region on vs. off, so a maintainer can see what it costs.
There was a problem hiding this comment.
instead of only adding it in the recipe, we should update the default local_compile region of all models, e.g.
torchtitan/torchtitan/models/muse_spark/model.py
Lines 523 to 539 in 210381e
| Example: | ||
| x, ffn_input = residual_rms_norm(x, attn_out, self.ffn_norm) | ||
| """ | ||
| if type(norm) is not RMSNorm: |
There was a problem hiding this comment.
I don't see why we need to specialize on RMSNorm. Does other norm not enjoying compile benefits?
| eps: float | None, | ||
| ) -> tuple[torch.Tensor, torch.Tensor]: | ||
| h_TD = residual_TD + delta_TD | ||
| return h_TD, F.rms_norm(h_TD, normalized_shape, weight_D, eps) |
There was a problem hiding this comment.
Do we have to call F.rms_norm, instead of norm(h_TD)?
| # Decode is launch-latency bound (#5537). Generator only: the fused region is | ||
| # not bitwise-identical to eager, so the trainer keeps its default numerics. | ||
| generator_model.local_compile.regions.append("residual_rmsnorm") |
There was a problem hiding this comment.
instead of only adding it in the recipe, we should update the default local_compile region of all models, e.g.
torchtitan/torchtitan/models/muse_spark/model.py
Lines 523 to 539 in 210381e
43b4fdc to
c3f70d0
Compare
…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
…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
c3f70d0 to
fe2e505
Compare
|
@claude review |
There was a problem hiding this comment.
Verdict: Request changes -- the code now does what @tianyu-l asked. But the region is now on by default in training for five model families, and the description claims the goldens won't move when they will. This PR also has no training perf/memory numbers and no decode measurement of its own.
What this PR does. It adds residual_norm(residual, delta, norm) in models/common/norm.py. This is a local_compile region that returns (residual + delta, norm(residual + delta)) and calls the norm module itself. llama3, qwen3, deepseek_v3 (+MTP), gpt_oss and qwen3_5 use it at their x + attn_out -> ffn_norm seam, and each lists "residual_norm" in its default local_compile.regions. So trainer and generator run it compiled by default.
Example.
# main (eager): two kernels
h = x + attn_out
ffn_out = self.feed_forward(self.ffn_norm(h))
# HEAD (compiled by default via BaseModel.parallelize -> local_compile.apply())
h, ffn_input = residual_norm(x, attn_out, self.ffn_norm)
ffn_out = self.feed_forward(ffn_input)
# one Inductor graph: different reduction order, and the norm reads the unrounded sumResolved since the last review
- @tianyu-l, "why specialize on RMSNorm": the
type(...) is RMSNormdispatch is gone, so any norm works. - @tianyu-l, "call
norm(h_TD)instead ofF.rms_norm": done. - @tianyu-l, "update the default regions of all models": done. The generator-only recipe append is gone, which also resolves my earlier trainer/generator mismatch item. The models left out are explained (Kimi K2 TODO, #5931 for Muse Glimmer, no such seam in deepseek_v4/kimi_k3/muse_spark).
Must fix
torchtitan/models/llama3/model.py:86-- the description's numerics paragraph is wrong, because no separate compile switch exists. Every golden-numerics entry runs the region compiled. Regenerate the llama3, llama3_pp, qwen3, deepseek_v3, deepseek_v3_cp_pp, gpt_oss and gpt_oss_pp goldens on all three backends, and explain the change (see inline).- No measurement of this PR. The PR now changes the main training path of five model families (CLAUDE.md principle 6), so please post training TPS and peak memory before/after for at least one recipe, e.g. Qwen3 or Llama 3 8B, with at least 10 steps. The 2.9% decode figure is the #5537 author's ROCm hand-fusion. Please also post decode ms/step with the region on vs. off for the generator recipe that motivates this.
tests/rl/unit_tests/cpu/test_model_defaults.py:82-105-- delete it. It re-reads a config default and testsdefault_factory.tests/unit_tests/cpu/models/common/test_rmsnorm.py:97-176-- deleteTestResidualNorm. With the dispatch gone, it only restates the two-line helper, and the goldens cover the compiled path.
Should consider
torchtitan/models/qwen3_5/model.py:267--OffsetRMSNorm.forwardis itself a region, so this is a compiled region nested inside another compiled region. Confirm the recompile count (see inline).
Not verified: Integration Tests and GPU unit tests were still queued, so I couldn't confirm the golden failures or the Qwen3.5 compile. A maintainer still needs to review, since this touches core model code.
| local_compile: LocalCompileConfig = field( | ||
| default_factory=lambda: LocalCompileConfig( | ||
| regions=["loss", "fused_binary_activation", "rope"] | ||
| regions=["loss", "fused_binary_activation", "rope", "residual_norm"] |
There was a problem hiding this comment.
The description says "CI runs with compilation off, so golden losses are not expected to change". That isn't true. No separate compile switch exists: BaseModel.parallelize always calls local_compile.apply() (models/base/model.py:167), and that compiles every region listed here. The only configs that clear the list are the ones that turn on SPMD typechecking (torchtitan_recipes/tests/__init__.py:30).
The golden-numerics entries in tests/integration_tests/models.py never call _set_spmd_typechecking(..., typechecking=True), so residual_norm now runs compiled in all of them. That covers llama3_fsdp+tp+cp (+region_ac), llama3_fsdp+tp+pp, qwen3_moe_fsdp+tp+cp+ep_param_groups, deepseek_v3_fsdp+ep, deepseek_v3_fsdp+cp+pp+ep, gpt_oss_fsdp+tp+ep and gpt_oss_pp+fsdp+cp+ep+sacop. The description itself says the compiled region "differs from step 1" on A100. So these goldens should change on every backend.
Please fix the numerics paragraph and regenerate the affected llama3, llama3_pp, qwen3, deepseek_v3, deepseek_v3_cp_pp, gpt_oss and gpt_oss_pp files under real_pg/a10g, real_pg/mi350x and fake_pg/a10g in this PR. Don't leave that to whatever CI produces. Also check sft.txt if its model is one of these. Unverified: Integration Tests were still queued.
| @pytest.mark.parametrize( | ||
| "builder", (build_qwen3_model_config, build_deepseek_v3_model_config) | ||
| ) | ||
| def test_residual_compile_defaults_are_isolated_between_rl_roles(builder) -> None: | ||
| trainer, generator = build_rl_model_configs( | ||
| builder, | ||
| "debugmodel", | ||
| trainer_parallelism=ParallelismConfig(), | ||
| generator_parallelism=InferenceParallelismConfig(), | ||
| ) | ||
| assert trainer.local_compile.regions.count("residual_norm") == 1 | ||
| assert generator.local_compile.regions.count("residual_norm") == 1 | ||
|
|
||
| generator.local_compile.regions.clear() | ||
|
|
||
| assert "residual_norm" in trainer.local_compile.regions | ||
| fresh_trainer, fresh_generator = build_rl_model_configs( | ||
| builder, | ||
| "debugmodel", | ||
| trainer_parallelism=ParallelismConfig(), | ||
| generator_parallelism=InferenceParallelismConfig(), | ||
| ) | ||
| assert "residual_norm" in fresh_trainer.local_compile.regions | ||
| assert "residual_norm" in fresh_generator.local_compile.regions |
There was a problem hiding this comment.
I'd delete this test. It was written for the earlier version, where the recipe appended to the generator's list. This version doesn't mutate any list. What remains re-reads the default that was just set (count("residual_norm") == 1) and checks that field(default_factory=...) hands each instance its own list. That is dataclass behavior, and build_rl_model_configs calls the builder once per role anyway. .claude/rules/tests.md says not to add tests that re-read a config.
| class _DoubledRMSNorm(RMSNorm): | ||
| def forward(self, input: torch.Tensor) -> torch.Tensor: | ||
| return 2 * super().forward(input) | ||
|
|
||
|
|
||
| class TestResidualNorm(unittest.TestCase): |
There was a problem hiding this comment.
I'd delete _DoubledRMSNorm and TestResidualNorm. Now that the helper is just h = r + d; return h, norm(h), none of the three tests guards anything that could break silently:
test_disabled_region_matches_moduleandtest_norm_subclass_keeps_its_forwardboth restate the two-line body in eager mode. With notype(...) isdispatch left, the subclass case is no longer a separate code path.test_enabled_region_compiles_custom_module_and_backwardchecks that Dynamo can trace a module call withfullgraph=Truethrough an eager backend. If that broke, thefullgraphregion would raise, which is a loud failure. The golden-loss integration tests already run this region compiled with real Inductor for five model families.
| x_TD = x_TD + h_TD | ||
|
|
||
| h_TD = self.ffn_norm(x_TD) | ||
| x_TD, h_TD = residual_norm(x_TD, h_TD, self.ffn_norm) |
There was a problem hiding this comment.
Here ffn_norm is OffsetRMSNorm, and its forward is already its own offset_rmsnorm region (line 84, recompile_limit=16), which is on by default. So residual_norm now traces a compiled function from inside another compiled region. Each norm class also adds its own graphs, all counted against residual_norm's default limit of 8. Unverified: please confirm the Qwen3.5 integration tests compile this as one graph with no recompile-limit error. If they do, add a short comment on the graph count, as the other regions have.
tianyu-l
left a comment
There was a problem hiding this comment.
torchtitan/models/llama3/model.py:86 -- the description's numerics paragraph is wrong, because no separate compile switch exists. Every golden-numerics entry runs the region compiled. Regenerate the llama3, llama3_pp, qwen3, deepseek_v3, deepseek_v3_cp_pp, gpt_oss and gpt_oss_pp goldens on all three backends, and explain the change (see inline).
sorry, what I said was wrong. I checked that today we only turn off compile in configs when spmd_typechecking is on https://github.com/pytorch/torchtitan/blob/main/torchtitan_recipes/tests/__init__.py#L30, so the CI could have configs with compile on.
I'll trigger CI, please wait until it finishes and update the golden numerics according to the CI results.
Also, please fix the latest comments from claude and me. Thanks!
| @local_compile("residual_norm", batch_invariant=False) | ||
| def residual_norm( |
There was a problem hiding this comment.
| @local_compile("residual_norm", batch_invariant=False) | |
| def residual_norm( | |
| @local_compile("residual_sum_and_norm", batch_invariant=False) | |
| def residual_sum_and_norm( |
to be precise
…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
fe2e505 to
a336ede
Compare
…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
a336ede to
14d9c37
Compare
|
@claude review |
|
Claude finished @tianyu-l's task in 2m 9s —— View job Approve -- please address the items below before merging: regenerate the non-PP |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- the code now does what @tianyu-l asked and the description explains the numerics. What's left: goldens that the next main push will check but this PR doesn't update, a TODO for the private donated_buffer workaround, and one training perf/memory run.
What changed since the last review. The region is renamed to residual_sum_and_norm, as @tianyu-l suggested. Both low-value tests are deleted (test_model_defaults.py and TestResidualNorm). The description's numerics paragraph is corrected. Seven golden files are regenerated from fake-PG CI. build_pipeline now sets torch._functorch.config.donated_buffer = False for split-backward (zero-bubble) schedules.
Example.
# main: two kernels
h = x + attn_out
ffn_out = self.feed_forward(self.ffn_norm(h))
# HEAD: one compiled region by default; ZB schedules also turn off donated buffers process-wide
h, ffn_input = residual_sum_and_norm(x, attn_out, self.ffn_norm)
ffn_out = self.feed_forward(ffn_input)Resolved
- The numerics paragraph is accurate now, and the fake-PG plus PP goldens are regenerated.
test_model_defaults.pyandTestResidualNormare deleted.- @tianyu-l's rename to
residual_sum_and_normis done.
Must fix
- The remaining goldens will fail on
main.llama3,deepseek_v3,qwen3andgpt_ossreadtests/assets/losses/{execution_mode}/{gpu_arch}/*.txt(tests/integration_tests/models.py:657,699,751,794). Amainpush runs the full real-PG suite on A10G (integration_test.yaml,set-matrix-real-pg) and on MI350X (integration_test_rocm.yaml). So the four non-PPreal_pg/a10gfiles, and all seven affectedreal_pg/mi350xfiles, will mismatch right after merge. Before merging, a maintainer should pushciflow/real-pgandciflow/rocmtags (or runworkflow_dispatchwithexport_results), and the PR should regenerate those files from that output. "No PR CI job runs them" means the PR has to opt in to those jobs. It doesn't make it safe to skip the files. torchtitan/distributed/pipeline_parallel.py:172-- add aTODOwith an upstream issue link for the private, process-widedonated_bufferworkaround (see inline).- Training perf/memory (still open). This makes a compiled region the default on the main training path for five model families, and the only number given is the #5537 ROCm decode hand-fusion. Please post TPS and peak memory with the region on vs. off for one recipe (e.g. Llama 3 8B or Qwen3, 10+ steps). That doesn't need another review unless it shows a regression.
Should consider
torchtitan/models/qwen3_5/model.py:267(still open from the last review) --OffsetRMSNorm.forwardis its ownoffset_rmsnormregion, so it now gets traced insideresidual_sum_and_norm. The Qwen3.5 PP integration test should show whether that compiles cleanly under the defaultrecompile_limit.
Not verified: Integration Tests and GPU Unit Tests (including the ZBV/InterleavedZeroBubble feature tests that exercise the donated_buffer change) were still queued at HEAD. A maintainer still needs to review, because this touches core model and PP code.
| # The input-gradient pass keeps the graph (retain_graph=True) for the | ||
| # weight-gradient pass, which a compiled backward with donated buffers | ||
| # rejects. Regions compile on their first call, after this point. | ||
| functorch_config.donated_buffer = False # pyrefly: ignore [bad-assignment] |
There was a problem hiding this comment.
This works around a PyTorch gap: the PP split-backward stages call autograd.grad(..., retain_graph=True), and an AOTAutograd backward with donated buffers rejects that. The fix sets a private, process-wide flag (torch._functorch.config). It isn't scoped to this model: once set, every compiled backward in the process stops donating saved buffers, including full-model compile. For ZB runs that may raise peak memory a little.
CLAUDE.md principle 3 asks for a TODO with an upstream issue link whenever we work around an upstream gap or touch a private API. Please file the issue (pytorch/pytorch, PP + donated buffers) and link it here:
| # The input-gradient pass keeps the graph (retain_graph=True) for the | |
| # weight-gradient pass, which a compiled backward with donated buffers | |
| # rejects. Regions compile on their first call, after this point. | |
| functorch_config.donated_buffer = False # pyrefly: ignore [bad-assignment] | |
| # The input-gradient pass keeps the graph (retain_graph=True) for the | |
| # weight-gradient pass, which a compiled backward with donated buffers | |
| # rejects. Regions compile on their first call, after this point. | |
| # TODO(<pytorch/pytorch issue>): drop once split-backward PP stages work | |
| # with donated buffers. | |
| functorch_config.donated_buffer = False # pyrefly: ignore [bad-assignment] |
There was a problem hiding this comment.
Here's suggestion from @sanketpurandare. Please update the comment:
- Rope, Swiglu and loss don’t error because they don’t participate in dW but rms norm does. It’s intermediate tensor is required in dW compute.
- The donated
buffers = Falseis okay for this case. But note that this is a workaround and not a proper fix because we are running the compiled node twice here once for di and another time for dw repeating the computation because torch.compile won’t partition the di/dw graph for you. This is okay in the rms norm case for composability and unblocking but its not a good long term fix. It negates the whole point of di/dw split in general. - This RFC is the best way of solving compile composability with di/dw since it targets the root cause [RFC] Input/weight backward split for torch.compile'd regions (zero-bubble schedules and DualPipeV) pytorch#202127
There was a problem hiding this comment.
I don't think the comments all included. Could you include all 3 points I've noted?
| # The input-gradient pass keeps the graph (retain_graph=True) for the | ||
| # weight-gradient pass, which a compiled backward with donated buffers | ||
| # rejects. Regions compile on their first call, after this point. | ||
| functorch_config.donated_buffer = False # pyrefly: ignore [bad-assignment] |
There was a problem hiding this comment.
I don't think the comments all included. Could you include all 3 points I've noted?
…er override; agent self-review; rl/transport (#6407) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it approved, 30 then got a formal "request changes" from a maintainer, and about 20 more got substantive inline asks. In nearly all of them the bot either saw the problem and approved anyway, or never asked the questions maintainers ask most ("does the repo already do this?", "who should own this?"). The opposite failure, the bot blocking something a maintainer was fine with, is rare: in the PRs we sampled, 2 of its 81 must-fix items were wrong and about a third were minor (the empty human-written summary was the biggest source). **Example** (#6112, controller sizes the rollout worker pool): ``` before: bot approved 10 times; tianyu-l then blocked: "the controller reads rollouter.rollouts_per_worker to compute a count it hands back to the Rollouter -- violates encapsulation" after: same commit, new skill -> Request changes, must-fix #1: "controller.py:589 -- wrong owner for the worker count ..." ``` There was also no way for a code owner to overrule the bot except dismissing its review in the GitHub UI, and a later `@claude review again` would block again. ## What changed **Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`): - Verdict rules: Approve only when every remaining item is an edit the bot could write itself. Anything the author still owes (a design change, an unexplained golden change, evidence the PR rests on) is Request changes; anything only a maintainer can decide is Needs discussion. A hedge like "a maintainer should decide" can't come with Approve. - Always must-fix: a violated written rule, a silent wrong result, a second definition of an existing concept, a gate finding. - Design gate: new questions for the existing counterpart, in-repo ownership, and the design behind a bug; "ban only what doesn't work on main"; read the numbers behind a claim. The overlapping-PR search is mandatory and reported. - Re-review covers every commit since the last full review, including code taken from the bot's own suggestions. A scoped question gets a `COMMENT`, not a whole-PR verdict. - The bot fact-checks its own proposed fixes, and cites a source for claims about external tools or marks them unverified (never must-fix). - An empty "Summary (human-written)" is a one-line "Before merge" note that never affects the verdict. - Checklist: config ownership direction, general shared wrappers, dead code the PR creates, model variants as flavors, a mechanical pass over every new or changed function. **Code owner override** (`SKILL.md`, `claude-code.yml`, `CONTRIBUTING.md`): a code owner comments `@claude override` (optionally `@claude override 2,3: <reason>`); the bot approves if nothing else is open and doesn't re-raise the overridden items. A code owner's GitHub approval or "LGTM" is not an override, so a teammate can approve without the bot dropping its findings. Dismissing the bot's review still unblocks the PR, but isn't an override: the bot can't tell who dismissed it. **Agent self-review** (`CLAUDE.md`, `pr-description`): an agent preparing a PR runs `pr-review` in branch mode first and records unaddressed items in an optional "Self-review" section. PRs written without an agent are unaffected; a missing section is never a finding. Where each new rule comes from (maintainer asks the bot missed): | Change | PRs | | --- | --- | | No Approve with open design/evidence items or a "maintainer should decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 | | Author waiver can't clear a must-fix | #6201, #6202, #6203 | | Existing counterpart; one source of truth | #5228, #6169, #5881, #5823, #5824, #6059, #5812 | | Responsibility owner; config ownership direction | #6112, #6332, #5802, #5803, #6325 | | Fix the design behind the bug; a TODO doesn't justify a workaround | #5572, #5689, #5657 | | Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819, #5543 | | Re-review covers all new commits; scoped asks don't approve | #5824, #5842 | | Mandatory overlap search | #5885, #6248 | | Ban only what doesn't work on main | #5543 | | Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868 | **Rules**: `design.md` gets the one-general-wrapper rule (moved from `models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the consumer owning its values; `config.md` gets ownership direction and "a Config doesn't read runtime state"; `direction.md` calls all-to-all the MoE reference implementation, so a new vendor-specific dispatch path (e.g. #6242) needs a reason the existing backends can't serve. **Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/` -> d4l3k. **Mechanical, skim**: `torchtitan/rl/transport/` holds data movement between RL actors. - `rl/model_state_dict_transport.py` -> `rl/transport/model_state_dict.py` - `rl/MODEL_STATE_DICT_TRANSPORT.md` -> `rl/transport/MODEL_STATE_DICT_TRANSPORT.md` - `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py` - tests: `tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py` -> `tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py` - imports, READMEs and `scripts/install_rl_env.sh` updated; no code changes. ## User-facing changes | Before | After | | --- | --- | | Overrule the bot: dismiss its review in the UI, and it blocks again on the next run | `@claude override [items]: <reason>`; the bot approves and doesn't re-raise them | | Empty human-written summary: bot must-fix | One "Before merge" line, no effect on the verdict | | `from torchtitan.rl.model_state_dict_transport import ...` | `from torchtitan.rl.transport.model_state_dict import ...` | | `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from torchtitan.rl.transport.rdma_microbatch import ...` | ## Testing Backtest: the new skill run locally (nothing posted) on each PR at the commit and thread state the bot originally saw. | PR | Bot then | New skill | What the maintainer asked | | --- | --- | --- | --- | | #6112 | Approve | Request changes | worker-count ownership (caught) | | #5837 | Approve | Request changes | apply to `dp_shard` too (caught) | | #5572 | Approve | Request changes | delete the injection design (caught) | | #6201 | Approve after author waived pins | Request changes, waiver ignored | pins broke GPU tests after merge (caught) | | #6007 | Approve | Request changes | fold K3.1 into K3 (caught) | | #5543 | Request changes: "ban it" | Request changes: keep main's path | don't break gpt-oss + DeepEP (fixed) | | #6144, #5905 (controls) | Approve | Approve | -- | | #6137 (control) | Approve | Needs discussion | -- (merge gate on an upstream API) | Code owner override, simulated on #6201: override by a code owner lifts the named item; `@claude override` from the author changes nothing; a code owner's "LGTM" approval followed by "review again" keeps Request changes. Transport move: 83 RL CPU unit tests pass locally (`transport/test_model_state_dict.py`, `test_trainer.py`, `test_engine_loop.py`). `transport/test_rdma_microbatch.py`, `test_generator.py` and `test_batcher_actor.py` fail to collect in my env on `origin/main` too (stale attention-gym / Monarch), so CI is the check for those. ## Known issues / follow-ups - Open PRs that edit the moved files rebase cleanly (git follows the renames), but new imports of the old module paths will break: #6309 (adds a delta transport that should live in `rl/transport/`), #6237, #6176, #6177, #5862, and drafts #6127, #6393, #6163, #5764. - The Actions bot can't read dependency source (e.g. SGLang); follow-up for the workflow. ## Self-review pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch mode diffs against `origin/main` and skips description findings before a description exists; the "Config doesn't read runtime state" rule no longer contradicts hardware validation; dismissal dropped as an override form (the bot can't tell who dismissed); `test_rdma_microbatch.py` added to the transport area. Not addressed: - One concern per PR -- the five changes ship together at the maintainer's request. - Open PRs touching the moved files -- listed above; the maintainer will coordinate.
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 #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:
residual_sum_and_norm(residual, delta, norm)inmodels/common/norm.py, aresidual_sum_and_normlocal 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 ashigher_precision_rms_norm) keeps its own math and the shared norm contract is unchanged.x + attn_out -> ffn_normseam 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 [muse_glimmer] Compile the residual sites and the attention output gate #5931, which already covers its residual sites.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 RMSNormrsqrtmakes this region the first default one in these models to hit it.build_pipelinenow setstorch._functorch.config.donated_buffer = Falsenext to the existing in-place WGRAD-accumulation opt-out when the schedule splits backward.residual_sum_and_normin the defaultlocal_compile.regionsof 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 inkimi_k2_7/model.py.Numerics:
These models now run the region compiled by default.
BaseModel.parallelizealways applieslocal_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 runsresidual + deltathennorm(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.txtreal_pg/a10g:llama3_pp.txt,deepseek_v3_cp_pp.txt,gpt_oss_pp.txtNot regenerated, because no PR CI job runs them: the non-PP
real_pg/a10gfiles and everyreal_pg/mi350xfile.Follow-up: fusing block i's trailing
x + ffn_outwith block i+1'sattention_normneeds a decoder-loop change and interacts with theffn_residualremat 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