Skip to content

fix MoE TP backward - #1878

Merged
tianyu-l merged 1 commit into
mainfrom
tp
Oct 15, 2025
Merged

tianyu-l merged 1 commit into
mainfrom
tp

Conversation

@tianyu-l

Copy link
Copy Markdown
Contributor

When TP is used for the matmul / grouped mm between input activations and routed experts, the same inputs are seeing different parameter values across TP ranks (inputs Replicate, param Shard) and thus the gradient flowing back should have Partial placement and need to be reduced. However, since we are using plain Tensor, instead of DTensor which can properly handle the gradient flow, we have to "manually" handle it. This PR fixes the issue by specifying the grad_placements field of to_local.

One can see that one more all-reduce is inserted in the backward every time it gets gradient from routed experts matmul.
before
image
after
image

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 15, 2025

@wwwjn wwwjn 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!

@wwwjn

wwwjn commented Oct 15, 2025 •

Copy link
Copy Markdown
Contributor

Verification with deepseek-671B model: (FSDP=EP=32, TP8)

  1. Enable loss compile + with this PR: The loss starts to shows NaN. (Previously it was gradients becomes NaN) - Will create another issue to track
Screenshot 2025-10-15 at 10 20 07 AM
  1. Disable loss compile + with this PR, the loss and gradient becomes normal. In the following steps, the gradient increase dramatically because of learning rate setup, not related to this issue.
Screenshot 2025-10-15 at 10 17 45 AM

xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 13, 2026
When TP is used for the matmul / grouped mm between input activations
and routed experts, the same inputs are seeing different parameter
values across TP ranks (inputs Replicate, param Shard) and thus the
gradient flowing back should have `Partial` placement and need to be
reduced. However, since we are using plain Tensor, instead of DTensor
which can properly handle the gradient flow, we have to "manually"
handle it. This PR fixes the issue by specifying the `grad_placements`
field of `to_local`.

One can see that one more all-reduce is inserted in the backward every
time it gets gradient from routed experts matmul.
before
<img width="767" height="74" alt="image"
src="https://github.com/user-attachments/assets/602487e4-57fb-4dd3-b22b-92db1729a857"
/>
after
<img width="790" height="121" alt="image"
src="https://github.com/user-attachments/assets/bc033c50-4bac-4ec7-b96f-ff3464e9bfa8"
/>
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 25, 2026
When TP is used for the matmul / grouped mm between input activations
and routed experts, the same inputs are seeing different parameter
values across TP ranks (inputs Replicate, param Shard) and thus the
gradient flowing back should have `Partial` placement and need to be
reduced. However, since we are using plain Tensor, instead of DTensor
which can properly handle the gradient flow, we have to "manually"
handle it. This PR fixes the issue by specifying the `grad_placements`
field of `to_local`.

One can see that one more all-reduce is inserted in the backward every
time it gets gradient from routed experts matmul.
before
<img width="767" height="74" alt="image"
src="https://github.com/user-attachments/assets/602487e4-57fb-4dd3-b22b-92db1729a857"
/>
after
<img width="790" height="121" alt="image"
src="https://github.com/user-attachments/assets/bc033c50-4bac-4ec7-b96f-ff3464e9bfa8"
/>
acisseJZhong added a commit that referenced this pull request Mar 2, 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
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
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

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.

2 participants