Repository navigation
Conversation
Dispatch autograd discarded received routing-weight gradients, cutting the gradient path from weighted expert outputs to the source router. Add a private, nonabstract backward hook and implement the NCCL path with native HT backward combine, returning one gradient per source token and top-k slot. Other backends retain their existing token-gradient path and return no weight gradient. Keep the existing combine autograd path and forward bindings. Cover mixed routes in both layouts, unused outputs, noncontiguous gradients, frozen tokens and a softmax-router MoE roundtrip, with a reference-backend fallback regression. Authored with assistance from OpenAI Codex GPT-6.1 Sol. Test Plan ```bash spin quicklint -- -a --paths-cmd 'git diff --name-only HEAD' --tee-json /tmp/weight-grad-results/lint.json ``` Scoped lint completed with exit 0. The independent container build and numerical tests are pending at draft creation; their final results are recorded in the MR. ```bash pip install -e . -v --no-build-isolation ``` Signed-off-by: Masaki Kozuki <[email protected]>
Restore ordinary NCCL test parametrization and NCCL2 inheritance so the routing-weight gradient patch stays focused. Keep the reference-test parametrization required by its new cases. Authored with GPT-6.1 Sol. Signed-off-by: Masaki Kozuki <[email protected]>
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/201642
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (1 Unrelated Failure)As of commit 62ba60a with merge base 4100392 ( NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following job failed, but the AI CI Advisor judged the failure not to be evidence against this change:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
kwen2501
left a comment
There was a problem hiding this comment.
The native implementations appear to support making this a backend contract: NCCL-EP has backward combine, and MoRI's combine has a routing-weight fold intended for training backward. I think unsupported weight gradients should fail loudly rather than silently stop router learning.
| def _dispatch_backward( | ||
| self, | ||
| routing: Routing, | ||
| grad_tokens: torch.Tensor, | ||
| grad_topk_weights: torch.Tensor | None, | ||
| ) -> tuple[torch.Tensor, torch.Tensor | None]: | ||
| out_tokens = grad_tokens.new_zeros( | ||
| routing.topk_idx.shape[0], grad_tokens.shape[-1] | ||
| ) | ||
| self._combine(routing, grad_tokens, out_tokens) | ||
| return out_tokens, None |
There was a problem hiding this comment.
Could _dispatch_backward be a required abstract backend method instead of providing a default that returns None for topk_weights? Silently dropping a requested gradient can leave the router untrained without an error. NCCL-EP has native backward combine, and MoRI also supports folding received weights back to source token/top-k positions, so both intended production backends can implement the contract.
There was a problem hiding this comment.
A concrete signature I would suggest is:
@abc.abstractmethod
def _dispatch_backward(
self,
routing: Routing,
grad_recv_tokens: torch.Tensor,
grad_recv_topk_weights: torch.Tensor,
out_token_grads: torch.Tensor,
out_topk_weight_grads: torch.Tensor,
) -> None:
...Three advantages of output buffers here:
- It matches the existing low-level
_dispatch/_combineconventions. - The base autograd code owns allocation, shapes, and dtypes instead of duplicating them in NCCL and MoRI.
- Both gradients are required by the contract, so a backend cannot silently return
Nonefor the routing-weight gradient.
Preferred layering: _DispatchAutograd.backward allocates both outputs and invokes this required primitive; NCCL-EP and MoRI implement only their backend-specific reverse-routing mechanics.
…ombine Make _dispatch_backward an abstract backend contract that fills both token and routing-weight gradient buffers, preventing silent loss of router gradients. Combine backward previously used forward dispatch with dummy routing metadata, causing incorrect expert-major routing-weight gradients. Use a dedicated backend primitive backed by native NCCL-EP backward dispatch, removing the dummy buffers. Authored with GPT-6.1 Sol Signed-off-by: Masaki Kozuki <[email protected]>
|
@pytorchbot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
viable/strict brings pytorch#201642, which makes _combine_backward and _dispatch_backward abstract on TokenSwitch and has dispatch backward return topk_weights gradients. TokenSwitchMoRI now implements both: combine backward replays the dispatch of the gradients, and dispatch backward combines the token gradients and returns each source weight's gradient from its receive slot on expert k's rank, gathered across ranks in fp32 and indexed with MoRI's dest map. The two new weight-gradient tests in _TokenSwitchFlatTests constructed TokenSwitchNCCL directly; they now get the backend from the host class, so they also run for TokenSwitchMoRI. Authored with Claude.
The viable/strict merge left pytorch#201642's parametrized weight-gradient and routing-dtype tests in _TokenSwitchFlatTests, and instantiate_parametrized_tests(TokenSwitchNCCLTest) cannot delete inherited methods, so the file failed at import. Expand them on the mixin instead, and move TokenSwitchNCCLTest's two explicit_rendezvous tests into an expanded mixin of their own, since the class-level call also trips over the mixin's expanded tests. Also split a line the formatter flagged. Authored with Claude.
…ptions Since pytorch#201642, _CombineAutograd.backward sized the gradient buffer by max_recv_tokens_per_rank, but TokenSwitchMoRI's expert_major combine input has up to max_expert_major_slots_per_rank rows, so its combine backward returned a short gradient. The buffer now holds max(max_recv_tokens_per_rank, rows of the combine input); NCCL inputs never exceed the bound, so NCCL is unchanged. TokenSwitchMoRI's flat combine now passes MoRI only its first recv_cap rows: the new dispatch backward combines whole dispatch outputs, which can be larger than MoRI's staging buffer, and the contract leaves the later rows unspecified. Two tests in the shared flat mixin assumed NCCL: test_create_routing checks the NCCL EP handle's receive count, which is now asserted only for TokenSwitchNCCL, and test_create_routing_invalid_dtype expects NCCL's topk_idx dtype check, which TokenSwitchMoRI.create_routing now performs too. Authored with Claude.
## Linked issue or supporting maintainer <!-- Keep the one line that applies and delete the others. Link an issue labeled "actionable", or name the maintainer who agreed to this change beforehand. PRs with neither will be automatically closed, unless the author has write access to the repo. --> Fixes pytorch#201470 Supported by @<!-- Handle of the maintainer who agreed to this PR --> ## Summary (human written only) Implement `topk_weights` gradients for TokenSwitchNCCL. ## Agent details (if applicable) ### Problem and behavior `TokenSwitch.dispatch` autograd drops `grad_out_topk_weights`, so a loss that weights expert outputs on the receiving rank cannot propagate through those weights to the source router. The NCCL implementation now returns a gradient for each source `(token, top-k slot)` using native HT backward combine. A private, nonabstract hook preserves the existing behavior of backends that do not implement routing-weight gradients. Expert indices remain discrete; the added path differentiates the selected weights. ### Scope and review order Review `_DispatchAutograd` and the default/NCCL `_dispatch_backward` hook first, then the native backward-combine binding, then the tests. Existing forward bindings and combine autograd remain unchanged. The extraction excludes async Work/compiler changes, fixed-capacity routing updates and explicit cleanup APIs from the larger integration branch; no FlexGEMM compiler changes are included. The regressions cover both layouts, multiple local experts and destinations, token-only and weight-only losses, frozen tokens, noncontiguous incoming gradients, invalid/padded flat slots, and dispatch through weighted expert outputs and combine with a softmax router. A CPU reference-backend test checks the fallback behavior. Existing NCCL test parametrization and ordinary NCCL2 inheritance are preserved; the reference class expands its new parametrized cases. Pull Request resolved: pytorch#201642 Approved by: https://github.com/fduwjj, https://github.com/kwen2501
## Linked issue or supporting maintainer <!-- Keep the one line that applies and delete the others. Link an issue labeled "actionable", or name the maintainer who agreed to this change beforehand. PRs with neither will be automatically closed, unless the author has write access to the repo. --> Fixes pytorch#201470 Supported by @<!-- Handle of the maintainer who agreed to this PR --> ## Summary (human written only) Implement `topk_weights` gradients for TokenSwitchNCCL. ## Agent details (if applicable) ### Problem and behavior `TokenSwitch.dispatch` autograd drops `grad_out_topk_weights`, so a loss that weights expert outputs on the receiving rank cannot propagate through those weights to the source router. The NCCL implementation now returns a gradient for each source `(token, top-k slot)` using native HT backward combine. A private, nonabstract hook preserves the existing behavior of backends that do not implement routing-weight gradients. Expert indices remain discrete; the added path differentiates the selected weights. ### Scope and review order Review `_DispatchAutograd` and the default/NCCL `_dispatch_backward` hook first, then the native backward-combine binding, then the tests. Existing forward bindings and combine autograd remain unchanged. The extraction excludes async Work/compiler changes, fixed-capacity routing updates and explicit cleanup APIs from the larger integration branch; no FlexGEMM compiler changes are included. The regressions cover both layouts, multiple local experts and destinations, token-only and weight-only losses, frozen tokens, noncontiguous incoming gradients, invalid/padded flat slots, and dispatch through weighted expert outputs and combine with a softmax router. A CPU reference-backend test checks the fallback behavior. Existing NCCL test parametrization and ordinary NCCL2 inheritance are preserved; the reference class expands its new parametrized cases. Pull Request resolved: pytorch#201642 Approved by: https://github.com/fduwjj, https://github.com/kwen2501
## Linked issue or supporting maintainer Part of #184147 ## BC-breaking? No ## Summary (human written only) There will certainly be follow-up work, but this is a verified initial implementation of TokenSwitch + MoRI. ## Agent details (if applicable) My agent came up with this analysis, but I've read and approved it. **What.** `TokenSwitchMoRI` implements the `TokenSwitch` contract from #198963 on MoRI EP v2 (https://github.com/ROCm/mori) with its flydsl kernel backend, intranode only. Both layouts are supported: flat directly, and expert_major built on MoRI's flat dispatch (slots ordered by local expert, then receive row; `max_expert_major_slots_per_rank` bounds the slot count). The first `dispatch` on a `Routing` computes the layout and later dispatches replay it. **Backward.** Since #201642, backends implement `_combine_backward` and `_dispatch_backward` themselves, and dispatch backward also returns `topk_weights` gradients. `TokenSwitchMoRI`'s combine backward replays the MoRI dispatch of the gradients. Its dispatch backward combines the token gradients, and gives each source weight `(t, k)` the gradient at its receive slot on expert k's rank: every rank's slot gradients are all_gathered in fp32 and indexed with MoRI's dest map (a MoRI combine would round them to the token dtype). **Changes to shared code.** - `_CombineAutograd.backward` sizes its gradient buffer as `max(max_recv_tokens_per_rank, rows of the combine input)`; MoRI's expert_major input can have up to `max_expert_major_slots_per_rank` rows. NCCL inputs never exceed `max_recv_tokens_per_rank`, so NCCL is unchanged. - In `test_token_switch.py`, the shared flat-layout mixin now holds #201642's weight-gradient tests (they get the backend from the test class instead of constructing `TokenSwitchNCCL`), so they run for MoRI too. Parametrized tests are expanded on the mixins that define them, which moves `TokenSwitchNCCLTest`'s two `explicit_rendezvous` tests into an NCCL-only mixin. `test_create_routing` checks the NCCL EP handle's receive count only for `TokenSwitchNCCL`, and `TokenSwitchMoRI.create_routing` raises the same `topk_idx` dtype `TypeError` as NCCL. **MoRI workarounds, in the code with comments.** - MoRI's routing handle aliases op-owned buffers that the next routing dispatch overwrites (ROCm/mori#715), so the adapter copies the dest map and receive count. ROCm/mori#733 adds `snapshot=True` for this; a TODO marks the copy for removal once a MoRI release includes it. - MoRI's kernels synchronize ranks on entry only, so two dispatches (or two combines) in a row can race a fast peer's writes into the receive buffers. The adapter fences with an `all_reduce` only when the same op repeats; alternating dispatch and combine is already ordered. **Known limitation.** On MI300X, MoRI's flydsl backend fails at op construction with default geometry (ROCm/mori#794, a MoRI tuning gap), so `TokenSwitchMoRI` currently works on MI355X but not MI300X. ROCm/mori#795 adds a tuned MI300X table. **Tests.** `TokenSwitchMoRITest` runs the flat, expert_major and contract test suites plus MoRI-only tests (38 tests) on 2+ GPUs. It skips when `mori` with flydsl is not importable, which includes current CI images, the same way the NCCL EP tests skip without `USE_NCCL_EP`. **Test Plan.** MI355X, 4 ranks and 2 ranks, torch nightly 2.16.0.dev20261117+rocm10.1 with this PR's `_token_switch.py` in place of the installed module, MoRI main e73ccc539 built from source, flydsl 0.5.0: ``` python test/distributed/test_token_switch.py -v ``` Each run: `TokenSwitchMoRITest` 38/38 passed, `TokenSwitchReferenceTest` 13/13 passed, NCCL EP classes skipped (no `USE_NCCL_EP` build). Lint (default linters and `lintrunner --take PYREFLY --all-files`) is clean. The NCCL side of the shared changes is covered only by NCCL CI. Pull Request resolved: #201225 Approved by: https://github.com/d4l3k
Linked issue or supporting maintainer
Fixes #201470
Supported by @
Summary (human written only)
Implement
topk_weightsgradients for TokenSwitchNCCL.Agent details (if applicable)
Problem and behavior
TokenSwitch.dispatchautograd dropsgrad_out_topk_weights, so a loss thatweights expert outputs on the receiving rank cannot propagate through those
weights to the source router. The NCCL implementation now returns a gradient
for each source
(token, top-k slot)using native HT backward combine.A private, nonabstract hook preserves the existing behavior of backends that
do not implement routing-weight gradients. Expert indices remain discrete;
the added path differentiates the selected weights.
Scope and review order
Review
_DispatchAutogradand the default/NCCL_dispatch_backwardhook first,then the native backward-combine binding, then the tests. Existing forward
bindings and combine autograd remain unchanged. The extraction excludes async
Work/compiler changes, fixed-capacity routing updates and explicit cleanup APIs
from the larger integration branch; no FlexGEMM compiler changes are included.
The regressions cover both layouts, multiple local experts and destinations,
token-only and weight-only losses, frozen tokens, noncontiguous incoming
gradients, invalid/padded flat slots, and dispatch through weighted expert
outputs and combine with a softmax router. A CPU reference-backend test checks
the fallback behavior. Existing NCCL test parametrization and ordinary NCCL2
inheritance are preserved; the reference class expands its new parametrized cases.