Skip to content

[moe][perf] Skip the per-expert token count in backends that don't read it (1/3) - #5516

Merged
felipemello1 merged 2 commits into
mainfrom
felipemello1/moe/6-skip-unused-count
Oct 27, 2026
Merged

felipemello1 merged 2 commits into
mainfrom
felipemello1/moe/6-skip-unused-count

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

TLDR: Only the token dispatchers that read the per-expert count now sum the routing map, so Dist-MoE, DeepEP and HybridEP skip one reduction per MoE layer (Qwen3.5-35B-A3B, Dist-MoE decode: -4.4 to -6.8% per layer, bitwise identical).

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

# PR Independent? Needs (stack positions)
1 Skip the per-expert token count in backends that don't read it yes —
2 Compile the MoE router and its load-balance sums yes —
3 Group-limited routing with argmax rounds in the compiled router no 2

Problem

  1. MoE.forward sums the (T, E) routing map into per-expert counts (routing_map_TE.sum(dim=0)) and passes them to the routed experts.
  2. Only the Local, AllToAll and TorchAO token dispatchers read them.
  3. DistMoeRoutedExperts.forward and the DeepEP and HybridEP dispatchers work from the expert ids and delete the counts unread.
  4. Cost: one reduction per MoE layer for nothing, 6.8-12.0 us per layer at decode with Dist-MoE.

Solution

  1. MoE, KimiLatentMoE and MuseSparkMoE pass the router's routing_map_TE to the routed experts instead of summing it.
  2. RoutedExperts.forward passes it on to token_dispatcher.dispatch: the Local, AllToAll and TorchAO dispatchers sum it; DeepEP and HybridEP delete it.
  3. DistMoeRoutedExperts.forward deletes it (its MXFP8 and LoRA variants inherit that).
  4. The count is now summed inside the routed experts' local SPMD region, so it is already local: the two mutate_type(P -> V) calls in the Local and AllToAll dispatchers go away.
  5. Unchanged: the stock dispatch kernels (the same sum, now inside dispatch) and the router's load-balance statistics (tokens_per_expert_E, aux loss).

Results

Numerics: bitwise identical.
- Dist-MoE: the MoE block's output on each of 4 ranks at T = 32 / 64 / 256, before vs after (12/12).
- Stock all-to-all dispatch, TP 2 x EP 2 on 2 CPU ranks (gloo), SP off and on: forward output, input grad,
  all parameter grads and the router's token counts equal main (32/32 tensors).

Qwen3.5-35B-A3B MoE block (router + Dist-MoE routed experts + inline shared experts), EP 4 on 4 GB300,
8 layers, CUDA graphs, decode (no grad), min of 2 interleaved processes, us per layer.
Timed on an earlier revision of this PR, whose Dist-MoE path also launched no sum (same kernels).
T per GPU    before    after    delta
32            153.2    146.4    -6.8  (-4.4%)
64            158.2    150.0    -8.2  (-5.2%)
256           177.4    165.4   -12.0  (-6.8%)

NOTE:

  • Not measured: end to end, prefill, training, DeepEP and HybridEP.
  • Under GraphTrainer the sum's node is now labeled {"EP": "dispatch"} instead of MoE.forward's {"EP": "compute"}. No pass reads that label; the EP overlap pass keys on the token-exchange annotations.
  • Not run: the typechecked GPU integration tests, and the TorchAO padded-dispatch GPU test (needs torchao).

You may ask:

  • Why sum in three dispatchers, not once in RoutedExperts.forward? DeepEP and HybridEP would still sum and throw it away.
  • Why pass the map, not derive the count from topk_expert_ids_TK? That adds a new kernel (a scatter_add) to the stock training path; summing the map keeps the kernel it runs today.

Test plan

  • pytest tests/unit_tests/cpu/models/common/test_moe.py -k routing_map: MoE, KimiLatentMoE and MuseSparkMoE hand the routed experts the (T, E) bool map; fails if a caller sums again.
  • CPU MoE suites: test_moe.py, test_dist_moe.py, test_aux_loss.py, recipes/test_inference_moe.py, models/kimi_k3, models/muse_spark. The 2 MXFP8 recipe tests need torchao.
  • The GPU tests that called the routed experts or dispatch with a count now pass a map, and pass on 2 GB300: gpu/models/common/test_dist_moe.py (stock vs Dist-MoE parity), test_quantile_balance.py, gpu/distributed/test_remat.py, test_remat_all_to_all.py (TorchAO case not run: no torchao), test_deepep_activation_checkpoint.py.
  • pytest torchtitan/experiments/graph_trainer/tests/test_passes.py -k "ep_overlap or moe_ep": the EP annotation and overlap-pass tests pass.
  • SPMD typechecker, 2 CPU ranks (gloo): the parallelized stock routed experts run a typechecked forward with EP 2 (all-to-all) and EP 1 (local fallback, DP 2); outputs equal main.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 19, 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 changed the base branch from felipemello1/moe/5-tp-token-split-check to main October 19, 2026 06:46
