Skip to content

[Bugfix] Force all reduce in bwd for router at MoE boundary - #2416

Merged
acisseJZhong merged 17 commits into
mainfrom
force_reduce_in_bwd
Mar 2, 2026
Merged

acisseJZhong merged 17 commits into
mainfrom
force_reduce_in_bwd

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Feb 21, 2026 •

Copy link
Copy Markdown
Contributor

solve #2387 where user reported a bug that MoE router weights diff on each rank due to a missing all reduce under certain senarios:

  • self.score_before_experts=False for both ETP=1 and ETP=TP
  • self.score_before_experts=True and ETP=1

similar fix was proposed #2388 by @fatih-uzlmz

Bug analysis

Case1:
When ETP=1 < TP, MoE is using TP2EP(etp_mesh is None, there is no ETP), gate is Replicated(via NoParallel), experts weight is Sharded(via EP mesh), MoE input is Replicated.

Root Cause: ReordererSequenceParallell is applied to split top_scores across TP ranks. Since each TP rank process its local slice of tokens through the experts, d_routed_input is Partial and there is no forced all-reduce.

Case2:
When ETP = TP, MoE is using DP2EP, gate is Replicated(via NoParallel), experts weight is Sharded(via ETP which force all reduce in bwd #1878), MoE input is Replicated on TP mesh.

Root Cause: The gradient flowing back to gate.weight is Partial when self.score_before_experts=False, which we incorrectly marked as Replicated and therefore results in wrong numerics.

Explanation:
When self.score_before_experts=True, d_routed_input is already all reduced because of the fix #1878 we added to ETP.

routed_input = routed_input * top_scores_experts_sorted
routed_output = self.experts(routed_input, ...) 
out_experts = routed_output_unsorted.sum(dim=1)    

When self.score_before_experts=False, gradient of top_scores from bmm is Partial. The previous all reduce fix only force all reduce on d_routed_input, but not d_top_scores which is wrong.

routed_output = self.experts(routed_input, ...)
out_experts = bmm(top_scores, routed_output_unsorted) 

The fix we propose that could fix both Case1 and 2

  • We revert the fix in fix MoE TP backward #1878 to keep Partial dx flowing back, and delay the all reduce later at the boundary of MoE.
  • We choose to not use ColWiseParallel/RowwiseParallel for shared expert as they force all reduce dx; but we want to keep Partial dx. So we introduced MoEColWiseParallel/MoERowwiseParallel which removed the input and output hooks. See the reasoning here for more details.
  • We annotate gradient of router to be partial in bwd through adding a field to NoParallel(), so that DTensor will handle the all reduce
image image

Caveat: The graph is plotted from Claude generated computational graph , please take it with a grain of salt.

cc @volcacius @fatih-uzlmz

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Feb 21, 2026
# so the router gate receives the correct full gradient.
top_scores = DTensor.from_local(
top_scores, device_mesh, (Replicate(),)
).to_local(grad_placements=(Partial(),))

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.

is doing 2 DTensor operations (to, from) really the best way here? why not just insert one autograd.function where the backwards is an all_reduce?

@acisseJZhong acisseJZhong Feb 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

yeah I guess we could also insert a customized function where fwd=no_op and bwd does all_reduce? I was following a similar fix #1878
cc @tianyu-l if you know why we might prefer this over customized function

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.

ok. well short term it seems harmless to land this, other than it would have more overhead. (worth confirming, but I assume it does not do any extra collectives or operations?) anyway, we could fix them all to use a dedicated function from spmd_types once that's available.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

it should not have any extra collectives other than the all reduce in bwd. yes I think we could directly use the function from spmd_types once it's ready!

@fatih-uzlmz

Copy link
Copy Markdown
Contributor

@acisseJZhong
Thanks for the ping and for putting together the great deep dive, very fascinating to see how the bug split into two distinct cases based on the ETP/TP config

I'm glad @volcacius and I were on the right track with the NoParallel wrapper being the correct conceptual boundary for the reduction, but your fix handling the activations directly is a really clean solution.

Really happy to have helped kick off this investigation and grateful for the opportunity to learn from the team here :)

Thanks everyone once again

@acisseJZhong

acisseJZhong commented Feb 25, 2026 •

Copy link
Copy Markdown
Contributor Author

@fatih-uzlmz thanks for the kind words! Turns out your fix was definitely on the right direction!

