Skip to content

[moe][perf] AllToAll dispatcher: permute and unpermute with gathers (1/4) - #5162

Merged
felipemello1 merged 5 commits into
mainfrom
felipemello1/lcp/dsv3-3-moe-ep-permute-gathers
Nov 8, 2026
Merged

felipemello1 merged 5 commits into
mainfrom
felipemello1/lcp/dsv3-3-moe-ep-permute-gathers

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: The AllToAll dispatcher's eager permute and unpermute become gathers: -5.2 ms per MoE layer at 16k tokens on every EP>1 step (DeepSeek-V3 EP2 rank, 1 GB300), bitwise identical. Today's Qwen3.5-35B-A3B and GPT-OSS RL recipes run this dispatcher in both roles; Dist-MoE and DeepEP have their own.

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

# PR Independent? Needs (stack positions)
1 AllToAll dispatcher: permute and unpermute with gathers yes —
2 Argsort expert ids on the narrowest integer type yes —
3 Gather-sum MoE dispatch and combine, training and inference, any EP no 2
4 Turn on gather-sum dispatch and combine for DeepSeek-V3/V4, Kimi K3, GPT-OSS and Qwen3 MoE no 3

Problem

  1. Permute. AllToAllTokenDispatcher._permute reorders the received rows with x[perm].
  2. Its backward. An accumulating index_put: a sort plus a zero fill.
  3. Unpermute. _unpermute writes out[perm] = y, a non-vectorized scatter.
  4. Where. Both run eagerly, outside any compile region, on every EP>1 step.
  5. Cost. 9.25 ms per MoE layer at 16k tokens (DeepSeek-V3, one EP2 rank).

Solution

  1. A permutation's inverse is a gather, so no accumulation is needed.
  2. _PermuteRows gathers by the permutation and backpropagates by gathering with its inverse.
  3. _unpermute gathers by the inverse.
  4. Unchanged: TorchAO's padded _unpermute.
before:  fwd x[perm]          bwd index_put accumulate (sort + zero fill)
         fwd out[perm] = y    (scatter)
after:   fwd x[perm]          bwd g[inv_perm]
         fwd y[inv_perm]

Results

Numerics: bitwise identical (pure row moves).

_permute + _unpermute fwd+bwd, DeepSeek-V3 EP2 rank (128 local experts), R = 8T rows x 7168 bf16,
random balanced counts, eager, GPU kernel time in us, median of 5 profiled calls, 1 GB300
T       main    this PR
4k      2356    1077    -54%
16k     9253    4083    -56%
per MoE layer: -5.2 ms at 16k, -1.3 ms at 4k

You may ask: does this change the reference dispatcher? Its output stays bitwise identical to main's, so the all-to-all dispatcher is still the correctness reference (torchtitan/models/common/moe/README.md:12).

NOTE:

  • Reaches every recipe with the AllToAll dispatcher at EP>1 (deepseek_v3_671b uses EP=2).
  • Under an outer compile, the inverse permutation adds two small scatters.
  • Exercised end to end with the rest of the stack in a 2-GPU TP2 + EP2 Qwen3.5-35B-A3B run (2 layers, fwd+bwd 64k): 119.9 -> 88.2 ms for the whole stack; this PR's share there is not split out.
  • Not tested: GraphTrainer with EP, H100.

Test plan

