Skip to content

[MoE] Apply router scores before W2 projection for HybridEP - #5976

Merged
tianyu-l merged 3 commits into
pytorch:mainfrom
Mystri:codex/hybridep-absorption-5543
Dec 1, 2026
Merged

tianyu-l merged 3 commits into
pytorch:mainfrom
Mystri:codex/hybridep-absorption-5543

Conversation

@Mystri

@Mystri Mystri commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

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.

Before: s * (W2(h) + b2)
After:  W2(s * h) + s * b2

Router-score absorption graph from #5543

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.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 9, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 9, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@Mystri
Mystri marked this pull request as ready for review November 18, 2026 08:07
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 18, 2026
receive tokens in the forward's order, so DeepEP uses a deterministic buffer, which
adds a sort to every dispatch. HybridEP derives token positions from prefix
scans. `FullActivationRematConfig` replays both backends' communication.
`ep_communication.combine`. Dispatch follows `ep_communication`; combine,

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.

change this comment to be more explicit. "ep_communication controls dispatch replay only. The combine region, including local unpermutation, is always saved; its backward needs only the dispatch handle."

scans. `FullActivationRematConfig` replays both backends' communication.
`ep_communication.combine`. Dispatch follows `ep_communication`; combine,
including local unpermutation, is always saved. Full remat replays dispatch
for both backends. DeepEP uses deterministic receive ordering, adding a sort;

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.

I think the old comment is more clear for deepep.

@acisseJZhong

Copy link
Copy Markdown
Contributor

@claude review, specifically help me understand how this hybrid ep optimization work with muse spark(has post expert norm) and gpt oss(has bias).

Comment thread torchtitan/models/common/moe/moe.py Resolved
Comment thread torchtitan/models/common/moe/README.md Outdated
`dispatch` and `combine` regions that include local reordering and collectives.
DeepEP and HybridEP use `ep_communication` to control dispatch replay and always
save the complete combine region, including unpermute. Full remat replays
DeepEP dispatch with deterministic receive ordering, adding a sort; HybridEP

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.

similar, can you be more clear about this.

Comment thread torchtitan/models/gpt_oss/moe.py Resolved
@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 5m 6s —— View job