Please feel free to help review the PR, and also test on your end to verify the bug goes away, and let us know if you have doubts. I used Claude extensively(e.g. claude thinking) for this bug fix so might be missing something lol

Although now each rank router weights are the same, there's actually no strong guarantee that MoE numerics are correct? Going forward, we plan to introduce spmd_types as a type checker for DTensor to guarantee correctness, and hopefully this kind of bugs could surface quicker.

@fatih-uzlmz

fatih-uzlmz commented Feb 26, 2026 •

Copy link
Copy Markdown
Contributor

@acisseJZhong haha yeah, it's honestly super validating to hear that! it's also pretty cool to know even the team relies on Claude's thinking mode for this kind of heavy DTensor math

I unfortunately don't have a multi-GPU hardware setup on my end to run the physical reproduction tests right now but the logic in the PR looks very solid to me.

and introducing spmd_types as a type checker to catch these boundary issues sounds like a massive quality-of-life improvement for the whole ecosystem. Excited for that!

# so gradient reduction happens once at the MoE boundary (reduce-scatter)
# rather than being duplicated inside the MoE.
if isinstance(x, DTensor):
x = x.to_local(grad_placements=(Partial(),))

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.

You are assuming

  • 1D mesh
  • The mesh is TP

At least do assertions on them.

Comment thread torchtitan/models/moe/moe.py Outdated
self.w3 = nn.Linear(dim, hidden_dim, bias=False)

def forward(self, x: torch.Tensor) -> torch.Tensor:
if getattr(self.w1, "_moe_no_hooks", False):

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.

hmm what's going on here

@acisseJZhong acisseJZhong Feb 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

this part is where I am not very certain of 🤣

Seems like this changes inside FeedFoward forward is necessary: because we remove the input and output hooks for Col and RowwiseParallel, and MoE input is Partial plain tensor because L496, so we need to convert the shared expert weight to plain tensor to avoid DTensor wrapping x as DTensor(Replicate).

However, FeedForward is used by both shared expert and dense FFN layers, and I only want this fix to apply for the first case. Therefore I added the check: to decide if I should do F.linear or self.w1

raise NotImplementedError(
"MoERowwiseParallel currently only supports nn.Linear and nn.Embedding!"
)
module._moe_no_hooks = True

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.

why do you need this field?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

answered above

transformer_block.set_modules_to_backward_prefetch([model.tok_embeddings])


class MoEColwiseParallel(ColwiseParallel):

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.

Name is bad. Does it have anything to do with MoE?

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.

Put them in distributed/tensor_parallel.py instead of here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

good point, it's parallel to MoE. Maybe rename it to ColwisePartitionOnly which indicates that it only partition the weights/no hooks?

Comment thread torchtitan/distributed/__init__.py Outdated
input_layout: Placement | None = None,
output_layout: Placement | None = None,
use_local_output: bool = True,
output_grad_as_partial: bool = False,

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 sounds too restrictive. Maybe merge use_local_output and this field as local_output_grad_placements. If None, then don't cast to local.

In some sense, we would require user to think about grad placement when casting to local, as there's no guarantee on correctness automatically.

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.

also need to audit all callsites
https://github.com/search?q=repo%3Apytorch%2Ftorchtitan%20NoParallel&type=code

The qwen3 one seems correct as it's not using local outputs.

@acisseJZhong acisseJZhong changed the title [Bugfix] Force reduce in bwd for MoE router weights [Bugfix] Force all reduce in bwd for router at MoE boundary Feb 26, 2026
Comment thread torchtitan/distributed/__init__.py Outdated
def _prepare_output_fn(
output_layout: Placement,
use_local_output: bool,
local_output_grad_placements: Sequence[Placement] | 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.

Suggested change
local_output_grad_placements: Sequence[Placement] | None,
local_output_grad_placements: tuple[Placement] | None,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Comment thread torchtitan/models/llama4/parallelize.py Outdated
{
"moe.shared_experts.w1": ColwiseParallel(),
"moe.shared_experts.w1": ColwiseParallel(
grad_placements=(Partial(),),

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.

wait did you add this support somewhere?
I didn't see it in #2416

I don't mind us creating ad hoc ParallelStyle in torchtitan/distributed/tensor_parallel.py

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

oops I literally was tying git push command and we went for lunch 😆

I added to ColwiseParallel https://github.com/pytorch/pytorch/pull/175867/changes#diff-b4e400af23b02b381f3f4ab90eb0bc0ae2691b63d2b587257c76d22848dd33bbL108, if you think it's too much change in pytorch, I am okay with creating a new Style in Torchtitan as well.

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 we can temporarily put it in torchtitan, given that we are going to migrate to spmd anyway.
The necessity to change ParallelStyle in core is not as much as that for changing from_local.

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.

Is it fair to say NoParallel is only used on TP mesh? If so, let's move it to tensor_parallel.py.

@acisseJZhong acisseJZhong Feb 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

yeah I think so, since the default desired input and output layout are all Replicate(1 dimensional). It's fair to claim this. All the current usages of NoParallel also always apply on TP mesh.

Returns:
out (torch.Tensor): Output tensor with shape ``(bs, slen, dim)``.
"""
# Convert DTensor to local tensor for MoE-internal computation.

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.

mention that in all cases [TP only, TP + EP and ETP=1, TP + EP and ETP=TP] x [router.gate, routed experts, shared experts] x [score before vs. after experts], the gradient that's flowing back is always Partial. That's why we are converting it to Partial here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

updated, please lmk if i misunderstand anything.

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.

should also update moe file, including gpt-oss/moe.py and moe_deepep.py

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

GptOssMoE inherits MoE here. Will update moe_deepep

#
# This holds for all MoE components (router.gate, routed experts, shared
# experts) and regardless of score_before_experts.
if isinstance(x, DTensor):

@acisseJZhong acisseJZhong Feb 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

this should be correct for deepep moe as it also has Reorderer when ETP=1

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

lgtm, please wait until pytorch side change is landed

Comment thread torchtitan/distributed/__init__.py Outdated

__all__ = [
"ParallelDims",
"NoParallel",

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.

NoParallel is not very special. Let's not add this shortcut. Instead, imports need to be changed to from ...tensor_parallel

)


class ColwiseParallelWithGradPlacement(ColwiseParallel):

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 should change all torchtitan to use these two, as they are strictly safer. Don't need to do in this PR.

device_mesh,
input_layouts,
run_check=False,
grad_placements=local_input_grad_placements,

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 we should enforce this field to be not None if input is plain tensor.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

sure, it's not enforced in pytorch from_local, but doesn't hurt to add a check in titan to force user think.

pytorchmergebot pushed a commit to pytorch/pytorch that referenced this pull request Feb 28, 2026
## Problem
While fixing a MoE numerics bug (pytorch/torchtitan#2416), we discovered the root cause was a lack of strict gradient placement control/strict typing in `from_local`. Specifically, `from_local(Replicate)` in `ColwiseLinear` (used by the shared expert) produced correct forward behavior, but the backward pass performed an unnecessary all-reduce. The desired backward gradient placement was `Partial`, not `Replicate`.

## Solution
To address this, we add a `grad_placements` keyword argument to `from_local`, mirroring the existing `grad_placements` support in `to_local`. When `grad_placements` is `None` (the default), the backward gradient placement follows the original guarantees established in #173153. When specified, it overrides the default and uses the user-provided gradient placements directly.

In the longer term, we hope to address this kind of issues through spmd_types as a type checker.

## Test
```
python3 test/distributed/tensor/test_dtensor.py -k test_from_local_grad_placements
```
Pull Request resolved: #175867
Approved by: https://github.com/wconstab, https://github.com/tianyu-l
@acisseJZhong
acisseJZhong merged commit de32920 into main Mar 2, 2026
25 of 31 checks passed
danielvegamyhre pushed a commit that referenced this pull request Mar 6, 2026
solve #2387 where user reported a bug that MoE router weights diff on
each rank due to a missing all reduce under certain senarios:
- `self.score_before_experts=False` for both ETP=1 and ETP=TP
- `self.score_before_experts=True` and ETP=1 

similar fix was proposed #2388 by @fatih-uzlmz 
## Bug analysis 
**Case1:** 
When ETP=1 < TP, MoE is using TP2EP(`etp_mesh` is None, there is no
ETP), `gate` is Replicated(via NoParallel), experts weight is
Sharded(via EP mesh), MoE input is Replicated.

_Root Cause:_ `ReordererSequenceParallell` is applied to split
`top_scores` across TP ranks. Since each TP rank process its local slice
of tokens through the experts, `d_routed_input` is Partial and there is
no forced all-reduce.

**Case2:** 
When ETP = TP, MoE is using DP2EP, `gate` is Replicated(via NoParallel),
experts weight is Sharded(via ETP which force all reduce in bwd #1878),
MoE input is Replicated on TP mesh.

_Root Cause:_ The gradient flowing back to `gate.weight` is Partial when
`self.score_before_experts=False`, which we incorrectly marked as
Replicated and therefore results in wrong numerics.

_Explanation:_ 
When `self.score_before_experts=True`, `d_routed_input` is already all
reduced because of the fix #1878 we added to ETP.
```
routed_input = routed_input * top_scores_experts_sorted
routed_output = self.experts(routed_input, ...) 
out_experts = routed_output_unsorted.sum(dim=1)    
```

When `self.score_before_experts=False`, gradient of `top_scores` from
`bmm` is Partial. The previous all reduce fix only force all reduce on
`d_routed_input`, but not `d_top_scores` which is wrong.
```
routed_output = self.experts(routed_input, ...)
out_experts = bmm(top_scores, routed_output_unsorted) 
```

## The fix we propose that could fix both Case1 and 2
- We revert the fix in #1878 to keep Partial dx flowing back, and delay
the all reduce later at the boundary of MoE.
- We choose to not use
[`ColWiseParallel/RowwiseParallel`](https://github.com/pytorch/pytorch/blob/e81980ea58c65a283cf01a7132e0f420834ecf10/torch/distributed/tensor/parallel/style.py#L181)
for shared expert as they force all reduce dx; but we want to keep
Partial dx. So we introduced `MoEColWiseParallel/MoERowwiseParallel`
which removed the input and output hooks. See the [reasoning
here](https://gist.github.com/acisseJZhong/b27ecd7eca9ca1f0c050282516de2e21)
for more details.
- We annotate gradient of router to be partial in bwd through adding a
field to NoParallel(), so that DTensor will handle the all reduce


<img width="4096" height="2056" alt="image"
src="https://github.com/user-attachments/assets/8c65e360-434c-4138-9c58-f99041da5389"
/>
<img width="4096" height="2056" alt="image"
src="https://github.com/user-attachments/assets/474f431f-a469-400c-9256-77b514a40d7f"
/>

**Caveat:** The graph is plotted from [Claude generated computational
graph
](https://gist.github.com/acisseJZhong/7101c2542530365b7b06bdf1f78068cb),
please take it with a grain of salt.

cc @volcacius @fatih-uzlmz
acisseJZhong added a commit that referenced this pull request Mar 11, 2026
solve #2387 where user reported a bug that MoE router weights diff on
each rank due to a missing all reduce under certain senarios:
- `self.score_before_experts=False` for both ETP=1 and ETP=TP
- `self.score_before_experts=True` and ETP=1 

similar fix was proposed #2388 by @fatih-uzlmz 
## Bug analysis 
**Case1:** 
When ETP=1 < TP, MoE is using TP2EP(`etp_mesh` is None, there is no
ETP), `gate` is Replicated(via NoParallel), experts weight is
Sharded(via EP mesh), MoE input is Replicated.

_Root Cause:_ `ReordererSequenceParallell` is applied to split
`top_scores` across TP ranks. Since each TP rank process its local slice
of tokens through the experts, `d_routed_input` is Partial and there is
no forced all-reduce.

**Case2:** 
When ETP = TP, MoE is using DP2EP, `gate` is Replicated(via NoParallel),
experts weight is Sharded(via ETP which force all reduce in bwd #1878),
MoE input is Replicated on TP mesh.

_Root Cause:_ The gradient flowing back to `gate.weight` is Partial when
`self.score_before_experts=False`, which we incorrectly marked as
Replicated and therefore results in wrong numerics.

_Explanation:_ 
When `self.score_before_experts=True`, `d_routed_input` is already all
reduced because of the fix #1878 we added to ETP.
```
routed_input = routed_input * top_scores_experts_sorted
routed_output = self.experts(routed_input, ...) 
out_experts = routed_output_unsorted.sum(dim=1)    
```

When `self.score_before_experts=False`, gradient of `top_scores` from
`bmm` is Partial. The previous all reduce fix only force all reduce on
`d_routed_input`, but not `d_top_scores` which is wrong.
```
routed_output = self.experts(routed_input, ...)
out_experts = bmm(top_scores, routed_output_unsorted) 
```

## The fix we propose that could fix both Case1 and 2
- We revert the fix in #1878 to keep Partial dx flowing back, and delay
the all reduce later at the boundary of MoE.
- We choose to not use
[`ColWiseParallel/RowwiseParallel`](https://github.com/pytorch/pytorch/blob/e81980ea58c65a283cf01a7132e0f420834ecf10/torch/distributed/tensor/parallel/style.py#L181)
for shared expert as they force all reduce dx; but we want to keep
Partial dx. So we introduced `MoEColWiseParallel/MoERowwiseParallel`
which removed the input and output hooks. See the [reasoning
here](https://gist.github.com/acisseJZhong/b27ecd7eca9ca1f0c050282516de2e21)
for more details.
- We annotate gradient of router to be partial in bwd through adding a
field to NoParallel(), so that DTensor will handle the all reduce


<img width="4096" height="2056" alt="image"
src="https://github.com/user-attachments/assets/8c65e360-434c-4138-9c58-f99041da5389"
/>
<img width="4096" height="2056" alt="image"
src="https://github.com/user-attachments/assets/474f431f-a469-400c-9256-77b514a40d7f"
/>

**Caveat:** The graph is plotted from [Claude generated computational
graph
](https://gist.github.com/acisseJZhong/7101c2542530365b7b06bdf1f78068cb),
please take it with a grain of salt.

cc @volcacius @fatih-uzlmz
EmanueleCoradin pushed a commit to EmanueleCoradin/pytorch that referenced this pull request Mar 30, 2026
## Problem
While fixing a MoE numerics bug (pytorch/torchtitan#2416), we discovered the root cause was a lack of strict gradient placement control/strict typing in `from_local`. Specifically, `from_local(Replicate)` in `ColwiseLinear` (used by the shared expert) produced correct forward behavior, but the backward pass performed an unnecessary all-reduce. The desired backward gradient placement was `Partial`, not `Replicate`.

## Solution
To address this, we add a `grad_placements` keyword argument to `from_local`, mirroring the existing `grad_placements` support in `to_local`. When `grad_placements` is `None` (the default), the backward gradient placement follows the original guarantees established in pytorch#173153. When specified, it overrides the default and uses the user-provided gradient placements directly.

In the longer term, we hope to address this kind of issues through spmd_types as a type checker.

## Test
```
python3 test/distributed/tensor/test_dtensor.py -k test_from_local_grad_placements
```
Pull Request resolved: pytorch#175867
Approved by: https://github.com/wconstab, https://github.com/tianyu-l
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
…2416)

solve pytorch#2387 where user reported a bug that MoE router weights diff on
each rank due to a missing all reduce under certain senarios:
- `self.score_before_experts=False` for both ETP=1 and ETP=TP
- `self.score_before_experts=True` and ETP=1 

similar fix was proposed pytorch#2388 by @fatih-uzlmz 
## Bug analysis 
**Case1:** 
When ETP=1 < TP, MoE is using TP2EP(`etp_mesh` is None, there is no
ETP), `gate` is Replicated(via NoParallel), experts weight is
Sharded(via EP mesh), MoE input is Replicated.

_Root Cause:_ `ReordererSequenceParallell` is applied to split
`top_scores` across TP ranks. Since each TP rank process its local slice
of tokens through the experts, `d_routed_input` is Partial and there is
no forced all-reduce.

**Case2:** 
When ETP = TP, MoE is using DP2EP, `gate` is Replicated(via NoParallel),
experts weight is Sharded(via ETP which force all reduce in bwd pytorch#1878),
MoE input is Replicated on TP mesh.

_Root Cause:_ The gradient flowing back to `gate.weight` is Partial when
`self.score_before_experts=False`, which we incorrectly marked as
Replicated and therefore results in wrong numerics.

_Explanation:_ 
When `self.score_before_experts=True`, `d_routed_input` is already all
reduced because of the fix pytorch#1878 we added to ETP.
```
routed_input = routed_input * top_scores_experts_sorted
routed_output = self.experts(routed_input, ...) 
out_experts = routed_output_unsorted.sum(dim=1)    
```

When `self.score_before_experts=False`, gradient of `top_scores` from
`bmm` is Partial. The previous all reduce fix only force all reduce on
`d_routed_input`, but not `d_top_scores` which is wrong.
```
routed_output = self.experts(routed_input, ...)
out_experts = bmm(top_scores, routed_output_unsorted) 
```

## The fix we propose that could fix both Case1 and 2
- We revert the fix in pytorch#1878 to keep Partial dx flowing back, and delay
the all reduce later at the boundary of MoE.
- We choose to not use
[`ColWiseParallel/RowwiseParallel`](https://github.com/pytorch/pytorch/blob/e81980ea58c65a283cf01a7132e0f420834ecf10/torch/distributed/tensor/parallel/style.py#L181)
for shared expert as they force all reduce dx; but we want to keep
Partial dx. So we introduced `MoEColWiseParallel/MoERowwiseParallel`
which removed the input and output hooks. See the [reasoning
here](https://gist.github.com/acisseJZhong/b27ecd7eca9ca1f0c050282516de2e21)
for more details.
- We annotate gradient of router to be partial in bwd through adding a
field to NoParallel(), so that DTensor will handle the all reduce


<img width="4096" height="2056" alt="image"
src="https://github.com/user-attachments/assets/8c65e360-434c-4138-9c58-f99041da5389"
/>
<img width="4096" height="2056" alt="image"
src="https://github.com/user-attachments/assets/474f431f-a469-400c-9256-77b514a40d7f"
/>

**Caveat:** The graph is plotted from [Claude generated computational
graph
](https://gist.github.com/acisseJZhong/7101c2542530365b7b06bdf1f78068cb),
please take it with a grain of salt.

cc @volcacius @fatih-uzlmz
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
…2416)

solve pytorch#2387 where user reported a bug that MoE router weights diff on
each rank due to a missing all reduce under certain senarios:
- `self.score_before_experts=False` for both ETP=1 and ETP=TP
- `self.score_before_experts=True` and ETP=1 

similar fix was proposed pytorch#2388 by @fatih-uzlmz 
## Bug analysis 
**Case1:** 
When ETP=1 < TP, MoE is using TP2EP(`etp_mesh` is None, there is no
ETP), `gate` is Replicated(via NoParallel), experts weight is
Sharded(via EP mesh), MoE input is Replicated.

_Root Cause:_ `ReordererSequenceParallell` is applied to split
`top_scores` across TP ranks. Since each TP rank process its local slice
of tokens through the experts, `d_routed_input` is Partial and there is
no forced all-reduce.

**Case2:** 
When ETP = TP, MoE is using DP2EP, `gate` is Replicated(via NoParallel),
experts weight is Sharded(via ETP which force all reduce in bwd pytorch#1878),
MoE input is Replicated on TP mesh.

_Root Cause:_ The gradient flowing back to `gate.weight` is Partial when
`self.score_before_experts=False`, which we incorrectly marked as
Replicated and therefore results in wrong numerics.

_Explanation:_ 
When `self.score_before_experts=True`, `d_routed_input` is already all
reduced because of the fix pytorch#1878 we added to ETP.
```
routed_input = routed_input * top_scores_experts_sorted
routed_output = self.experts(routed_input, ...) 
out_experts = routed_output_unsorted.sum(dim=1)    
```

When `self.score_before_experts=False`, gradient of `top_scores` from
`bmm` is Partial. The previous all reduce fix only force all reduce on
`d_routed_input`, but not `d_top_scores` which is wrong.
```
routed_output = self.experts(routed_input, ...)
out_experts = bmm(top_scores, routed_output_unsorted) 
```

## The fix we propose that could fix both Case1 and 2
- We revert the fix in pytorch#1878 to keep Partial dx flowing back, and delay
the all reduce later at the boundary of MoE.
- We choose to not use
[`ColWiseParallel/RowwiseParallel`](https://github.com/pytorch/pytorch/blob/e81980ea58c65a283cf01a7132e0f420834ecf10/torch/distributed/tensor/parallel/style.py#L181)
for shared expert as they force all reduce dx; but we want to keep
Partial dx. So we introduced `MoEColWiseParallel/MoERowwiseParallel`
which removed the input and output hooks. See the [reasoning
here](https://gist.github.com/acisseJZhong/b27ecd7eca9ca1f0c050282516de2e21)
for more details.
- We annotate gradient of router to be partial in bwd through adding a
field to NoParallel(), so that DTensor will handle the all reduce


<img width="4096" height="2056" alt="image"
src="https://github.com/user-attachments/assets/8c65e360-434c-4138-9c58-f99041da5389"
/>
<img width="4096" height="2056" alt="image"
src="https://github.com/user-attachments/assets/474f431f-a469-400c-9256-77b514a40d7f"
/>

**Caveat:** The graph is plotted from [Claude generated computational
graph
](https://gist.github.com/acisseJZhong/7101c2542530365b7b06bdf1f78068cb),
please take it with a grain of salt.

cc @volcacius @fatih-uzlmz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu 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.

4 participants