Skip to content

[moe][perf] Compile the MoE router and its load-balance sums - #5343

Draft
felipemello1 wants to merge 28 commits into
mainfrom
felipemello1/qwen35-router
Draft

felipemello1 wants to merge 28 commits into
mainfrom
felipemello1/qwen35-router

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

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.

before:  gate GEMM -> softmax -> topk (ATen) -> gather + norm -> [T, E] sums (eager)
after:   gate GEMM -> [softmax + argmax rounds] [gather + norm] -> [expert counts + score sums]
                      moe_router_topk region (3 kernels for Qwen3.5)  moe_aux_loss region

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

  1. The Qwen3.5 router picks 8 of 256 experts per token with torch.topk.
  2. Inductor can't fuse topk: it runs a separate ATen kernel.
  3. The load-balance loss sums two [T, 256] tensors in eager.
  4. Cost. Qwen3.5's router takes 691 µs per MoE layer fwd+bwd at 16k tokens, and 30-58 µs at decode.

Solution

  1. Argmax rounds. The compiled router picks the k best experts one at a time: take the highest score, then hide it (_topk_ids_by_argmax). The rounds fuse with the softmax. Eager keeps topk.
    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. topk makes no promise on ties.
  2. New region moe_router_topk on _score_and_select_experts: score, select, gather, normalize, routing map. A region is a function that local_compile compiles. With Inductor's batch_invariant option, it gives a token the same result at T = 1 to 16k.
  3. Load-balance sums move into the existing moe_aux_loss region.
  4. On by default for the 8 models on the shared router (GPT-OSS not on ROCm, see NOTE).
  5. Unchanged: the gate GEMM, the per-expert token counter (tokens_per_expert_E), the aux-loss gradient and the collectives stay eager. forward returns the same 3 tensors.

Results

Numerics: not bitwise vs main. Every difference is rounding.

  • Layer: at most 0.5x main's own compile change for Kimi K3, about 0.1x or less for the other 7 models (table below).
  • Loss: in every FSDP and TP run, the step-1 loss differs from main by at most 6.6e-5 relative (Kimi K3). Main's own rounding changes (eager vs compiled, or all-to-all vs DeepEP) move it by up to 1.5e-4 (Muse Spark). In the 10-step runs it is identical for Qwen3.5, DeepSeek-V3, DeepSeek-V4 and Kimi K2.5.
  • Bitwise: regions off vs main (all but Kimi K3); a token's region output at T = 1 to 16k; grads with and without remat (recomputing activations in backward).

Why the numbers move:

  1. Scores. The compiled softmax or sigmoid rounds differently (fp32). Max |diff| vs main, same experts: Qwen3.5 4.5e-8, DeepSeek-V3 1.2e-7, Kimi K3 2.2e-8.
  2. Expert ids. A score that moved one rounding step can swap two near-tied experts. One router, T = 1 to 32k: Qwen3.5 0 tokens, DeepSeek-V3 1 of 16k, Kimi K3 2 of 8k and 1 of 32k.
  3. Grads. The backward of scoring, gather and normalization is compiled too.
  4. Kimi K3, regions off only. Its quantile router returns its picks unsorted (main: sorted), so route_norm adds 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).

               rel L2, this PR vs main              yardstick: main eager vs compiled
model          output  input grad  worst w. grad    output   input grad  worst w. grad
Qwen3 30B      2.6e-5  1.3e-4      1.1e-4           5.5e-3   5.5e-3      4.2e-3
Qwen3.5 35B    1.5e-5  9.3e-5      9.5e-5           5.4e-3   6.1e-3      6.3e-3
DeepSeek-V3    2.1e-5  1.2e-4      1.1e-4           5.2e-3   5.2e-3      4.3e-3
Kimi K2.5      2.0e-5  1.1e-4      8.8e-5           5.3e-3   5.3e-3      4.3e-3
Kimi K3        1.3e-4  5.1e-4      1.3e-3           1.7e-3*  2.0e-3      2.6e-3
GPT-OSS 120b   2.7e-5  1.3e-4      1.8e-4           5.1e-3   5.6e-3      8.5e-3
DeepSeek-V4    1.7e-5  8.8e-5      9.6e-5           4.7e-3   4.8e-3      4.3e-3
Muse Spark     6.8e-5  1.9e-4      6.1e-4           6.3e-3   6.6e-3      6.5e-3
* the floor. Measured: 4.9e-4 (compiling main barely changes Kimi K3).

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
Cell = worst rel L2 vs main / yardstick. "=" bitwise. "-" not run (path unchanged). a2a = all-to-all.
L: the layer above, train (eager and compiled) or inference (CUDA graph at T = 1 / 64 / 2048; eager for a2a).
E: debug flavor through the trainer, step 1: loss, grad norm, worst non-MoE grad, expert flips. Yardstick: max of
   main eager vs compiled and main a2a vs DeepEP. Tensors floored at 1.7e-3. Loss and grad norm not floored.
   Muse Spark: remat off (main crashes with it).

                    Qwen3 Qwen3.5  DSv3 DSv3grp Kimi2.5 KimiK3 GPT-OSS  DSv4  Muse
