Repository navigation
[deepep] Train on the expand layout; drop the eager permute and unpermute - #5708
felipemello1 wants to merge 13 commits into
Conversation
|
Reply from claude: @claude please review |
|
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 |
There was a problem hiding this comment.
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
- Convergence evidence. This changes computation (the combine's rounding order), and
.claude/CLAUDE.mdasks 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_deepepat FSDP 4 x EP 4, the CI config). That would show the step-11 jump is transient. 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 withcuda_graph_compatible=True".
Questions
- #5315 (yuweih205, graph_trainer DeepEP tracing + shared-expert overlap) adds fake kernels for the compact
_permute_tokenspath and alaunch_dispatch/wait_dispatchsplit for it. Have you agreed with them that it rebases onto expand? Does DeepEP'sdefer_epiloguesupportdo_expand=True? - Memory under default remat: DeepEP now saves the expanded rows, the same as
AllToAllTokenDispatcher(its dispatch region returnsrouted_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 usefused_swiglu).
Details
- No stale references: no remaining in-repo use of
_permute_tokens,_unpermute_tokens,permuted_indices/num_recv_tokenson the DeepEPDispatchState, or the old 5-outputdeepep::dispatchschema.graph_trainer/memory_policy.py:93only tags the op. combine_tokensnow assumesrecv_scoresis 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_dispatcherearns its cost. It guards expand-mode backward (x grad, score grad through combinetopk_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_deepepis 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).
c9a86d5 to
0040493
Compare
|
Reply from claude:
@claude please review |
|
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 |
There was a problem hiding this comment.
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.pyside-stream docstring: resolved.torchtitan/models/common/moe/moe.py:814now reads "DeepEP withcuda_graph_compatible=True".
Must fix
- The H100 CI (
ciflow/h100.8: this PR's DeepEP GPU test plusqwen3_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_tokenspath that this PR deletes. Maintainers should decide the order. If this lands first, #5315 has to rebase onto expand. Itsdefer_epiloguesplit also needs DeepEP >= 2.5, and nobody has checked that withdo_expand=True. - Memory under default remat: DeepEP now saves the expanded rows, as
AllToAllTokenDispatcheralready does. Forfused_swigluconfigs (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_tokensnow takes 1-Drecv_scores(unsqueeze(1))._combine_backwardpassesdo_expand=Trueexplicitly for the cached-handle dispatch.DispatchStatekeeps onlyhandle_idandrecv_scores.- No in-repo references to the deleted symbols or to the old 5-output op schema remain.
test_matches_all_to_all_dispatcheris worth its cost. Routing(t + k) % Ewith 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_dispatchmatches 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).
0040493 to
4fcc35b
Compare
4fcc35b to
5ceecae
Compare
…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.
5ceecae to
80eb09e
Compare
|
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 ( 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 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 |
There was a problem hiding this comment.
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
- H100 CI (
ciflow/h100.8) is still queued at80eb09e. The last green run (41000410503) was on5ceecae72, which predates the hooks. It is the only EP 4 / H100 coverage ofpack/unpack, so wait for it to pass. 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 theRuntimeErrorinto anassert. Drop theexpert_alignmentcheck, because torchtitan never setsexpert_alignment.torchtitan/distributed/deepep/deepep.py:546-- store the handle instead of its id._combine_setup_contextpops the id from_handle_cache, so a pack that runs after combine would raise aKeyError.deepep.pynow uses the shape suffixesU/K/R/D..claude/CLAUDE.mdasks 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:
packpasses through every non-2-D tensor. That is safe at HEAD._dispatch_setup_contextsaves 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 onlyrecv_xis 2-D (recv_scoresis[R],combine_tokensusesunsqueeze(1)).use_fp8_dispatchhas no caller that sets it to True, sorecv_xis never an fp8 tuple. - No host syncs in
pack/unpack:handle_idis a CPU tensor (_get_next_handle_id), and the scatter,amaxandindex_selectall run on device.row_to_token_Ristorch.empty. Withdo_cpu_sync=Trueand 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_tokenis 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).
… 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.
|
Reply from claude: Addressed the 19:40 review in bebd6b2: a TODO plus an assert on DeepEP's @claude please review |
|
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 |
There was a problem hiding this comment.
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
EPHandleitself, looked up from_handle_cacheright after dispatch returns; - asserts that
recv_src_metadatahas2 + top_kcolumns, 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_alignmentcheck dropped: resolved (deepep.py:410).- Hooks keep the handle instead of its id: resolved (
deepep.py:550). In replay,.getreturnsNoneonce combine has removed the entry. Nothing is packed in replay, soNoneis never read. - Shape-suffix legend: resolved (
deepep.py:32-33).
Must fix
- The H100 CI (
ciflow/h100.8, which runs this PR's DeepEP GPU test andqwen3_fsdp+deepep) is still queued atbebd6b2. It is the only EP 4 / H100 coverage ofpack/unpackand 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 ofdispatch_tokenson every forward, not only insidepack. That is harmless today:handle_idis 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_compilewraps only the router, activation, norm and rope regions. deepep::dispatchhas 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_handlealready keeps it alive until backward, and under no_grad the hooks object dies whendispatch_tokensreturns. test_deepep_activation_checkpoint.pydoesn't touch the hooks' attributes, so the rename fromhandle_idtohandleneeds no test change.
Not verified: GPU test results at this head, and DeepEP's kMetadataStride = 2 + kNumTopk (from the author's reply).
|
Reply from claude: Related open PR: #5543 (Mystri) applies the router scores before w2 on the DeepEP path.
|
…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
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.Stack (merge bottom-up; this PR is in bold)
Problem
deepep.pykept expand for inference only, quoting a DeepEP kernel assert ("must not be backward")._permute_tokensexpanded and sorted the rows in eager before the grouped GEMM: a boolean-mask gather, an argsort,repeat_interleave,index_select. The masks andrepeat_interleavesync with the host._unpermute_tokenssummed each token's rows with a bf16scatter_add_. It rounds after every add, and it is non-deterministic outside torch's deterministic mode.Solution
deep_ep/impls/combine.cuh:42, assert at:69). Withallow_multiple_reduction=True(theElasticBufferdefault, now passed explicitly inget_buffer), combine sums a token's rows on the expert rank first and accepts one score per row.do_expand=True.cuda_graph_compatiblenow only picksdo_cpu_sync. Combine's backward re-dispatches withdo_expand=Truetoo._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._permute_tokens,_unpermute_tokens, the compact fields ofDispatchState, and the op'srecv_topk_idxoutput.cuda_graph_compatible=Truestays inference-only. Without a host sync,recv_xreserves up toep_sizetimes the routed rows: too many to keep for backward. Scores are still applied incombine_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.
scatter_add_, one rounding per added row.deep_ep/impls/combine_utils.cuh:115-165).combine_utils.cuh:68-70).What was compared (stack matrix at this head, script not in this PR):
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):
Worst cell, Kimi K3 at EP 4 (2.9x):
routed_upto the combine output (models/kimi_k3/moe.py:89). So the rounding change also reaches the expert, router androuted_downgrads (2.6e-3, 2.7e-3, 5.2e-3).Every model and layout (stack matrix grid)
Determinism (one MoE layer, DeepSeek-V3 and Qwen3.5, EP 2, deterministic mode off):
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.
Memory: kept for backward stays at base
Speed
You may ask:
DispatchStatelayout. The hooks are torch_remat's API for storing a kept tensor in another form.do_cpu_sync=False)?recv_xand the expert activations would be up toep_sizetimes larger, and autograd keeps them for backward.w13? Thenw13keeps 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:
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).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:AllToAllTokenDispatcherup 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;ciflow/h100.8) at this head: the DeepEP test (4 passed) andqwen3_fsdp+deepep(FSDP 4 x EP 4) pass.test_transforms.py,test_inference_moe.py,test_debug_config_defaults.py,test_integration_test_definitions.py: 105 passed.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.