Repository navigation
[dsv3][perf] Group-limited routing with argmax rounds in the compiled router - #5574
felipemello1 wants to merge 12 commits into
Conversation
9ab5003 to
eb85d2d
Compare
374e752 to
736988a
Compare
736988a to
6c88eb2
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 1m 55s —— View job Approve -- please address the items before merging (make |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The change is small, stays inside the DeepSeek-V3 model folder, keeps the eager path unchanged, and the router speedup is measured. The remaining items are local edits. A maintainer still needs to review, and should also decide how this relates to the fused-router PRs (see Questions).
What this PR does. Inside the compiled moe_router_topk region, DeepSeekV3Router._select_experts used to call torch.topk three times: top-2 per group, top groups, top experts. It now uses PR 1's argmax rounds for all three, so Inductor can fuse the whole selection. Eager still uses topk. The final pick now goes through the base _select_experts (bias None, since it was already added), which in eager is the same topk(sorted=False) as before. The group checks move to build time, and two new checks ban configs where argmax rounds would repeat an id.
Example. For 671B, scores_TE has shape (T, 256) and is unflattened to (T, 8, 32).
eager: topk(2) per group -> sum -> topk(4) groups -> mask -> topk(8) (3 ATen kernels)
compiled: argmax x2 per group -> gather+sum -> argmax x4 -> mask -> argmax x8 (fused region)
tie row (from the new test): scores [.5 .5 | .25 .75 | .5 .5 | .125 .125], keep 2 groups, top 2
group scores 1.0 1.0 1.0 0.25 -> compiled keeps groups {0, 1} (lower ids win) -> ids [3, 0]
eager topk on ties: implementation-defined
The two-value sum is order-independent and both paths emit [max, second], so group scores are bitwise equal. The only numerics difference is the order in which route_norm sums the 8 picked scores, as the description says.
Must fix
torchtitan/models/deepseek_v3/moe.py:12-- imports the private_topk_ids_by_argmaxfrom another module. It now has two consumers, so make it public (topk_ids_by_argmax) and export it fromtorchtitan.models.common.moe.torchtitan/models/deepseek_v3/moe.py:31-59-- the group checks belong inDeepSeekV3Router.Config.__post_init__, not__init__(rules/config.md; same pattern asRoutedExperts.Config). Update the test attest_deepseek_v3_moe.py:145-155to build the config insideassertRaisesRegex.
Should consider
torchtitan/models/deepseek_v3/moe.py:67-68-- thenum_limited_groups is Nonebranch can't be reached and reads like a fallback. Branch onnum_expert_groupsalone and assert the invariant.
Questions
- Several open PRs also speed up the DSv3 router: #5551 (fused general-shape router fwd/bwd, opt-in), #5258, #5264, and #5682 (compile router postprocessing). If #5551 also lands, DSv3 has two ways to speed up the same step. Maintainers should decide whether both should exist, or whether one supersedes the other. The description's side-by-side has the fused kernel ahead at decode and at its tuned 4k fwd+bwd shape, and this PR ahead at 16k and above.
Details
- Gate: the problem is real and quantified. Three ATen
topkkernels break the compiled region; the PR measures the router alone at -43% to -76%, and estimates about 0.7% of a fwd+bwd MoE layer. The change is model-local; the shared router is untouched. - The new checks guard real silent failures. If
num_limited_groups * num_experts_per_group < top_k, eagertopkwould pick-inf-masked experts. If kept groups exceed total groups, eager raises at runtime but argmax rounds would repeat ids. No in-repo flavor (236B: 8/3, 671B: 8/4) or the transformers-backend HF mapping trips them for real DSv3 configs. - Finite-score assumption: with a
-infexpert bias, a group whose other experts are all-infhas a second argmax that can return the already-picked id, so the group score becomes2*maxinstead of-inf. The description already notes this; no shipped bias does it. - Tests: the tie-row test covers the compiled branch on CPU via the patched
is_compiling. The existing GPUtest_router_compile.pyalready includes the 671B router (compiled vs eager, batch-size invariance), so no new GPU test is needed. Neither the shipped flavors nor the integration configs turn on group routing, so no golden loss files change.
Not verified: the GPU timings, and the claim that compiled and eager pick bitwise-equal expert ids on the 671B shapes (I couldn't run GPU tests).
6c88eb2 to
cc6140d
Compare
|
Reply from claude: applied both. |
cc6140d to
1fc8d61
Compare
1fc8d61 to
ab31923
Compare
…ting When compiled, DeepSeekV3Router._select_experts scored the groups and picked experts with three ATen topk calls, which Inductor can't fuse. It now uses the argmax rounds the base router uses (_topk_ids_by_argmax) for the top-2 group score and the kept groups, and the base _select_experts for the final top-k. Eager is unchanged. Ties pick the lower id, as CUDA topk does. Two build-time ValueErrors cover the group configs where argmax rounds would repeat ids: more kept groups than groups, or kept groups that hold fewer than top_k experts. No shipped flavor trips them. DeepSeek-V3 671B router region (E256, 8 groups, 4 kept, top-8), region alone, 1x GB300, CUDA graphs, us per call, eager -> compiled: fwd T=1 44.2 -> 11.1 fwd T=64 48.1 -> 14.1 fwd T=1024 74.5 -> 15.6 fwd T=16384 504.0 -> 32.1 fwd+bwd 1024 96.3 -> 21.4 fwd+bwd 16384 536.0 -> 49.4 Expert ids equal eager's in every cell. With topk inside the region (the previous PR), 16k forward was 468.2.
_select_experts keeps main's 'num_limited_groups is None -> ValueError' lines unchanged; they also narrow the type, so no local variable or assert is needed. Config.__post_init__ rejects that config first.
ab31923 to
12bb343
Compare
|
Reply from claude: Rebased on main. One change: @claude please review |
|
Claude finished @felipemello1's task in 1m 8s —— View job Approve -- all earlier review items are resolved at the rebased HEAD, and the rebase adds no new problems. Full review: #5574 (review) |
There was a problem hiding this comment.
Verdict: Approve -- all three earlier items are resolved at HEAD, and the rebase adds no new problems. A maintainer still needs to review this, and should decide how it relates to #5551 (see Questions).
What this PR does. Inside the compiled moe_router_topk region, DeepSeekV3Router._select_experts now uses argmax rounds (topk_ids_by_argmax) instead of three torch.topk calls, so Inductor can fuse the whole group-limited selection. Eager keeps the topk calls. The group checks now live in Config.__post_init__, along with three new checks for configs that would otherwise fail silently.
Example. This is the tie row from the new test (test_deepseek_v3_moe.py:121-136): 8 experts in 4 groups, keep 2 groups, top_k=2.
scores [.5 .5 | .25 .75 | .5 .5 | .125 .125]
group scores 1.0 1.0 1.0 0.25
compiled: keep groups {0, 1} (lower ids win the 3-way tie)
mask groups 2, 3 -> argmax x2 over [.5 .5 .25 .75 -inf ...] -> ids [3, 0]
eager: same top-2 sums; which group wins a tie is implementation-defined
Earlier items
- Private import: resolved.
topk_ids_by_argmaxis public, exported fromtorchtitan.models.common.moe(__init__.py:18,:32), and imported from there (deepseek_v3/moe.py:11). - Checks in
__post_init__: resolved (deepseek_v3/moe.py:26-59).TokenChoiceTopKRouter.Confighas no__post_init__, so not callingsuper()is fine. The test builds theConfiginsideassertRaisesRegex. - Unreachable fallback branch: resolved.
_select_expertsbranches onnum_expert_groups is Nonealone. Thenum_limited_groups is Noneraise at:78-81is main's code, kept to narrow the type, and__post_init__rejects that config first. Your choice to keep it over an assert is fine.
Questions
- #5551 (fused general-shape DSv3 router fwd/bwd, opt-in) and #5682 (compile router postprocessing) are still open. If #5551 lands too, DSv3 gets two ways to speed up the same step. Maintainers should decide whether both should exist. Per the description's side-by-side, the fused kernel is faster at decode and at 4k fwd+bwd, and this PR is faster at 16k and above.
Details
- Checked at HEAD: the compiled path is correct for every config
__post_init__accepts, assuming finite scores. The kept groups hold at leasttop_kfinite experts, so the final argmax rounds at:111never pick an id that is already taken or a-infid.topk_ids_by_argmaxworks on the 3-Dscores_TGP, becausearange(P) == top_id_TG1broadcasts over the leading dims. - No in-repo caller trips the new checks: the 236B flavor uses 8/3 (
flavors.py:675-676), the 671B flavor 8/4 (:763-764), and the transformers backend buildsDeepSeekV3Routeronly whenn_groupis set (moe_replacement.py:479-489). - No integration config turns on group routing, so no golden loss files change.
Not verified: the GPU timings, and that compiled and eager pick the same expert ids on 671B shapes. I couldn't run GPU tests; the author reports the 671B router compile test passes at this HEAD.
|
Reply from claude: Similar open PR: #5551 (sanketpurandare), an opt-in fused DeepSeek-V3 router kernel for one recipe, with TP = 1 and CP = 1. It complements this PR: every other DeepSeek-V3 config runs the default group-limited routing this PR speeds up. |
… 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.
Summary (human-written)
Agent details
Written with Claude Code: the analysis, measurements and test plan below.
TLDR: When compiled, DeepSeek-V3's group-limited router picks its groups and experts with argmax rounds (k argmax calls, each masking the previous pick) instead of three
torch.topkcalls. The whole selection then fuses into PR 1's router region. Every test picks the same experts as before; scores move by at most 1.2e-7. The 671B router gets 40-48% faster at decode, 59-76% at prefill and 43% in fwd+bwd, about 1% of a training MoE layer (estimate).Stack (merge bottom-up; this PR is in bold)
Problem
moe_router_topk). It picks experts with argmax rounds, which Inductor fuses with the scoring.torch.topk3 times: top-2 per group, top groups, top experts.topkas a separate ATen kernel, so with PR 1 alone the 671B router stays slow.Solution
topk_ids_by_argmaxpicks the top-2 experts of each group (their scores are summed), then the kept groups. The final pick calls the base_select_experts, which already uses argmax rounds when compiled. Ties go to the lower id.topk_ids_by_argmaxbecomes public (exported fromtorchtitan.models.common.moe): it now has two users.DeepSeekV3Router.Config.__post_init__. A bad config now fails at build time with aValueError, not inside the compiled region. Three checks are new:num_limited_groupsset withoutnum_expert_groups(it used to fall back to ungrouped routing silently),top_kexperts.The last two would make argmax rounds repeat ids. No shipped flavor trips them.
topkcalls. Every other router is untouched.Numerics: same experts; scores and grads differ only by rounding
Why not bitwise: the picked experts are the same, but argmax rounds return them in descending score order, and
topk(sorted=False)doesn't. Soroute_normsums the 8 picked scores in another order.Every model and layout (stack matrix grid)
Memory: unchanged. In the matrix, kept and peak memory equal PR 2's in every cell.
Speed
batch_invariant=True,recompile_limit=16).All shapes
You may ask:
amaxplus a masked secondamax? One selection helper instead of a copied round. Theamaxform was 0.7-2.0 µs faster per call (16k forward: 30.1 vs 32.1 µs, earlier run).NOTE:
Test plan
pytest tests/unit_tests/cpu/models/deepseek_v3/test_deepseek_v3_moe.py: the compiled branch on a tie row (three groups and two experts tie; the lower ids win), and each newValueErrorby its message. 8 passed at this head.pytest tests/unit_tests/gpu/models/common/test_router_compile.py: the 671B router compiled vs eager (fwd + bwd), and its outputs don't depend on batch size (bitwise). 2 passed on GB300 (same diff as this head).