Request changes: review explains how the change works for Muse Spark (its post-expert norm keeps scoring after W2, now with FP32 scores, and combine is always saved) and GPT-OSS (computes W2(s*h) + s*b, with bias add following W2's remat setting). It also flags your two open doc comments and asks for FullAC peak-memory evidence for the W2 override.

@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: Request changes -- @acisseJZhong's two doc comments are still open, and the FullAC W2 override needs a peak-memory number before it lands.

What this PR does. HybridEP dispatch now returns the FP32 permuted scores in EPDispatchMetadata.scores_R. DeepEPDispatchMetadata is folded into that class, so RoutedExperts sends HybridEP down the same absorbed-score path as DeepEP. HybridEP combine becomes an always-saved region, and only dispatch follows ep_communication. Separately, for BF16 experts on the absorbed path, W2 and GPT-OSS's bias_add are forced to recompute=False. FullAC therefore no longer replays a W2 GEMM whose output nothing reads during replay. That last change affects DeepEP too.

Muse Spark (post-expert norm)

Muse Spark sets output_postprocess (_input_scaled_gain_norm, muse_spark/flavors.py:568). Since norm(s*y) != s*norm(y), absorption is off: moe.py:172 takes the plain self.w2(hidden_RF, offsets_E) branch, and W2 keeps its configured remat policy.

before: hybridep.combine_tokens: norm(W2 h) * bf16(s)          # scores rounded to BF16 first
after:  RoutedExperts (moe.py:215): bf16(norm(W2 h) * fp32(s))  # same code DeepEP already uses
        combine_tokens: unpermute + reduce only, always saved

For Muse Spark the PR changes three things:

  1. Scores are no longer rounded to BF16 before the multiply. This is a small numerics change.
  2. FullAC no longer replays the combine all-to-all. Combine backward uses only the dispatch handle.
  3. Nothing changes for W2 or the norm. Nonblocking mode still goes through _masked_output_postprocess.

Muse Spark gets no W2 savings from this PR.

GPT-OSS (bias)

GPT-OSS has no postprocess, so it takes the absorbed path (gpt_oss/moe.py:33-61):

x_RF = bf16(h_RF * fp32(s_R))           # linear.py:457
o_RD = grouped_mm(x_RF, W2)
B_RD = bf16(expand(b_ED) * fp32(s_R))   # tail capacity rows use a non-parameter zero row
y_RD = o_RD + B_RD                      # bias_add region, same recompute as the GEMM
  • Algebra. s*(W2 h + b) = W2(s h) + s b holds exactly.
  • Gradients. The bias gradient is unchanged: db_e = sum_{r in e} s_r g_r. The score gradient becomes ds_r = <dx_r, h_r> + <g_r, b_e(r)>, so it no longer needs W2's output.
  • Rounding. There are now two BF16 casts (s*h before the GEMM, and s*b) instead of one cast of the scored output.
  • Remat. Under FullAC both the GEMM and the add are saved. The add saves nothing for backward.
  • Coverage. No in-repo recipe runs GPT-OSS with DeepEP or HybridEP. Only the new GPU unit-test cases exercise this path.

Must fix

  1. torchtitan/distributed/ACTIVATION_REMAT.md:331, :333 -- @acisseJZhong's comments are not addressed at HEAD. She asked for explicit wording that ep_communication controls dispatch replay only, and to keep the old DeepEP sentence.
  2. torchtitan/models/common/moe/moe.py:180 -- the FullAC W2 recompute=False override may keep W2's scored input [R, F] resident in every MoE layer. Needs a peak-memory measurement (inline comment).
  3. PR description -- the C4 run covers only the absorbed path. The postprocess path's BF16 -> FP32 score change for Muse Spark isn't listed under Changes or Validation. Add a short muse_spark HybridEP debug-model loss comparison, or explain why it isn't needed.

Should consider

  • torchtitan/models/common/linear/linear.py:462 -- the same subclass check also appears at gpt_oss/moe.py:41, and it silently ignores an explicit override. Move the check into the single caller (inline comment).
  • The W2 replay skip is independent of HybridEP absorption: it also changes DeepEP under FullAC and was validated separately. It could go in its own PR.
Details
  • Nonblocking tail rows (absorbed path). Rows past offsets_E[-1] hold garbage in forward and in combine backward. I found no new leak into parameters:
    • The GPT-OSS bias tail comes from a new_zeros row, which isn't a parameter.
    • grouped_mm weight gradients sum only over valid groups.
    • Garbage score gradients flow into dispatch backward, as they did before when combine_tokens multiplied the scores there.
  • Padding. The test compares HybridEP with pad_multiple=64 against an AllToAll reference with GPT-OSS bias, so in-segment padding rows reaching the bias gradient would be caught.
  • Saved combine with replayed dispatch. This relies on HybridEP's prefix scans reproducing the forward row order, so the forward handle used by the saved combine backward still matches. This is the same assumption DeepEP already makes with deterministic receive ordering.
  • Goldens. The fsdp+hybridep H100 entry (DeepSeek V3 and Muse Spark) only runs; it has no golden file, so no golden needs regenerating.

Not verified: GPU tests, and whether torch_remat retains a saved region's backward inputs under FullAC. A maintainer still needs to review.

Comment thread torchtitan/models/common/moe/moe.py Outdated
Comment on lines +180 to +183
# TODO: Let remat skip unused W2: https://github.com/meta-pytorch/remat/issues/6
recompute=False
if routed_input_RD.dtype == torch.bfloat16
else None,

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.

There's no evidence yet that forcing recompute=False on W2 is memory-neutral under FullAC, which is the policy users pick to minimize memory.

The "Trailing adds" section of ACTIVATION_REMAT.md says a saved region keeps resident whatever it saves for backward ("a saved add keeps nothing resident" because an add saves nothing). grouped_mm saves its input. If that also holds here, W2's scored input [R, F] in BF16 now stays alive from forward to backward in every MoE layer under FullAC. That is the same size as one routed-expert activation, which FullAC exists to drop. The PR shows that W2's output isn't retained and that 5 GEMMs are saved, but it says peak memory is "unestablished".

Please report FullAC peak memory before and after, or the number of BACKWARD-kind saved bytes measured with remat.saved_tensors_hooks in the existing GPU test. If memory grows, drop the override and keep only the TODO for meta-pytorch/remat#6. If it doesn't, add a one-line comment saying why (remat rebuilds the saved region's input from replay), because the docs suggest the opposite.

A smaller point: this also silently overrides a user's explicit recompute_regions=["*routed_experts.w2.*"]. ACTIVATION_REMAT.md should say so.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 33s —— View job


Approve -- please address the items before merging: 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 two new commits (cf2b72b, 6652b5c) resolve every must-fix item from the last review. What's left is a stale PR description and a GPU run of the new memory assertion.

What changed since the last review.

  • The doc wording now follows @acisseJZhong's suggestions.
  • The TODO now names @anijain2305.
  • The native-kernel check moved from GroupedLinear into the caller.
  • The SAVE exception for W2 is documented.
  • A zero-bytes assertion for W2 saved tensors was added to the GPU test.
  • HybridEP's postprocess scoring keeps main's BF16 score rounding, so Muse Spark numerics no longer change.

Example (Muse Spark, HybridEP, at HEAD).

main: dispatch: s16 = bf16(s); combine: y = norm(W2 h) * s16
HEAD: RoutedExperts (moe.py:218): y = norm(W2 h) * bf16(s)   # same rounding, same result
      combine: unpermute + reduce only, always saved
DeepEP + postprocess (unchanged): y = bf16(norm(W2 h) * fp32(s))

Earlier must-fix items

  1. Doc comments on ACTIVATION_REMAT.md / MoE README.md -- resolved.
  2. FullAC W2 recompute=False memory -- resolved, conditional on the GPU run. The CPU saved-tensor-hook diagnostic shows zero BACKWARD bytes for W2. The GPU test now asserts the same, and the "SAVE exception" paragraph documents the recompute_regions override.
  3. Muse Spark postprocess precision change -- resolved by keeping main's numerics instead of changing them.

Must fix

  1. PR description no longer matches the code:

    • The Changes table says "FP32 score products ... or after postprocessing".
    • The summary says "Muse Spark keeps scoring after its expert norm, now with FP32 scores rather than BF16-rounded scores".
    • "Pending GPU validation" still lists a Muse Spark postprocess loss comparison, and "Current head" says cf2b72b3b.

    At HEAD, the HybridEP postprocess path keeps BF16 score rounding, so Muse Spark numerics match main. Update these lines.

  2. The new GPU assertions (zero W2 BACKWARD bytes, replay counts) have only run on CPU equivalents. Get ciflow/h100.8 green before merging. Also, the zero-bytes assertion can pass without checking anything (inline comment).

Should consider

  • torchtitan/models/common/moe/moe.py:218 -- shared MoE code now picks the score precision by dispatcher type. Either unify on FP32 with a short Muse Spark loss comparison and delete the branch, or keep it with a comment that states the current reason (inline comment).

A maintainer still needs to review: this touches common MoE, GroupedLinear, and the remat docs.

Not verified: GPU tests, and the torch_remat saved-tensor-kind behavior that the zero-bytes assertion relies on.

Comment thread torchtitan/models/common/moe/moe.py Resolved
Comment on lines +396 to +397
if check_w2_saved_bytes:
self.assertEqual(sum(w2_saved_storages.values()), 0)

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.

This assertion is the only GPU evidence for the memory claim behind the W2 SAVE override. Right now it can pass without checking anything. If no packed tensor has kind is BACKWARD and a region containing .w2. (for example, region naming changes or remat reports a different kind), w2_saved_storages stays empty and the sum is 0.

Add a positive control so the check fails when the hook never sees W2. For example, count every pack call whose info.region contains .w2., of any kind, and assert the count is non-zero next to the zero-bytes assertion. I haven't verified which kind remat assigns to these tensors. Whichever control you choose, confirm it on GPU.

"""Combine expert outputs back to original token order.

Applies deferred scores (if any), then unpermutes via the opaque dispatch handle.
Unpermutes and reduces rows already weighted by their router scores.

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.

Can you make this comment more clear and state that we always save combine because it removes extra dependency on W2's output?

)
output_shape = self.weight.shape[1:-1]
weight_EOI = self.weight.flatten(1, -2)
if recompute is False and type(self)._grouped_mm is GroupedLinear._grouped_mm:

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.

Can you explain this condition a little bit more?

output_shape = self.weight.shape[1:-1]
weight_EOI = self.weight.flatten(1, -2)
if recompute is False and type(self)._grouped_mm is GroupedLinear._grouped_mm:
# Keep the cast outside SAVE so remat rebuilds it instead of retaining it.

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.

Can you add more details to this comment? I have to ask my agent in order to understand this.

if recompute is None:
recompute = self.remat_should_recompute("grouped_mm")
output_RO = remat.region(
self._grouped_mm,

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.

Maybe delete the cast inside this function? since we are moving it outside.

Comment thread torchtitan/models/common/moe/moe.py Outdated
# remat rebuilds the scored input during replay rather than retaining it.
# TODO(@anijain2305): Let remat skip unused W2: https://github.com/meta-pytorch/remat/issues/6
recompute=False
if routed_input_RD.dtype == torch.bfloat16

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.

I feel this condition is hard to understand. Can you explain it a little bit more and, if possible, maybe make it a property?

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 18s —— View job


Approve -- please address the items before merging: 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 commit 6f962a5 is correct. What's left is three comment-only edits that @acisseJZhong asked for and a GPU run.

What changed since the last review (6652b5c -> 6f962a5).

  • GroupedLinear.forward takes output_dtype and applies the cast inside the grouped_mm region.
  • GPT-OSS applies the cast inside bias_add, after the add.
  • The absorbed path no longer requires BF16 routed inputs before it forces W2 SAVE. Any dtype now qualifies, as long as the kernel is native.
  • The native-kernel check is now the uses_native_grouped_mm property.
  • The HybridEP combine docstring now says why combine is always saved.

Example (absorbed W2, FullAC, DeepEP or HybridEP, no postprocess).

6652b5c, BF16 routed input: W2 SAVE; type_as outside is a no-op
6652b5c, FP32 routed input: W2 follows policy (replayed twice); bare type_as pins W2 output
HEAD, any routed dtype:     W2 SAVE, region = _grouped_mm(...).to(input dtype)
HEAD, GPT-OSS:              bias_add region = (o + bf16(s*b)).to(input dtype)
non-absorbed paths:         unchanged (type_as + pin stay in the else branch)

Tensor.to(dtype=None) returns self, so local, AllToAll and postprocess callers are unaffected.

Earlier items

  • PR description mismatch -- resolved. "Current head" and the Muse Spark wording now match the code.
  • @acisseJZhong, hybridep.py combine comments -- resolved. The docstring now says combine is always saved so that combine replay never needs W2's output.
  • GPU run and positive control for the zero-W2-bytes assertion (test_deepep_activation_checkpoint.py:397) -- still open. Only the CLA/import checks have run on this head, and ciflow/h100.8 isn't applied. The assertion still passes trivially if the hook never sees a .w2. region.
  • moe.py:218 HybridEP-only BF16 score branch -- still open (should consider). The comment still narrates history ("formerly done by dispatch"). The # Promote the product ... comment is still dropped.

Must fix

  1. torchtitan/models/common/linear/linear.py:469 -- @acisseJZhong's requests to explain the condition and comment, and her question about deleting the inner cast, aren't addressed at HEAD. The inner cast can't simply be deleted; the inline comment explains why and suggests replacement text.
  2. torchtitan/models/common/moe/moe.py:176 -- the comment still doesn't explain why only native W2 is forced to SAVE, which is the rest of @acisseJZhong's request. Suggested text is inline.
  3. Run ciflow/h100.8 on this head, with a positive control added to the W2 saved-bytes check (see above).

A maintainer still needs to review: this touches common MoE, GroupedLinear, and the remat docs.

Not verified: GPU tests. Also not verified: that remat rebuilds a saved region's out-of-region inputs rather than retaining them. The memory claim depends on this, and the inline comments rely on it.

Comment on lines +469 to +471
if recompute is False and self.uses_native_grouped_mm:
# Keep the cast outside SAVE so remat rebuilds it instead of retaining it.
weight_EOI = weight_EOI.bfloat16()

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.

@acisseJZhong's two comments here are still open at HEAD. The comment text hasn't changed, and the cast inside _grouped_mm is still there.

Can the inner cast be deleted? Not by itself. _grouped_mm's weight_EOI.bfloat16() is still the only cast for:

  • w13,
  • w2 on the non-absorbed paths,
  • every call that uses the configured policy (recompute=None),
  • LoRA's super()._grouped_mm(...).

When weights are already BF16 (FSDP with a BF16 param dtype, the usual training path), both casts are no-ops. The outer cast only matters for FP32 stored weights.

Why the outer cast exists. Per ACTIVATION_REMAT.md:7, ops outside saved regions are recomputed during backward, while a saved region keeps whatever its ops save. With FP32 stored weights, the BF16 copy made inside a saved _grouped_mm would stay resident from forward to backward. Cast outside the region, it is rebuilt instead.

Suggest spelling that out:

Suggested change
if recompute is False and self.uses_native_grouped_mm:
# Keep the cast outside SAVE so remat rebuilds it instead of retaining it.
weight_EOI = weight_EOI.bfloat16()
if recompute is False and self.uses_native_grouped_mm:
# A saved region retains what its ops save for backward, while ops
# outside regions are rebuilt. With FP32 stored weights, the BF16 copy
# made inside _grouped_mm would stay resident from forward to backward;
# casting here lets remat rebuild it. _grouped_mm still casts for the
# configured-policy and LoRA calls; on BF16 weights both are no-ops.
weight_EOI = weight_EOI.bfloat16()

Comment thread torchtitan/models/common/moe/moe.py Outdated
Comment on lines +176 to +178
# W2 inputs are rebuilt during replay; its output cast is saved with W2.
# TODO(@anijain2305): Let remat skip unused W2: https://github.com/meta-pytorch/remat/issues/6
recompute = False if self.w2.uses_native_grouped_mm else None

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.

The property addresses half of @acisseJZhong's request ("explain it a little bit more ... maybe make it a property"). The comment still doesn't say why only the native kernel gets SAVE. A reader has to work out from the docs that quantized and LoRA kernels keep their configured policy.

My reading of the reason, which the author should confirm: native W2 saves only tensors built outside its region (the scored input and the BF16 weight), and replay rebuilds those. So SAVE skips the W2 forward replay without keeping any activation resident. MXFP8/NVFP4 quantized copies and LoRA's lora_hidden_RL are created inside the region, so SAVE would keep them resident.

Suggested change
# W2 inputs are rebuilt during replay; its output cast is saved with W2.
# TODO(@anijain2305): Let remat skip unused W2: https://github.com/meta-pytorch/remat/issues/6
recompute = False if self.w2.uses_native_grouped_mm else None
# Native W2 saves only tensors built outside its region (scored input,
# BF16 weight), which replay rebuilds, so SAVE skips a W2 replay
# without retaining activations. Quantized and LoRA kernels create
# tensors inside the region, so they keep the configured policy.
# TODO(@anijain2305): Let remat skip unused W2: https://github.com/meta-pytorch/remat/issues/6
recompute = False if self.w2.uses_native_grouped_mm else None

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude

Sorry, taking a step back, as I wanted to understand what's going on.

Before seeing this PR, I thought the changes would be mechanical

However, I'm seeing very large changes

  • the introduction of is_hybridep flag in moe/moe.py
  • the introduction of uses_native_grouped_mm in linear.py
  • the remat policy change in moe/moe.py
  • the output_dtype change in gpt_oss/moe.py

Could you explain every single non-mechanical changes in layman terms? I don't feel comfortable looking at the massive code change at all.

@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 35s —— View job


Comment, no new verdict: explanation. About half the diff is the HybridEP port of #5543 you expected. is_hybridep exists only to keep Muse Spark's numerics bit-identical to main. The remat change, uses_native_grouped_mm and output_dtype are one separate Full AC optimization that also changes DeepEP, and I'd split them into their own PR.

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

Short answer. Your expectation is right. About half the diff is the mechanical port of #5543 that you expected. None of the four things you listed is needed for HybridEP absorption:

  • Three of them (the remat change, uses_native_grouped_mm, output_dtype) together make up one separate optimization: skip a wasted W2 re-run under Full AC. It also changes DeepEP.
  • is_hybridep exists only to keep Muse Spark's HybridEP numerics bit-identical to main.

A. The mechanical port (what you expected)

  • hybridep.py:516: dispatch now returns the scores. They used to be stashed in DispatchState, and combine no longer multiplies by them.
  • token_dispatcher.py:856: DeepEPDispatchMetadata is folded into EPDispatchMetadata.scores_R so HybridEP can carry scores. moe.py:173 now checks EPDispatchMetadata.
  • hybridep.py:544: combine is always saved (recompute=False). This is the one step that isn't purely mechanical, but #5543 did exactly the same for DeepEP. If combine is re-run in backward, it needs its input (W2's output) kept around, and freeing that memory is the point of absorption.
  • Docs, and test updates (combine replays drop to 0; GPT-OSS cases added).

B. is_hybridep (moe.py:195-219): keeping Muse Spark's numerics

Muse Spark normalizes each expert's output. Since norm(s*y) != s*norm(y), the score can't move before W2 and is still applied after the norm. On main, the two backends round differently:

DeepEP   (moe.py on main):          y = bf16(norm(W2 h) * fp32(s))
HybridEP (inside combine on main):  y = norm(W2 h) * bf16(s)

This PR moves HybridEP's multiply out of combine and into moe.py. To keep main's numerics, it keeps both formulas there and picks one by dispatcher type. The alternative is to use DeepEP's formula for both. That costs a tiny rounding change for Muse Spark on HybridEP and needs one short loss comparison, and it deletes the branch.

C. The W2 remat change (moe.py:176-178): a separate optimization

Full AC discards activations in forward and re-runs each layer's forward during backward to rebuild them. After absorption, nothing in backward reads W2's output:

  • W2's own backward needs only its input and weight.
  • The score gradient now flows through W2's input.
  • Combine is saved, and its backward needs only the dispatch handle.

remat still re-runs the W2 GEMM anyway, because it can't tell that the result is unused (meta-pytorch/remat#6). The PR forces W2 to "save" so the re-run is skipped. That is one fewer GEMM per MoE layer per microbatch (40 -> 35 in the PR's debug run). This isn't HybridEP-specific. DeepEP on main has the same wasted re-run, and this PR changes DeepEP as well.

D. uses_native_grouped_mm and the extra weight cast (linear.py:429, :469-471): only needed because of C

"Save" means remat keeps whatever the GEMM stashes for backward. That is free only if each stashed tensor was created outside the region, because remat rebuilds those anyway:

  • The native GEMM stashes its input and a BF16 weight. With FP32-stored weights (param_dtype="float32"), the BF16 copy is made inside _grouped_mm and would stay in memory. That is why there is an extra .bfloat16() before the region.
  • MXFP8/NVFP4 stash quantized copies and LoRA stashes lora_hidden_RL. All of these are made inside the region, so saving would keep them in memory. That is why only the native kernel gets the change, which is what uses_native_grouped_mm detects.

E. output_dtype, and recompute in GPT-OSS (linear.py:479, gpt_oss/moe.py:39-86): also only because of C

  • GPT-OSS recompute. GPT-OSS's bias add is its own region after W2. If it were re-run while W2 is saved, it would need W2's output, so it has to follow W2's decision. This is needed even in BF16.
  • output_dtype. After W2, moe.py casts the output to the activation dtype. In BF16 that is a no-op. With FP32 activations it is a real op outside W2's region, and re-running it would again need W2's output, so the cast moved inside the saved region. Commits 4e3ac75/cf2b72b avoided this by applying C only to BF16 inputs; 6f962a5 extended C to FP32 and added the plumbing.

Recommendation

Split C-E into their own PR:

  • They apply equally to DeepEP.
  • They need their own Full AC throughput and memory numbers.
  • They work around remat#6; fixing that upstream would delete them.

What remains here is the change you expected: A, plus either B or the unified formula. The split removes all of the linear.py and gpt_oss/moe.py changes, the override in moe.py, the W2 call-count and saved-tensor hooks in the test, and the "SAVE exception" doc paragraphs. That is roughly half of the +189 lines. Whether to split is your call.

Details
  • On main, HybridEP under Full AC needed the W2 re-run: its combine was re-run too and multiplied by the scores, so it read W2's output (remat.recompute_needs_tensor(routed_output_RD) in HybridEPTokenDispatcher.combine). Only after A does that re-run become wasted, which is why C looks attached to this PR.
  • param_dtype="float32" exists in torchtitan/config/configs.py:115. I found no in-repo MoE recipe that uses it with DeepEP/HybridEP, so the FP32-only parts of D and E have no in-repo user.
  • The type_as pin in moe.py:186-192 moved into the else branch with unchanged logic. Non-absorbed paths behave as on main.

Not verified: GPU tests, and the remat behavior that C-E rely on (a saved region's inputs that were created outside it get rebuilt rather than retained).

@tianyu-l

Copy link
Copy Markdown
Contributor

@Mystri could you help split this PR to address A and B first? The C -- E seem a bit hard to understand / review, especially when mixed together.

@Mystri

Mystri commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

@tianyu-l Split the PR as requested. #5976 keeps A and B.

@Mystri

Mystri commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

@sdmyzlp could you run @claude review on the split PR at 3b617c8

Comment thread torchtitan/models/common/moe/moe.py Resolved

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

one comment

Comment thread torchtitan/models/common/moe/moe.py Resolved
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 3s —— View job


Approve -- please address the items before merging (unify HybridEP's postprocess score precision with DeepEP as @acisseJZhong and @tianyu-l asked, then update docs and description): 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. After the split, this PR contains only the expected HybridEP port of #5543. One maintainer request is still open: unify the postprocess score precision with DeepEP. It is a mechanical edit plus a matching doc and description update.

What this PR does.

  • HybridEP dispatch now returns the FP32 permuted scores, and DeepEPDispatchMetadata is folded into EPDispatchMetadata.scores_R. With no postprocess, RoutedExperts therefore absorbs scores into W2's input for both backends.
  • HybridEP combine no longer multiplies by the scores. It is always saved, and its backward needs only the forward dispatch handle.

Example (HybridEP, Full AC).

                 main                               HEAD
GPT-OSS / DSV3:  combine(s16 * (W2 h + b))          combine(W2(s*h) + s*b), FP32 score products
                 combine replayed, needs W2 out     combine saved, dispatch still replayed
Muse Spark:      combine(norm(W2 h) * bf16(s))      same rounding, multiply moved to moe.py
after the fix:                                      bf16(norm(W2 h) * fp32(s))  (= DeepEP)

Earlier items (review of 6f962a5)

  • FullAC W2 SAVE override, uses_native_grouped_mm, output_dtype, the W2 saved-bytes check and its GPU run -- moved to #6430, so they no longer apply here.
  • @acisseJZhong's linear.py and moe.py:176 comment requests -- moved with that code to #6430.
  • @acisseJZhong's combine comments in hybridep.py -- resolved in 0dda772.
  • moe.py HybridEP-only BF16 branch -- still open, and it is now a maintainer request (item 1).

Must fix

  1. torchtitan/models/common/moe/moe.py:209 -- @acisseJZhong and @tianyu-l asked to use DeepEP's FP32 product for HybridEP too and to delete the is_hybridep branch. The inline comment has a drop-in suggestion.

  2. ROUTER_SCORE_ABSORPTION.md:69 and muse_spark/README.md:139 -- after item 1, both describe a HybridEP-specific rounding that no longer exists. Inline suggestions restore main's wording or delete the note.

  3. PR description -- update it after item 1:

    • Replace "HybridEP casts the score to the dispatched activation dtype ... preserving its existing rounding" with the expected change: Muse Spark on HybridEP moves from BF16-rounded scores to an FP32 product.
    • Drop or re-run the "Muse Spark ... matched ... bitwise" claim.

    fsdp+hybridep has no golden loss file, so there is nothing to regenerate.

Details
  • Handle lifetime with saved combine plus replayed dispatch. _combine_setup_context stores the forward handle_id in ctx, and the weakref.finalize on that CPU tensor keeps _handle_cache[key] alive until combine backward. A replayed dispatch creates a new handle for dispatch backward. Row order then relies on the prefix-scan determinism documented in HybridEPTokenDispatcher, which is the same assumption DeepEP already makes.
  • Scores remat. permuted_scores was dropped from recompute_needs_tensor in dispatch_tokens. It is now marked by its consumers: GroupedLinear.forward (linear.py:450) and moe.py:208.
  • Test. The CUBLAS_WORKSPACE_CONFIG patch matches what set_determinism (distributed/utils.py:169) sets for spawned ranks. GPT-OSS cases and pad_multiple=64 extend the existing HybridEP test instead of adding a new one.
  • Overlap search ("HybridEP", "router score absorption"): #6430 is the split-off W2 replay change. #5977 edits ROUTER_SCORE_ABSORPTION.md, and #5765 / #6320 touch score multiplication placement. Expect doc and merge conflicts, but none of them supersedes this PR.

Not verified: GPU tests, and the fsdp+hybridep H100 integration entry at HEAD (ciflow/h100.8 not applied).

Comment thread torchtitan/models/common/moe/moe.py Resolved
Comment thread torchtitan/models/muse_spark/README.md Resolved
@tianyu-l

tianyu-l commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

@claude I saw numerics changed from CI tests. Is it expected? The failed tests were not running HybridEP.

@claude

claude Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 24s —— View job


Yes, it's expected, and this PR didn't cause it. The branch was last merged with main on Nov 17. Its A10G golden loss files predate #6398, which regenerated them on Nov 26 after the torch nightly dev20261125 changed numerics. CI installs the current nightly but compares against the branch's old goldens. Merging current main into the branch should fix it.

Evidence

Failing job. Only "1 GPU Integration (Fake PG)" failed (job). It failed on six tests:

  • Golden-loss mismatches: llama3_fsdp+tp+cp, llama3_fsdp+tp+cp+region_ac, deepseek_v3_fsdp+ep, qwen3_moe_fsdp+tp+cp+ep_param_groups, muse_glimmer_text_fsdp.
  • A crash: gpt_oss_fsdp+tp+ep, with NotImplementedError: Backpropagating through the lse returned by varlen_attn requires ... FA4.

It's the drift #6398 describes. Its example for llama3_fsdp+tp+cp matches this run exactly:

step  golden on branch (old nightly)   this CI run (= #6398's new golden)
4     gn 0.76279575                    gn 0.76279598
5     3.6227007                        3.6228001
10    3.4226971                        3.4225903

Llama 3 is dense, so no MoE code runs in it at all. The four mismatching golden files are the same four fake_pg/a10g/*.txt files that #6398 refreshed. The GPT-OSS crash is the separate nightly break that #6398 points to, and #6400 fixed it on Nov 26. The branch has neither fix: the last commit to touch tests/assets/losses/fake_pg/a10g/ on this branch is #5837. Other recent PRs on current main pass this job (#6446, #6443, #6429).

The PR's code doesn't reach these tests. The changes are in hybridep.py, the DeepEP/HybridEP metadata in token_dispatcher.py, and two isinstance(metadata, EPDispatchMetadata) checks in moe.py. The MoE tests above use the local or all-to-all dispatchers. Those return LocalDispatchMetadata / AllToAllDispatchMetadata (token_dispatcher.py:67, :75), which aren't subclasses of EPDispatchMetadata (:856). So the checks don't match and those paths are unchanged.

Fix. The author merges current main into the branch and re-runs ciflow/fake-pg. No golden files need regenerating in this PR. I can't merge branches from here.

Not verified:

  • The re-run after the merge.
  • The PR's own HybridEP numerics. The HybridEP checkpoint test lives in "GPU Unit Tests", which is still queued on this head, and ciflow/h100.8 (the fsdp+hybridep entry) isn't applied.

@tianyu-l

tianyu-l commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

@Mystri could you rebase?

@Mystri
Mystri force-pushed the codex/hybridep-absorption-5543 branch from ffcf823 to 6860591 Compare December 1, 2026 09:15
@Mystri

Mystri commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@tianyu-l rebased onto 2492504af. The new head is 686059180. Could you approve workflows for this head so ciflow/fake-pg can run?

@tianyu-l
tianyu-l merged commit fb7a104 into pytorch:main Dec 1, 2026
24 of 25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants