Repository navigation
[moe][perf] Compile the MoE router and its load-balance sums - #5343
felipemello1 wants to merge 28 commits into
Conversation
05fad9a to
60a7dda
Compare
|
Follow-up after this lands: Muse Spark doesn't enable the router region yet; it needs a one-line addition to |
96c058e to
b967fe4
Compare
72b43ba to
1b6831e
Compare
5d29be6 to
352824c
Compare
| "moe_router_topk", | ||
| batch_invariant=True, | ||
| recompile_limit=16, | ||
| options={"batch_invariant": True}, |
There was a problem hiding this comment.
why passing this again?
There was a problem hiding this comment.
Reply from claude: They are two different flags with the same name. The decorator's batch_invariant=True only declares that the region is safe in batch-invariant mode: local_compile checks it before allowing the region there (local_compile.py:83-88). It doesn't change compilation. options={"batch_invariant": True} is the Inductor setting that makes it true for this region, which has reductions: it fixes each reduction's launch config, so a token gets the same result at T = 1 and T = 16k. Without it, 4 of 7 runs gave a token different outputs at small T. Its cost on GB300 is a few µs per call at decode sizes and none from 4k tokens. I added a line to the comment above saying which flag does what (e75975b).
| scores_for_choice_TE = ( | ||
| scores_TE if expert_bias_E is None else scores_TE + expert_bias_E | ||
| ) | ||
| if torch.compiler.is_compiling(): |
There was a problem hiding this comment.
Reply from claude: Inductor can't fuse topk: it lowers it to a separate ATen kernel. Inside the compiled region, k "pick the max, then hide it" rounds fuse with the scoring into the same kernel, which is where most of the decode speedup comes from. In eager, the rounds are separate kernels and much slower than one topk. GB300, Qwen3.5 (E = 256, k = 8), T = 1: 25 µs for topk vs 309 µs for the rounds. Kimi K3 (E = 896, k = 16): 24 vs 544 µs. The eager path still runs when regions are off, for example in the batch-invariant RL recipes, so it keeps topk. Both pick the same experts except on exact ties, where topk makes no promise and the rounds pick the lower id. I added a one-line comment with this trade-off (e75975b).
There was a problem hiding this comment.
… into moe_router_topk The router region now also returns the per-expert statistics (train mode, padding excluded). The counter keeps exact integer counts. The aux losses get this DP rank's fp32 counts and normalized-score sums, so they take two (E,) vectors. Removed: _expert_counts, _microbatch_load_balance_local_stats, AuxLoss._norm_sum_scores_over_tokens, the moe_aux_loss region, and the second eager count in forward. recompile_limit 16 -> 32: DeepSeek-V4's router reaches 28 graphs in the worst call order. DeepSeek-V3 router + aux loss fwd+bwd, GB300, with #5574 merged: 208.6 -> 189.2 us at 4096 tokens, 480.3 -> 443.4 us at 16384 (median of 3 interleaved processes). Bitwise equal to the previous region.
… recompile_limit 48 - Names: the DP-local sums keep main's names, local_counts_E and local_prob_sums_E (_RoutingOutputs fields, loss arguments, locals). No numerics change: the GPU router tests (compiled vs eager, bitwise batch-size check, remat) pass unchanged. - Comments: the int64 sum says why it exists (exact in batch-invariant mode, where a float sum runs as mean * T). The DP-local comment no longer says BatchWise balances per microbatch. _RoutingOutputs gets a one-line docstring and per-field comments, and each local_compile kwarg its own comment. The batch-invariant cost is scoped to the inference graph it was measured on. REMAT.md and the GPT-OSS ROCm TODO match the code. - recompile_limit 32 -> 48, a real upper bound: 2 layer kinds x train or eval x grad on or off x padding or none x static, dynamic or 1-token T. The previous commit's "28 graphs in the worst call order" was wrong: eval calls with a padding mask (vLLM Dist-MoE) first give 29. - Tests: the 8-rank typecheck cases in test_aux_loss.py run the router region's statistics (_score_and_select_experts) instead of a copy of them. The bitwise batch-size test also runs the padded trainer graph. Deleted test_masked_routing_rows_do_not_affect_aux_loss: it only compared test helpers. The region's padding logic stays covered by test_moe.py::test_router_masks_padding_only_for_aux_loss, test_router_compile.py::test_flavor_routers_match_eager (padded subtests) and test_aux_loss.py::test_batch_wise_reduction_matches_reference (padded, 8 ranks).
…normalize, GPT-OSS ROCm TODO
The limit counts the graphs one process compiles. A vLLM generator compiles 6 (DeepSeek-V4: 2 router kinds x first T, other T, T = 1); a trainer with its validator compiles 4. The CPU test now checks those two processes with exact counts, instead of one process that runs every call kind (28 graphs, which no real job does).
Conflicts: tests/assets/losses/real_pg/a10g/{deepseek_v3_cp_pp,gpt_oss_pp}.txt
(#5563 refreshed them on main). Took main's side; CI regenerates them.
|
Reply from claude: New head 529bf75. Changes since your last review (you approved 5a3cb07):
Numerics of the one-region change:
Speed (DeepSeek-V3 router + aux loss, fwd+bwd, GB300, median of 3 interleaved processes, measured with #5574 merged): 208.6 -> 189.2 µs at 4096 tokens, 480.3 -> 443.4 µs at 16384. @claude please review. |
|
Claude finished @felipemello1's task in 3m 54s —— View job Approve -- please address the items below before merging (fill in the human-written summary; reply to tianyu-l's request for changes; push the remaining goldens; a maintainer still needs to review): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The one-region rewrite removes three helpers and the moe_aux_loss region, and keeps the aux-loss reductions and gradient injection. tianyu-l's request for changes still needs their re-review, and this is core MoE code, so a maintainer still needs to review it.
What changed since 5a3cb07. _score_and_select_experts now also returns this DP rank's per-expert counts and normalized-score sums, as fields of a _RoutingOutputs NamedTuple. Both aux losses take these two (E,) vectors instead of (scores_TE, routing_map_TE, padding_mask_T). The tokens_per_expert_E buffer gets a separate int sum. BatchWise reinterprets the DP-local counts as Partial over DP before its all-reduce. recompile_limit=16 is now justified by a CPU test that counts the graphs.
Example. One training forward, DeepSeek-V3, regions on:
before: gate -> [moe_router_topk: score, select, gather, norm, map]
-> eager: map & ~pad, int sum -> buffer
-> aux loss: [moe_aux_loss: cast+sum, normalize+sum] -> reduce -> inject
after: gate -> [moe_router_topk: ... map, int sum, fp32 counts, prob sums]
-> eager: buffer.add_(int sum); aux loss: reduce (E,) vectors -> inject
Earlier review
- Resolved: the upstream gate gap is now a
TODOwith thepytorch/pytorch#197381link (moe.py:367-368). - Answered: Qwen3.5 run-to-run nondeterminism. No tracking issue exists, and main is not bitwise with a fresh cache either.
- Still open: the GPT-OSS ROCm TODO has no tracking issue (
gpt_oss/model.py:238).
Must fix
- The "Summary (human-written)" section is still empty. Felipe, as the author, needs to fill it in.
- tianyu-l's CHANGES_REQUESTED ("regions are quite scattered ... have you considered wrapping bigger regions?") has no reply on its thread. The one-region change answers it in code. Reply there with the new layout (
moe.py+aux_loss.pynow have onelocal_compile). Also say why you didn't override the whole router config, the #5551 approach tianyu-l pointed to. Then ask for re-review. - Push the goldens this head still needs: A10G
gpt_oss.txtanddeepseek_v3_cp_pp.txt, and MI350Xdeepseek_v3_cp_pp.txt(Integration Tests (ROCm) fails at this head). CPU Unit Test and GPU Unit Tests show as skipped at 529bf75. Make sure they run on the final head: they cover the rewrittentest_aux_loss.pyreductions, the new graph-count test, andtest_router_compile.py.
Should consider
moe.py:413-423-- the comment says batch-invariant mode doesn't give exact float sums, yetlocal_counts_Eis a float sum in the same region. Explain which statement is right (inline).
Details
- Gate: unchanged from earlier reviews. The problem is real on main (an ATen
topkfallback and eager[T, E]sums), and the fix lives in the owning module. The PR shrinks the region surface instead of adding to it. - SPMD:
local_counts_Ewas summed insidespmd_local_context("dp"), so it is V over DP and Partial over CP/TP.BatchWisereinterprets V -> P over DP, then_reduce_token_partials(include_dp_axis=True). That matches main's typing, where the count was summed outside the DP-local context. Withdp == 1, both skip the reinterpret. - Callsites: no remaining references to
moe_aux_loss,_microbatch_load_balance_local_stats,_norm_sum_scores_over_tokensor_expert_counts. No subclass overridesforwardor callsaux_loss(...)with the old signature (DeepSeek-V3/V4, round-robin, quantile). DeepSeek-V4'sSparseIndexerLossis a separateAuxLossand is not affected. - Deleted test:
test_masked_routing_rows_do_not_affect_aux_loss. Padding masking moved into the router. It is still covered bytest_router_masks_padding_only_for_aux_loss(counts and prob sums under padding) and bytest_batch_wise_reduction_matches_reference(padding, typechecked). _statsintest_aux_loss.py: a copy of the router's statistics for the loss-only tests. The reduction tests use the real router, so drift in the router's code is still caught there.
Not verified: the claim that Inductor computes sums as mean * T under batch_invariant; tracing spmd_local_context("dp") inside the fullgraph region with dp > 1 (the graph-count test uses dp == 1; the author's FSDP 2 runs suggest it works).
| # Exact integer counts for the tokens_per_expert_E buffer: batch-invariant mode runs | ||
| # a float sum as mean * T, which isn't exact. Summed outside the DP-local context | ||
| # below, so they are Partial over DP, as the buffer is. | ||
| tokens_per_expert_E = valid_map_TE.sum(dim=0) | ||
| if self.aux_loss is not None: | ||
| if aux_loss_denominator is None: | ||
| raise ValueError("An auxiliary-loss denominator is required.") | ||
| topk_scores_TK = self.aux_loss( | ||
| scores_TE, | ||
| masked_routing_map_TE, | ||
| carrier=topk_scores_TK, | ||
| padding_mask_T=padding_mask_T, | ||
| denominator=aux_loss_denominator, | ||
| ) | ||
| return ( | ||
| # DP-local: each loss picks its own DP reduction. MicrobatchWise keeps DP ranks | ||
| # apart; BatchWise sums the counts over DP. | ||
| with spmd_local_context("dp"): | ||
| # Cast before summing: casting a Partial tensor is non-linear and | ||
| # rejected by spmd_types. | ||
| local_counts_E = valid_map_TE.to(scores_TE.dtype).sum(dim=0) |
There was a problem hiding this comment.
This comment and line 423 disagree. The comment says the region's batch-invariant mode computes a float sum as mean * T, which isn't exact. That is why tokens_per_expert_E uses an int sum. But local_counts_E (line 423) is a float sum in the same region. If the claim holds, the aux-loss counts aren't exact integers either whenever T isn't a power of two: RL's packed microbatches, or a CP/SP shard of uneven length. These counts feed f_E and BatchWise's rolling _cumulative_expert_counts_E, which adds them up over every microbatch in the step.
The effect is only rounding. Still, a reader can't tell which statement is right, and the tests can't settle it. TOKENS = 256 in test_router_compile.py, and the 16k checks also use a power of two, where mean * T is exact. Pick one:
- If the claim covers fewer sums than it says, write down which sums it covers.
- Otherwise, add a line at 423: under the compiled region the aux-loss counts are rounded to fp32, and only the buffer gets exact counts.
Unverified: I couldn't inspect how Inductor lowers sum under batch_invariant.
There was a problem hiding this comment.
Reply from claude: Both statements hold, in different places. Fixed the comment in cd90ad7.
set_batch_invarianceoverridesaten::sum.dim_IntListat the CUDA dispatch key withmean_dim(...) * T(torchtitan/distributed/batch_invariant.py). Only eager calls hit it. Inside the compiled region, Inductor lowerssumitself.- Probe in batch-invariant mode, one GPU, a
[T, 256]routing map with 8 picks per token:- eager fp32 sum: off by up to 7.6e-6 at T = 777, 3000 and 4095 (127 of 256 entries at T = 4095);
- compiled with
options={"batch_invariant": True}: exact integers at every T tried (777, 3000, 4095, 4096, 16383).
- So
local_counts_Eis exact in the region. It rounds only when the region runs eagerly in batch-invariant mode, and it only feeds the loss. The buffer gets the int sum in both cases.
… sums, not the compiled region) Probe in batch-invariant mode, GPU, [T, 256] map with 8 picks per token: an eager fp32 sum (mean * T override) is off by up to 7.6e-6 at T = 777, 3000, 4095. The compiled region with Inductor's batch_invariant option gives exact integers at every T tried.
…rged) Values copied from the "Baseline metrics in import file format" blocks; each file keeps its header lines, and tests that share a file printed equal values. A10G, this PR's router change on top of main (main 0d35b95 passes these, run 41949298464): - gpt_oss.txt (gpt_oss_fsdp+tp+ep): run 41972028044, job 127062299616 - gpt_oss_pp.txt, deepseek_v3_cp_pp.txt: run 41972026933, job 127062295743 (same values in run 41972028044, job 127062299616) MI350X: run 41972020032, job 127062288544. Main 0d35b95 fails the same 3 tests (run 41949298459): - llama3_pp.txt, gpt_oss_pp.txt: values equal to main's own run (main's change) - deepseek_v3_cp_pp.txt: main's change plus this PR's
…6 goldens) into felipemello1/deepep/expand-training
|
Claude finished @felipemello1's task in 2m 29s —— View job Approve -- please address the items below before merging (fill in the human-written summary; reply to tianyu-l's request for changes; get the unit tests to run, since they are skipped while the PR is a draft; split out the two MI350X goldens that come from main's own drift; a maintainer still needs to review): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The two new commits are a correct comment fix and golden refreshes. The open items are process items: the summary, tianyu-l's request for changes, unit tests that never ran, and two goldens that belong to main. This is core MoE code, so a maintainer still needs to review it.
What changed since 529bf75.
- cd90ad7: the comment above
tokens_per_expert_Enow says which sums round. Only eager float sums in batch-invariant mode round:_sum_dim_batch_invariantreturnsmean_dim(...) * num_reduced_elementsfor fp16/bf16/fp32 (batch_invariant.py:59-62), and it computes int and bool sums with acumsumscan. The compiled region sums exactly, and the fp32 aux-loss counts only feed the loss. The comment matches the code. - 34f5820: 6 real-PG goldens. A10G
gpt_oss.txtstep 1 moves 4.4e-6 relative in loss and 1.2e-5 in grad norm. Later steps diverge further (step 5 grad norm 6.29 -> 7.15), as expected for a 10-step debug run after a rounding change at step 1.
Example. Which goldens come from which change:
A10G gpt_oss, gpt_oss_pp, deepseek_v3_cp_pp this PR (main 0d35b9599 passes them)
MI350X deepseek_v3_cp_pp main's drift + this PR
MI350X llama3_pp, gpt_oss_pp main's drift only (dense model; GPT-OSS regions off on ROCm)
Earlier review
- Resolved: the
moe.py:413-423comment vs float sum (cd90ad7). - Resolved: A10G
gpt_oss.txt/deepseek_v3_cp_pp.txtand MI350Xdeepseek_v3_cp_pp.txtare pushed. Integration Tests (A10G, H100, B200, ROCm, RL) pass at 34f5820. - Still open: the GPT-OSS ROCm TODO has no tracking issue (
gpt_oss/model.py:238).
Must fix
- The "Summary (human-written)" section is still empty. Felipe, as the author, needs to fill it in.
- tianyu-l's CHANGES_REQUESTED (2026-11-04, "regions are quite scattered ... have you considered wrapping bigger regions?") still has no reply on its thread. Reply with the one-region layout and why the whole router config isn't overridden (the #5551 approach). Then ask for re-review.
- The unit tests have never run in CI on this PR. The PR is a draft, and
set-matrix.yamlskipspull_requestjobs for drafts, so1 GPU Unit Tests,Multi-GPU Unit Testsand the CPU unit tests show as skipped at 34f5820. Only the ciflow-label jobs ran. Mark the PR ready for review (or trigger the workflows) sotest_router_compile.py,test_router_compile_regions.py,test_aux_loss.pyand the newtest_remat.pycase run on the final head. tests/assets/losses/real_pg/mi350x/llama3_pp.txt:9-- this golden andmi350x/gpt_oss_pp.txtfix main's MI350X CI, not this PR's numerics. Move them to a separate CI-fix PR, or at least list them in the description (details inline).
Details
- Gate: unchanged from earlier reviews. These two commits add no logic.
- Golden list in the description: it says "10 re-recorded" and lists A10G real PG (5), A10G fake PG (2) and MI350X (3). The diff now touches 12 golden files. The extra two are
mi350x/gpt_oss_pp.txtandmi350x/llama3_pp.txt. - Bitwise claim: the earlier update said the one-region rewrite is bitwise equal to the previous region on GB300. The A10G
gpt_oss.txtrefresh shows it is not bitwise on A10G (step-1 grad norm 1.2e-5 relative). That is rounding and fits the description's numerics section. Still, the description should not suggest that the one-region change is bitwise on every GPU.
| 5 5.075322151184082 2.458505153656006 | ||
| 6 4.709461688995361 2.2392613887786865 | ||
| 7 4.471437931060791 1.9792442321777344 | ||
| 8 4.387261390686035 1.8555552959442139 | ||
| 9 4.382673263549805 1.6735212802886963 | ||
| 10 4.196091651916504 1.691859245300293 |
There was a problem hiding this comment.
This PR doesn't touch Llama 3: it's a dense model with no router. Your commit message says these values (and mi350x/gpt_oss_pp.txt, where GPT-OSS on ROCm keeps the regions off) equal main 0d35b95's own output, and main fails the same tests (run 41949298459). So these two files fix main's MI350X CI, not this PR's numerics. The PR description's golden list ("10 re-recorded") doesn't name them either.
Mixing them in makes it hard to tell which golden moves come from the router. They will also conflict with whoever refreshes main's MI350X PP goldens. Please move mi350x/llama3_pp.txt and mi350x/gpt_oss_pp.txt into a separate CI-fix PR (like #5557) and land it first. If you keep them here, list them in the description's Goldens note as main's drift, separate from this PR's.
Reuse the shared router implementation from Felipe Mello in PR pytorch#5343, keeping the existing model defaults and numerical reference files. Keep state updates and auxiliary-gradient injection outside the fused boundary, and preserve the existing moe_aux_loss region through a shared statistics helper. Cover masks, statistics, graph counts, gradients and full-size router flavors.
Summary (human-written)
Agent details
TLDR: When compiled, the MoE router runs scoring and top-k selection in one fused kernel. Its load-balance sums move into a compiled region.
Numerics: rounding only. In one MoE layer, compiling main already moves the output and grads by some rounding. This PR moves them at most half as much (Kimi K3), and about a tenth as much or less for the other 7 models. End to end, step 1 stays within 1.6x of main's own change, except Kimi K3: its loss and 4 changed expert picks (main: 0).
Speed (Qwen3.5-35B-A3B, GB300): the router is 41-63% faster at inference and 49-52% faster in fwd+bwd. The whole MoE layer is 3.4-3.6% faster in fwd+bwd.
Stack (merge bottom-up): this is PR 1 of 4. PR 3 (group-limited routing with argmax rounds) needs it. PR 2 (shared experts on a side stream) and PR 4 (DeepEP expand-layout training) are independent.
Problem
torch.topk.topk: it runs a separate ATen kernel.[T, 256]tensors in eager.Solution
_topk_ids_by_argmax). The rounds fuse with the softmax. Eager keepstopk.Example: scores [0.1, 0.9, 0.5, 0.9], k = 2. Pick 1: expert 1 (it ties with expert 3; the lower id wins). Pick 2: expert 3.
topkmakes no promise on ties.moe_router_topkon_score_and_select_experts: score, select, gather, normalize, routing map. A region is a function thatlocal_compilecompiles. With Inductor'sbatch_invariantoption, it gives a token the same result at T = 1 to 16k.moe_aux_lossregion.tokens_per_expert_E), the aux-loss gradient and the collectives stay eager.forwardreturns the same 3 tensors.Results
Numerics: not bitwise vs main. Every difference is rounding.
Why the numbers move:
route_normadds them in another order: same experts, scores 1.5e-8 apart.How big. One MoE layer at real size, T = 4096, both regions on, local experts. rel L2 = ||this PR - main|| / ||main||.
Yardstick = the rel L2 of main eager vs main compiled, the rounding main already accepts, floored at one bf16 rounding (1.7e-3).
Every model and layout: all 44 layer cells (4 dispatch layouts, training and inference) are at most 0.5x the yardstick. End to end (step 1, 3 parallelisms): at most 1.6x, except Kimi K3: its loss and 4 changed expert picks (main: 0).
Kimi K3's step-1 loss moves 6.6e-5 (FSDP 2 x EP 2) and 9.6e-6 (TP 2 x EP 2) relative to main. Main's own changes move the other models' step-1 loss by 7e-6 to 1.5e-4: the same size.
It is 18x and 83x K3's own yardstick only because that yardstick is near zero: compiling main changes nothing in K3's first 4-8 MoE layers.
Grid: 9 models x 4 layer layouts and 3 end-to-end parallelisms
Training (the Loss line): 10 steps, FSDP 2 x TP 2 (SP) x EP 2, 4x GB300, 8 debug models (Kimi K2.5: FSDP 4 x EP 4; Muse Spark: remat off).
Memory: same as main. Activations kept for backward are equal or 1-2 MiB lower in all 22 training layer cells (T = 4096 and 16384). Peak memory is equal.
Speed (GB300, CUDA graphs, default regions, µs per MoE layer, main -> this PR, torch 2.16.0.dev20261030)
You may ask:
batch_invariant? It keeps the region from adding its own batch-size dependence. Without it, the region gave a token other outputs at small T than at 16k in 4 of 7 runs (with it: 0 of 7). The gate GEMM before it is still not batch-invariant. Cost: up to 3.8 µs per MoE layer at decode, at most 1.9% of the whole layer (Qwen3, DeepEP EP 2, T = 1: 2.1 of 113 µs), within run-to-run noise from 4k tokens. Small, so kept on.inplace_wgrad_accum=Trueraises. With it off, compile rounds its fp32 weight grad to bf16 under FSDP2 (fix open: [Dynamo] Preserve leaf gradient dtype through compiled backward pytorch#197381). Counter, aux-loss accumulators, K3's histogram: they update buffers. Remat replays the region, so an update inside would need anis_recomputing()guard, and that guard makes Dynamo compile a second graph.topkuntil stack PR 3). Kimi K3 (top 16 of 896): decode 48-63%, prefill 38-58%, fwd+bwd 13-14%.NOTE:
real_pg/mi350x/llama3_pp.txtandreal_pg/mi350x/gpt_oss_pp.txttake main 0d35b95's own values (main fails the same tests, run 41949298459). Llama 3 has no router, and GPT-OSS on ROCm keeps main's regions. They can move to a separate CI-fix PR if main fixes them first.inplace_wgrad_accum=False). TODO atmoe.py:359.b832ae419except the 10-step runs (vsad7a9937b). Speed: this head. Grid, memory:b1f079b6e(later commits: comments, goldens, names). All on GB300. CI also runs H100, A10G, MI350X.Test plan
pytest tests/unit_tests/gpu/models/common/test_router_compile.py tests/unit_tests/cpu/models/common/test_router_compile_regions.pypytest tests/unit_tests/gpu/distributed/test_remat.py -k "router or quantile"apply()accepts every region each MoE model lists.test_aux_loss.py+test_router_compile_regions.py20 passed (CPU);test_router_compile.py+test_remat.py24 passed (1 GB300).