L DeepEP EP2 train  <0.1x  <0.1x  <0.1x      -   <0.1x   n/a1    n/a2 <0.1x  n/a3
L DeepEP EP2 graph  <0.1x      =      =      -       =   n/a1    n/a2     =  n/a3
L DeepEP EP4 train      -      -      -      -       -   0.1x       -     -     -
L DeepEP EP4 graph      -      -      -      -       -  <0.1x       -     -     -
L a2a EP2 train     <0.1x  <0.1x  <0.1x      -   <0.1x   0.5x   <0.1x <0.1x  0.1x
L a2a EP2 infer     <0.1x  <0.1x  <0.1x      -   <0.1x   0.1x   <0.1x <0.1x <0.1x
L local EP1 train   <0.1x  <0.1x  <0.1x      -   <0.1x   0.5x   <0.1x <0.1x  0.1x
L local EP1 graph   <0.1x  <0.1x  <0.1x      -   <0.1x   0.1x   <0.1x <0.1x <0.1x
E FSDP2xEP2 a2a      0.6x  <0.1x   0.2x   0.3x   <0.1x   18x*    0.5x <0.1x  0.3x
E TP2xEP2 a2a        0.9x  <0.1x   0.2x   0.2x    n/a4   83x*    0.3x <0.1x  0.3x
E PP2 a2a            1.6x  <0.1x   0.2x   0.4x    0.4x   0.5x    0.5x  n/a5 <0.1x