@felipemello1
felipemello1 force-pushed the felipemello1/moe/6-skip-unused-count branch from ff6017e to ea6129d Compare October 19, 2026 06:47
@felipemello1
felipemello1 changed the base branch from main to felipemello1/moe/5-tp-token-split-check October 19, 2026 06:48
@felipemello1
felipemello1 added this pull request to stack #5532 October 19, 2026 06:48
@felipemello1
felipemello1 removed this pull request from stack #5532 October 19, 2026 07:18
@felipemello1
felipemello1 changed the base branch from felipemello1/moe/5-tp-token-split-check to main October 19, 2026 07:18
@felipemello1
felipemello1 force-pushed the felipemello1/moe/6-skip-unused-count branch from ea6129d to 9266852 Compare October 19, 2026 07:18
@felipemello1
felipemello1 added this pull request to stack #5534 October 19, 2026 07:19
@felipemello1 felipemello1 changed the title [moe][perf] Dist-MoE: skip the per-expert token count it doesn't read [moe][perf] Dist-MoE: skip the per-expert token count it doesn't read (1/3) Oct 19, 2026
def count_tokens(self, routing_map_TE: torch.Tensor) -> torch.Tensor | None:
"""Skip the count: ``forward`` builds its dispatch from the expert ids."""
if spmd.is_type_checking():
# The typechecker rejects ``None`` where a tensor input is declared.

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.

I feel introducing this function is not ideal and it a little bit confusing.

what about passing routing map into routed experts? and dist moe just delete it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

reply from claude:

Agreed, and done one level deeper than you suggested, so DeepEP and HybridEP skip the sum too. Only the Local / AllToAll / TorchAO dispatchers read the per-expert count; the router's stats (tokens_per_expert_E, aux loss) sum their own padding-masked map.

Changes:

  • MoE, KimiLatentMoE and MuseSparkMoE pass routing_map_TE to the routed experts and stop summing.
  • RoutedExperts.forward passes it to token_dispatcher.dispatch: Local / AllToAll / TorchAO sum it, DeepEP / HybridEP del it. DistMoeRoutedExperts.forward dels it.
  • count_tokens and its typechecker branch are gone: the map is a real tensor at the local_map boundary.
  • The count is now summed inside the local region, so the two mutate_type(P -> V) calls go away.

Same kernels: the stock path sums inside dispatch (bitwise vs main, TP 2 x EP 2 on 2 CPU ranks, output and all grads), and Dist-MoE still launches no sum, so the body's numbers hold.

@felipemello1 felipemello1 changed the title [moe][perf] Dist-MoE: skip the per-expert token count it doesn't read (1/3) [moe][perf] Skip the per-expert token count in backends that don't read it (1/3) Oct 20, 2026
@felipemello1
felipemello1 marked this pull request as ready for review October 20, 2026 16:44
@pytorch-bot pytorch-bot Bot added ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests labels Oct 20, 2026
@felipemello1
felipemello1 force-pushed the felipemello1/moe/6-skip-unused-count branch from c28ea9a to 062b072 Compare October 20, 2026 18:42
@felipemello1
felipemello1 removed this pull request from stack #5534 October 20, 2026 18:42
@felipemello1
felipemello1 added this pull request to stack #5571 October 20, 2026 18:43
@felipemello1 felipemello1 changed the title [moe][perf] Skip the per-expert token count in backends that don't read it (1/3) [moe][perf] Skip the per-expert token count in backends that don't read it (1/2) Oct 20, 2026
@felipemello1 felipemello1 changed the title [moe][perf] Skip the per-expert token count in backends that don't read it (1/2) [moe][perf] Skip the per-expert token count in backends that don't read it (1/3) Oct 20, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

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


Review of #5516: Skip the per-expert token count in backends that don't read it

  • Gather diff and context
  • Review token dispatchers / routed experts / MoE callers
  • Review tests
  • Post review

Verdict: LGTM. I found no correctness problems. The change is a clean way to address @acisseJZhong's comment, and it goes one level further than asked, so DeepEP and HybridEP skip the sum as well.

What I checked

