Repository navigation
[MoE] Apply router scores before W2 projection - #5543
Conversation
|
|
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows. |
|
@tianyu-l, could you take a look when you have time, particularly at moving router scores before W2 and the never-replayed combine regions? I’ve included dispatcher parity tests and before/after saved-tensor reports. If another maintainer would be better placed to review this, please point me to them. Thanks! |
|
@claude explain the gain from this PR for different combinations of (remat policy, deepep / hybridep dispatcher) combinations. The complexity is quite high, so I wanted to understand if the change is worth it; and if so if there are other ways to make it more maintainable. Some notes:
|
|
Claude finished @tianyu-l's task in 3m 40s —— View job Is this PR worth its complexity? Gain by (remat policy × dispatcher)Short answer: the memory gain is real and large for one combination: DeepEP + a policy that saves I got the numbers below by reading the code, not by running it. Sizes are for 671B per GPU: T=4096, top_k=8, D=7168, F=2048, so R = T·top_k = 32768. Per layer, the
Notes on the table:
Is it worth it?For DeepEP with the Default policy, yes: the How to make it more maintainable
|
|
@Mystri wouldn't recomputing |
Yes, recomputing
Also, reconstructing the score multiplication’s input does not cost just
|
|
why the computation can be dropped? you still need to recompute W2(h_RF) for the gradient? |
@acisseJZhong, the implementation moves expert scoring before W2, disables the original scoring in combine, so the score gradient needed the unweighted W2 output, # In GroupedLinear.forward, before W2's grouped GEMM:
input_RI = (input_RI.float() * routed_scores_R.reshape(-1, 1)).to(
input_RI.dtype
)The dispatcher then ensures the score is applied exactly once:
So in theory we don't depend on the activation W2(h_RF) in backward calculation anymore. After that it was just some tweaks with remat to ensure that output is not to be recomputed. |
Compared the output of these 3 configs with 5-moe-layer Deepseek-V3 debug model:
This shows that W2(h_RF) is neither recomputed or saved. |
NVIDIA/Megatron-LM@2659630 some reference PR. |
is this the overall idea? essentially you just save one matmul(GEMM 3) but introduces one more elementwise multiplication( |
|
thanks for the detailed data! so you are saying for each backward it could save us
could you help me understand using my example? thanks! |
Oh, I was reading it wrong. I was talking about dh = s * da replaces the original dz = s * g; there is a score multiplication in backward either way. Indeed a = s * h needs to be rebuilt. |
for each recompute phase we expect to save around |
Apply router scores to the expert activations before the down (W2) projection instead of multiplying the expert output in combine, so the combine reduces to a plain sum: - Token dispatchers expose absorb_router_scores. When set, dispatch returns routed_scores_R in its metadata and combine skips its score multiply. Covered backends: standard (local + all-to-all), TorchAO (EP=1 padded and EP>1), and DeepEP/HybridEP (opt-in). - GroupedLinear.forward takes routed_scores_R and scales the projection input in float32, restoring the input dtype before the grouped GEMM. RoutedExperts passes it to W2 only, and only when a score is actually absorbed, so W2 modules that do not know about scores are unaffected. - GptOssGroupedLinear scales its post-W2 bias rows by the same scores, so the result stays score * (h @ W2 + b2). - DeepEP/HybridEP dispatchers take the per-row scores the backend already tracks and clear them from the dispatch state, which is what makes the backend combine skip its fused score multiply. - make_routed_experts_config leaves the standard backend on auto and the DeepEP family off. Auto resolves when RoutedExperts is built: the score is absorbed unless output_postprocess owns the expert outputs, because absorbing scales W2's input while the postprocess runs after W2, and a scale-invariant postprocess (e.g. post-expert RMSNorm) would drop the score. Asking for both explicitly raises a ValueError. - swap_token_dispatcher propagates the flag through MoE quantization. Replay: with router scores absorbed, combine no longer scales expert outputs, so the DeepEP compact combine would read the W2 output from a bare _unpermute_tokens on the replay path. Fold the score multiply, unpermute and combine kernel into one never-replayed region, which keeps the W2 and combine outputs off the saved-tensor set. On the standard all-to-all path the absorbed scores are an output of the saved dispatch region, so mark them before W2's bare scaling; that marker is a no-op on the DeepEP/HybridEP paths and without an active checkpoint. Squashed from the router-score-pre-w2-review series and rebased onto current upstream main. Absorbed and post-combine paths agree to bf16 rounding; loss convergence on a representative dataset is still pending.
Give the local, all-to-all and TorchAO dispatchers the combine structure DeepEP got with router-score absorption: one never-replayed "<fqn>.combine" region whose body reads the w2 output, instead of bare ops guarded by recompute_needs_tensor markers. - Local and TorchAO EP=1 ran the scatter-add (and the padded unpermute) as bare ops, so replay needed the w2 output persisted: the marker pinned the full expert-output tensor (R x D) per MoE layer even with absorbed scores, where no backward consumer needs it (the scatter-add saves only indices). - The EP>1 combine region was policy-replayable. Replaying it re-ran the combine all-to-all and required the w2 output real on the replay path (pinning it under policies that save w2), while saving it retains only the small permutation indices and scores, so no policy benefits from replaying it. Dispatch stays policy-driven everywhere, like DeepEP's dispatch. Replay: the combine body runs only on the original forward; replay skips it, so nothing on the replay path reads the w2 or combine outputs, and with absorbed scores the w2 output is freed after the forward. Also fix the stale DeepEP docs and AC test left by the absorption commit: the DeepEP combine region is never replayed, so only dispatch call counts grow under the full policy. Tests: - New tests/unit_tests/cpu/models/common/test_token_dispatcher.py: the combine body runs exactly once under every policy while the w2 projection's replay still follows the policy; with absorbed scores and w2 saved, the w2 output storage is freed after the forward; loss and grads match the un-checkpointed run bitwise. It fails on the previous code. - test_remat_all_to_all: the combine never replays, so the full policy replays 2 collectives (was 3) and saving dispatch alone stops all replay; the w2-retention test now saves only w2.grouped_mm, pinning that the combine is always saved. Docs: REMAT.md and the activation-remat config docstrings now state that the dispatcher combines are always saved and only dispatch follows the policy. Numerics: remat-structure change only. On CPU, loss and gradients are bitwise identical to the un-checkpointed run (and to the previous code) for the local and EP=1 paths and for the EP>1 path through a 1-rank EP mesh, absorbed and not, under the full, default and save-w2-only policies.
…hers Add two named debug recipes so the token-dispatcher backend matrix is runnable on DeepSeek V3, alongside the existing HybridEP config: - deepseek_v3_debugmodel_alltoall: the stock dispatcher at EP=2, so routed tokens actually cross ranks. The plain deepseek_v3_debugmodel (EP=1) already runs the same dispatcher's local fallback, which covers the local backend without a duplicate config. - deepseek_v3_debugmodel_deepep: DeepEP v2 at EP=2 via TokenDispatcherTransform, following qwen3_moe_deepep: the compact, host-synced training path, buffer capacity from the microbatch shape, CUDA graphs off like the stock all-to-all, plus the NVLink-only env notes for local devgpu. Both keep the default activation-remat policy, under which every dispatcher's combine is saved (never replayed) and the standard backend absorbs router scores before W2, so these exercise the paths changed by the never-replayed-combine work. Registered in the debug-config defaults test. Validated on CPU: both configs build, DeepEPTokenDispatcher.Config gets hidden_dim=256 (from w13.in_features) and num_max_tokens_per_rank=16384 (the 8 x 2048 microbatch over CP x TP), and the base EP=1 config keeps CUDA graphs on while both EP=2 configs disable them.
One fp64 parity test per dispatcher family: with rounding gone, the absorbed and post-combine paths compute the same function, so a dropped, doubled or misaligned router score is an O(1) error. Both tests assert the loss and every input/parameter gradient at the float32 scale W2's input scaling applies. - Standard dispatchers (GPU, world 2): local, all-to-all at EP=1 (local fallback) and EP=2, TorchAO at EP=1 (padded permute, zero-sentinel scores) and EP=2, through the existing _grouped_mm override seam. - DeepEP (CPU, gloo, world 2): stub deep_ep's ElasticBuffer with a pure-PyTorch implementation (all_gather + local selection, deterministic layout, autograd-correct dispatch/combine backward), so the dispatcher, the torchtitan deepep wrapper, its custom ops and their autograd run in float64 without the bf16-only CUDA kernels. The stub module is injected only when deep_ep is absent, and the CPU op impls reuse the wrapper's CUDA impls. Replaces the bf16-tolerance and activation-replay variants and the HybridEP-only file. Verified the DeepEP test fails on double-applied and on misaligned (rolled) scores.
|
Claude finished @acisseJZhong's task in 1m 32s —— View job Rows 1 and 2 are right, but row 3 is wrong. In this PR, setting W2 to "recompute" changes nothing. The W2 GEMM is not replayed either way, so "PR + recompute W2" saves the same 2.6–4.8% FLOPs against "main + recompute W2" as row 1 does. The ~0.0023% figure is the FLOP change for row 2, not row 3. Details: why the W2 policy doesn't matter in this PRSymbols: How a W2 policy works in torch_remat The policy only decides how backward gets two tensors:
So the policy only matters when something needs
The four cases (DeepEP, per MoE layer per microbatch)
Your three rows, corrected
In short, the PR removes the trade-off that Evidence and caveats
|
|
@claude so is this the conclusion?
|
|
Claude finished @acisseJZhong's task in 34s —— View job Yes, all three rows are right, with a few qualifiers. They hold only for DeepEP, the 2.6–4.8% is a FLOP estimate rather than a measured step time, and "same memory" means within a few hundred KiB per layer.
In short: on Qualifiers
|
| @dataclass(frozen=True, kw_only=True) | ||
| class DeepEPDispatchMetadata(EPDispatchMetadata): | ||
| """DeepEP dispatch state and per-row router scores.""" | ||
|
|
||
| routed_scores_R: torch.Tensor # noqa: N815 |
There was a problem hiding this comment.
I think we should do this optimization to both DeepEP and HybridEP
- all-to-all dispatcher is more of a reference implementation, which is OK to be not optimized
- DistMoE handles its own optimizations
There was a problem hiding this comment.
Would it be okay to work on HybridEP in a follow-up PR? I'd prefer to keep this PR focused and not introduce more changes
There was a problem hiding this comment.
Conceptually I'm OK, but practically I don't know if the change is going to be bigger or smaller.
E.g. DeepEPDispatchMetadata doesn't need to be introduced if we directly work on EPDispatchMetadata which is shared by both.
| if self.w2.num_linears != 1: | ||
| raise ValueError("w2 must contain one down projection") | ||
| if isinstance(self.token_dispatcher, DeepEPTokenDispatcher.Config) and ( | ||
| self.output_postprocess is not None or self.w2.bias |
There was a problem hiding this comment.
It seems you are making absorption the default and the only choice -- it makes the PR look much more succinct, but it means gpt-oss would no longer work with DeepEP (or HybridEP per other comment). Is it intended?
There was a problem hiding this comment.
this PR would require no bias and no post expert norm, so gpt-oss and muse spark wouldn't work with this particular optimization.
There was a problem hiding this comment.
That's claude's idea lol. Is anyone really training GPT-OSS?
There was a problem hiding this comment.
apparently yes?
- [bug] gpt-oss quantized weight loading broken #5189
- [gpt_oss] HF export writes routed experts under MXFP4
*_blocksnames, so transformers re-initializes every expert #4996
also it breaks muse spark open
There was a problem hiding this comment.
apparently yes?
- [bug] gpt-oss quantized weight loading broken #5189
- [gpt_oss] HF export writes routed experts under MXFP4
*_blocksnames, so transformers re-initializes every expert #4996also it breaks muse spark open
Sorry, should've checked the updates before questioning the use case. Anyway, for context, I removed the post-W2 scoring path following #5543 (comment), which explicitly recommended rejecting these combinations to simplify the implementation.
So, before revising it again, lets align on the approach:
- s * (W2(h) + b2) = W2(s * h) + s * b2
- fallback to post-expert scoring when
output_postprocessis enabled:
This might add some complexity to the code, but the models will not break.
There was a problem hiding this comment.
could you help me understand why you do W2(s * h) + s * b2 instead of just s * (W2(h) + b2)? how much compute saving this will bring?
similar to what we derived above, #5543 (comment)
on a side note, I think this is worth mentioning in the pr description for future reference.
| return remat.region( | ||
| self._add_grouped_bias, | ||
| self.remat_region_name("bias_add"), | ||
| recompute=self.remat_should_recompute("bias_add"), |
There was a problem hiding this comment.
this feel cheap op to me, why making remat policy configurable, instead of always recompute like before?
| With DeepEP, router scores scale W2's input and its per-expert bias: | ||
|
|
||
| ```text | ||
| s * (W2(h) + b2) = W2(s * h) + s * b2 |
There was a problem hiding this comment.
the formula itself is not obviously correct; it's only correct because _expand_grouped_bias expands on the tokens dimension -- maybe add a note
| if routed_scores_R is not None: | ||
| # The bare multiply reads scores produced by the dispatch region. | ||
| remat.recompute_needs_tensor(routed_scores_R) | ||
| input_RI = input_RI * routed_scores_R.to(input_RI.dtype).reshape(-1, 1) |
There was a problem hiding this comment.
I know this is a separate request, but I think we should do fp32 multiply here, according to https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/moe/token_dispatcher.py#L163-L168. We should duplicate the note as well.
Should also do this for HybridEP, but can leave to next PR together with the other request.
| if ( | ||
| isinstance(self.token_dispatcher, DeepEPTokenDispatcher.Config) | ||
| and self.output_postprocess is not None | ||
| ): | ||
| raise ValueError("DeepEP does not support output_postprocess") |
There was a problem hiding this comment.
Can we still support output_postprocess, without applying this optimization? o/w model like Muse Spark Open couldn't run with DeepEP any more.
| input_RI: torch.Tensor, | ||
| offsets_E: torch.Tensor, | ||
| *, | ||
| routed_scores_R: torch.Tensor | None = None, |
There was a problem hiding this comment.
| routed_scores_R: torch.Tensor | None = None, | |
| scores_R: torch.Tensor | None = None, |
to be more neutral to MoE
| Args: | ||
| input_RI: Input rows grouped by the selected linear. | ||
| offsets_E: Exclusive cumulative row end for each group. | ||
| routed_scores_R: Optional per-row scores absorbed into the input. |
There was a problem hiding this comment.
add more docstring about "this normally is applied to w2 in MoE to reduce overhead"
There was a problem hiding this comment.
It would be very helpful to add a note similar to https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/moe/SHARDING.md with picture illustrations.
tianyu-l
left a comment
There was a problem hiding this comment.
very cool! thanks a lot!
There was a problem hiding this comment.
I feel we could say more about the motivation, on reducing memory / compute overhead, at least qualitatively if not quantatively.
But can be done in follow-up PR.
|
@claude review again |
|
Claude finished @tianyu-l's task in 5m 35s —— View job Approve -- please address the listed items before merging: see the review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The new commits fix the GPT-OSS and muse_spark breakage correctly: bias experts absorb with s*b2, and postprocess models keep post-expert scoring. What's left is docs and the PR description.
What changed since the last review.
- Postprocess models (muse_spark): with DeepEP plus an
output_postprocess, the scores are now multiplied inRoutedExperts.forwardafter the postprocess, instead of being banned. - GPT-OSS:
GptOssGroupedLinearscales its expanded per-row bias by the scores. The bias add moves into abias_addregion that follows thegrouped_mmpolicy, replacing the old pin on the W2 output. - FP32 scoring: all score multiplies now compute in FP32 by type promotion, as @tianyu-l requested.
- Combine: DeepEP combine is always a SAVE region, so it always receives rows that are already weighted.
- Docs and test: a new
ROUTER_SCORE_ABSORPTION.mddoc, and the GPU test now runs all four expert configs against a_PostW2reference.
Example (DeepEP, per routed row):
bias-free: main s*W2(h) -> PR W2(s*h)
GPT-OSS: main s*(W2(h) + b) -> PR W2(s*h) + s*b (exact algebra)
postprocess: main s*post(W2(h)) -> PR s*post(W2(h)) (unchanged order, now FP32 multiply)
combine: main replays under FullAC -> PR never replays (keeps R int64 indices)
Earlier items
- Resolved:
- The silent wrong numerics for w2 bias /
output_postprocess(previous must-fix 2) is fixed by supporting both paths correctly instead of banning them. - The
_permuterewraps are reverted. - The combine docstring now states the weighted-input contract.
- The end-to-end compute question was answered analytically in the thread, and @acisseJZhong confirmed the conclusion.
- The silent wrong numerics for w2 bias /
- Still open:
deepep.py:62("Under FullAC with absorbed scores") anddeepep.py:113("absorbed combine is never replayed"). Combine is now saved on every path, including the unabsorbed postprocess path, so drop "with absorbed scores" and "absorbed".
Must fix
- The PR description is stale on numerics.
- It says the PR "casts the score to the hidden dtype before scaling W2's input". At HEAD, every score multiply is FP32 by type promotion (
linear.py:598,gpt_oss/moe.py:974,moe.py:784). - The 200-step run is from
8b9ced058(BF16 scores, no bias or postprocess paths), so it doesn't measure HEAD's numerics. Either rerun it at HEAD, or say explicitly that FP32 scoring and the GPT-OSS/postprocess paths came after the run. - The Implementation section also doesn't mention that
output_postprocessturns absorption off.
- It says the PR "casts the score to the hidden dtype before scaling W2's input". At HEAD, every score multiply is FP32 by type promotion (
torchtitan/distributed/REMAT.md:296-301is now wrong for DeepEP. It says DeepEP and HybridEP "both save or replay dispatch and combine together, followingep_communication" and that "FullActivationRematConfigreplays both backends' communication". This PR updated the same text inmoe/README.mdbut not here. Mirror that wording: DeepEP always saves combine, and only dispatch followsep_communication.ROUTER_SCORE_ABSORPTION.md:102: "FullAC can still replay the W2 GEMM" contradicts the PR's main gain unless it is scoped to the cast/postprocess cases (inline).
Details
- All
GroupedLinearsubclasses still compose withscores_R. MXFP8, NVFP4 and LoRA all override_grouped_mm, notforward. LoRA on W2 stays linear, soW2(s*h) + c*B(A(s*h)) = s*(W2 h + c*BAh). Each projection'sforwardis only overridden byGptOssGroupedLinear, which forwardsscores_R. - The
bias_addregion costs no memory.- w13 (no scores): save-all keeps the bias-add output (pinned by
recompute_needs_tensor(gate_up_R2F)) instead of the pinned grouped_mm output, which is the same R x 2F. Default recomputes both, as before. - Absorbed w2: nothing reads the bias-add output, so it is neither kept nor replayed.
- w13 (no scores): save-all keeps the bias-add output (pinned by
- GPT-OSS without AC.
bias_RO * scores_Rsaves the expanded bias (R x D) for the score gradient. So the no-AC memory gain does not apply to GPT-OSS, though it is no worse thanmain. Under any remat policy,_expand_grouped_biasis a bare op and is rebuilt cheaply. This doesn't block; a fusedrowsum(g * b[expert(r)])could avoid it if no-AC GPT-OSS + DeepEP ever matters. - RL. The trainer (compact layout) and the generator (expand layout) both absorb through the same
GroupedLinearpath. Per-row expand scores are stillsumover the single valid entry, now computed in dispatch. So trainer/generator parity keeps the same form. - Scope. HybridEP is deferred to a follow-up, as agreed with @tianyu-l. When it lands, put
scores_Ron the sharedEPDispatchMetadataand replace theisinstance(metadata, DeepEPDispatchMetadata)checks inRoutedExperts.forward.
Not verified:
- The GPU checkpoint tests at the
2 * epsrelative-norm tolerance for router/expert gradients (all four expert configs). - The REMAT/README memory claims for the GPT-OSS path.
@tianyu-l has approved this. It touches shared MoE and linear code, so this approval doesn't replace a maintainer's review.
| output; saving both avoids this dependency. Other replayed consumers, such as a | ||
| dtype conversion, can still need W2's output, so saved combine alone does not | ||
| guarantee its complete removal from retained memory. FullAC can still replay | ||
| the W2 GEMM and its bias addition. |
There was a problem hiding this comment.
"FullAC can still replay the W2 GEMM and its bias addition" reads like a general statement, and it contradicts the main gain of this PR. In the common case (bf16 routed input, no output_postprocess) nothing in backward reads W2's output: the type_as is a no-op, moe.py doesn't pin it, and combine is a SAVE region whose backward needs only indices. So under FullAC the W2 GEMM is not replayed, which is exactly the 40 -> 35 grouped-GEMM count in the thread. The replay only happens when a bare op reads W2's output: a real dtype cast (the moe.py pin), or a postprocess, which also turns absorption off.
Scope the sentence to those cases:
| output; saving both avoids this dependency. Other replayed consumers, such as a | |
| dtype conversion, can still need W2's output, so saved combine alone does not | |
| guarantee its complete removal from retained memory. FullAC can still replay | |
| the W2 GEMM and its bias addition. | |
| output; saving both avoids this dependency. A bare consumer of W2's output, | |
| such as a real dtype cast or an output postprocess (which also disables | |
| absorption), still needs it: with W2 saved it stays resident, and under FullAC | |
| the W2 GEMM and bias addition replay. In the common bf16 case without a | |
| postprocess, W2's output is neither retained nor rebuilt. |
|
numerics change is not introduced in this PR, so merging |
Keep the pytorch#5543 motivation and memory/recompute explanation in ROUTER_SCORE_ABSORPTION.md. Leave README and remat communication-policy updates to the HybridEP support follow-up.
Embed the original PR schematic in the motivation section, with a short caption scoping activation labels, hidden-width storage, and the W2 SAVE replay benefit.
Remove the mocked CPU HybridEP scoring test and its unused imports. Keep the existing GPU checkpoint suite's post-W2 reference, gradient, bias, postprocess, padding, and replay coverage, matching the approach in pytorch#5543.
Follow SHARDING.md with an implementation intro, illustrated Overview, Configurations tables, and Submodule behavior notes. Consolidate duplicate diagrams while retaining the pytorch#5543 graph, backward dependency, remat tradeoffs, analytical examples, and correctness caveats.
…er override; agent self-review; rl/transport (#6407) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it approved, 30 then got a formal "request changes" from a maintainer, and about 20 more got substantive inline asks. In nearly all of them the bot either saw the problem and approved anyway, or never asked the questions maintainers ask most ("does the repo already do this?", "who should own this?"). The opposite failure, the bot blocking something a maintainer was fine with, is rare: in the PRs we sampled, 2 of its 81 must-fix items were wrong and about a third were minor (the empty human-written summary was the biggest source). **Example** (#6112, controller sizes the rollout worker pool): ``` before: bot approved 10 times; tianyu-l then blocked: "the controller reads rollouter.rollouts_per_worker to compute a count it hands back to the Rollouter -- violates encapsulation" after: same commit, new skill -> Request changes, must-fix #1: "controller.py:589 -- wrong owner for the worker count ..." ``` There was also no way for a code owner to overrule the bot except dismissing its review in the GitHub UI, and a later `@claude review again` would block again. ## What changed **Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`): - Verdict rules: Approve only when every remaining item is an edit the bot could write itself. Anything the author still owes (a design change, an unexplained golden change, evidence the PR rests on) is Request changes; anything only a maintainer can decide is Needs discussion. A hedge like "a maintainer should decide" can't come with Approve. - Always must-fix: a violated written rule, a silent wrong result, a second definition of an existing concept, a gate finding. - Design gate: new questions for the existing counterpart, in-repo ownership, and the design behind a bug; "ban only what doesn't work on main"; read the numbers behind a claim. The overlapping-PR search is mandatory and reported. - Re-review covers every commit since the last full review, including code taken from the bot's own suggestions. A scoped question gets a `COMMENT`, not a whole-PR verdict. - The bot fact-checks its own proposed fixes, and cites a source for claims about external tools or marks them unverified (never must-fix). - An empty "Summary (human-written)" is a one-line "Before merge" note that never affects the verdict. - Checklist: config ownership direction, general shared wrappers, dead code the PR creates, model variants as flavors, a mechanical pass over every new or changed function. **Code owner override** (`SKILL.md`, `claude-code.yml`, `CONTRIBUTING.md`): a code owner comments `@claude override` (optionally `@claude override 2,3: <reason>`); the bot approves if nothing else is open and doesn't re-raise the overridden items. A code owner's GitHub approval or "LGTM" is not an override, so a teammate can approve without the bot dropping its findings. Dismissing the bot's review still unblocks the PR, but isn't an override: the bot can't tell who dismissed it. **Agent self-review** (`CLAUDE.md`, `pr-description`): an agent preparing a PR runs `pr-review` in branch mode first and records unaddressed items in an optional "Self-review" section. PRs written without an agent are unaffected; a missing section is never a finding. Where each new rule comes from (maintainer asks the bot missed): | Change | PRs | | --- | --- | | No Approve with open design/evidence items or a "maintainer should decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 | | Author waiver can't clear a must-fix | #6201, #6202, #6203 | | Existing counterpart; one source of truth | #5228, #6169, #5881, #5823, #5824, #6059, #5812 | | Responsibility owner; config ownership direction | #6112, #6332, #5802, #5803, #6325 | | Fix the design behind the bug; a TODO doesn't justify a workaround | #5572, #5689, #5657 | | Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819, #5543 | | Re-review covers all new commits; scoped asks don't approve | #5824, #5842 | | Mandatory overlap search | #5885, #6248 | | Ban only what doesn't work on main | #5543 | | Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868 | **Rules**: `design.md` gets the one-general-wrapper rule (moved from `models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the consumer owning its values; `config.md` gets ownership direction and "a Config doesn't read runtime state"; `direction.md` calls all-to-all the MoE reference implementation, so a new vendor-specific dispatch path (e.g. #6242) needs a reason the existing backends can't serve. **Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/` -> d4l3k. **Mechanical, skim**: `torchtitan/rl/transport/` holds data movement between RL actors. - `rl/model_state_dict_transport.py` -> `rl/transport/model_state_dict.py` - `rl/MODEL_STATE_DICT_TRANSPORT.md` -> `rl/transport/MODEL_STATE_DICT_TRANSPORT.md` - `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py` - tests: `tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py` -> `tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py` - imports, READMEs and `scripts/install_rl_env.sh` updated; no code changes. ## User-facing changes | Before | After | | --- | --- | | Overrule the bot: dismiss its review in the UI, and it blocks again on the next run | `@claude override [items]: <reason>`; the bot approves and doesn't re-raise them | | Empty human-written summary: bot must-fix | One "Before merge" line, no effect on the verdict | | `from torchtitan.rl.model_state_dict_transport import ...` | `from torchtitan.rl.transport.model_state_dict import ...` | | `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from torchtitan.rl.transport.rdma_microbatch import ...` | ## Testing Backtest: the new skill run locally (nothing posted) on each PR at the commit and thread state the bot originally saw. | PR | Bot then | New skill | What the maintainer asked | | --- | --- | --- | --- | | #6112 | Approve | Request changes | worker-count ownership (caught) | | #5837 | Approve | Request changes | apply to `dp_shard` too (caught) | | #5572 | Approve | Request changes | delete the injection design (caught) | | #6201 | Approve after author waived pins | Request changes, waiver ignored | pins broke GPU tests after merge (caught) | | #6007 | Approve | Request changes | fold K3.1 into K3 (caught) | | #5543 | Request changes: "ban it" | Request changes: keep main's path | don't break gpt-oss + DeepEP (fixed) | | #6144, #5905 (controls) | Approve | Approve | -- | | #6137 (control) | Approve | Needs discussion | -- (merge gate on an upstream API) | Code owner override, simulated on #6201: override by a code owner lifts the named item; `@claude override` from the author changes nothing; a code owner's "LGTM" approval followed by "review again" keeps Request changes. Transport move: 83 RL CPU unit tests pass locally (`transport/test_model_state_dict.py`, `test_trainer.py`, `test_engine_loop.py`). `transport/test_rdma_microbatch.py`, `test_generator.py` and `test_batcher_actor.py` fail to collect in my env on `origin/main` too (stale attention-gym / Monarch), so CI is the check for those. ## Known issues / follow-ups - Open PRs that edit the moved files rebase cleanly (git follows the renames), but new imports of the old module paths will break: #6309 (adds a delta transport that should live in `rl/transport/`), #6237, #6176, #6177, #5862, and drafts #6127, #6393, #6163, #5764. - The Actions bot can't read dependency source (e.g. SGLang); follow-up for the workflow. ## Self-review pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch mode diffs against `origin/main` and skips description findings before a description exists; the "Config doesn't read runtime state" rule no longer contradicts hardware validation; dismissal dropped as an override form (the bot can't tell who dismissed); `test_rdma_microbatch.py` added to the transport area. Not addressed: - One concern per PR -- the five changes ship together at the maintainer's request. - Open PRs touching the moved files -- listed above; the maintainer will coordinate.
## Summary (human-written) Follow up on #5543 by extending router-score absorption to the HybridEP dispatcher backend. Avoid W2-output replay/retention when HybridEP is selected. ## Scope HybridEP now passes per-row router scores to the same expert path as DeepEP. With absorption, the router gradient uses W2's input and input gradient. HybridEP combine receives weighted outputs and its backward uses the dispatch handle. Default FullAC still replays the W2 forward GEMM. Skipping that replay is a separate change. ```text Before: s * (W2(h) + b2) After: W2(s * h) + s * b2 ```  When an expert has an output norm, both backends apply the router score after the norm. HybridEP now uses DeepEP’s FP32 product and casts the result back to the output dtype. This changes BF16 rounding on HybridEP. The shared dispatch metadata carries the per-row scores for both backends. ## Validation Absorption changes BF16 rounding. In a paired 200-update C4 run on two H800s, the 83M-parameter debug model processed 13,107,200 training tokens per arm. Pre-PR HybridEP (`8e63247`) and the absorption implementation (`56a213b`) had mean training losses of 6.62618 and 6.62351 over the final 20 steps. Final held-out losses were 6.625461 and 6.629344. Both arms had finite losses and gradient norms. This is a single-seed, short-run comparison. The HybridEP checkpoint test covers biased experts, output postprocessing, blocking and nonblocking dispatch, and zero combine replays. All 3 HybridEP checkpoint tests passed (0 skipped) at `3b617c823`, before the post-norm precision change. GPU validation of the FP32 post-norm path is pending. GPU environment: 2× NVIDIA H800, PyTorch `2.16.0.dev20261029+cu130`, CUDA 13.0, DeepEP HybridEP build.

[MoE] Apply router scores before W2 projection
Supersedes #4095 with a DeepEP-only implementation: router scores are absorbed before W2 when
output_postprocessis absent, and DeepEP combine is one never-replayed remat region.Motivation
The original DeepEP path applies router scores to each routed expert output after the W2 projection in
combine_tokens:This multiplication causes the post-W2
routed_output_RDto retain for backward. Because W2 is linear, the router score can be applied earlier to the SwiGLU activation, immediately before W2:See the diagram below:
Expected memory gain in full model:
Combine output:
T * D * 2 = 4096 * 7168 * 2 = 56.0 MiBper layer,* 58 layers = 3.17 GiBW2 output:
(T * top_k) * D * 2 = 4096 * 8 * 7168 * 2 = 448.0 MiBper layer,* 58 layers = 25.4 GiBTotal per GPU:
25.4 + 3.17 = 28.6 GiBExpected recomputation gain in FullAC
check #5543 (comment)
GPT-OSS scoring overhead
Let
Rdenote routed rows,Dmodel width, andFexpert intermediate width. Assuming post-W2 scoring is inside SAVE combine, while absorbed multiplications replay:RDRF + RD0RF + RDRDRF + RD≈2RD≈2RF + 2RD≈4RD≈5RF + 5RDCommon bias additions and expert bias-gradient reductions are excluded. The extra scoring work is approximately
5RF + RD. For GPT-OSS,D = F = 2880, giving17280Radditional FLOPs—about0.026%of FullAC's W2 GEMM FLOPs.Implementation
Functionalities
DeepEPDispatchMetadata, rather than storing them in backend state for combine.output_postprocessis absent, DeepEP absorbs router scores into W2's input. GPT-OSS additionally scales W2's per-expert bias, computingW2(s*h) + s*b2in exact arithmetic.output_postprocess, absorption is disabled and DeepEP applies scores after postprocessing. Score products compute in FP32 and are cast back to the activation/output dtype.GPT-OSS bias handling and compute cost
For biased experts:
Applying scores after W2 makes the score gradient depend on the full unscaled expert output. Absorption removes that dependency; when W2 and its bias addition are saved, that output need not remain resident. The bias branch adds pointwise operations and reductions, with no additional GEMM.
Tests
_PostW2reference that applies scores after W2, comparing loss and input/router/expert gradients while preserving checkpoint equivalence and communication replay checks.Measured memory/recompute improvment
Measured by adding:
in
def _non_pp_forward_backward_microbatchintraining_engine.py.DeepEP dispatcher
Memory saved, with Selective AC
deepseek_v3_debugmodel_deepep(T=16384, top_k=3, EP=2, RegionAC save-all),ep_communication.combineregion per MoE layer.
Baseline:
Absorb:
Debug model A/B (
deepseek_v3_debugmodel_deepep, T=16384, top_k=3, EP=2, RegionAC save-all):ep_communication.combineretainedWhole-run resident: 2.52 GiB -> 2.43 GiB. Nothing else in the report changes.
671B (T=4096, top_k=8, D=7168, 58 MoE layers, per GPU): w2 output
R*D*2= 448 MiB/layerT*D*2=56 MiB/layer (independent marker cleanup, 3.17 GiB) = 28.6 GiB/GPU avoided retention, with no
recompute cost in exchange (w2 GEMM and combine are not replayed).
Recompute saved, with FullAC
see #5543 (comment)
Numerics
Moving router-score multiplication before a bias-free W2 is equivalent in exact
arithmetic but changes BF16 rounding and therefore outputs and gradients. The
original DeepEP path casts the score to the W2-output dtype before multiplying.
The current implementation computes score products in FP32 via type promotion,
then casts the product back to the activation/output dtype. When absorption is
used, the scaled input is cast back to the activation dtype before W2.
GPT-OSS additionally scales its
per-expert bias. With
output_postprocess, absorption is disabled and scoresare applied after postprocessing.
FP32 score multiplication preserves score precision during the product, but
casting the scaled input before W2 still differs from scoring W2's rounded
output. This change does not preserve bitwise-identical outputs, losses, or
gradients.
Historical 200-step DeepEP comparison against main (BF16 scoring)
The results below were measured at
8b9ced058, before FP32 score multiplicationand support for GPT-OSS bias and output-postprocess paths. They document the
earlier BF16-scoring implementation and do not validate current-head numerics
or those additional paths. A fresh training comparison is needed to establish
convergence for the current implementation.
8b9ced05834691fa51b3a5fa3c54f5e30c95279d, DeepEP EP=2,router scores cast to the activation dtype (BF16) before scaling W2's input.
b832ae41936a626ac0c8dc9ab1ae8dd556fd428b, DeepEP EP=2,with the original post-W2 score multiplication in combine. Main has no
pre-W2 absorption path.
Both runs use two ranks, sequence length 2048, 16384 tokens per microbatch per
DP rank, seed 42,
debug.deterministic=True, and 200 steps. The primaryreference now uses the same DeepEP dispatcher as the PR, replacing the earlier
AllToAll reference.
Across 200 steps, the mean absolute loss difference is
0.01011365, the maximumis
0.02818, and the mean relative difference is0.37725%(main loss as thedenominator). The final-20-step mean loss is
0.016978lower for the PR(
0.65307%relative to main). Both loss curves decrease and all suppliedgrad_normvalues remain finite. The loss and gradient trajectories differ;this comparison does not claim bitwise parity or an improvement in model quality.
Statistics are calculated from the supplied rounded per-step metrics.
This is a single-seed, 200-step training comparison on the bundled
c4_testfixture (
tests/assets/c4_test/data.json); it does not establish long-run orfull-C4 convergence. Additional AllToAll and Local runs at EP=1 match, consistent
with the AllToAll local fallback; they do not provide extra distributed EP coverage.
Run configuration (recorded in
loss_conv_configs2.py, based ondeepseek_v3_debugmodel):(five MoE, one dense), eight routed experts, two shared experts,
MoE hidden dim 256, top-k 3, sigmoid router with score normalization.
expert_parallel_degree=2,dp_shard=2in both runs;DeepEP
num_max_tokens_per_rank=16384.ConcatThenSplitPackingConfig.debug.deterministic=True, FlexAttention,AdamW LR
8e-4, two warmup steps, linear decay 0.8, minimum LR 0.EP_DISABLE_GIN=1,NCCL_GIN_CROSS_NIC=0for the no-RDMA environment.2.16.0.dev20261029+cu130(CUDA 13.0),torchtitan 0.2.2, DeepEP 2.1.0 rebuilt from v2.1.0 against NCCL 2.32.3.
Verification reports
format_saved_tensors_report, as shown above.8b9ced058(BF16 score before W2) vs mainb832ae419(score after W2), both EP=2, seed 42 anddebug.deterministic=True; configuration, versions, loss differences, and final gradient norms are reported above. This run predates FP32 scoring and GPT-OSS bias/output-postprocess support and does not validate current-head convergence._PostW2and check checkpoint equivalence and dispatch/combine replay counts.