DSv4: layer 3. DSv3grp: 64 experts, 8 groups, 4 kept. EP4: 4 GPUs, others 2. n/a1: DeepEP holds at most 256
experts per rank. n/a2: DeepEP needs hidden % 256 == 0. n/a3: no DeepEP path. n/a4: recipe rejects TP. n/a5: no PP.
*Kimi K3. Compiling main changes nothing in its first 4-8 of 16 MoE layers.
 So its loss yardstick is near zero: 3.6e-6 (FSDP2xEP2), 1.2e-7 (TP2xEP2).
 This PR moves layer 0's scores by 1.2e-7. At the last layer, the MoE output is 2.9e-3 from main, vs 2.8e-3 for
 compiling main (TP2xEP2).
 Step-1 loss vs main: 6.6e-5 (FSDP2xEP2, 4 of 16384 near-tie picks changed), 9.6e-6 (TP2xEP2, none changed).
 Worst non-MoE grad: layers.0.ffn_res_proj, a near-zero tensor (norm 4e-5; the total grad norm is about 1).
 This PR moves it 39%. Compiling main moves it 25-31%.

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

  • Step-1 grad norm: within 3.7e-5 relative of main (Kimi K3's is logged in bf16).
  • Routers whose input equals main's (layer 0 always) pick the same experts.
  • Run twice: bitwise, except GPT-OSS (main isn't either) and Qwen3.5.
  • Qwen3.5 with a fresh compile cache: 4 different loss curves in 5 plain runs on this PR, 2 in 7 on main. With debug env flags added, this PR gave 9 in 26. On this PR, the first difference is in the vision encoder's grads.

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)

router = gate GEMM + scoring + selection + per-expert token count (`routing_map.sum(0)`). No expert bias (Qwen3.5 has none).
                                  T        main     this PR   delta
Qwen3.5 router, decode            1        29.9     12.4      -58%
                                  64       33.0     18.7      -43%
                                  1024     57.6     29.5      -49%
Qwen3.5 router, prefill           16384   261.9     97.6      -63%
Qwen3.5 router, fwd+bwd           16384   691.1    350.0      -49%
                                  32768  1197.8    572.4      -52%
Qwen3.5 MoE layer, fwd+bwd, EP 1  16384  8531.9   8220.9      -3.6%
                                  32768 16152.7  15596.0      -3.4%
Qwen3.5 MoE layer, decode,        1       153      134        -13%
  DeepEP EP 2                     64      313      293    -4 to -7%

You may ask:

  • Why 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.
  • Why do the gate, counter and aux loss stay eager? Gate: traced, its default inplace_wgrad_accum=True raises. 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 an is_recomputing() guard, and that guard makes Dynamo compile a second graph.
  • Other routers? DeepSeek-V3: decode 26-33% faster, prefill 1-21%, fwd+bwd 5-8% (its group selection keeps topk until stack PR 3). Kimi K3 (top 16 of 896): decode 48-63%, prefill 38-58%, fwd+bwd 13-14%.

NOTE:

  • Goldens: 10 re-recorded. A10G real PG: qwen3, gpt_oss, gpt_oss_pp, deepseek_v3, deepseek_v3_cp_pp. A10G fake PG: qwen3, gpt_oss. MI350X: qwen3, deepseek_v3, deepseek_v3_cp_pp. Step-1 loss moves at most 6.1e-6 relative.
  • Main's MI350X drift, not this PR: real_pg/mi350x/llama3_pp.txt and real_pg/mi350x/gpt_oss_pp.txt take 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.
  • Follow-up: when [Dynamo] Preserve leaf gradient dtype through compiled backward pytorch#197381 lands, try the gate inside the region (inplace_wgrad_accum=False). TODO at moe.py:359.
  • GPT-OSS on ROCm keeps main's regions (TODO in its config): its MI350X CI loss varied run to run with them. Qwen3 MoE, same router, matched its golden.
  • GraphTrainer: CI's B200 lane (DeepSeek-V3 MoE) passes. It should trace the eager path: no speedup. Numerics vs main not compared.
  • Trees: all vs main b832ae419 except the 10-step runs (vs ad7a9937b). 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.py
pytest tests/unit_tests/gpu/distributed/test_remat.py -k "router or quantile"

  • 5 production routers (Qwen3.5, DeepSeek-V3, Kimi K2.5, Muse Spark, Kimi K3): compiled vs eager fwd+bwd (grads rel L2 < 1e-3), and the bitwise batch-size check (T = 1, 3, 34, 256, 16k).
  • Remat, region on: the histogram records once, and grads with and without remat are bitwise equal.
  • CPU: apply() accepts every region each MoE model lists.
  • Ran at 34f5820 (the PR is a draft, so CI skips these): test_aux_loss.py + test_router_compile_regions.py 20 passed (CPU); test_router_compile.py + test_remat.py 24 passed (1 GB300).

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 12, 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 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 force-pushed the felipemello1/qwen35-router branch from 05fad9a to 60a7dda Compare October 14, 2026 03:24
@felipemello1 felipemello1 changed the title [qwen3.5][perf] Compile the MoE router and its load-balance sums [qwen3.5][perf] Compile the MoE router and its load-balance sums (6/7) Oct 14, 2026
@felipemello1
felipemello1 changed the base branch from main to felipemello1/gen-perf/6-mamba-state-copy October 14, 2026 03:24
@felipemello1
felipemello1 added this pull request to stack #5388 October 14, 2026 03:25
Comment thread torchtitan/models/common/moe.py Resolved
Comment thread torchtitan/models/common/moe.py Resolved
Comment thread torchtitan/models/common/moe/moe.py Resolved
@felipemello1

Copy link
Copy Markdown
Contributor Author

Follow-up after this lands: Muse Spark doesn't enable the router region yet; it needs a one-line addition to MuseSparkModel.Config.local_compile_regions. At Muse Spark's 256-expert router width: 245 -> 169 us per layer at 4k, 651 -> 441 us at 16k (CUDA graphs).

@felipemello1 felipemello1 changed the title [qwen3.5][perf] Compile the MoE router and its load-balance sums (6/7) [qwen3.5][perf] Compile the MoE router and its load-balance sums (6/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/gen-perf/6-mamba-state-copy to main October 18, 2026 04:16
@felipemello1
felipemello1 force-pushed the felipemello1/qwen35-router branch from 96c058e to b967fe4 Compare October 18, 2026 04:18
@felipemello1 felipemello1 changed the title [qwen3.5][perf] Compile the MoE router and its load-balance sums (6/9) [qwen3.5][perf] Compile the MoE router and its load-balance sums Oct 18, 2026
@felipemello1
felipemello1 added this pull request to stack #5519 October 19, 2026 02:17
@felipemello1
felipemello1 removed this pull request from stack #5519 October 19, 2026 06:46
@felipemello1
felipemello1 added this pull request to stack #5532 October 19, 2026 06:48
@felipemello1 felipemello1 changed the title [qwen3.5][perf] Compile the MoE router and its load-balance sums [moe][perf] Compile the MoE router and its load-balance sums Oct 19, 2026
@felipemello1
felipemello1 removed this pull request from stack #5532 October 19, 2026 07:18
@felipemello1
felipemello1 force-pushed the felipemello1/qwen35-router branch from 72b43ba to 1b6831e Compare October 19, 2026 07:18
@felipemello1
felipemello1 changed the base branch from main to felipemello1/moe/7-shared-experts-side-stream October 19, 2026 07:19
@felipemello1
felipemello1 added this pull request to stack #5534 October 19, 2026 07:19
@felipemello1 felipemello1 changed the title [moe][perf] Compile the MoE router and its load-balance sums [moe][perf] Compile the MoE router and its load-balance sums (3/3) Oct 19, 2026
@felipemello1
felipemello1 force-pushed the felipemello1/qwen35-router branch from 5d29be6 to 352824c Compare October 20, 2026 08:17
"moe_router_topk",
batch_invariant=True,
recompile_limit=16,
options={"batch_invariant": True},

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.

why passing this again?

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: 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():

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.

why this check?

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: 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).

@tianyu-l tianyu-l Nov 4, 2026 •

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.

The optimized regions are quite scattered in this file, to an extent that readability is affected. Have you considered wrap bigger regions?

E.g. in @ydwu4 's work #5551, DeepSeekV3Router.Config and RoundRobinTokenChoiceTopKRouter.Config are being overridden in their entirety.

Felipe Mello added 7 commits November 3, 2026 18:33
… 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).
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).
From the "Baseline metrics in import file format" block of this PR's
ciflow/rocm run 41931019311 on 2b9e149 (models job). The same values
came out at 8517e38. Steps 1-4 are unchanged; steps 5-10 move by
about 5e-6 relative.
@felipemello1
felipemello1 marked this pull request as draft November 5, 2026 05:03
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.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: New head 529bf75. Changes since your last review (you approved 5a3cb07):

  1. One compiled region per router call (5ccb62d, review fixes 3a0498e). moe_router_topk now also returns this DP rank's per-expert counts and normalized-score sums (train mode, padding rows excluded).
    • The tokens_per_expert_E counter gets exact integer counts.
    • The aux losses take two (E,) vectors. They keep the rank reductions, the formula and the gradient injection.
    • Removed: the moe_aux_loss region, _expert_counts, _microbatch_load_balance_local_stats, AuxLoss._norm_sum_scores_over_tokens, and the second eager count in forward.
    • moe.py + aux_loss.py now have one local_compile, as on main.
  2. recompile_limit=16, counted per process (2b9e149). DeepSeek-V4 compiles at most 6 router graphs in a generator, and 4 in a trainer with its validator. test_router_compile_regions.py checks both counts exactly.
  3. Comments only (b692e45, e75975b, 127bc14, 8517e38): the TODO for pytorch/pytorch#197381 you asked for, why eager keeps topk, the two batch_invariant flags, measured graph counts, the eps note next to F.normalize, the GPT-OSS ROCm TODO.
  4. Merged main 0d35b95 (529bf75). Conflicts only in 2 A10G PP goldens that main refreshed in #5563. I took main's side.
  5. Goldens. MI350X deepseek_v3.txt steps 5-10 refreshed (eb46053). This head's failing goldens get refreshed from its CI run once the A10G jobs finish.
    • Expected from the run on eb46053 (41936441455): A10G gpt_oss.txt (step-1 grad norm 1.2e-5 relative) and deepseek_v3_cp_pp.txt (from step 9).
    • MI350X fails 3 PP tests at this head. Main 0d35b95 fails the same 3. gpt_oss_pp and llama3_pp match main's values exactly. deepseek_v3_cp_pp also moves from this PR.

