Skip to content

[moe][perf] Gather-sum MoE dispatch and combine, training and inference, any EP (3/4) - #5382

Draft
felipemello1 wants to merge 1 commit into
mainfrom
felipemello1/gen-perf/3-train-gather-combine
Draft

felipemello1 wants to merge 1 commit into
mainfrom
felipemello1/gen-perf/3-train-gather-combine

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: Compiled MoE dispatch and combine sum each token's top_k expert 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.

main:     sort routes -> experts -> x score -> scatter-add into tokens        backward: index_put accumulate
this PR:  [sort + row of each route] -> experts -> gather each token's top_k rows -> fp32 sum   backward: gathers

Stack (4 PRs, merge bottom-up; this PR is in bold)

# PR Independent? Needs (stack positions)
1 AllToAll dispatcher: permute and unpermute with gathers yes —
2 Argsort expert ids on the narrowest integer type yes —
3 Gather-sum MoE dispatch and combine, training and inference, any EP no 2
4 Turn on gather-sum dispatch and combine for DeepSeek-V3/V4, Kimi K3, GPT-OSS and Qwen3 MoE no 3

Problem

  1. Combine. LocalTokenDispatcher.combine and the all-to-all combine add each token's top_k expert rows back with deterministic_scatter_add: a sort, an index_put_(accumulate=True) and 2 _assert_async checks.
  2. Its backward. In training, the token gather x[token_indices] backpropagates through another accumulating index_put.
  3. Not needed. Each token owns exactly top_k rows, so a gather and a sum are enough, forward and backward.
  4. Cost. One Qwen3.5-35B-A3B MoE layer on main: the combine and residual add take 342 us at 2048 tokens (30 kernels); the combine backward takes 2361 us at 16k tokens. Per-layer torch.compile does them in 198 and 224 us.

Solution

  1. One region. Five functions share the local-compile region moe_dispatch_combine, so one list entry turns them all on. Qwen3.5 (and Qwen3.6 / 3.8) lists it.
  2. Dispatch. _sort_routes_and_gather (no grad) and _sort_routes_for_training sort 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 keys expert_id * N + route); above that they use the narrow argsort.
  3. Combine. _gather_weighted_sum gathers each token's top_k rows, sums them in fp32 and rounds once.
  4. Training. _DispatchGather and _CombineGatherSum are autograd Functions whose backwards also gather (_sum_routes_per_token, _gather_weighted_sum_backward).
  5. EP>1. AllToAllTokenDispatcher sorts with the same region before the all-to-all, and its combine calls _CombineGatherSum.
  6. Unchanged: eager runs (argsort + scatter-add, bitwise equal to main), TorchAO at EP=1 (a TODO at its call site), Dist-MoE, DeepEP and HybridEP.

Results

Numerics: not bitwise vs main (fp32 sum and one rounding, vs a bf16 rounding per route).
  op level (CPU probe): max rel L2 vs fp64, scatter-add combine 2.34e-3, gather-sum 1.66e-3 (the bf16 floor)
  2 Qwen3.5-35B-A3B layers, routing fixed, this PR vs main: output rel L2 1.5e-3 at decode 64 and 1.2e-3 at
  prefill 2048 (main's own spread for a 1-ulp input change: 7.2e-3 / 7.1e-3); fwd+bwd 16k: all 30 tensors (output,
  input grad, every weight grad) inside that spread (worst 0.44 of it)
  Trainer MoE output == generator MoE output, bitwise (unit test, eager backend). Compiled fwd+bwd is bitwise equal
  across runs at EP=2 (GPU test). The pairwise rank gives the same order as the stable argsort (unit test).

Loss: Qwen3.5 debug MoE, FSDP 2 + EP 2 (all-to-all dispatcher), 100 steps, scripts/loss_compare.py (seed
checkpoint, deterministic). Dataset: C4 text (tests/assets/c4_test, 2000 documents). 100 steps read 410k tokens,
so no document repeats. lr 5e-3, warmup 2. Each arm ran in its own process with its own fresh, empty Inductor
and Triton cache.
                main      this PR