pytest tests/unit_tests/cpu/distributed/test_expert_parallel.py -k test_permute_and_unpermute_match_indexing_with_grads

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Oct 8, 2026
@felipemello1
felipemello1 added this pull request to stack #5165 October 8, 2026 15:15
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 8, 2026
@felipemello1 felipemello1 changed the title [MoE] Move EP tokens between rank-major and expert-major order with gathers [moe][perf] Move EP tokens between rank-major and expert-major order with gathers Oct 9, 2026
@felipemello1
felipemello1 force-pushed the felipemello1/lcp/dsv3-3-moe-ep-permute-gathers branch from 9985821 to 30f0b98 Compare October 9, 2026 05:11
@felipemello1
felipemello1 force-pushed the felipemello1/lcp/dsv3-3-moe-ep-permute-gathers branch from 30f0b98 to 27e472c Compare October 9, 2026 17:18
@felipemello1
felipemello1 removed this pull request from stack #5165 October 18, 2026 22:08
@felipemello1
felipemello1 force-pushed the felipemello1/lcp/dsv3-3-moe-ep-permute-gathers branch from 27e472c to 9966477 Compare October 18, 2026 22:09
@felipemello1
felipemello1 changed the base branch from felipemello1/lcp/dsv3-2-dsv3-mla-qk-region to main October 18, 2026 22:09
@felipemello1
felipemello1 force-pushed the felipemello1/lcp/dsv3-3-moe-ep-permute-gathers branch from 9966477 to f6e3ab5 Compare October 19, 2026 02:16
@felipemello1
felipemello1 changed the base branch from main to felipemello1/lcp/gptoss-1-grouped-expert-bias October 19, 2026 02:17
@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/lcp/gptoss-1-grouped-expert-bias to main October 19, 2026 06:47
@felipemello1
felipemello1 force-pushed the felipemello1/lcp/dsv3-3-moe-ep-permute-gathers branch from f6e3ab5 to 698dd37 Compare October 19, 2026 06:47
@felipemello1
felipemello1 added this pull request to stack #5533 October 19, 2026 06:48
@felipemello1 felipemello1 changed the title [moe][perf] Move EP tokens between rank-major and expert-major order with gathers [moe][perf] AllToAll dispatcher: permute and unpermute with gathers (1/6) Oct 19, 2026
@felipemello1
felipemello1 removed this pull request from stack #5533 November 7, 2026 06:00
@felipemello1
felipemello1 force-pushed the felipemello1/lcp/dsv3-3-moe-ep-permute-gathers branch from 698dd37 to f5a3ed1 Compare November 7, 2026 06:00
@felipemello1
felipemello1 added this pull request to stack #5932 November 7, 2026 06:00
@felipemello1 felipemello1 changed the title [moe][perf] AllToAll dispatcher: permute and unpermute with gathers (1/6) [moe][perf] AllToAll dispatcher: permute and unpermute with gathers (1/4) Nov 7, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 3s —— View job


Verdict: Approve -- please fill in the human-written summary before merging; 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 item below before merging -- the change is a correct, bitwise-identical substitution of scatters by gathers in a path that runs eagerly on every EP>1 step; the only open item is the empty human-written summary. The PR touches models/common/, so a maintainer still needs to review.

What this PR does. AllToAllTokenDispatcher._permute still gathers x[perm], but through _PermuteRows, whose backward gathers by inv_perm instead of autograd's default accumulating index_put (sort + zero fill). _unpermute drops out[perm] = y and gathers y[inv_perm]. inv_perm comes from one R-length int scatter (_inverse_permutation). TorchAOTokenDispatcher keeps its own _permute/_unpermute, since its indices are not a permutation: they include a sentinel row for padding.

Example. 2 EP ranks, 1 local expert each... take perm = [2, 0, 1], inv = [1, 2, 0]:

permute fwd     main: x[perm]                PR: x[perm]
permute bwd     main: zeros.index_put_(perm, g, accumulate=True)
                PR:   g[inv]
unpermute fwd   main: out = empty; out[perm] = y
                PR:   y[inv]          (out[perm[i]] = y[i]  <=>  out[j] = y[inv[j]])
unpermute bwd   main: g[perm]         PR: g[inv(inv)] = g[perm]

All row moves, so outputs and grads are identical as long as perm is a full permutation of the R received rows, which _permute guarantees (seg_ids has output_size=total).

Must fix

  1. PR description -- the "Summary (human-written)" section is empty. Per CONTRIBUTING.md ("AI-assisted contributions"), the author fills it in before merge.