Numerics of the one-region change:

  • GB300: bitwise equal to the previous region. 27 of 27 tensors match: expert ids, weights, d(logits) and dispatcher counts, at 1 to 16k tokens.
  • MI350X: deepseek_v3_fsdp+ep steps 1-4 are unchanged. Step 5 moves 4.9e-6 relative in loss.

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

claude Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

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

@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: 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 TODO with the pytorch/pytorch#197381 link (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

  1. The "Summary (human-written)" section is still empty. Felipe, as the author, needs to fill it in.
  2. 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.py now have one local_compile). Also say why you didn't override the whole router config, the #5551 approach tianyu-l pointed to. Then ask for re-review.
  3. Push the goldens this head still needs: A10G gpt_oss.txt and deepseek_v3_cp_pp.txt, and MI350X deepseek_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 rewritten test_aux_loss.py reductions, the new graph-count test, and test_router_compile.py.

Should consider

  • moe.py:413-423 -- the comment says batch-invariant mode doesn't give exact float sums, yet local_counts_E is 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 topk fallback 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_E was summed inside spmd_local_context("dp"), so it is V over DP and Partial over CP/TP. BatchWise reinterprets 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. With dp == 1, both skip the reinterpret.
  • Callsites: no remaining references to moe_aux_loss, _microbatch_load_balance_local_stats, _norm_sum_scores_over_tokens or _expert_counts. No subclass overrides forward or calls aux_loss(...) with the old signature (DeepSeek-V3/V4, round-robin, quantile). DeepSeek-V4's SparseIndexerLoss is a separate AuxLoss and is not affected.
  • Deleted test: test_masked_routing_rows_do_not_affect_aux_loss. Padding masking moved into the router. It is still covered by test_router_masks_padding_only_for_aux_loss (counts and prob sums under padding) and by test_batch_wise_reduction_matches_reference (padding, typechecked).
  • _stats in test_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).