step 1         13.0330   13.0330    (13.03299 vs 13.03296)
step 100        2.4579    2.4650
1-100 mean      2.9352    2.9318    (-0.0034)
window means (1-10, 11-25, 26-50, 51-75, 76-100) differ by at most 0.009; grad_norm 1-100 mean 0.826 vs 0.820
On the recipe's default dataset (cc12m-test, 32 image captions, repeated), the sign of the gap follows the
compile cache: warm cache 2.771 -> 2.810, cold cache 2.808 -> 2.777 (main -> this PR, 1-100 mean).
Stack position 2's 100 losses equal main's bitwise (--assert-equal, cc12m-test).

Qwen3.5-35B-A3B, 2 layers (GDN + gated attention, each with a 256-expert MoE), EP=1, the model's regions,
CUDA-graph replay, 1 GB300. One process per arm, one run per row.

inference (no grad, compiled in the generator's order 2048, 1536, then largest to smallest), us
before = stack position 2, after = this PR, same GPU, one run per row
tokens          before    this PR             per-layer compile*
decode 1          496       358    -27.8%            382
decode 32         654       506    -22.6%            602
decode 64         679       524    -22.7%            614
decode 128        709       541    -23.7%            638
decode 256        786       603    -23.2%            688
decode 512        916       658    -28.2%            857
prefill 1024     1290       911    -29.4%           1201
prefill 2048     1878      1272    -32.3%           1680
prefill 4096     3172      2119    -33.2%           2657
prefill 8192     5900      3950    -33.0%           4838
peak memory: prefill 2048 393 -> 210 MiB, prefill 8192 1574 -> 838 MiB
* main's tree, an earlier run on another GB300 of the same box

training fwd+bwd, 32 local experts (the recipe's EP8 share), ms; before = main. Measured before the fold, which
changes no compiled kernel (16k full AC on the folded code: 25.2 ms)
                     main    this PR             peak GiB
full AC (recipe) 16k   38.3     25.1   -34.5%
                 32k   74.2     48.7   -34.4%
                 64k  145.8     95.9   -34.2%    23.4 -> 13.4
no AC            16k   29.1     19.8   -31.9%
                 32k   56.4     38.1   -32.5%
                 64k  110.2     74.9   -32.0%    35.1 -> 23.1
per-layer torch.compile, no AC, 64k: 81.3 ms (this PR is 7.8% faster)

eager dispatch and combine (moe_dispatch_combine off, the other regions on), us
                         CUDA graphs                     no graphs (host time counts)
                         main    this PR   gather-sum*   main    this PR   gather-sum*
decode 64                 652      624       601         7269     6040      6383
fwd+bwd 16k, full AC    38203    37994     38308        39470    39163     39478
fwd+bwd peak, MiB        6177     6177      6690
* the one-path alternative: this PR's gather-sum run as eager ops (a harness patch, not in this PR)
No-graph decode is host-bound (~6-7 ms of host time for ~0.6 ms of GPU work), so its spread is mostly host noise.

TP2 + EP2 (2 GB300, real all-to-all, SP on, 64 experts in total), fwd+bwd 64k, full AC, no CUDA graphs (the
all-to-all copies its split sizes to the host), slowest rank, with stack positions 1-2:
main 119.9 ms -> this PR 88.2 ms (-26.4%), peak 11.9 -> 8.8 GiB
inference at TP2 + EP2, this PR's region on vs off in one process: no measurable change; without CUDA graphs each
2-layer call spends ~15-17 ms on the host for 0.5-2 ms of GPU work. An EP rank with 0 rows: finite, no extra graph.

graphs per compiled function (limit 8 each): generator decode sort 4, combine 3; prefill 3 / 2; trainer 1 each
(3 steps, new routing each step, world 1 and FSDP 2), no recompiles

You may ask:

  • Why custom autograd Functions? Autograd's backward of a gather is the accumulating index_put this PR removes.
  • Why keep the scatter-add in eager (two combine paths)? So eager stays bitwise equal to main, and stays the reference. Compiled runs, which today's RL recipes use, get the gather-sum. Main already does this for RoPE: compiled, it rotates in real arithmetic (within 1 bf16 ulp of eager), and eager keeps the complex ops (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.
  • Why not a one-hot counting sort? 5 kernels at decode (9.1 vs 5.1 us at 34 tokens), and its cumsum is slow at 1024-2048 tokens (114 vs 50 us for the region at 2048).
  • Why stop the pairwise rank at 2048 routes? It is O(N^2): 241 us at 16,384 routes, vs 50-53 us for the whole region with the narrow argsort.

NOTE:

  • Qwen3.5 reaches this through its own list. DeepSeek-V3/V4, Kimi K3, GPT-OSS and Qwen3 MoE get it in stack position 4.
  • The Qwen3.5-35B-A3B terminal-bench generator runs the all-to-all without CUDA graphs (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.
  • Conflicts with the open PR "[MoE] Make the token combine one op that backends can override": it removes _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.
  • Not run: the vLLM engine end to end (the numbers are from a layer-level harness), step wall time, EP 4/8, a full-size loss curve.

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 torchao

CI 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_bitwise also fails if one of the five functions sits under another region name or runs eager.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 14, 2026
@felipemello1
felipemello1 added this pull request to stack #5386 October 14, 2026 03:04
@felipemello1
felipemello1 removed this pull request from stack #5386 October 14, 2026 03:13
@felipemello1
felipemello1 changed the base branch from felipemello1/gen-perf/2-moe-counting-sort-dispatch to felipemello1/qwen35-router October 14, 2026 03:14
@felipemello1
felipemello1 force-pushed the felipemello1/gen-perf/3-train-gather-combine branch from 268820f to 5b667bf Compare October 14, 2026 03:14
@felipemello1 felipemello1 changed the title [moe][perf] Gather-sum combine for training at EP=1 (3/6) [moe][perf] Gather-sum combine for training at EP=1 (6/6) Oct 14, 2026
@felipemello1
felipemello1 changed the base branch from felipemello1/qwen35-router to felipemello1/gen-perf/6-mamba-state-copy October 14, 2026 03:14
@felipemello1
felipemello1 added this pull request to stack #5387 October 14, 2026 03:15
@felipemello1
felipemello1 removed this pull request from stack #5387 October 14, 2026 03:23
@felipemello1
felipemello1 changed the base branch from felipemello1/gen-perf/6-mamba-state-copy to main October 14, 2026 03:24
@felipemello1
felipemello1 force-pushed the felipemello1/gen-perf/3-train-gather-combine branch from 5b667bf to 74d97a8 Compare October 14, 2026 03:24
@felipemello1 felipemello1 changed the title [moe][perf] Gather-sum combine for training at EP=1 (6/6) [moe][perf] Gather-sum combine for training at EP=1 (7/7) Oct 14, 2026
@felipemello1
felipemello1 changed the base branch from main to felipemello1/qwen35-router October 14, 2026 03:24
@felipemello1
felipemello1 added this pull request to stack #5388 October 14, 2026 03:25
@felipemello1 felipemello1 changed the title [moe][perf] Gather-sum combine for training at EP=1 (7/7) [moe][perf] Gather-sum combine for training, at any EP (7/7) Oct 15, 2026
@felipemello1 felipemello1 changed the title [moe][perf] Gather-sum combine for training, at any EP (7/7) [moe][perf] Gather-sum combine for training, at any EP (7/9) Oct 15, 2026
@felipemello1
felipemello1 removed this pull request from stack #5388 October 18, 2026 04:16
@felipemello1
felipemello1 changed the base branch from felipemello1/qwen35-router to main October 18, 2026 04:16
@felipemello1
felipemello1 force-pushed the felipemello1/gen-perf/3-train-gather-combine branch from 3bb5e29 to 471c829 Compare October 18, 2026 04:17
@felipemello1
felipemello1 changed the base branch from main to felipemello1/gen-perf/2-moe-counting-sort-dispatch October 18, 2026 04:17
@felipemello1
felipemello1 added this pull request to stack #5497 October 18, 2026 04:18
@felipemello1 felipemello1 changed the title [moe][perf] Gather-sum combine for training, at any EP (7/9) [moe][perf] Gather-sum combine for training, at any EP Oct 18, 2026
@felipemello1
felipemello1 removed this pull request from stack #5497 October 18, 2026 21:35
@felipemello1
felipemello1 force-pushed the felipemello1/gen-perf/3-train-gather-combine branch from 471c829 to d189fb9 Compare October 18, 2026 21:36
@felipemello1
felipemello1 changed the base branch from felipemello1/gen-perf/2-moe-counting-sort-dispatch to main October 19, 2026 02:15
@felipemello1
felipemello1 force-pushed the felipemello1/gen-perf/3-train-gather-combine branch from d189fb9 to 5a92595 Compare October 19, 2026 02:16
@felipemello1
felipemello1 changed the base branch from main to felipemello1/gen-perf/2-moe-counting-sort-dispatch October 19, 2026 02:17
@felipemello1
felipemello1 added this pull request to stack #5519 October 19, 2026 02:17
@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

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 is_compiling(). See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: 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

  1. The "Summary (human-written)" section is empty. Per CONTRIBUTING.md, the author writes it.
  2. No loss evidence. Rows in Qwen3.5's default region list change training numerics, and the PR says "Not run: ... a loss curve". CLAUDE.md requires 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.
  3. torchtitan/models/common/moe/token_dispatcher.py:386 -- the eager/compiled algorithm split keyed on is_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 through AllToAllTokenDispatcher._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_gather there, then _CombineGatherSum after _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, and test_remat_all_to_all already checks it bitwise (inline).

Questions

  • How does this land alongside #5719 (one score_and_scatter_add op 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 through row_of_route_N). The score grad now reaches topk_scores_TK directly, so detaching the sorted scores is safe: no other consumer of topk_scores_experts_sorted_N exists (moe.py doesn't read it). Batch-invariant RL recipes clear local_compile.regions (torchtitan_recipes/rl/alphabet_sort.py), so they don't hit the batch_invariant=False ValueError. The AllToAll _combine rows 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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: 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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: done in a602279. Both eager-vs-scatter tests are gone.



@unittest.skipUnless(torch.cuda.is_available(), "needs CUDA")
class TestCompiledTrainingDeterminism(unittest.TestCase):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: 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.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: round 2 is in a602279.

  • Loss (now in the body): Qwen3.5 debug MoE, FSDP 2 + EP 2, 100 steps, scripts/loss_compare.py. Step 1 is equal (12.947). The 1-100 mean loss goes 2.797 -> 2.807. The same "before" code run in a second invocation moves that mean by 0.026 (2.797 vs 2.771), so the gap is inside run-to-run noise. Stack position 2 vs main: all 100 losses bitwise equal.
  • Two combine paths: kept. Eager timings are in the body; see the inline thread.
  • TorchAO at EP=1: a TODO at its call site. No test runs TorchAO at EP=1 (its test runs EP=2 and needs torchao), so I did not move it untested.
  • Tests: the two eager-vs-scatter tests and the GPU determinism file are gone.
  • The open combine-op PR: whichever lands second moves the call sites. With the region compiled, the gather-sum skips an overridden combine op. Picking one extension point is for maintainers.
  • Inference table: re-run on one quiet GPU on the folded code. Decode 64 reads 679 -> 524 us, the same as before.
  • Smaller: expert_sort_N is now route_indices_experts_sorted_N; _sort_routes returns early in eager (no unused arange); _score_and_scatter_add is a method again, as on main.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 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.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: 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

  1. The "Summary (human-written)" section is still empty (still open).
  2. 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.md expects 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 by is_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_gather takes 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_N indexes the N rows after the reverse all-to-all. For TorchAO at EP>1 that is after _unpermute strips 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.forward change (stride-3 ids, top_k from 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, so scatter_ 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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: done in 5c6bacb. The bitwise test now runs the backward and asserts the five compiled functions; the separate test and its class are gone.

@felipemello1

Copy link
Copy Markdown
Contributor Author

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.

  • main with a warm compile cache: bitwise-equal losses in 3 invocations, on GPUs 0+1, 0+2 and 2+3.
  • main with a cold cache (fresh TORCHINDUCTOR_CACHE_DIR): differs from step 3. 1-100 mean 2.808 vs 2.771. The earlier "before" run had compiled on a cold cache.
  • main with one more op in eager (OffsetRMSNorm off its region): 1-100 mean 2.779.
  • this PR: 2.810 (warm cache), 2.777 (cold cache).

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 test_compiled_training_combine_matches_inference_bitwise (it runs the backward and checks all five functions ran compiled). I watched it fail with _sum_routes_per_token moved to another region name. The separate test is gone.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 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.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: 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

  1. 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 by torch.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 under deterministic=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 in CLAUDE.md. Worth an issue?
Details
  • Re-checked at HEAD (5c6bacb): _inputs makes x_TD and scores_TK require grad, so training_TD.sum().backward() reaches both _sum_routes_per_token and _gather_weighted_sum_backward. All five functions appear in _compiled_calls only if each one is registered under moe_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).

@felipemello1 felipemello1 added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 7, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: round 3 is in bef8857.

  • Loss on C4 (now the body's main loss block): tests/assets/c4_test, 2000 documents, no repeats in 100 steps. Each arm ran with its own fresh, empty Inductor and Triton cache. Step 1: 13.0330 both. Step 100: 2.458 vs 2.465. 1-100 mean: 2.935 vs 2.932. The cc12m-test cache flip stays as one line.
  • _sort_and_gather is now _reorder_by_expert.
  • I tried _inverse_permutation in _sort_routes and kept the inline index_put: on the same GPU, decode 64 read 541 vs 523 us (~3% slower). A comment at the site says so.
  • Two combine paths: the body now cites main's RoPE region, which also switches algorithm when compiled (torchtitan/models/common/rope.py:301-303).
  • CI: added ciflow/fake-pg. DeepSeek-V3, GPT-OSS and Qwen3 MoE don't list the region at this stack position, so their goldens must pass unchanged. I also started the GPU unit tests by workflow dispatch, since drafts skip them; that run installs torchao for the TorchAO test.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 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.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: 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 (Local dispatch, 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 do x[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

  1. 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 by torch.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_determinism turns off autotuning only for flex attention, so with deterministic=True the 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).

@felipemello1
felipemello1 force-pushed the felipemello1/gen-perf/3-train-gather-combine branch from bef8857 to aaa0090 Compare November 7, 2026 20:52
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review (merged #5436's head: the sort functions now take expert_ids_sort_dtype from LocalTokenDispatcher instead of num_experts, because #5436 picks the dtype once in __init__ and deleted _argsort_expert_ids)

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

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.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: 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 0eedb36 match (+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 builds expert_ids_N * num_routes + routes_N from the int64 ids, so a uint8 cast can't overflow the key.
  • Both region functions get self.expert_ids_sort_dtype, from the Local dispatch and from the AllToAll _dispatch through _reorder_by_expert, which BaseEPTokenDispatcher inherits. Before the all-to-all the ids are global, and the dtype comes from the global num_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_ids and the num_experts= keyword are gone from all callers and tests. test_pairwise_rank_matches_stable_argsort passes torch.uint8 for E=5, which is the dtype the dispatcher would pick.

Must fix

  1. 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 by torch.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).

Base automatically changed from felipemello1/gen-perf/8-narrow-argsort to main November 8, 2026 03:48
…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
@felipemello1
felipemello1 force-pushed the felipemello1/gen-perf/3-train-gather-combine branch from f34d881 to 9cc71a7 Compare November 8, 2026 04:37
bvolpato added a commit to bvolpato/torchtitan that referenced this pull request Nov 28, 2026
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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant