Repository navigation
[gpt_oss][perf] Add expert biases with a gather and a one-hot GEMM backward - #5192
felipemello1 wants to merge 11 commits into
Conversation
02806ed to
ad29313
Compare
ad29313 to
917b7a0
Compare
917b7a0 to
048b3db
Compare
048b3db to
37bea9f
Compare
GPT-OSS's grouped expert bias was expanded per row with repeat_interleave and added in eager; its backward scatter-added every row into the expert bias (sort/TMA scatter, bf16 accumulation). Gather each row's bias instead and sum the bias gradient with a one-hot [E + 1, R] GEMM (deterministic, fp32 accumulation). Faster in eager too; the grouped_expert_bias region fuses the gather into the add. The bias_add remat region keeps its policy. With DeepEP (scores_R), the compiled region adds the score-scaled bias in fp32 and rounds once, so that path is not bitwise vs main; the stock dispatchers stay bitwise.
_GatherGroupedBias is a per-rank gather with a per-rank GEMM backward, so it gets the local rule (as HiMidLoLinear). Without it, the first GPT-OSS forward under debug.spmd_typechecking raises SpmdTypeError. The new SPMD test fails without the decorator. The grouped-bias test moves into test_gpt_oss_moe.py and clones one set of inputs per arm.
…atic, TODO wording The recompile_limit comment now gives the probed counts (4 graphs in grad mode, 6 with no_grad, 14 at most with 0- and 1-row EP ranks). mark_static is called unconditionally, as in fused_binary_activation. The TODO on fusing w13's bias into the activation says why a plain merge does not pay in training.
README and ROUTER_SCORE_ABSORPTION.md (Precision): with grouped_expert_bias compiled, the DeepEP score-scaled W2 bias is added in FP32 and rounded once (main rounds it, then the sum). Not bitwise vs main on that path; the stock dispatchers pass no scores and stay bitwise. ROUTER_SCORE_ABSORPTION.md points at add_grouped_bias instead of the deleted _expand_grouped_bias.
37bea9f to
978933c
Compare
|
Reply from claude: @claude review |
|
Claude finished @felipemello1's task in 2m 20s —— View job Request changes: the regenerated GPT-OSS golden loss files are not in the diff, and the human-written summary is empty. Review |
There was a problem hiding this comment.
Verdict: Request changes -- the bias grads change on purpose, but the golden loss files the description says were regenerated are not in the diff, so the exact-numerics GPT-OSS integration tests can't match at HEAD.
What this PR does. In GPT-OSS, each routed row now gets its expert's bias by index (searchsorted on offsets_E, then a gather) instead of repeat_interleave. A custom autograd Function, _GatherGroupedBias, computes the bias grad as one GEMM, one_hot[E+1, R] @ grad[R, O]. That GEMM accumulates in fp32, where the old backward was a bf16 scatter-add. The whole add is a new grouped_expert_bias local-compile region, enabled by default in GptOssModel.Config. Forward outputs stay bitwise on the stock dispatchers. Bias grads change.
Example. offsets_E = [2, 2, 5], 7 rows (rows 5-6 are padding):
expert_ids_R = searchsorted([2,2,5], [0..6], right=True) = [0,0,2,2,2,3,3]
forward: out[r] += padded_bias[expert_ids_R[r]] (row 3 of padded_bias is zeros)
backward: grad_bias[e] = sum over rows with expert e of grad_out[r]
main: bf16 scatter-add over R rows
PR: one_hot[4, 7] @ grad_out[7, O], fp32 accumulation, then rows [:3]
Must fix
- Goldens not in the diff. The description says the 5 GPT-OSS goldens were regenerated, but none of them is in the diff:
tests/assets/losses/{fake_pg/a10g/gpt_oss.txt, real_pg/a10g/gpt_oss.txt, real_pg/a10g/gpt_oss_pp.txt, real_pg/mi350x/gpt_oss.txt, real_pg/mi350x/gpt_oss_pp.txt}.tests/integration_tests/models.py:803and:811compare against them exactly, and the bias grads change, so those entries should fail. Commit the regenerated files, and in the description say how much loss and grad_norm moved (they should move only slightly, since only the bias-grad accumulation changes). - Empty human summary. The "Summary (human-written)" section is empty. Per
CONTRIBUTING.md/CLAUDE.md, the author fills it in.
Should consider
torchtitan/models/gpt_oss/moe.py:87-- foldscores_Rinto_GatherGroupedBias. That removes the eager+DeepEP[R, O]retention (about 94 MB per layer, per the description) and the eager/compiled rounding split. See the inline comment.
Details
Gate.
- The problem is real on
main: a slow, bf16-accumulated scatter-add in the bias backward. The fix sits in the GPT-OSS model folder, which owns the per-expert bias, and does not touch core. - The perf gain is measured end to end on a 2-layer harness: -6.6% fwd+bwd with CUDA graphs, fewer kernel launches without.
- The precision gain is measured: 4.2e-2 -> 1.7e-3 rel L2 against fp64.
- The design is not one-sided: trainer and generator share the same region.
- The
mark_staticinside the region andrecompile_limit=16follow the existing pattern inmodels/common/activation.py.
Correctness checked.
searchsorted(right=True)maps empty experts and padding rows correctly: padding rows get idE, which indexes the appended zero row and is sliced off in backward.- The backward returns the grad in the bias's compute dtype.
- The remat
bias_addregion keeps thegrouped_mmpolicy.
One-hot GEMM cost. It scales with the local expert count: (E+1) * R * O. At 16 local experts it is negligible. For 120b at EP=1 (128 experts) it is still about 4% of the w13 grouped GEMM's FLOPs (E / I = 128 / 2880), so no concern. It was not measured.
Tests. The fp64 CPU test against the repeat_interleave reference guards the custom backward, which would otherwise be wrong without any error. It is worth its cost. The 2-rank CPU SPMD test guards the register_local_autograd_function registration.
Not verified: GPU numbers, golden deltas, and the TP=2, multi-GPU EP and GPU DeepEP paths (I can't run GPU tests here; there were no CI results yet).
…path With regions off, autograd saves the gathered [R, O] bias for the score grad; the compiled region saves only the [E + 1, O] bias. Kept that way: only eager pays, and folding the score into _GatherGroupedBias would give it an fp32 GEMM backward and a second mode.
Fixes two crashes in the GPT-OSS PP integration jobs: - gpt_oss_pp+fsdp+cp+ep+sacop raised CheckpointError. Microbatch B's forward compiled a dynamic-rows graph before microbatch A's backward replayed the region. The replay ran B's graph, which saves a bf16 one-hot where A's static graph saved a bool mask. Rows are now marked dynamic before the region, so every row count >= 2 runs one graph. - gpt_oss_pp+fsdp+ep+sacop raised in Dynamo on the bias input. FSDP2 keeps an fp32 .grad on the bf16 unsharded bias between microbatches, and fake-tensor conversion copies .grad before grad_dtype. The region now gets a copy of the bias (one [E, O] copy per projection per forward). test_grouped_bias_region_in_pipeline_order fails without either change. Graphs per process drop to 6 per grad mode, 12 with both modes.
fake_pg/a10g, real_pg/a10g and real_pg/mi350x gpt_oss.txt, from this PR's CI run (gpt_oss_fsdp+tp+ep mismatch reports). Step-1 loss is unchanged; grad norms move from step 1, e.g. a10g real_pg 46.2483 -> 46.2560.
…lation real_pg/a10g and real_pg/mi350x gpt_oss_pp.txt, from this PR's CI run (gpt_oss_pp+fsdp+cp+ep+sacop mismatch reports). Step-1 loss is unchanged; the step-1 grad norm moves 42.1434 -> 42.1665 on a10g.
|
Reply from claude: @claude review |
|
Claude finished @felipemello1's task in 1m 57s —— View job Approve (please address the listed items before merging): the goldens are now regenerated, and what's left is the human-written summary and a few small edits. Review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- the regenerated goldens are now in the diff with explained deltas, and the new PP fix (dynamic rows plus a bias copy) is local to GPT-OSS and covered by a CPU test. What's left is the human summary and a few small edits.
What changed since the last review. Commit 1925a55 marks the routed-row dim dynamic before the grouped_expert_bias region and passes self.bias.flatten(1).clone() into it. Together these fix two crashes: a CheckpointError when microbatch B's dynamic graph is replayed for A's backward, and a Dynamo error on FSDP2's fp32 .grad under PP. It also adds test_grouped_bias_region_in_pipeline_order. Commits 110bce9 and 2811945 regenerate the 5 GPT-OSS goldens.
Example (PP order the fix targets).
fwd A (64 rows) -> compiles static-64 graph, saves bool mask
fwd B (32 rows) -> recompiles dynamic-rows graph, saves bf16 one-hot
bwd A (recompute)-> dispatches to dynamic graph -> saved tensors differ -> CheckpointError
with this PR: rows dynamic from call 1 -> one graph for both -> same saved tensors
Earlier findings
- Goldens not in the diff: resolved. All 5 files are updated. Step-1 loss is unchanged everywhere (the forward is bitwise), step-1 grad_norm moves by about 1e-4 relative, and step-10 loss stays within 0.22%, which matches the description.
- Fold
scores_Rinto_GatherGroupedBias: accepted. The author's reply holds: only eager with DeepEP pays, and the cost is now documented atmoe.py:416.
Must fix
- The human-written summary is still empty (still open). The author has to write it; agents don't.
torchtitan/models/gpt_oss/moe.py:61-- the bias-copy TODO needs an upstream issue link (inline comment).
Should consider
torchtitan/models/gpt_oss/moe.py:50-- also markscores_R's row dim dynamic, or the DeepEP + PP path may hit the same CheckpointError (inline comment, unverified).- Re-time at HEAD. The headline GPU numbers (-6.6% fwd+bwd, -12% decode) predate dynamic rows and the clone. Dynamic-shape Inductor kernels and the extra clone kernel could eat into the gain, especially in decode. One re-run of the fwd+bwd 4096 and decode 64 rows would confirm the claim the PR rests on.
Questions
- The
CheckpointErrorcomes from alocal_compileregion recompiling between a checkpointed forward and its recompute, which isn't specific to this region. Doesfused_binary_activation, which also sees varying routed rows under PP, avoid it only because its static and dynamic graphs happen to save the same tensors? If so, a follow-up could mark the dynamic dims inlocal_compileorrematinstead of in each caller.
Details
- The
is_compiling()guard aroundmaybe_mark_dynamicis right: with an outer compile (GraphTrainer), the region is inlined and the mark can't be traced. flatten(1)on the 2-D output returns the same tensor, so the dynamic mark lands on the temporary GEMM output only, with no effect on other consumers.- The new test exercises both failure modes it names: the fp32
.gradwithgrad_dtypeset, and forward A, forward B, then backward A undercheckpoint. It's cheap (CPU, tiny shapes) and guards a crash that existing tests didn't catch. - The recompile-limit comment now matches the graph count (3 per width x 2 grad modes = 12 <= 16).
Not verified: GPU timings at HEAD, the DeepEP + PP dynamic-shape behavior (I couldn't run tests here).
On the DeepEP path, scores_R has the routed rows too. Left static, it makes the region's first graph specialize to static rows, and the next row count compiles a second graph: the PP replay problem the row mark prevents. CPU, PP order (4096 then 2048 rows, then the first backward): 2 graphs -> 1.
|
Reply from claude: the round-2 items are in.
Reply from claude: @claude review |
|
Claude finished @felipemello1's task in 42s —— View job Approve (two small items left before merging: write the human summary, and replace the personal-fork issue link in the TODO with a pytorch/pytorch issue): Review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- the round-2 code items are fixed at HEAD and the re-timed numbers hold up. Two small edits are left before merge: the human-written summary and the upstream issue link.
What changed since the last review.
ae82faemarksscores_R's rows dynamic along with the routed output (moe.py:52-53).b9e2116adds an issue reference to the bias-copy TODO (moe.py:64-65).- The description's timing table was re-run at HEAD. It still shows -6.8% for fwd+bwd 4096 and -10.2% for decode 64, and kernels drop from 648 to 570. So dynamic rows and the clone did not eat the gain.
Example (DeepEP + PP, the case ae82fae fixes).
before: fwd A (4096 rows): output marked dynamic, scores_R static
-> the broadcast guards s0 == 4096, so graph 1 specializes to static rows
fwd B (2048 rows) -> graph 2 (dynamic)
after: both inputs marked -> one dynamic graph for A and B (author's CPU probe: 2 graphs -> 1)
Earlier findings
- Mark
scores_Rdynamic: resolved (moe.py:52). The author checked that this path did not raise before the fix, because both graphs save the same tensor shapes. So adding ascores_Rcase to the pipeline-order test would not catch a regression, and leaving the test as is is right. - Re-time at HEAD: resolved. The body table is updated.
- Question about
fused_binary_activation: answered. Its static-rows and dynamic-rows graphs save the same tensors. Only this region's graphs differ: one saves a bool mask, the other a bf16 one-hot. Moving the dynamic mark intolocal_compileis a fair follow-up and not needed here.
Must fix
- The human-written summary is still empty (still open). The author has to write it; agents don't.
torchtitan/models/gpt_oss/moe.py:65-- the TODO links tofelipemello1/pytorch#23, an issue draft in a personal fork. A later reader can't use that to tell when the clone can go, and the draft may be deleted. File the issue inpytorch/pytorchand put that link in the TODO before merging.
Details
moe.py:77-79: the recompile-limit comment still matches after thescores_Rmark. The mark doesn't add graphs; it merges the DeepEP static and dynamic graphs into one.- The
scores_Rmark sits inside the sameis_compiling()guard, so it stays correct when GraphTrainer compiles the caller. maybe_mark_dynamiconscores_Rchanges only Dynamo's guard metadata on that tensor; nothing else reads it differently.
Not verified: GPU timings and the GPU DeepEP + PP path (I couldn't run GPU tests here).
Summary (human-written)
Agent details
TLDR: GPT-OSS's per-expert bias grad becomes one GEMM with fp32 accumulation instead of a bf16 scatter-add. Per layer at 4096 tokens it drops from 168 to 65 us, and it is 25x closer to fp64. 2 GPT-OSS-20b layers, fwd+bwd 4096 tokens, CUDA graphs: -6.8%. The GPT-OSS RL recipe runs without CUDA graphs, so today it gets fewer kernel launches (harness: 648 -> 570 kernels per 2-layer step).
Problem
repeat_interleavecopies the bias out to all R rows, then adds it.Solution
add_grouped_bias)._GatherGroupedBiassums each expert's rows asone_hot[E+1, R] @ grad[R, O], accumulated in fp32, in a fixed order.grouped_expert_biasfuses the gather into the add. It is on inGptOssModel.Config.bias.clone(). Under PP, FSDP2 leaves an fp32.gradon the bf16 bias between microbatches, and Dynamo raises on such a parameter input (PyTorch bug, TODO inmoe.py).bias_addremat region keeps its policy.Results
You may ask:
torch.compile? Inductor lowers the gathered bias's backward to an atomicindex_add: 128 us for w13 alone at 4096 tokens, vs 44 us here, and float atomics are not deterministic.index_put(a sort + scatter), the slow path this PR removes.one_hot @ biasin forward (autograd would then give the GEMM backward)? The forward would be a GEMM plus a separate add, not one fused gather-add.fused_binary_activation? In no_grad that is one kernel instead of two (106 -> 56 us per layer at 16384 rows). In training it only pays if SwiGLU's backward recomputes the bias add, and then SwiGLU reads the unrounded fp32 sum: not bitwise. The next PR in this stack does it.NOTE:
cuda_graphmode NONE. Without graphs this harness's fwd+bwd 4096 wall is ~3x its GPU time, so there the kernel-launch cut is what helps. The CUDA-graph rows apply once those graphs are on.gpt_oss_fsdp+tp+epandgpt_oss_pp+fsdp+cp+ep+sacopcompare exact losses and grad norms to golden files, and the bias grads change. The 5 GPT-OSS goldens (fake_pg/a10g/gpt_oss.txt,real_pg/a10g/gpt_oss.txt,real_pg/a10g/gpt_oss_pp.txt,real_pg/mi350x/gpt_oss.txt,real_pg/mi350x/gpt_oss_pp.txt) are regenerated from this PR's CI run. How muchgpt_oss.txtmoves over its 10 steps: step-1 loss is unchanged (forward bitwise). Step-1 grad norm moves +1.7e-4 relative on real_pg a10g and mi350x, +6e-6 on fake_pg. Step-10 loss stays within 0.22% on all three.gpt_oss_pp.txt(a10g, mi350x): step-1 loss unchanged, step-1 grad norm +5.5e-4, step-10 loss within 0.08%.gpt_oss_pp+fsdp+cp+ep+sacop, microbatch B's forward compiles a dynamic-rows graph before microbatch A's backward replays the region. That graph saves a bf16 one-hot where A's graph saved a bool mask, so checkpointing raisesCheckpointError. Ingpt_oss_pp+fsdp+ep+sacop, Dynamo raises on the fp32 bias.grad(step 5).test_grouped_bias_region_in_pipeline_orderfails without either step.scores_R, thebias_addregion keeps the gathered[R, O]bias for the score grad when the remat policy savesgrouped_mm. That is ~94 MB per MoE layer for w2 at 16384 rows (4096 tokens x top-4). Main replayed that multiply instead. The default compiled region keeps nothing extra.scores_R), GraphTrainer, 120b, loss curves.Test plan