Comment thread torchtitan/models/common/moe/moe.py Outdated
Comment on lines +413 to +423
# 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)

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

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: Both statements hold, in different places. Fixed the comment in cd90ad7.

  • set_batch_invariance overrides aten::sum.dim_IntList at the CUDA dispatch key with mean_dim(...) * T (torchtitan/distributed/batch_invariant.py). Only eager calls hit it. Inside the compiled region, Inductor lowers sum itself.
  • 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_E is 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.

Felipe Mello added 2 commits November 4, 2026 23:26
… 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
felipemello1 pushed a commit that referenced this pull request Nov 5, 2026
…outer comment, 6 goldens) into felipemello1/dsv3-group-argmax
felipemello1 pushed a commit that referenced this pull request Nov 5, 2026
…6 goldens) into felipemello1/deepep/expand-training
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review again. Since your approval on 529bf75, head 34f5820:

  • cd90ad7: the router comment now says which sums batch-invariant mode rounds (eager float sums, not the compiled region), per your moe.py:423 note.
  • 34f5820: 6 real-PG goldens refreshed from CI on 529bf75 (main 0d35b95 merged).

@claude

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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

@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: 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_E now says which sums round. Only eager float sums in batch-invariant mode round: _sum_dim_batch_invariant returns mean_dim(...) * num_reduced_elements for fp16/bf16/fp32 (batch_invariant.py:59-62), and it computes int and bool sums with a cumsum scan. 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.txt step 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-423 comment vs float sum (cd90ad7).
  • Resolved: A10G gpt_oss.txt / deepseek_v3_cp_pp.txt and MI350X deepseek_v3_cp_pp.txt are 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

  1. The "Summary (human-written)" section is still empty. Felipe, as the author, needs to fill it in.
  2. 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.
  3. The unit tests have never run in CI on this PR. The PR is a draft, and set-matrix.yaml skips pull_request jobs for drafts, so 1 GPU Unit Tests, Multi-GPU Unit Tests and 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) so test_router_compile.py, test_router_compile_regions.py, test_aux_loss.py and the new test_remat.py case run on the final head.
  4. tests/assets/losses/real_pg/mi350x/llama3_pp.txt:9 -- this golden and mi350x/gpt_oss_pp.txt fix 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.txt and mi350x/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.txt refresh 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.

Comment on lines +9 to +14
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

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

elfiegg pushed a commit to elfiegg/torchtitan that referenced this pull request Nov 25, 2026
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.

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/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/h100.8 Trigger H100.8 CI ciflow/real-pg Run the full 8-GPU Real PG integration suite ciflow/rl ciflow/rocm 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.

3 participants