Skip to content

[TokenSwitch] Support topk_weights gradients - #201642

Closed
crcrpar wants to merge 3 commits into
mainfrom
crpa_codex/token-switch-dispatch-weight-grad
Closed

crcrpar wants to merge 3 commits into
mainfrom
crpa_codex/token-switch-dispatch-weight-grad

Conversation

@crcrpar

@crcrpar crcrpar commented Oct 21, 2026

Copy link
Copy Markdown
Collaborator

Linked issue or supporting maintainer

Fixes #201470

Supported by @

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.

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]>
@pytorch-bot pytorch-bot Bot added ciflow/h100-symm-mem ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (c10d) release notes category labels Oct 21, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

🔗 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 (image):

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:

  • Lint / lintrunner-noclang-all / lint (gh)
    >>> Lint for test/test_hub.py:

    AI verdict: AI verdict: not related

    The only lint error is a PYFMT formatting warning in test/test_hub.py, a file the suspect commit doesn't touch. The same failure already shows up at the PR's merge base (4100392), and recent trunk commits pass this job, so the PR is just carrying a lint break that was in its stale base and has since been fixed on main.

    Full reasoning on HUD →

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@fduwjj fduwjj left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@kwen2501 kwen2501 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Comment thread torch/distributed/_token_switch.py Outdated
Comment on lines +293 to +303
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

@kwen2501 kwen2501 Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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:

  1. It matches the existing low-level _dispatch / _combine conventions.
  2. The base autograd code owns allocation, shapes, and dtypes instead of duplicating them in NCCL and MoRI.
  3. Both gradients are required by the contract, so a backend cannot silently return None for 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]>
@crcrpar crcrpar added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 28, 2026
@crcrpar

crcrpar commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

jeffdaily added a commit to ROCm/pytorch that referenced this pull request Oct 29, 2026
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.
jeffdaily added a commit to ROCm/pytorch that referenced this pull request Oct 29, 2026
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.
jeffdaily added a commit to ROCm/pytorch that referenced this pull request Oct 29, 2026
…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.
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
## 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
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
## 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
pytorchmergebot pushed a commit that referenced this pull request Nov 23, 2026
## 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/h100-symm-mem ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: distributed (c10d) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[TokenSwitch] Support topk_weights gradient in dispatch so the MoE router can train

5 participants