Skip to content

[deepep] Train on the expand layout; drop the eager permute and unpermute - #5708

Draft
felipemello1 wants to merge 13 commits into
felipemello1/dsv3-group-argmaxfrom
felipemello1/deepep/expand-training
Draft

felipemello1 wants to merge 13 commits into
felipemello1/dsv3-group-argmaxfrom
felipemello1/deepep/expand-training

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

Written with Claude Code: the analysis, measurements and test plan below.

TLDR: DeepEP training now dispatches into DeepEP's expand layout, whose rows are already grouped by expert. That deletes the eager gather before the grouped GEMM, the bf16 scatter_add_ after it, and their host syncs.

  • Numerics: not bitwise, but within rounding. A token's expert rows are now summed in fp32 inside DeepEP's combine, instead of by bf16 adds. On one MoE layer of 5 models at EP 2, the change is 0.4-0.6x of the compile yardstick and every weight grad stays bitwise. The generator's output stays bitwise.
  • Memory: kept for backward stays at base (2-10 MiB per layer below it).
  • Speed: one MoE layer fwd+bwd at EP 2, default remat: DeepSeek-V3 671B 5-8% faster, Qwen3.5-35B-A3B 18-27% faster.
base:    dispatch (compact) -> gather + sort (host syncs) -> experts -> * scores -> scatter_add_ (bf16) -> combine
this PR: dispatch (expand) ---------------------------------> experts -> * scores -> combine (sums a token's rows in fp32)
# before: _dispatch_op_impl
do_expand=cuda_graph_compatible,      # training: compact, then _permute_tokens in eager
# after
do_expand=True,                       # backward-safe: get_buffer sets allow_multiple_reduction=True
do_cpu_sync=not cuda_graph_compatible,

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

# PR Independent? Needs (stack positions)
1 Compile the MoE router and its load-balance sums yes —
2 Shared experts on a side stream in CUDA graphs at inference yes —
3 Group-limited routing with argmax rounds in the compiled router no 1
4 DeepEP: train on the expand layout; drop the eager permute and unpermute yes —
5 DeepEP: apply the routing scores inside the expert SwiGLU, before w2 no 4

Problem

  1. DeepEP v2's dispatch has two layouts. Compact: one row per received token. Expand: one row per (token, local expert) pick, grouped by expert.
  2. Training used compact. deepep.py kept expand for inference only, quoting a DeepEP kernel assert ("must not be backward").
  3. So _permute_tokens expanded and sorted the rows in eager before the grouped GEMM: a boolean-mask gather, an argsort, repeat_interleave, index_select. The masks and repeat_interleave sync with the host.
  4. After the experts, _unpermute_tokens summed each token's rows with a bf16 scatter_add_. It rounds after every add, and it is non-deterministic outside torch's deterministic mode.
  5. The generator already used expand, so the trainer's forward and the generator's forward differed.
  6. Cost. On Qwen3.5 at 16k tokens per rank, removing them saves 2.2 of the layer's 10.8 ms (eager fwd+bwd, no remat).

Solution

  1. Expand is backward-safe when combine sums locally. DeepEP's assert fires only when combine sends expanded rows without summing them first (deep_ep/impls/combine.cuh:42, assert at :69). With allow_multiple_reduction=True (the ElasticBuffer default, now passed explicitly in get_buffer), combine sums a token's rows on the expert rank first and accepts one score per row.
  2. The dispatch op always passes do_expand=True. cuda_graph_compatible now only picks do_cpu_sync. Combine's backward re-dispatches with do_expand=True too.
  3. Remat keeps one row per received token. In expand, a token that picked several of this rank's experts arrives as identical rows. Saved-tensor hooks (_OneRowPerTokenHooks) keep each token once plus a row-to-token index, and rebuild the rows with a gather in replay, bitwise. Without remat they never run.
  4. Deleted: _permute_tokens, _unpermute_tokens, the compact fields of DispatchState, and the op's recv_topk_idx output.
  5. Unchanged: cuda_graph_compatible=True stays inference-only. Without a host sync, recv_x reserves up to ep_size times the routed rows: too many to keep for backward. Scores are still applied in combine_tokens.

Numerics: not bitwise; within rounding, and closer to fp64 than base

Why: only one step changes, the sum of a token's expert rows on each rank.

  • Base: a bf16 scatter_add_, one rounding per added row.
  • This PR: DeepEP's combine, fp32 accumulation, one rounding (deep_ep/impls/combine_utils.cuh:115-165).
  • Tokens with at most 2 rows on a rank get the same result in both: DeepEP then uses one bf16 add (combine_utils.cuh:68-70).
  • CPU check of the sum alone (4 ranks x 4 rows per token, bf16 rows), rel L2 vs fp64: base 3.1e-3, this PR 2.4e-3.

What was compared (stack matrix at this head, script not in this PR):

  • This PR vs PR 3: one production-size MoE layer, same weights and inputs, 4096 tokens per rank, 2x GB300 (4 for Kimi K3). Eager and compiled fwd+bwd in deterministic mode, and the generator's CUDA-graph inference at T = 1 / 64 / 2048.
  • rel L2 = ||this PR - PR 3|| / ||PR 3||, over all ranks.
  • Yardstick = how much compiling alone moves main (main eager vs main compiled), floored at one bf16 rounding (1.7e-3).
One MoE layer, DeepEP, this PR vs PR 3   out      input grad   weight grads   yardstick (out / input grad)   ratio
Qwen3 30B-A3B          EP 2              3.4e-3   3.2e-3       bitwise        5.3e-3 / 5.6e-3                0.6x
Qwen3.5 35B-A3B        EP 2              2.4e-3   2.4e-3       bitwise        5.3e-3 / 6.1e-3                0.5x
DeepSeek-V3 671B       EP 2              2.8e-3   2.8e-3       bitwise        5.1e-3 / 5.1e-3                0.6x
Kimi K2.5              EP 2              2.9e-3   2.9e-3       bitwise        5.2e-3 / 5.1e-3                0.6x
DeepSeek-V4 flash      EP 2              2.0e-3   2.0e-3       bitwise        4.7e-3 / 4.7e-3                0.4x
Kimi K3                EP 4              4.3e-3   5.0e-3       <= 5.2e-3      4.5e-4 / 1.7e-3 (floor 1.7e-3) 2.9x  <- worst
Eager = compiled in every row. fused_swiglu (the shipped DeepEP recipes): the same numbers.
CUDA-graph inference, T = 1 / 64 / 2048: bitwise in all 6 rows.

Trainer runs (debug recipes through the trainer, step 1 of 3, default remat, DeepEP, FSDP 2 x EP 2 and TP 2 x EP 2, 7 debug configs):

  • Step-1 loss within 1.9e-5 (relative) of PR 3. Qwen3.5 and DeepSeek-V4: bitwise.
  • Every cell is 1.0-1.7x the yardstick, except GPT-OSS at TP 2 x EP 2: 2.0x (grad norm 7.8e-5 vs 3.9e-5, with 9 routing flips vs 8 in the yardstick).
  • Yardstick here: the larger of main eager vs compiled and main all-to-all vs DeepEP (loss, grad norm, dense grads, routing flips).

Worst cell, Kimi K3 at EP 4 (2.9x):

  1. Its absolute change, 4.3e-3, is close to the EP 2 models' 2.0-3.4e-3.
  2. Its yardstick is small: compiling barely changes Kimi K3's layer (out 4.5e-4). So the floor of one bf16 rounding sets the ratio.
  3. Kimi K3 applies RMSNorm and routed_up to the combine output (models/kimi_k3/moe.py:89). So the rounding change also reaches the expert, router and routed_down grads (2.6e-3, 2.7e-3, 5.2e-3).
  4. In the other models the combine is the layer's last op, so in this one-layer test their weight grads stay bitwise. In a full model the next layer passes the change on, as the e2e rows show.
Every model and layout (stack matrix grid)
=  bitwise    0.6x = worst rel L2 / yardstick    * = 2-8x, explained above or below    - = not run (not reached)
                              Qwen3  Qwen3.5     DSv3 DSv3-grp  Kimi2.5   KimiK3  GPT-OSS     DSv4     Muse
layer DeepEP EP2 train         0.6x     0.5x     0.6x        -     0.6x     n/a1     n/a2     0.4x     n/a3
layer DeepEP EP2 graph            =        =        =        -        =     n/a1     n/a2        =     n/a3
layer DeepEP fused train       0.6x     0.5x     0.6x        -     0.6x     n/a1     n/a2     0.4x     n/a3
layer DeepEP EP4 train            -        -        -        -        -    2.9x*        -        -        -
layer DeepEP EP4 graph            -        -        -        -        -        =        -        -        -
layer DeepEP EP4 fused            -        -        -        -        -    2.9x*        -        -        -
e2e FSDP2xEP2 DeepEP           1.4x        =     1.0x     1.5x     1.7x     n/a4     1.3x        =     n/a3
e2e TP2xEP2 DeepEP             1.1x        =     1.5x     1.0x     n/a5     n/a4    2.0x*        =     n/a3
DSv3 = DeepSeek-V3 671B (8 groups, 4 kept); DSv3-grp = DSv3 debug with 64 experts, 8 groups, 4 kept;
DSv4 = DeepSeek-V4 flash, layer 3 (its first top-k router); fused = fused_swiglu.
n/a1: DeepEP holds at most 256 experts per rank (deep_ep/common/layout.cuh:21,40); Kimi K3 at EP 2 has 448, so the EP 4 rows run it
n/a2: DeepEP combine needs hidden % 256 == 0 (deep_ep/impls/combine.cuh:109); GPT-OSS 120b hidden = 2880
n/a3: Muse Spark's MoE accepts only the local and all-to-all dispatchers (models/muse_spark/moe.py:55-73)
n/a4: as n/a2: the Kimi K3 debug flavor has hidden = 128
n/a5: the Kimi K2.5 recipe rejects TP > 1 (torchtitan_recipes/tests/models/kimi_k2_7.py:558-565)

Determinism (one MoE layer, DeepSeek-V3 and Qwen3.5, EP 2, deterministic mode off):

  • Output and input grad are bitwise on rerun. Base: not (bf16 atomics).
  • Routed-expert weight grads still vary between runs, on base and on this PR: DeepEP's receive order changes their summation order.
  • Default remat equals no remat, bitwise. Base: not.

Trainer-generator parity: the training forward (grad on, host sync) equals the generator's CUDA-graph forward, bitwise, at every T = 1-16384 (routed experts, DeepSeek-V3 and Qwen3.5, earlier revision of this PR). Base: not.

Training run: TP 2 x EP 2, Qwen3 MoE debug, SP on, default remat, deterministic, 20 steps.

  • Step-1 loss 7.693660 vs base 7.693661. Step 20: 3.950907 vs 3.953434.
  • The largest gap is at step 11 (-6.7e-3). There, every arm we ran lands in one of two loss bands, including PR 1's region on vs off.
  • Over 300 steps (earlier stack), this PR's mean loss is 0.010-0.024 below base over steps 21-300.

Memory: kept for backward stays at base

Kept for backward per MoE layer, 16k tokens per rank, compiled + default remat, MiB (stack matrix, this head)
model                  base (PR 3)   this PR   main
Qwen3 30B-A3B             720          718      721
Qwen3.5 35B-A3B           890          888      890
DeepSeek-V3 671B         2836         2834     2837
Kimi K2.5                2848         2846     2849
DeepSeek-V4 flash        1426         1424     1426
Kimi K3 (EP 4)           3377         3367     3379
fused_swiglu: the same. Peak: equal to base in every cell.
  • Why the hooks matter. Expand has about 4 rows per received token (DeepSeek-V3 4.07, Qwen3.5 4.01 at EP 2, 16k tokens per rank). Without the hooks, the default remat would keep every row: 4183 vs 2834 MiB per DeepSeek-V3 layer (+48%), about +77 GiB over its 58 MoE layers.
  • What the hooks cost, vs keeping every row (DeepSeek-V3, default remat, 16k / 32k): +1.0 / +2.2 ms eager (+2.0 / +2.4%), +1.3 / +2.7 ms compiled (+2.9 / +3.2%). Qwen3.5: within process noise. The speed table below includes this cost.

Speed

One MoE layer (router + DeepEP routed experts + shared experts), EP 2 without FSDP, 2x GB300, bf16 params, random inputs.
fwd+bwd ms (rank-max, median of 20 iters); remat = the trainer's DefaultActivationRematConfig; base = PR 3.
                                      16k tokens/rank              32k tokens/rank
DeepSeek-V3 671B   eager           42.30 -> 39.82   -5.9%       79.74 ->  78.15   -2.0%
                   compiled        39.58 -> 37.26   -5.9%       74.75 ->  70.92   -5.1%
                   eager, remat    54.22 -> 50.64   -6.6%      101.37 ->  95.79   -5.5%
                   compiled, remat 50.59 -> 46.41   -8.2%       93.30 ->  87.99   -5.7%
Qwen3.5-35B-A3B    eager           10.76 ->  8.54  -20.6%       17.04 ->  14.43  -15.3%
                   compiled        10.73 ->  8.26  -23.1%       15.39 ->  12.79  -16.9%
                   eager, remat    17.27 -> 12.54  -27.4%       22.79 ->  18.65  -18.2%
                   compiled, remat 15.91 -> 12.75  -19.9%       21.26 ->  16.58  -22.0%
One process per arm; this PR's remat rows: median of 2 interleaved processes. Processes differ by up to 9% (Qwen3.5).
Timed on an earlier revision of this PR. Since then only the remat hooks changed (int32 row index instead of int64, cleanups).
  • Inference (the generator's CUDA-graph path, routed experts only, EP 2): output bitwise vs base. Qwen3.5 2-5% faster at T = 1-16; DeepSeek-V3 within ±2.2%. Earlier revision of this PR.

You may ask:

  • Why saved-tensor hooks, not the compact layout under remat? Compact would bring back the gather, its host syncs, and a second DispatchState layout. The hooks are torch_remat's API for storing a kept tensor in another form.
  • Why not skip the host sync in training too (do_cpu_sync=False)? recv_x and the expert activations would be up to ep_size times larger, and autograd keeps them for backward.
  • How do we know combine returns rows to the right tokens? A new 2-GPU test checks the output and every grad against the all-to-all dispatcher. In the matrix, every weight grad is bitwise vs base on 5 models.
  • And a remat policy that also saves w13? Then w13 keeps the expand rows itself, on top of the hooks' copy: about +441 MiB per DeepSeek-V3 layer at 16k. Main keeps the same extra rows in that case. No in-tree DeepEP config uses such a policy.

NOTE:

  • Not run: multi-node, which uses DeepEP's hybrid kernels. Their combine has the same expand + local-sum branch (hybrid_combine.cuh:48, 117-119, 305-313). EP > 2 ran only for Kimi K3 (EP 4, GB300) and in the H100 CI (FSDP 4 x EP 4).
  • The hooks are torch_remat's. GraphTrainer's graph-level memory policy doesn't run them, so a traced expand dispatch there would keep one row per pick.
  • The hooks read DeepEP's recv_src_metadata[:, 2:], an internal layout. A TODO in the code asks DeepEP to expose the row-to-token map.

Test plan

  • pytest tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py (2 GPUs), 4 tests:
    • dispatch and combine are saved, not replayed; remat replay is exact;
    • new: the expand path matches AllToAllTokenDispatcher up to bf16 rounding on the output, input grad, router-score grad and expert grads. A combine that returns rows to the wrong tokens fails it;
    • new: a saved dispatch under remat keeps one row per received token (3.98 MiB kept vs 8.42 MiB without the hooks, bound 5.75 MiB), and replay rebuilds the rows bitwise.
  • H100 CI (ciflow/h100.8) at this head: the DeepEP test (4 passed) and qwen3_fsdp+deepep (FSDP 4 x EP 4) pass.
  • CPU at this head: test_transforms.py, test_inference_moe.py, test_debug_config_defaults.py, test_integration_test_definitions.py: 105 passed.
  • Stack matrix and layer benchmark: scripts not in this PR.

Hardware: 2x GB300 (SM 10.3), DeepEP v2.1.0 (01dc3aa). Stack matrix: torch 2.16.0.dev20261030+cu132. Layer timings: torch 2.16.0.dev20261014+cu132.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 29, 2026
@felipemello1
felipemello1 added this pull request to stack #5710 October 29, 2026 22:53
@felipemello1 felipemello1 added the ciflow/h100.8 Trigger H100.8 CI label Oct 29, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

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


Needs discussion: the design is sound, but it needs convergence evidence beyond the 20-step debug run, and maintainers need to coordinate with #5315, which builds on the compact path this PR deletes. 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: Needs discussion -- the design is sound and deletes code (net -79). Before it lands, it needs convergence evidence beyond 20 debug steps, and maintainers need to coordinate with #5315, which builds on the compact path this PR deletes.

What this PR does. DeepEP training now dispatches with do_expand=True, like the generator already does. Expand-mode combine is backward-safe because allow_multiple_reduction=True: combine sums a token's rows on the expert rank, and it accepts one topk_weights per row in dispatch backward. That deletes _permute_tokens and _unpermute_tokens (the eager gather/argsort/repeat_interleave, the bf16 scatter_add_, and 4 host syncs per layer), plus the compact fields of DispatchState. cuda_graph_compatible now only controls do_cpu_sync.

Example. This rank holds e0 and e1. Token A picks e0 and e1, B picks e1, C picks e0.

before: dispatch -> recv_x=[A,B,C], recv_topk_idx
        _permute_tokens -> [A,C,A,B]   (mask gather, argsort, repeat_interleave: host syncs)
        experts, * scores -> scatter_add_ into [A,B,C] (bf16 atomics) -> combine
after:  dispatch -> recv_x=[A,C,A,B], counts=[2,2] (device-side psum)
        experts, * scores -> combine (DeepEP sums A's two rows, then across ranks)

Must fix

  1. Convergence evidence. This changes computation (the combine's rounding order), and .claude/CLAUDE.md asks for loss convergence on a representative dataset in that case. The only training evidence is 20 steps of the Qwen3 MoE debug model at TP 2 x EP 2. At step 11 the grad norm is 4.42 vs 2.91, and the loss stays 4-10e-3 above base afterward, while PR 5 stays within 1e-3. A routing flip is a plausible explanation, but please add a few-hundred-step C4 comparison against base (e.g. qwen3_moe_deepep at FSDP 4 x EP 4, the CI config). That would show the step-11 jump is transient.
  2. torchtitan/models/common/moe/moe.py:810 (not in the diff) -- "DeepEP expand: capturable -> side stream" is now misleading. After this PR the trainer also uses expand, and that path host-syncs. It should say "DeepEP with cuda_graph_compatible=True".

Questions

  • #5315 (yuweih205, graph_trainer DeepEP tracing + shared-expert overlap) adds fake kernels for the compact _permute_tokens path and a launch_dispatch/wait_dispatch split for it. Have you agreed with them that it rebases onto expand? Does DeepEP's defer_epilogue support do_expand=True?
  • Memory under default remat: DeepEP now saves the expanded rows, the same as AllToAllTokenDispatcher (its dispatch region returns routed_input_RD, token_dispatcher.py:394-412). So this is parity with the default dispatcher, not a new cost. Please confirm that maintainers accept the measured +48% per layer at EP 2 for DeepEP users who don't take PR 5 (the shipped RL recipes use fused_swiglu).
Details
  • No stale references: no remaining in-repo use of _permute_tokens, _unpermute_tokens, permuted_indices/num_recv_tokens on the DeepEP DispatchState, or the old 5-output deepep::dispatch schema. graph_trainer/memory_policy.py:93 only tags the op.
  • combine_tokens now assumes recv_scores is 1-D [R] (unsqueeze(1)). The old reshape-sum was defensive. The new GPU test compares the [T, D] output against all-to-all, so a shape change would fail it.
  • The new test test_matches_all_to_all_dispatcher earns its cost. It guards expand-mode backward (x grad, score grad through combine topk_weights, expert grads) against a reference, and the per-token loss weighting catches rows returned to the wrong token.
  • The recipe and test docstring edits are mechanical. Dropping "step-1 bitwise" from qwen3_moe_deepep is correct, because step 1 is no longer bitwise.

Not verified: DeepEP kernel line references (combine.cuh, combine_reduce_epilogue.cuh), GPU test results, and the perf/memory numbers. A maintainer still needs to review (core distributed code).

@felipemello1
felipemello1 force-pushed the felipemello1/deepep/expand-training branch from c9a86d5 to 0040493 Compare October 30, 2026 01:12
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude:

  1. Convergence, 300 steps: Qwen3 MoE debug, TP 2 x EP 2 + DeepEP, default remat, deterministic, c4_test (2 GPUs; FSDP 4 x EP 4 needs 4 free GPUs).
    steps     base     this PR   PR - base (mean)   max |PR - base|
    1-10      5.9342   5.9343    +0.0001            0.0004
    11-20     3.7536   3.7628    +0.0092            0.0134
    21-50     2.9648   2.9549    -0.0099            0.2450
    51-100    2.9506   2.9392    -0.0113            0.0737
    101-200   2.8249   2.8067    -0.0182            0.0765
    201-300   2.8380   2.8139    -0.0242            0.0806
    
    The step-11 jump doesn't persist; step 300: 3.0294 vs 3.0374.
  2. The side-stream docstring now says "DeepEP with cuda_graph_compatible=True" (fixed in PR 2, where the line lives).
  • [graph_trainer] Trace compact DeepEP and overlap the shared experts with the dispatch wait #5315: not coordinated yet. It builds on the compact path and needs DeepEP v2.5's defer_epilogue; CI pins 2.1.0 (01dc3aa), which has no defer_epilogue, so I couldn't check it with do_expand=True. Reaching out to yuweih205 is Felipe's call.
  • Memory: yes, parity with AllToAllTokenDispatcher. PR 5 brings it below base for the stock SwiGLU; fused_swiglu configs keep +1.3 GiB per DSv3 layer at EP 2, shrinking with EP.

@claude please review

@claude

claude Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 30s —— View job


Approve, but address the items below before merging: both earlier must-fix items are resolved. Before merging, the pending H100 CI needs to pass and maintainers need to coordinate with #5315. 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. Both must-fix items from the last review are resolved, and HEAD (0040493) has no new problems. What remains is to get the H100 CI green and to coordinate with #5315. A maintainer still needs to review, because this is core distributed code.

What this PR does. DeepEP training now uses the expand layout (do_expand=True), which the generator already used. get_buffer passes allow_multiple_reduction=True, so in dispatch backward an expand-mode combine sums a token's rows on the expert rank and accepts one topk_weights per row. This deletes _permute_tokens/_unpermute_tokens: the boolean-mask gather, argsort, repeat_interleave, bf16 scatter_add_, and 4 host syncs per layer. cuda_graph_compatible now only selects do_cpu_sync.

Example. This rank holds e0 and e1. Token A picks e0 and e1, B picks e1, C picks e0.

before: dispatch -> recv_x=[A,B,C] + recv_topk_idx
        _permute_tokens -> [A,C,A,B] (host syncs) -> experts * scores -> scatter_add_ -> combine
after:  dispatch -> recv_x=[A,C,A,B], counts=[2,2] (device-side psum)
        experts * scores -> combine (DeepEP sums A's two rows, then sums across ranks)

Earlier findings

  • Convergence: resolved. 300 steps of the Qwen3 MoE debug model on c4_test (TP 2 x EP 2, deterministic, default remat). The step-11 gap goes away: from step 21 on, the PR's mean loss is 0.010-0.024 below base. That fits a routing flip, not a correctness bug.
  • moe.py side-stream docstring: resolved. torchtitan/models/common/moe/moe.py:814 now reads "DeepEP with cuda_graph_compatible=True".

Must fix

  1. The H100 CI (ciflow/h100.8: this PR's DeepEP GPU test plus qwen3_fsdp+deepep, FSDP 4 x EP 4) is still pending. It is the only coverage for EP 4 and H100, so wait for it to pass before merging.

Questions

  • #5315 (graph_trainer DeepEP tracing plus shared-expert overlap; open, last updated 2026-10-20) builds on the compact _permute_tokens path that this PR deletes. Maintainers should decide the order. If this lands first, #5315 has to rebase onto expand. Its defer_epilogue split also needs DeepEP >= 2.5, and nobody has checked that with do_expand=True.
  • Memory under default remat: DeepEP now saves the expanded rows, as AllToAllTokenDispatcher already does. For fused_swiglu configs (the shipped DeepEP RL recipes), that is +43-48% per MoE layer at EP 2, shrinking as EP grows. Maintainers should accept this explicitly.
Details
  • No new findings at HEAD. Re-checked:
    • combine_tokens now takes 1-D recv_scores (unsqueeze(1)).
    • _combine_backward passes do_expand=True explicitly for the cached-handle dispatch.
    • DispatchState keeps only handle_id and recv_scores.
    • No in-repo references to the deleted symbols or to the old 5-output op schema remain.
  • test_matches_all_to_all_dispatcher is worth its cost. Routing (t + k) % E with E = 8 and top-2 over 2 ranks gives both cases: tokens whose two picks land on one rank (exercising the local sum in expand mode) and tokens whose picks split across ranks. The per-token loss weight (t + 1) catches a combine that returns rows to the wrong tokens. The test checks no-grad output, grad-mode output, input grad, gate grad and expert grads against all-to-all.
  • The renamed test_trainer_keeps_host_synced_dispatch matches what it asserts. The recipe and docstring edits are mechanical.

Not verified: DeepEP kernel line references, the GPU test results, and the perf, memory and convergence numbers (all from the author's runs).

@felipemello1
felipemello1 force-pushed the felipemello1/deepep/expand-training branch from 0040493 to 4fcc35b Compare October 30, 2026 03:08
@felipemello1
felipemello1 force-pushed the felipemello1/deepep/expand-training branch from 4fcc35b to 5ceecae Compare October 30, 2026 03:59
Felipe Mello added 2 commits November 2, 2026 09:09
…mute

DeepEP's expand layout returns the received rows already grouped by local
expert, and its combine sums each token's rows on the expert rank before
sending them. Training used the compact layout instead, then gathered the rows
into expert order and scatter-added them back in eager: boolean-mask indexing,
an argsort, repeat_interleave and a copy of the counts (host syncs), and a bf16
atomic scatter_add_. The expand layout is backward-able: DeepEP's "must not be
backward" assert only covers expanded send without that local sum, and
get_buffer now sets allow_multiple_reduction=True explicitly.

cuda_graph_compatible now only picks do_cpu_sync. It stays inference-only
because without a host sync recv_x reserves about num_tokens_per_rank *
ep_size * min(top_k, num_local_experts) rows.

One MoE layer fwd+bwd, EP 2 on 2x GB300, no remat, 16k / 32k tokens per rank:
DeepSeek-V3 671B 44.7 -> 39.8 / 79.1 -> 77.0 ms eager; Qwen3.5-35B-A3B 11.6 ->
9.0 / 17.7 -> 14.4 ms eager. Under the default remat the saved dispatch output
is now the expanded rows (+1349 MiB per DeepSeek-V3 layer at 16k, EP 2). The
training forward now equals the generator's CUDA-graph forward bitwise.
The expand layout copies a token once per local expert it picked, so recv_x
has R rows for U received tokens (R/U = 4.07 for DeepSeek-V3 and 4.01 for
Qwen3.5 at EP 2, 16k tokens per rank). The default remat saves the dispatch
region and keeps recv_x for the replayed w13, so it kept R rows where main's
compact layout kept U: +1349 MiB per DeepSeek-V3 layer at 16k tokens per rank.

Saved-tensor hooks around the dispatch region now keep one row per received
token plus each row's token index (int32), read from DeepEP's handle
(recv_src_metadata[:, 2:]), and rebuild recv_x with a gather in replay. The
rows are copies, so the rebuilt recv_x is bitwise equal. Kept memory per layer
is now 2-3 MiB below main's (DeepSeek-V3 2834.0 -> 2831.7 MiB at 16k). Without
remat the hooks never run.
@felipemello1
felipemello1 force-pushed the felipemello1/deepep/expand-training branch from 5ceecae to 80eb09e Compare November 2, 2026 19:26
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Rebased on main, and fixed a memory regression in the previous head. With default remat, the kept dispatch output had one row per expert pick, so kept memory per layer grew 43-48% at EP 2. It now keeps one row per received token plus an index (_OneRowPerTokenHooks in deepep.py), and replay gathers the rows back bitwise.

kept memory per MoE layer, EP 2, 16k tokens per rank (MiB)
model        main   previous head   this head
DSv3         2834   4183            2832
Qwen3.5       888   1271             886

The remat cost is 2-3% per layer; the layer is still 6.6-27% faster than main. The description has the details.

@claude please review

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items below before merging: wait for the queued H100 CI to pass at this head, and add a TODO for the DeepEP-internal recv_src_metadata layout. 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 new remat hooks fix the +43-48% kept-memory regression from the previous head without host syncs. What's left is small local edits plus the H100 CI. A maintainer still needs to review, because this is core distributed code.

What changed since the last review. With the default remat, the saved dispatch region keeps recv_x for the replayed w13. In the expand layout recv_x has one row per (token, local expert) pick. _OneRowPerTokenHooks (installed with remat.saved_tensors_hooks around the dispatch region) now packs recv_x as one row per received token plus a per-row token index. Both come from DeepEP's recv_src_metadata. unpack rebuilds recv_x with a gather.

Example. This rank holds e0 and e1. Token A picks e0 and e1, B picks e1, C picks e0.

recv_x = [A, C, A, B]             recv_src_metadata[:, 2:] = [[0, 2], [3, -1], [1, -1]]   (A, B, C)
pack:   recv_x_UD = recv_x[amax] = [A, B, C]     row_to_token_R = [0, 2, 0, 1]
unpack: recv_x_UD[row_to_token_R] = [A, C, A, B]  (bitwise)
kept: 3 rows + 4 int32 instead of 4 rows; without remat the hooks never run

Must fix

  1. H100 CI (ciflow/h100.8) is still queued at 80eb09e. The last green run (41000410503) was on 5ceecae72, which predates the hooks. It is the only EP 4 / H100 coverage of pack/unpack, so wait for it to pass.
  2. torchtitan/distributed/deepep/deepep.py:415 -- recv_src_metadata[:, 2:] relies on an undocumented DeepEP layout. Add a TODO (and optionally a shape assert); see the inline comment.

Should consider

  • torchtitan/distributed/deepep/deepep.py:405-413 -- turn the RuntimeError into an assert. Drop the expert_alignment check, because torchtitan never sets expert_alignment.
  • torchtitan/distributed/deepep/deepep.py:546 -- store the handle instead of its id. _combine_setup_context pops the id from _handle_cache, so a pack that runs after combine would raise a KeyError.
  • deepep.py now uses the shape suffixes U/K/R/D. .claude/CLAUDE.md asks for a one-line legend at the top of the file.

Questions

  • #5315 is still open (last updated 2026-10-20) and builds on the compact path this PR deletes. Maintainers still need to decide the merge order. This is unchanged from the last review.
Details
  • Hook filter: pack passes through every non-2-D tensor. That is safe at HEAD. _dispatch_setup_context saves no tensors (it keeps only the dtype and the handle), so the only tensors retained in the region are the 4 outputs, and of those only recv_x is 2-D (recv_scores is [R], combine_tokens uses unsqueeze(1)). use_fp8_dispatch has no caller that sets it to True, so recv_x is never an fp8 tuple.
  • No host syncs in pack/unpack: handle_id is a CPU tensor (_get_next_handle_id), and the scatter, amax and index_select all run on device. row_to_token_R is torch.empty. With do_cpu_sync=True and alignment 1, every row is the target of exactly one (token, k), so no entry stays uninitialized.
  • amax(dim=1): every received token has at least one non-negative row id on this rank, so the max is a valid row.
  • test_saved_dispatch_keeps_one_row_per_token is worth its CI cost. It guards both the memory regression (the previous head had it, and nothing caught it) and the bitwise rebuild across DeepEP version bumps. The bound sits halfway between the two row counts, so it discriminates.
  • Rebase: the diff against the stack base contains no unrelated changes.

Not verified: torch_remat's pack timing (I couldn't inspect torch_remat.saved_tensors_hooks), the DeepEP recv_src_metadata column semantics, the GPU test results, and the memory, perf and convergence numbers (all from the author's runs).

Comment thread torchtitan/distributed/deepep/deepep.py Resolved
Comment thread torchtitan/distributed/deepep/deepep.py Resolved
Comment thread torchtitan/distributed/deepep/deepep.py Resolved
… add a TODO and a legend

recv_src_metadata[:, 2:] is a DeepEP-internal layout: a TODO says so, and an assert on its
width (2 + top_k, kMetadataStride in DeepEP's kernels) turns a layout change into an error.
The hooks keep the handle instead of its id, so pack no longer depends on running before
combine pops the cache entry. Internal checks are asserts; the expert_alignment check is
gone (torchtitan never sets it). deepep.py gets a shape-suffix legend.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Addressed the 19:40 review in bebd6b2: a TODO plus an assert on DeepEP's recv_src_metadata width (2 + top_k), the internal checks as asserts without the expert_alignment check, the hooks keeping the handle instead of its id, and a shape-suffix legend in deepep.py. ciflow/h100.8 re-runs the DeepEP tests on this head.

@claude please review

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 53s —— View job


Approve -- please address the items below before merging: all four earlier items are resolved in bebd6b2; the only blocker left is the H100 CI, which is still queued at this head. 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. bebd6b2 resolves all four items from the last review and adds no new problems. The only remaining blocker is the H100 CI, which is still queued at this head. A maintainer still needs to review, because this is core distributed code.

What changed since the last review. _OneRowPerTokenHooks now:

  • takes top_k;
  • keeps the EPHandle itself, looked up from _handle_cache right after dispatch returns;
  • asserts that recv_src_metadata has 2 + top_k columns, under a TODO that names the DeepEP-internal layout.

The RuntimeError/ValueError checks are now one assert, and the expert_alignment check is gone. deepep.py also gets a shape-suffix legend (U/R/K/D).

Example. This is the ordering hazard the handle change removes:

before: pack -> _handle_cache[handle_id.item()]   # KeyError if pack ever ran after combine popped the entry
after:  dispatch_tokens -> hooks.handle = _handle_cache.get(handle_id.item())   # once, before combine
        pack -> hooks.handle.recv_src_metadata     # no cache lookup, no ordering dependency

Earlier findings

  • recv_src_metadata[:, 2:] TODO: resolved (deepep.py:410-417). The width assert turns a DeepEP column change into a hard error.
  • RuntimeError -> assert, expert_alignment check dropped: resolved (deepep.py:410).
  • Hooks keep the handle instead of its id: resolved (deepep.py:550). In replay, .get returns None once combine has removed the entry. Nothing is packed in replay, so None is never read.
  • Shape-suffix legend: resolved (deepep.py:32-33).

Must fix

  1. The H100 CI (ciflow/h100.8, which runs this PR's DeepEP GPU test and qwen3_fsdp+deepep) is still queued at bebd6b2. It is the only EP 4 / H100 coverage of pack/unpack and of the new width assert, so wait for it to pass.

Questions

  • #5315 is unchanged since the last two reviews. It builds on the compact path this PR deletes, and maintainers still need to decide the merge order.
Details
  • handle_id.item() now runs in the body of dispatch_tokens on every forward, not only inside pack. That is harmless today:
    • handle_id is a CPU tensor (_get_next_handle_id), so there is no device sync, and the call is safe under CUDA-graph capture.
    • Core never compiles dispatch_tokens: local_compile wraps only the router, activation, norm and rope regions.
    • deepep::dispatch has no fake kernel, so graph_trainer can't trace it.
  • Once #5315 adds fake kernels and traces this function, this line will need a non-traced path. This is a coordination point for #5315, not a defect here.
  • Holding the handle on the hooks object adds no memory: ctx.saved_handle already keeps it alive until backward, and under no_grad the hooks object dies when dispatch_tokens returns.
  • test_deepep_activation_checkpoint.py doesn't touch the hooks' attributes, so the rename from handle_id to handle needs no test change.

Not verified: GPU test results at this head, and DeepEP's kMetadataStride = 2 + kNumTopk (from the author's reply).

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Related open PR: #5543 (Mystri) applies the router scores before w2 on the DeepEP path.

Felipe Mello added 6 commits November 3, 2026 18:33
…ipemello1/deepep/expand-training

Conflict: tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py.
#5770 on main split the test into a shared _EPActivationCheckpointing harness with
DeepEP and HybridEP subclasses (_DeepEPBlock -> _EPBlock(num_experts, dispatcher_config)).
Kept main's harness; moved this PR's two tests (test_matches_all_to_all_dispatcher,
test_saved_dispatch_keeps_one_row_per_token) into TestDeepEPActivationCheckpointing,
building each model with its dispatcher config instead of swapping the dispatcher.

Also updates the DeepEP row of #5770's moe/README.md: training now dispatches into
the expand layout.
…6 goldens) into felipemello1/deepep/expand-training

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/h100.8 Trigger H100.8 CI 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.

1 participant