Callsite audit (CLAUDE.md principle 6)

  • I grepped the repo for num_local_tokens_per_expert_E, .dispatch(, routed_experts( and every def dispatch( override.
  • Every producer and consumer is updated:
    • callers: MoE, KimiLatentMoE, MuseSparkMoE;
    • RoutedExperts.forward and DistMoeRoutedExperts.forward;
    • all six dispatcher dispatch methods: Local, Base, AllToAll, TorchAO, DeepEP, HybridEP;
    • all the GPU tests that build a count by hand.
  • MXFP8DistMoeRoutedExperts and the LoRA Dist-MoE variant don't override forward, so they inherit the new signature.
  • The remaining mentions of num_local_tokens_per_expert_E are dispatch outputs and internal locals. That is fine.

SPMD types (moe/sharding.py:158)

  • routing_map_TE now enters the local region with experts_input_layout, the same layout as topk_expert_ids_TK.
  • Since the sum now runs inside the local region on the local token shard, it is already V. Dropping the two mutate_type(P -> V) calls in token_dispatcher.py is correct.
  • _tokens_per_expert_placement is still needed by router_sharding_config and the quantile-balance test, so it is not dead code.

Numerics and kernels

  • The stock path still runs one routing_map_TE.sum(dim=0) per layer, just one frame deeper. Bitwise parity with main is what I'd expect.
  • In AllToAllTokenDispatcher.dispatch the sum stays outside the <fqn>.dispatch remat region, and the region still receives the (E,) count. Saved and recomputed dispatch behave as before.

Remat pins

  • The sum is still a bare op on the router output, as it was in MoE.forward. No new recompute_needs_tensor is needed for core MoE or Kimi.
  • MuseSparkMoE still has remat.recompute_needs_tensor(routing_map_TE) (muse_spark/moe.py:121). It now covers the sum inside dispatch, so keeping it is correct.

GraphTrainer

  • paged_stash_memory_policy.find_layer_token_counts reads its count from output 2 of hybridep.dispatch, not from the old MoE.forward sum, so this PR doesn't affect it.
  • I agree with the PR note that the node changes label ({"EP": "dispatch"} instead of {"EP": "compute"}) and that no pass reads that label.

Nits (optional)

  1. Duplicated sum (token_dispatcher.py:702): the TorchAO EP=1 branch repeats the LocalTokenDispatcher.dispatch sum next to its own _permute. That is fine because the branch already duplicates Local's reorder. The comment above it ("so num_local_tokens_per_expert_E is already the full per-expert count") now sits right above the line that creates the count. A small rewording would read better, e.g. "...so summing the local map gives the full per-expert count."

  2. Test coverage (test_moe.py): _forward_with_routed_mask now stubs MuseSpark's pooler, pre_expert_norm, unpooler and remat hooks. test_moe_hands_the_routed_padding_mask_to_the_experts could loop over MuseSparkMoE too at no extra cost; today it only covers (MoE, KimiLatentMoE).

  3. Compatibility for external callers: any out-of-tree caller of RoutedExperts or dispatch that still passes an (E,) count breaks:

    • With EP it fails loudly: sum(dim=0) returns a 0-d tensor and .view(ep_size, -1) raises.
    • On the EP=1 local path it would compute a 0-d offsets_E and fail later, in the grouped GEMM, with an error that is harder to trace.

    No code in this repo is affected. A one-line note in the PR description about the signature change would help downstream users.

Not done

  • I couldn't run the CPU tests or pre-commit: the sandbox needs approval for pytest. This review is from reading the code only.
  • I diffed against the branch's base commit b93d5c0, because the shallow checkout has no merge base with origin/main.

Felipe Mello added 2 commits October 27, 2026 07:16
MoE.forward summed the (T, E) routing map into per-expert token counts for
every routed-experts backend. Dist-MoE builds its dispatch from the expert ids
and deleted the counts unread. Routed experts now expose count_tokens(): the
stock RoutedExperts returns the sum; Dist-MoE returns None (the sum only while
the SPMD typechecker runs, which rejects None for a declared tensor input), so
MoE, MuseSparkMoE and KimiLatentMoE skip the sum.

Qwen3.5-35B-A3B MoE block (router + Dist-MoE routed experts + inline shared
experts), EP 4 on 4 GB300, 8 layers, CUDA graphs, decode, min of 2 processes,
us per layer:

  T per GPU     32      64     256
  before     153.2   158.2   177.4
  after      146.4   150.0   165.4

Outputs bitwise equal (12/12 saved per-rank outputs).
Only the Local, AllToAll and TorchAO token dispatchers read the per-expert
token count. The MoE now passes the router's (T, E) routing map to the routed
experts, and RoutedExperts passes it to token_dispatcher.dispatch:

- Local, AllToAll and TorchAO dispatch sum it; DeepEP and HybridEP delete it.
- DistMoeRoutedExperts.forward deletes it (its MXFP8 and LoRA variants inherit).
- MoE, KimiLatentMoE and MuseSparkMoE no longer sum; count_tokens and its
  typechecker branch are gone.
- The count is now summed inside the routed experts' local SPMD region, so it
  is already local: the two mutate_type(P -> V) calls are gone. The sharding
  config declares the map with the layout of topk_expert_ids_TK.

What moved: the sum runs at the top of dispatch (before AllToAll's dispatch
remat region), so the stock path launches the same kernels. In Kimi and Muse
the sum now runs a few ops later.
Under GraphTrainer its node is now labeled {"EP": "dispatch"} instead of
MoE.forward's {"EP": "compute"}. No pass reads that label: the EP overlap pass
keys on EP_token_exchange and EP_token_count_sync.

CPU, 2 ranks on gloo, TP 2 x EP 2: MoE forward + backward with SP off and on is
bitwise equal to the previous commit (32/32 tensors). The parallelized routed
experts pass the SPMD typechecker with EP 2 and EP 1.
@felipemello1
felipemello1 force-pushed the felipemello1/moe/6-skip-unused-count branch from 062b072 to d76a48d Compare October 27, 2026 14:29
@felipemello1
felipemello1 merged commit 72a3a12 into main Oct 27, 2026
29 of 31 checks passed
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/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants