Repository navigation
fix(MoE): Apply grad_placements=Partial() to router to_local for TP - #2388
fatih-uzlmz wants to merge 8 commits into
Conversation
There was a problem hiding this comment.
Thanks for the catch :)
I accidentally branched off my PR history, just reverted train.py so it should be clean now,
And I am also currently working on the unit test to verify the gradients, will update you soon
wconstab
left a comment
There was a problem hiding this comment.
can you add a small test case showing the numerics issue / validating the fix?
|
I opened the original issue here #2387 this does not look like the right fix. It might work for TP but I don't think is correct for EP. |
|
Thanks @volcacius for the input, You're right, I think my fix enforces I think the robust fix is to make it conditional, so something like
Does that align with what you were thinking? |
|
cc: @volcacius @wconstab I went ahead and pushed a new commit with this conditional logic, the code now explicitly checks I also re ran our unit test with the new logic to ensure everything is still functioning properly and everything passes
Let me know if there's anything else needed here 👍 |
| # Only enforce Partial grad placement if the weight is actually replicated (TP). | ||
| # If it's sharded (EP), we shouldn't reduce gradients across different experts. | ||
| is_replicated = isinstance(self.w1.placements[0], Replicate) | ||
| grad_placement = (Partial(),) if is_replicated else None |
There was a problem hiding this comment.
I'm not sure if it fixes anything. In EP / TP, the weights are always sharded.
For activations, https://github.com/pytorch/torchtitan/blob/main/torchtitan/distributed/expert_parallel.py#L57 fixes the issue.
I think there's one more issue here https://github.com/pytorch/torchtitan/blob/main/torchtitan/distributed/expert_parallel.py#L285
|
I don't think this works. It's not the expert weights that are replicated, it's the gate weights through NoParallel. If you look at my original issue I suggested a different fix. |
|
Okay I think I understand whats going on now, thank you guys both for the guidance. First off my apologies, I accidentally applied the @volcacius is right about the divergence reported in #2387 , its happening because the Router Gate weights are replicated, and they are losing their backward reduction when passing through the I will revert my changes to moe.py and move the @tianyu-l for the manual slice in expert_parallel.py L285—since that drops the DTensor backward communication, would you like me to include a fix for that in this PR as well, or should we isolate this PR strictly to the NoParallel router fix? |
Sorry it's not clear to me what the root cause is, and why it's not the one that I mentioned. Could you include under what parallelism do you see the problem? The slicing one I mentioned would only occur during ETP=1 TP > 1 EP > 1. I would be surprised if it happens with TP = ETP. |
|
Yeah fair point, Since I picked this up from the issue tracker, I don't have the original reproduction config. @volcacius could you share your exact TP, EP, and ETP degrees? |
|
Looks like #2416 addresses the root cause via the activations. Closing this out, thanks for the great discussion everyone :) |
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
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
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
…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
…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



Description
Fixes #2387 (MoE router replication broken w/ TP).
The Issue
When Tensor Parallelism (TP) is enabled, the MoE router weights were diverging immediately after the first step. This was caused by
to_local()being called on the router weights without specifyinggrad_placements. As a result, the backward pass was treating the local gradients as final gradients rather than partial sums, skipping the necessary AllReduce synchronization across ranks.The Fix
Added
grad_placements=(Partial(),)to theto_local()conversion intorchtitan/models/moe/moe.py. This explicitly signals to the autograd engine that the resulting local tensor gradients must be reduced (summed) across the TP mesh before the optimizer step.Verification
Partialis correctly imported fromtorch.distributed._tensor.tests/unit_tests/test_compile_moe.pylocally; tests passed successfully.