Repository navigation
Conversation
|
Hi @bvolpato! Thank you for your pull request and welcome to our community. Action RequiredIn 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. ProcessIn 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 If you have received this in error or have any questions, please contact us at [email protected]. Thanks! |
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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. |
1e5e51b to
741a93f
Compare
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
|
@claude review |
There was a problem hiding this comment.
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
- 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.pyregion list andtest_offset_rmsnorm.py. #6320 (yours) also rewrites_score_and_scatter_addand 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. torchtitan/distributed/local_compile.py:71-- new globalis_local_compile_enabledprobe that switches algorithms in shared code (inline).token_dispatcher.py:341--guard_or_falseshape check is a silent fallback (inline).token_dispatcher.py:169--perm_Nis neverNone; make it required (inline).token_dispatcher.py:233--_local_reorderkept only as a BC shim; delete it (inline).test_qwen3_5_moe.py:119-- the test belongs intests/unit_tests/cpu/models/common/test_token_dispatcher.py(inline).- 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 undermoe_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.
- It lists
Should consider
token_dispatcher.py:99-- the single-gradient backward branches duplicate the compiled backward (inline).
Questions
token_dispatcher.py:43-- isbatch_invariant=Trueright for a backward that reduces overD? (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 --searchfor "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 returnsrow_of_route_N=Nonein eager, so combine knows which path to take without any new global state inlocal_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_Nthrough the<fqn>.combineremat region as a tensor, so it is recomputed consistently. TorchAO EP=1 unpads before combine, soR == T*Kholds 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.
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.
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.
|
On two B200s at 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 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 To repeat the rounding and gradient checks on CPU, run |
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.
d7909e2 to
8c37bd8
Compare
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.
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].[-0.5, 0.5, 0][-0.4995, 0.5, 0]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.pyby 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 to8c37bd86left 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.compileandaot_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.
90ae735d7909e2Held-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, enablingmoe_weighted_gather_sumincreased 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 onb3e6a66, 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.