Skip to content

[moe] Reuse the route permutation to sum expert outputs in FP32 - #6326

Open
bvolpato wants to merge 4 commits into
pytorch:mainfrom
bvolpato:bvolpato/moe-combine-gather-sum
Open

bvolpato wants to merge 4 commits into
pytorch:mainfrom
bvolpato:bvolpato/moe-combine-gather-sum

Conversation

@bvolpato

@bvolpato bvolpato commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary (reviewed and approved by the author)

Local and all-to-all combine used to round each weighted expert output before adding it to its token. This change restores router order with the existing row permutation, sums in FP32, then casts once. For example, BF16 rounds 257 to 256, so rounding the contributions 257 and −256 separately loses their sum of 1.

This uses ordinary autograd and removes the scatter-add helper. DeepEP score absorption moves scoring before the expert output projection. This change acts after that projection and leaves DeepEP alone.

Worked example

I reproduced the change with scores that sum to one. For one token, the experts return [0, -1, 1]. Dispatch recorded the route order [1, 2, 0], so combine pairs [-1, 1, 0] with scores [0.4995, 0.5, 0.0005].

Local dispatcher on CPU Weighted rows Sum returned in BF16
Base, round before summing [-0.5, 0.5, 0] 0
PR, sum before rounding [-0.4995, 0.5, 0] 0.0004997253

Review decision

Should the eager reference change its rounding? #5382 uses gather and sum in compiled dispatch and combine, and keeps the existing eager fallback. This PR changes eager combine for local and all-to-all dispatch, including the TorchAO paths, and preserves dispatch backward. #5719 also proposes a shared combine operation. We should agree on a single reference and check the affected loss baselines before merging.

If #6320 lands first, resolve the conflict in token_dispatcher.py by using this sum for local and all-to-all combine. The scored grouped linear and DeepEP paths from #6320 stay in place.

Validation

The B200 results are from d7909e2c. Squashing to 8c37bd86 left every file unchanged.

On two B200s, local and uneven NCCL all-to-all combine matched exactly, including gradients, TorchAO padding and checkpoint replay. On CPU, the regression also checks gradients with torch.compile and aot_eager.

I compared two layers of Qwen3-30B-A3B on B200 with seed 42, a 2,048-token vocabulary and 20 BF16 AdamW updates at a learning rate of 0.0002. Each update used four 2,048-token C4 sequences. Four separate sequences were held out. I repeated the comparison in reverse order.

Revision Initial held-out loss Final held-out loss Median warm step in each trial Peak allocated
Base 90ae735 7.95779 3.06627 30.81 / 30.57 ms 11.26 GiB
Eager combine at d7909e2 7.95790 3.07517 29.82 / 30.13 ms 10.85 GiB

Held-out loss increased by 0.00890. Each revision reproduced its own losses and gradient norms exactly. Timing and peak allocation start at update 6. This short run does not establish full-model throughput or convergence.

Earlier B200 measurements and the removed compile option

At bd83fef, eager dispatch and combine took 5.42 ms versus 6.07 ms on the baseline at 16,384 tokens, eight routes per token and width 2,048. In a separate comparison, enabling moe_weighted_gather_sum increased forward and backward time from 5.92 to 13.44 ms while reducing extra peak allocation from 4,163 to 1,161 MiB.

That optional region had no model consumer and was removed in d7909e2. The earlier 20-update C4 held-out losses were 3.066 on b3e6a66, 3.075 with eager combine and 3.083 with the removed region.

Self-review

At d7909e2, the substantive changes are the dispatch metadata and the reduction. Removing the unused scatter helper and its references is cleanup. The Hugging Face compatibility results predate the new reference. Recheck numerical equivalence and the affected MoE loss fixtures on each supported backend.

@meta-cla

meta-cla Bot commented Nov 23, 2026

Copy link
Copy Markdown

Hi @bvolpato!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@pytorch-bot

pytorch-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/rl
  • ciflow/fake-pg

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@bvolpato
bvolpato force-pushed the bvolpato/moe-combine-gather-sum branch from 1e5e51b to 741a93f Compare November 25, 2026 02:17
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 25, 2026
@meta-cla

meta-cla Bot commented Nov 25, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@bvolpato
bvolpato marked this pull request as ready for review November 25, 2026 13:14
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 25, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 4m 13s —— View job


Needs discussion: the change duplicates the open #5382 stack (and overlaps #6320), so maintainers need to choose one. 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 -- this is the same optimization as the open #5382 stack (gather-sum MoE combine, compiled, enabled for Qwen3.5), and it overlaps the author's own #6320. Maintainers need to pick one before line-level polish is worth it.

What this PR does. When the moe_weighted_gather_sum local_compile region is enabled, _score_and_scatter_add stops doing scale -> bf16 round -> deterministic_scatter_add. Instead it uses the dispatch sort permutation perm_N to gather each token's top_k expert rows and sum them in fp32, with a gather-only backward. To pass perm_N from dispatch to combine, the PR adds it to LocalDispatchMetadata. A new global, is_local_compile_enabled, tells combine whether the region is on.

Example. T=2, top_k=2, token 0 is routed to sorted rows 3 and 0:

main:     out = zeros(T, D); out.scatter_add_(token_idx, bf16(row * score))   # one bf16 rounding per route
this PR:  inv = inverse(perm); out[0] = bf16(fp32(row[3])*s + fp32(row[0])*s')  # fp32 sum, rounded once

This is a numerics change for Qwen3.5 by default: the description reports a loss difference of 1.34e-3 at step 11. There are no qwen3_5 golden files, so nothing needs regenerating.

Must fix

  1. Overlapping work (gate). #5382 (felipemello1, part 3 of a 4-PR stack, with #5518 turning it on for DSv3/V4, Kimi K3, GPT-OSS and Qwen3) already covers this: a compiled gather-sum combine, plus a gather-based dispatch backward, inference, and any EP. It edits the same qwen3_5/model.py region list and test_offset_rmsnorm.py. #6320 (yours) also rewrites _score_and_scatter_add and the same test files. Please coordinate: rebase onto #5382, close this in its favor, or explain in the description what this PR covers that #5382 doesn't. Also say how it relates to #6320.
  2. torchtitan/distributed/local_compile.py:71 -- new global is_local_compile_enabled probe that switches algorithms in shared code (inline).
  3. token_dispatcher.py:341 -- guard_or_false shape check is a silent fallback (inline).
  4. token_dispatcher.py:169 -- perm_N is never None; make it required (inline).
  5. token_dispatcher.py:233 -- _local_reorder kept only as a BC shim; delete it (inline).
  6. test_qwen3_5_moe.py:119 -- the test belongs in tests/unit_tests/cpu/models/common/test_token_dispatcher.py (inline).
  7. The description doesn't match the code.
    • It lists "moe_weighted_gather_sum_bwd" as an enabled region, but no such region exists; both functions register under moe_weighted_gather_sum.
    • "The combine output matches eager bitwise" contradicts Table 1 (error vs the fp32 reference goes from 9.27e-3 to 1.94e-3) and the end-to-end loss diff. Eager rounds each scaled route to bf16 (token_dispatcher.py:356) before summing; the fused path doesn't, so the outputs can't be bitwise equal in general.

Should consider

  • token_dispatcher.py:99 -- the single-gradient backward branches duplicate the compiled backward (inline).

Questions

  • token_dispatcher.py:43 -- is batch_invariant=True right for a backward that reduces over D? (inline)
  • If this PR is the one to keep: why only Qwen3.5? The path is model-agnostic, and #5518 enables the equivalent for every MoE model.
Details
  • Overlap search: gh pr list --search for "token_dispatcher", "gather sum combine" and "scatter_add" found #5382, #5518, #6320, #5719 ("Make the token combine one op that backends can override") and #5708.
  • #5382 gates inside its compiled dispatch region with torch.compiler.is_compiling() and returns row_of_route_N=None in eager, so combine knows which path to take without any new global state in local_compile.py.
  • GraphTrainer requires local_compile.regions == [] (experiments/graph_trainer/trainer.py:69), so with this PR's gate it always takes the scatter path.
  • Parallelisms: EP>1 passes perm_N through the <fqn>.combine remat region as a tensor, so it is recomputed consistently. TorchAO EP=1 unpads before combine, so R == T*K holds on every path I traced.
  • RL generator: it applies the same model_config.local_compile, so trainer and generator take the same combine path.

Not verified: the B200 kernel and end-to-end numbers, and batch invariance of the compiled regions; these need a GPU.

Before merge: fill in the human-written summary is present; no action needed there.

Comment thread torchtitan/distributed/local_compile.py Resolved
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.
@bvolpato bvolpato changed the title Fuse MoE combine score-scaling and gather-sum in token_dispatcher [moe] Reuse the route permutation to sum expert outputs in FP32 Nov 28, 2026
bvolpato added a commit to bvolpato/torchtitan that referenced this pull request Nov 30, 2026
Inductor can choose different Triton reduction schedules for the FP32
score gradient depending on the row count, so dScores is not bitwise
batch-invariant across batch sizes (verified on CUDA: at I=128 splits
17/64/512/2048 vs 4096 differ by up to 3.82e-6; at I=2048 split 1 vs
4096 differs by 7.63e-6). Forward output and dX remain bitwise equal.

Aligns the batch_invariant convention with moe_weighted_gather_sum in
pytorch#6326.
@bvolpato

Copy link
Copy Markdown
Contributor Author

On two B200s at d7909e2, I ran an eager NCCL all-to-all with 37 tokens per rank, width 128 and three routes per token. The split was uneven and one of eight experts was idle.

The outputs matched an independent FP32 sum in router order. Input and score gradients matched local dispatch exactly in FP32 and BF16, including TorchAO padding and checkpoint replay. This checks agreement with the new reference. With the normalized scores in the description, both revisions gave score gradients of [-1, 1, 0] on CPU, even though their forward outputs differed.

In the two-layer C4 run, training loss first differed at step 1 and gradient norm at step 6. A separate trace found different expert sets in layer 2 for 195 of 8,192 tokens at step 1 versus b3e6a66. Both baseline revisions reproduced the same losses. The two trials of this PR finished 0.00890 higher on the held-out batch. The trace cannot tell us how much of that gap came from routing.

To repeat the rounding and gradient checks on CPU, run pytest tests/unit_tests/cpu/models/common/test_token_dispatcher.py -k combine. I did not validate the full set of model loss baselines or long-run convergence.

Local and all-to-all combine used to round each weighted expert output
before adding it to its token. This change restores router order with
the existing row permutation, sums in FP32, then casts once. For
example, BF16 rounds 257 to 256, so rounding the contributions 257 and
−256 separately loses their sum of 1.

The tested revision d7909e2
has the same Git tree as this commit.
@bvolpato
bvolpato force-pushed the bvolpato/moe-combine-gather-sum branch from d7909e2 to 8c37bd8 Compare November 30, 2026 15:03
Eager combine still materializes the weighted rows after W2. Document
what checkpoint replay recomputes and why DeepEP saves combine.

Flatten the batch and sequence in the comparison script so dispatch
can index one row per token. With seed 42 and two routes per token,
the maximum BF16 output differences from Hugging Face on CPU fell
from 0.00391 for Qwen3 MoE and OLMoE and 0.0625 for Mixtral to zero.
Record the shared-expert weight transfer and Gemma 4 limitations.

The dispatcher and training code are unchanged.
Keep the FP32 sum in router order for local and all-to-all dispatch.
Document that HybridEP now absorbs scores like DeepEP and that both
dispatchers save combine even when dispatch replays.

On CPU, a two-layer Qwen3 MoE with causal SDPA reproduced the pre-merge
losses and gradient norms exactly over 20 BF16 AdamW steps on the C4
test data. With seed 42, held-out loss fell from 7.67972 to 3.66080
on the branch and from 7.67960 to 3.66051 on main.

Two Gloo ranks matched local outputs and gradients with checkpoint
replay in FP32 and BF16. Uneven splits used the compiled exchange.
On CPU, Qwen3 MoE, OLMoE and Mixtral matched Hugging Face. GPU loss
baselines still need validation.

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

Status: Todo

Development

Successfully merging this pull request may close these issues.

3 participants