Repository navigation
[moe][perf] Gather-sum MoE dispatch and combine, training and inference, any EP (3/4) - #5382
felipemello1 wants to merge 1 commit into
Conversation
268820f to
5b667bf
Compare
5b667bf to
74d97a8
Compare
3bb5e29 to
471c829
Compare
471c829 to
d189fb9
Compare
d189fb9 to
5a92595
Compare
|
Claude finished @felipemello1's task in 4m 54s —— View job Request changes: no loss comparison for a change to Qwen3.5's default training numerics, and the combine has two algorithms with different numerics, picked implicitly by |
There was a problem hiding this comment.
Verdict: Request changes -- This changes the numerics of Qwen3.5's default training path but shows no loss comparison. It also keeps two combine algorithms, which give different numerics, chosen implicitly by torch.compiler.is_compiling().
What this PR does. With the moe_dispatch_combine region compiled, MoE dispatch records each route's row in the expert-sorted order. Combine then gathers each token's top_k rows and sums them in fp32, instead of a bf16 scatter-add. Custom autograd Functions make the backward use gathers too. This applies at EP=1 and around the AllToAll. Eager runs, and TorchAO at EP=1, keep the argsort + scatter-add. Qwen3.5 adds the region to its default list.
Example.
token t, top_k=2, expert rows r_a, r_b (bf16), scores s_a, s_b
eager / region off: out[t] = bf16(bf16(s_a*r_a) + bf16(s_b*r_b)) (scatter-add, index_put backward)
region on: out[t] = bf16(fp32(s_a*r_a) + fp32(s_b*r_b)) (gather-sum, gather backward)
Adding or removing one name from local_compile.regions now changes the loss, not just the speed.
Must fix
- The "Summary (human-written)" section is empty. Per
CONTRIBUTING.md, the author writes it. - No loss evidence. Rows in Qwen3.5's default region list change training numerics, and the PR says "Not run: ... a loss curve".
CLAUDE.mdrequires loss convergence for computation changes. Please add a Qwen3.5 MoE before/after loss and grad_norm comparison (scripts/loss_compare.py, e.g. C4, enough steps to show convergence). Layer-level rel L2 doesn't replace it. torchtitan/models/common/moe/token_dispatcher.py:386-- the eager/compiled algorithm split keyed onis_compiling(). The single-path version is sketched inline, along with what it deletes and what it costs. Maintainers should weigh in on whether eager keeps the scatter-add.
Should consider
torchtitan/models/common/moe/token_dispatcher.py:1090(unchanged line) -- TorchAO at EP=1 still calls_local_reorder+_score_and_scatter_add, but TorchAO at EP>1 now gets the gather-sum throughAllToAllTokenDispatcher._combine. So turning on MX/float8 MoE at EP=1 quietly gives Qwen3.5 different numerics and speed than the same run at EP>1. Calling_sort_and_gatherthere, then_CombineGatherSumafter_unpermute(~10 lines), would make TorchAO EP=1 match and delete_local_reorder, whose only other consumer is a test.tests/unit_tests/cpu/models/common/test_token_dispatcher.py:80-- two eager-vs-eager tests that guard nothing (inline).tests/unit_tests/gpu/models/common/test_token_dispatcher_determinism.py:16-- determinism is guaranteed by construction, andtest_remat_all_to_allalready checks it bitwise (inline).
Questions
- How does this land alongside #5719 (one
score_and_scatter_addop that backends can override)? With this region compiled, the combine skips that op, so an out-of-tree backend kernel (torch-neuronx) is never reached on compiled Qwen3.5 runs, and on any model after stack position 4. Maintainers should pick one combine extension point before both land.
Details
- Gate: the problem is real (the combine and its index_put-accumulate backward are measured hot), the layer is right (shared dispatcher), and it is not one-sided (trainer and generator both use
_gather_weighted_sum). Nothing it depends on is non-PyTorch. - Checked: the forward and backward formulas of
_DispatchGather/_CombineGatherSum(grad_x[t] = sum_k grad[row[t*K+k]], and the score grad is unsorted throughrow_of_route_N). The score grad now reachestopk_scores_TKdirectly, so detaching the sorted scores is safe: no other consumer oftopk_scores_experts_sorted_Nexists (moe.pydoesn't read it). Batch-invariant RL recipes clearlocal_compile.regions(torchtitan_recipes/rl/alphabet_sort.py), so they don't hit thebatch_invariant=FalseValueError. The AllToAll_combinerows are in dispatch's expert-sorted order after the reverse all-to-all. - No golden loss file covers Qwen3.5 MoE (
tests/assets/losses/*only has dense qwen3), so no golden needs regenerating, which is one more reason item 2 needs a manual loss run.
Not verified: GPU timings and memory; behavior of the custom autograd Functions under spmd_typechecking=True at TP x EP.
| expert_ids_N = topk_expert_ids_TK.reshape(-1) | ||
| num_routes = expert_ids_N.numel() | ||
| routes_N = torch.arange(num_routes, device=expert_ids_N.device) | ||
| compiling = torch.compiler.is_compiling() |
There was a problem hiding this comment.
This line picks between two combine algorithms, and they give different numerics. When row_of_route_N is None, both combines fall back to argsort + scatter-add (bf16 rounding per route). Otherwise they take the gather-sum with custom autograd (fp32 sum, one rounding). So adding or removing moe_dispatch_combine from a region list now changes the algorithm and the loss, not just speed. That makes eager stop being a reference for the compiled run, and the same logic splits dispatch/combine (x2)/metadata into None branches. Also, torch.compiler.is_compiling() is true under any dynamo trace, not just this region. An outer torch.compile around the MoE would turn the gather-sum on even with the region off. No in-repo caller does that today: vLLM uses CompilationMode.NONE, and graph_trainer uses make_fx.
Smallest single-path version: always compute row_of_route_N. In eager that is one index_put of the inverse permutation (the code already sits in the argsort branch below). Then always use _DispatchGather and _CombineGatherSum, and keep the pairwise rank as a compile-only shortcut, since it gives the same result. That deletes the None branches, the Optional metadata fields, the .detach() subtlety, _score_and_scatter_add at the Local and AllToAll call sites, and both eager-vs-scatter tests. The cost is eager speed (~3 x top_k small kernels). After stack position 4 that only hits regions-cleared runs (batch-invariant RL) and TorchAO EP=1. design.md says eager fallback paths don't get optimizations. If you keep the split, please put eager timings for those runs in the PR so maintainers can weigh it.
There was a problem hiding this comment.
Reply from claude: we keep both paths. Eager stays bitwise equal to main, so it stays the reference.
Eager timings are now in the body (moe_dispatch_combine off, the other regions on, 2 Qwen3.5-35B-A3B layers, 1 GB300). The one-path version (this PR's gather-sum run as eager ops) vs the eager scatter-add:
- time: -4% to +6% (decode 64 and fwd+bwd 16k, with and without CUDA graphs)
- peak memory at fwd+bwd 16k: 6690 vs 6177 MiB (+8%)
On is_compiling(): an outer torch.compile around the MoE would pick the gather-sum, which is the compiled algorithm anyway. No in-repo caller does that today. Leaving the one-path question to maintainers.
| actual_TD = self._dispatch_combine(x_TD, scores_TK, ids_TK, E) | ||
| torch.testing.assert_close(actual_TD, expected_TD, rtol=0, atol=0) | ||
|
|
||
| def test_eager_no_grad_combine_matches_the_scatter_path(self): |
There was a problem hiding this comment.
This test and test_eager_training_matches_the_scatter_path (line 227) compare the eager path with itself. Eager no-grad, eager grad and _local_reorder + _score_and_scatter_add all run the same _argsort_expert_ids -> gather -> scatter-add ops, so these tests can only fail if someone edits those ops on purpose. That breaks tests.md ("re-read a config they just set" / duplicate coverage). Please delete both. If eager moves to the gather-sum (see the comment on _sort_routes), they go away anyway.
There was a problem hiding this comment.
Reply from claude: done in a602279. Both eager-vs-scatter tests are gone.
|
|
||
|
|
||
| @unittest.skipUnless(torch.cuda.is_available(), "needs CUDA") | ||
| class TestCompiledTrainingDeterminism(unittest.TestCase): |
There was a problem hiding this comment.
This new GPU file costs a GPU job (T=8192, D=2048) to check something the code already guarantees by construction. The compiled backward is only gathers plus a non-accumulating index_put of a permutation, with no atomics. The new test_compiled_gather_sum_matches_eager in test_remat_all_to_all.py already runs the compiled gather-sum forward+backward several times and checks bitwise equality (_assert_results_equal(compiled, run(save_regions))), at EP=2 with real all-to-alls, which is the harder setup. Please drop this file, or fold its single assertion into that test.
There was a problem hiding this comment.
Reply from claude: done in a602279. The file is gone. test_compiled_gather_sum_matches_eager in test_remat_all_to_all.py still checks the compiled forward and backward bitwise across runs, at EP=2.
|
Reply from claude: round 2 is in a602279.
|
|
Reply from claude: @claude review |
|
Claude finished @felipemello1's task in 2m 57s —— View job Needs discussion: round 1's code items are fixed. The remaining decisions are for maintainers: the eager/compiled combine split, and the extension point to keep alongside #5719. Two things are still for the author: the human-written summary is empty, and the loss-noise baseline rests on an unexplained cross-invocation non-determinism. See the review. |
There was a problem hiding this comment.
Verdict: Needs discussion -- Round 1's code items are fixed. What's left needs maintainers to decide: whether eager keeps a second combine algorithm with different numerics, and which combine extension point to keep alongside #5719. Separately, the noise floor the loss comparison relies on comes from a non-determinism nobody has explained.
What this PR does. With the moe_dispatch_combine region compiled, dispatch also returns each route's row in the expert-sorted order. Combine then gathers each token's top_k rows and sums them in fp32, with gather-only backwards (custom autograd Functions), at EP=1 and around the AllToAll. Eager runs and TorchAO at EP=1 keep argsort + scatter-add. Qwen3.5 turns the region on by default.
Example.
token t, top_k=2, rows r_a, r_b (bf16), scores s_a, s_b
region off / eager: out[t] = bf16(bf16(s_a*r_a) + bf16(s_b*r_b)) backward: index_put accumulate
region on: out[t] = bf16(fp32(s_a*r_a) + fp32(s_b*r_b)) backward: gathers
Resolved since round 1: loss comparison added (FSDP 2 + EP 2, 100 steps). The two eager-vs-eager tests and the GPU determinism file are deleted. TorchAO EP=1 has a TODO at its call site. _score_and_scatter_add is a method again.
Must fix
- The "Summary (human-written)" section is still empty (still open).
- Loss noise floor. The PR's loss gap (+0.010) is judged against "the same before code in a second invocation differs from step 3 on (cause not investigated)".
CLAUDE.mdexpects two runs with the same parallelisms and debug options to give bitwise-identical loss and grad_norm. Two cases:- The two invocations differ in setup (seed checkpoint, data order, GPU). Then say so; the noise estimate is valid as a "different setup" spread.
- They don't. Then position 2 / main is non-deterministic at FSDP 2 + EP 2 under
deterministic=True. That is a bug, and it should be filed, not used as the tolerance.
Either way, one sentence in the PR settles it.
Still open (maintainers' call; the author answered and kept both paths)
token_dispatcher.py:571-- two combine algorithms with different numerics, picked byis_compiling(). Adding or removing the region name changes the loss, not just speed. Eager timings for the one-path alternative are now in the body: -4% to +6% time, +8% peak memory.- #5719 is still open. With this region compiled, the combine bypasses its overridable op. Pick one combine extension point before both land.
Should consider
tests/unit_tests/cpu/models/common/test_token_dispatcher.py:108-- fold the region-name test into the trainer == generator bitwise test (inline).
Details
- Re-checked at HEAD:
_sort_and_gathertakes the eager branch with the same ops as_local_reorder(_argsort_expert_ids, score gather,// top_k, token gather), so "eager bitwise equal to main" holds. In AllToAll_combine,row_of_route_Nindexes the N rows after the reverse all-to-all. For TorchAO at EP>1 that is after_unpermutestrips the padding, so the shapes line up. The detached sorted scores have no consumer besides_CombineGatherSum's backward, and TorchAO EP=1 still uses_local_reorder, so it keeps its score gradient (the TODO says why). - The
_AllToAllBlock.forwardchange (stride-3 ids,top_kfrom the dispatcher, sigmoid scores) also changes the inputs of the existing remat and TorchAO tests in that file. Those tests compare two configurations against each other, so they stay valid. With E=4 and stride 3, each token's two experts are distinct, soscatter_builds a correct routing map.
Not verified: GPU timings, memory, and the EP=2 GPU test; custom autograd Functions under spmd_typechecking=True at TP x EP.
A maintainer still needs to review (shared MoE dispatcher code).
|
|
||
|
|
||
| class TestDispatchCombineRegion(unittest.TestCase): | ||
| def test_one_region_name_compiles_every_function(self): |
There was a problem hiding this comment.
This test mostly repeats test_compiled_training_combine_matches_inference_bitwise (line 182). The only region-name split that changes numerics is _sort_routes_for_training or _sort_routes_and_gather running eager: then one side scatter-adds, and the bitwise trainer == generator check already fails. A misnamed _gather_weighted_sum, _sum_routes_per_token or _gather_weighted_sum_backward only costs speed. To catch those too without a separate test, add a .sum().backward() to the training forward in line 182's test and assert set(_compiled_calls) there, then delete this test along with its class.
There was a problem hiding this comment.
Reply from claude: done in 5c6bacb. The bitwise test now runs the backward and asserts the five compiled functions; the separate test and its class are gone.
|
Reply from claude: on the loss noise floor (must-fix 2): it was a setup difference, the compile cache. I re-ran and updated the body.
So harmless rounding changes move main's 1-100 mean by up to 0.037, and this PR moves it by -0.031 to +0.039. The table in the body has all five runs per window. Also in 5c6bacb: the region-name check now lives in |
|
Reply from claude: @claude review |
|
Claude finished @felipemello1's task in 1m 5s —— View job Needs discussion: round 2's items are resolved (the loss noise came from the compile cache; the region-name check is folded into the bitwise test). Still open: the empty human-written summary, plus maintainer decisions on the eager/compiled combine split and #5719. See the review. |
There was a problem hiding this comment.
Verdict: Needs discussion -- Round 2's code and evidence items are resolved. Two decisions belong to maintainers: eager and compiled use combine algorithms with different numerics, and the combine extension point has to be reconciled with #5719. The human-written summary is still empty.
What this PR does. With the moe_dispatch_combine region compiled, dispatch also returns each route's row in the expert-sorted order. Combine then gathers each token's top_k rows and sums them in fp32. Custom autograd Functions keep the backward to gathers too. This works at EP=1 and around the AllToAll. Eager runs and TorchAO at EP=1 keep argsort + scatter-add. Qwen3.5 turns the region on by default.
Example.
token t, top_k=2, rows r_a, r_b (bf16), scores s_a, s_b
region off / eager: out[t] = bf16(bf16(s_a*r_a) + bf16(s_b*r_b)) backward: index_put accumulate
region on: out[t] = bf16(fp32(s_a*r_a) + fp32(s_b*r_b)) backward: gathers
Resolved since round 2
- Loss noise floor: the earlier spread came from a different setup, a cold vs warm Inductor compile cache. It was not non-determinism under the same setup. With a warm cache, main gives bitwise-equal losses across 3 invocations. The PR's gap (+0.039 warm, -0.031 cold, 1-100 mean) is about the same size as harmless rounding changes to main (up to 0.037).
- The region-name check now lives in
test_compiled_training_combine_matches_inference_bitwise, which also runs the backward. The separate test class is deleted.
Must fix
- The "Summary (human-written)" section is still empty (open since round 1). Per
CONTRIBUTING.md, the author writes it, not an agent.
Still open (maintainers' call; the author answered and kept both paths)
token_dispatcher.py_sort_routes: two combine algorithms with different numerics, picked bytorch.compiler.is_compiling(). Adding or removing the region name changes the loss, not just speed. The body gives the one-path alternative's eager cost: -4% to +6% time and +8% peak memory.- #5719 is still open. With this region compiled, the combine bypasses that PR's overridable op. Pick one combine extension point before both land.
Questions
- A follow-up, not for this PR:
set_determinism(torchtitan/distributed/utils.py:167-172) turns off autotuning only for flex attention. So underdeterministic=True, losses from other compiled regions still depend on cache state (cold vs warm). That gap is in main, not in this PR, but it weakens the "two runs give bitwise-identical loss" contract inCLAUDE.md. Worth an issue?
Details
- Re-checked at HEAD (5c6bacb):
_inputsmakesx_TDandscores_TKrequire grad, sotraining_TD.sum().backward()reaches both_sum_routes_per_tokenand_gather_weighted_sum_backward. All five functions appear in_compiled_callsonly if each one is registered undermoe_dispatch_combine. A function moved to another name runs eager and drops out of the set, as the author says they checked. - The loss table has all five runs per window. In the warm-cache comparison, the 76-100 window has the largest gap (1.544 vs 1.626), and the cold-cache pair is the other way round (1.580 vs 1.549). So the sign of the gap follows rounding noise, not the PR.
Not verified: GPU timings, memory and the EP=2 GPU test. The custom autograd Functions under spmd_typechecking=True at TP x EP are also unchecked.
A maintainer still needs to review (shared MoE dispatcher code).
|
Reply from claude: round 3 is in bef8857.
|
|
Reply from claude: @claude review |
|
Claude finished @felipemello1's task in 52s —— View job Needs discussion: the round-3 changes are fine and the C4 loss comparison settles the evidence question. Still open: the empty human-written summary, plus maintainer decisions on the eager/compiled combine split and #5719. See the review. |
There was a problem hiding this comment.
Verdict: Needs discussion -- Round 3 introduced no new problems, and the C4 loss comparison resolves the evidence question. Still open: the empty human-written summary, plus two maintainer decisions (the eager/compiled combine split, and the extension point to keep alongside #5719).
What this PR does. With the moe_dispatch_combine region compiled, dispatch also returns each route's row in the expert-sorted order. Combine then gathers each token's top_k rows and sums them in fp32. Custom autograd Functions make the backwards use gathers too. This works at EP=1 and around the AllToAll. Eager runs and TorchAO at EP=1 keep argsort + scatter-add. Qwen3.5 turns the region on by default.
Example.
token t, top_k=2, rows r_a, r_b (bf16), scores s_a, s_b
region off / eager: out[t] = bf16(bf16(s_a*r_a) + bf16(s_b*r_b)) backward: index_put accumulate
region on: out[t] = bf16(fp32(s_a*r_a) + fp32(s_b*r_b)) backward: gathers
Changes since round 3 (bef8857, checked at HEAD)
_sort_and_gather->_reorder_by_expert. All 3 call sites are updated (Localdispatch, AllToAll_dispatch, the TorchAO TODO), and no stale references are left in the repo._sort_routes(token_dispatcher.py:394) has a new comment explaining why both branches invert inline instead of calling_inverse_permutation. The comment matches the code: both branches dox[perm] = routes_N.- Loss on C4 (
tests/assets/c4_test, no repeated documents in 100 steps, a fresh compile cache per arm): step 1 is equal, and the 1-100 mean moves 2.9352 -> 2.9318. That is the same size as the rounding-only spread measured on main in round 2. This settles the loss-evidence item from round 1.
Must fix
- The "Summary (human-written)" section is still empty (open since round 1). Per
CONTRIBUTING.md, the author writes it, not an agent.
Still open (maintainers' call; the author has answered and kept both paths)
token_dispatcher.py:390-- there are two combine algorithms with different numerics, chosen bytorch.compiler.is_compiling(). Adding or removing the region name changes the loss, not just speed. Per the body, a single gather-sum path in eager would cost -4% to +6% time and +8% peak memory. The RoPE precedent the body cites (rope.py:301-303) is a fair comparison, but RoPE's compiled path stays within 1 bf16 ulp of eager, while here the difference is a different rounding order.- #5719 is still open. With this region compiled, the combine bypasses that PR's overridable op. One combine extension point should be picked before both land.
Details
- CI status at review time: lint passed; Fake PG, RL and the multi-GPU unit tests were still running. The PR's claim that the DeepSeek-V3 / GPT-OSS / Qwen3 MoE goldens stay unchanged at this stack position depends on that Fake PG run.
- The round-2 follow-up question (
set_determinismturns off autotuning only for flex attention, so withdeterministic=Truethe losses of other compiled regions still depend on cache state) is about main, not this PR, and remains a candidate issue.
Not verified: GPU timings, memory, and the EP=2 GPU test; the custom autograd Functions under spmd_typechecking=True at TP x EP.
A maintainer still needs to review (shared MoE dispatcher code).
bef8857 to
aaa0090
Compare
|
Claude finished @felipemello1's task in 1m 12s —— View job Needs discussion: the merge of #5436's head is correct and adds no new problems. Still open: the empty human-written summary, plus maintainer decisions on the eager/compiled combine split and #5719. See the review. |
There was a problem hiding this comment.
Verdict: Needs discussion -- the merge of #5436's head is correct and adds no new problems. Still open: the empty human-written summary, plus two maintainer decisions (the eager/compiled combine split, and which extension point to keep alongside #5719).
What this PR does. With the moe_dispatch_combine region compiled, dispatch also returns each route's row in the expert-sorted order. Combine then gathers each token's top_k rows and sums them in fp32. Custom autograd Functions make the backwards use gathers too. This works at EP=1 and around the AllToAll. Eager runs and TorchAO at EP=1 keep argsort + scatter-add. Qwen3.5 turns the region on by default.
Example (this round's change).
before (round 3): _sort_routes(ids_TK, num_experts) -> _argsort_expert_ids(ids_N, num_experts)
after (0eedb36): _sort_routes(ids_TK, self.expert_ids_sort_dtype)
-> torch.argsort(ids_N.to(expert_ids_sort_dtype), stable=True)
pairwise branch: key_N = expert_ids_N * N + routes_N (still the uncast int64 ids)
Merge of #5436 (0eedb36, checked at HEAD)
- The merge result equals #5436's head (1a6ebfc) plus this PR's 7 files: the PR diff against the base and
git diff 1a6ebfc 0eedb36match (+583/-24). So nothing from #5436 was dropped or changed while resolving conflicts. _sort_routes(token_dispatcher.py:384-401) casts only in the two argsort branches. The pairwise rank still buildsexpert_ids_N * num_routes + routes_Nfrom the int64 ids, so a uint8 cast can't overflow the key.- Both region functions get
self.expert_ids_sort_dtype, from the Localdispatchand from the AllToAll_dispatchthrough_reorder_by_expert, whichBaseEPTokenDispatcherinherits. Before the all-to-all the ids are global, and the dtype comes from the globalnum_experts, so the width is right. Training and inference get the same dtype, so the trainer == generator bitwise claim still holds. - No stale references:
_argsort_expert_idsand thenum_experts=keyword are gone from all callers and tests.test_pairwise_rank_matches_stable_argsortpassestorch.uint8for E=5, which is the dtype the dispatcher would pick.
Must fix
- The "Summary (human-written)" section is still empty (open since round 1). Per
CONTRIBUTING.md, the author writes it, not an agent.
Still open (maintainers' call; the author has answered and kept both paths)
token_dispatcher.py:385-- two combine algorithms with different numerics, chosen bytorch.compiler.is_compiling(). Adding or removing the region name changes the loss, not just speed. Per the body, a single gather-sum path in eager would cost -4% to +6% time and +8% peak memory.- #5719 is still open. With this region compiled, the combine skips that PR's overridable op. One combine extension point should be picked before both land.
Not verified: GPU timings, memory, and the EP=2 GPU test. I also couldn't run the CPU unit tests in this job (no permission to run commands).
A maintainer still needs to review (shared MoE dispatcher code).
…ce, any EP Rebased on main after #5162 and #5436 merged. One commit with the PR's changes from: - 8ad2584 [moe][perf] Gather-sum MoE dispatch and combine, training and inference, any EP - 2e3549b [moe] Address review: names, docstrings, fewer tests, TorchAO EP=1 TODO - 742288d [moe] Fold the region-name check into the trainer == generator test - aaa0090 [moe] Rename _sort_and_gather to _reorder_by_expert
f34d881 to
9cc71a7
Compare
Keep main's dispatch indexing, backward and scatter-add. Gather-sum changes the reduction and overlaps the work in pytorch#5382 and pytorch#6326. Use scale_rows_by_scores for dispatcher combine, GroupedLinear and DeepEP after output postprocessing. Promoting only the scores keeps the saved activation in its original dtype. Fusion can avoid writing the FP32 product and gradient intermediates. Under block remat, local combine and the W2 input multiply replay. All-to-all scoring follows the enclosing combine policy. Enable the region in Qwen3.5 and its derivatives, including Flash-Next. Other models using these paths can opt in via model.local_compile.regions. Check saved tensors and both gradients in eager and compiled modes. Compared with b3e6a66 on CPU, loss and grad norm matched for 12 steps of one Qwen3.5 MoE block with causal SDPA, BF16, full remat and seed 42. At width 2048, FP32 score gradients differed by up to 3.82e-5. The earlier GPU training numbers include gather-sum and do not isolate the speedup or peak memory benefit of score_scale.
Summary (human-written)
Agent details
TLDR: Compiled MoE dispatch and combine sum each token's
top_kexpert rows with gathers instead of a scatter-add, in training and inference, at EP=1 and around the EP>1 all-to-all. Qwen3.5-35B-A3B, 2 layers, 1 GB300: decode 64 tokens 679 -> 524 us (-23%), prefill 2048 1878 -> 1272 us (-32%), training fwd+bwd at 64k tokens with the recipe's full activation checkpointing 145.8 -> 95.9 ms (-34%), training peak memory 23.4 -> 13.4 GiB. Trainer and generator sum a token's routes the same way, bitwise.Stack (4 PRs, merge bottom-up; this PR is in bold)
Problem
LocalTokenDispatcher.combineand the all-to-all combine add each token'stop_kexpert rows back withdeterministic_scatter_add: a sort, anindex_put_(accumulate=True)and 2_assert_asyncchecks.x[token_indices]backpropagates through another accumulatingindex_put.top_krows, so a gather and a sum are enough, forward and backward.torch.compiledoes them in 198 and 224 us.Solution
moe_dispatch_combine, so one list entry turns them all on. Qwen3.5 (and Qwen3.6 / 3.8) lists it._sort_routes_and_gather(no grad) and_sort_routes_for_trainingsort the routes by expert and return each route's row. Up to 2048 routes they rank the routes pairwise in one fused kernel (a route's row = the number of smaller keysexpert_id * N + route); above that they use the narrow argsort._gather_weighted_sumgathers each token'stop_krows, sums them in fp32 and rounds once._DispatchGatherand_CombineGatherSumare autograd Functions whose backwards also gather (_sum_routes_per_token,_gather_weighted_sum_backward).AllToAllTokenDispatchersorts with the same region before the all-to-all, and its combine calls_CombineGatherSum.Results
You may ask:
index_putthis PR removes.torchtitan/models/common/rope.py:301-303). One path (the gather-sum in eager too) would cost -4% to +6% time and +8% peak memory in eager (table above). Maintainers' call.NOTE:
torchtitan_recipes/rl/verifiers_terminal_bench.py:295), so at EP>1 inference this PR mostly cuts GPU time that is hidden under host time today._score_and_scatter_add, which the eager path here keeps calling. Whichever lands second moves the call sites. With the region compiled, the gather-sum bypasses an overridden combine op.Test plan
pytest tests/unit_tests/cpu/models/common/test_token_dispatcher.py tests/unit_tests/cpu/models/common/test_moe.py tests/unit_tests/cpu/models/qwen3_5/test_offset_rmsnorm.py pytest tests/unit_tests/gpu/distributed/test_remat_all_to_all.py # 2 GPUs; its TorchAO test needs torchaoCI on this head: the Fake PG goldens of DeepSeek-V3, GPT-OSS and Qwen3 MoE pass unchanged ("All losses are equal"), since those models list the region only from stack position 4. That checks the eager path against main. The GPU unit tests, which drafts skip, ran by a manual workflow dispatch with torchao installed: 1 GPU 303 passed, multi-GPU 47 passed, including all 4 tests in
test_remat_all_to_all.py(the TorchAO one too).test_compiled_training_combine_matches_inference_bitwisealso fails if one of the five functions sits under another region name or runs eager.