Details
  • Necessity: the problem is real on main. Both ops run outside any compile region, and the description measures them (9.25 ms -> 4.08 ms per layer at 16k tokens, DSv3 EP2). This PR is not superseded by the rest of the stack: #5382 and #5518 change the local sort/combine (_local_reorder / _score_and_scatter_add), not the EP rank-major -> expert-major _permute.
  • Subclasses: TorchAOTokenDispatcher is the only subclass, and it overrides both _permute and _unpermute, so _PermuteRows never sees its padded, non-permutation indices.
  • Determinism: scatter_ with unique indices and gathers are deterministic, and under use_deterministic_algorithms(True) scatter with a src tensor has a deterministic kernel, so it won't raise.
  • Memory: the saved index has the same R int64 size as before (perm, or inv for unpermute). The extra cost is one R-length int scatter in each of permute bwd, unpermute fwd and unpermute bwd. That is negligible next to the R x D bf16 row moves, and the benchmark already includes it.
  • Test: the new CPU test checks forward and both backwards against the old indexing semantics with exact tolerances. The custom backward is otherwise only guarded by GPU EP goldens, so the test is cheap and earns its place.

Not verified: GPU timings, the spmd_types type-checking run with EP, and GraphTrainer + EP (the description already lists the last one as untested). I couldn't run the unit test here because pytest needs approval.

…athers

_permute's x[perm] backpropagates with an accumulating index_put (sort plus
zero fill) and _unpermute's out[perm] = y is a non-vectorized scatter. For a
permutation both are gathers: gather by the permutation and backpropagate by
gathering with its inverse.
Review fix: the base _unpermute gathers by the inverse permutation, which keeps
every row, so input_shape is unused there; TorchAO's padded override needs it.
@felipemello1
felipemello1 force-pushed the felipemello1/lcp/dsv3-3-moe-ep-permute-gathers branch from f5a3ed1 to 89629f1 Compare November 7, 2026 20:52
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review (docstring-only change in f03292a: _PermuteRows and _inverse_permutation now draw a 3-row example)

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 50s —— View job


Verdict: Approve. Before merging, the empty human-written summary still needs filling in, and 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 item below before merging. The new commits 89629f1 and f03292a change only comments and docstrings, and the examples are correct. The one open item from the last review is still open. This PR touches models/common/, so a maintainer still needs to review.

What changed since the last review. _PermuteRows, _inverse_permutation, and AllToAllTokenDispatcher._unpermute now explain themselves with a 3-row example instead of >>> doctests. _unpermute also says why input_shape is unused. No code changed.

Example check (token_dispatcher.py:27-32, :58-60):

perm = [2, 0, 1], x = [a, b, c]
x[perm]             = [x2, x0, x1]       = [c, a, b]       matches
inv[perm[i]] = i    -> inv[2]=0, inv[0]=1, inv[1]=2 = [1, 2, 0]   matches
grad_out[inv]       = [go1, go2, go0]    = [ga, gb, gc]    matches
x[perm][inv][j]     = x[perm[inv[j]]]    = x[j]            matches

The added lines are ASCII only. The two non-ASCII dashes in the file, at :413 and :1020, were already there.

Must fix

  1. PR description: the "Summary (human-written)" section is still empty (still open from the last review). Per CONTRIBUTING.md ("AI-assisted contributions"), the author fills it in before merge.

Should consider

  • token_dispatcher.py:38-39: item 3 of the "Why not plain x[perm]" list is a GB300 benchmark number, not a reason. Hardware-specific timings in a docstring go stale when kernels or hardware change, and the PR description already has the numbers. Items 1-2 make the case on their own, so item 3 could be dropped.

Not verified: GPU timings (unchanged from the last review).

@felipemello1
felipemello1 marked this pull request as ready for review November 7, 2026 20:58
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 7, 2026

@tianyu-l tianyu-l 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.

sgtm

felipemello1 pushed a commit that referenced this pull request Nov 8, 2026
@felipemello1
felipemello1 merged commit c0df32e into main Nov 8, 2026
felipemello1 pushed a commit that referenced this pull request Nov 8, 2026
…ce, any EP

Rebased on main after #5162 and #5436 merged. One commit with the PR's changes from:
- 8ad2584 [moe][perf] Gather-sum MoE dispatch and combine, training and inference, any EP
- 2e3549b [moe] Address review: names, docstrings, fewer tests, TorchAO EP=1 TODO
- 742288d [moe] Fold the region-name check into the trainer == generator test
- aaa0090 [moe] Rename _sort_and_gather to _reorder_by_expert
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants