Skip to content

[ROCm][TokenSwitch] Add TokenSwitchMoRI, a MoRI EP v2 backend - #201225

Closed
jeffdaily wants to merge 18 commits into
pytorch:mainfrom
ROCm:tokenswitch-mori
Closed

jeffdaily wants to merge 18 commits into
pytorch:mainfrom
ROCm:tokenswitch-mori

Conversation

@jeffdaily

@jeffdaily jeffdaily commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

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 [TokenSwitch] Support topk_weights gradients #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.

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.

cc @sunway513 @jithunnair-amd @pruthvistony @ROCmSupport @jataylo @hongxiayang @naromero77amd @pragupta @jerrymannil @xinyazhang

TokenSwitch's semantics for top-k > 1 were implicit in what NCCL EP happens to do, and nothing checked them: every test uses TOP_K=1 with one expert per rank, and all of them skip in CI because no CI job builds with USE_NCCL_EP. Writing a second backend (MoRI, for ROCm) showed which properties callers and the autograd functions actually rely on. This change writes them down and tests them.

Read the change in this order. First, the TokenSwitch class docstring states the contract, matching NCCL EP's HT flat layout as read from its source: a Routing fixes the receive-slot layout and a later dispatch on it replays that layout (combine's backward depends on this); a token is received once per destination rank; out_topk_idx holds the receiving rank's local expert ids in ascending order, packed, padded with -1, with weights aligned; combine is an unweighted sum of one row per receive slot; rows past the received count are unspecified. Second, max_recv_tokens_per_rank becomes an abstract property, so _CombineAutograd.backward no longer reads the NCCL subclass's private attribute. Third, the tests: _TokenSwitchContractTests holds seven tests at top-k 2 with two experts per rank and random routing, _ReferenceTokenSwitch is a test-only all_gather implementation of the contract, and TokenSwitchReferenceTest runs the contract tests on it over gloo on CPU, so they run in CI without an EP library. TokenSwitchNCCLTest mixes the same tests in.

Alternatives considered: making NCCL follow MoRI's forwarded global top-k instead is not possible, because NCCL EP's receiver only gets a bitmap of its own experts. Leaving the contract tests NCCL-only would keep them skipped in CI, hence the reference backend.

Test Plan:

The installed torch is a ROCm build (2.15.0a0) that predates this branch's base, so the tests were run from this branch's test file with this branch's torch/distributed/_token_switch.py loaded in place of the installed module (the change is pure Python). Reference backend with no visible GPU (as a CPU-only CI shard runs it):

```
HIP_VISIBLE_DEVICES= ROCR_VISIBLE_DEVICES= python run_upstream_ts_tests.py -v -k Reference
```

7 passed. The same test file run against a TokenSwitchMoRI prototype (flat layout) on 2 and 4 gfx950 GPUs, subclassing TokenSwitchNCCLTest with MoRI factories:

```
HIP_VISIBLE_DEVICES=6,7 python run_mori_contract_tests.py -v -k TokenSwitchMoRIUpstreamTest
HIP_VISIBLE_DEVICES=4,5,6,7 python run_mori_contract_tests.py -v -k TokenSwitchMoRIUpstreamTest
```

14 passed (7 contract tests and the 7 existing flat TOP_K=1 tests), 7 skipped (expert-major and NCCL symmetric-memory tests). Against deliberately broken variants of that prototype, the contract tests fail as intended: global top-k instead of local packed ids fails test_contract_flat_dispatch_rows_and_topk, aliased routing handles fail test_contract_two_routings_autograd, and a re-dispatch that moves no payload fails test_contract_autograd_roundtrip.

Not run: the contract tests on TokenSwitchNCCL (no NVIDIA hardware). They respect NCCL EP's documented constraints (num_experts divisible by ranks, top-k <= 32, max_recv_tokens_per_rank >= max_dispatch_tokens_per_rank). They create a second NCCL EP group on the same process group, which is untested.

```
lintrunner -a --take PYFMT,RUFF,FLAKE8,CODESPELL,NEWLINE,SPACES,TABS,NOQA,TEST_HAS_MAIN,TEST_DEVICE_BIAS,DOCSTRING_LINTER,TYPEIGNORE torch/distributed/_token_switch.py test/distributed/test_token_switch.py
```

This change was authored with Claude (AI assistant).
The contract tests always alternated dispatch and combine, so nothing checked that calls on different Routings can be interleaved, e.g. dispatching one layer or micro-batch ahead. That pattern broke the MoRI backend prototype: MoRI's kernels synchronize ranks on entry only and a dispatch writes into peers' receive buffers before that point, so two dispatches in a row let a fast peer overwrite a slower peer's buffer before it copied the previous result out (the same holds for two combines). Alternating calls are ordered by the other op's entry barrier, which is why the existing tests passed.

This adds the guarantee to the TokenSwitch contract docstring and a test_contract_interleaved_routings test that runs three rounds of dispatch r1, dispatch r2, combine r1, combine r2 with autograd (so the backward also runs two combines' and two dispatches' backwards back to back), with a different gradient scale per routing.

Test Plan:

Same harness as the previous commit (this branch's torch/distributed/_token_switch.py loaded over an installed ROCm torch 2.15.0a0; the change is pure Python). Reference backend, no visible GPU:

```
HIP_VISIBLE_DEVICES= ROCR_VISIBLE_DEVICES= python run_upstream_ts_tests.py -v -k Reference
```

8 passed. TokenSwitchMoRI prototype with a fence on repeated same-kind calls (a one-element all_reduce), 2 MI355X GPUs, three runs:

```
HIP_VISIBLE_DEVICES=0,1 python run_mori_contract_tests.py -v -k TokenSwitchMoRIUpstreamTest.test_contract
```

8 passed each run. Without the fence, test_contract_interleaved_routings fails in all three runs (the ranks deadlock and the harness reports the failure at its 300 s per-test timeout); at larger sizes (64 tokens, hidden 128, top-k 4) the same pattern produces wrong results instead (max forward error ~5, max grad error ~6). Not run on TokenSwitchNCCL (no NVIDIA hardware).

```
lintrunner --take PYFMT,RUFF,FLAKE8,CODESPELL,DOCSTRING_LINTER torch/distributed/_token_switch.py test/distributed/test_token_switch.py
```

This change was authored with Claude (AI assistant).
Adds TokenSwitchMoRI, a TokenSwitch backend for ROCm built on MoRI's EP v2 dispatch/combine with the flydsl kernel backend (pytorch#184147). It is pure Python: mori is imported when a TokenSwitchMoRI is constructed (_import_mori, like _import_nccl_ep), so there is no build flag, CMake or C++. Stacked on the TokenSwitch contract PR (pytorch#198963); it implements that contract for the flat layout.

Read torch/distributed/_token_switch.py first. MoRI computes routing inside its first dispatch, so create_routing returns a Routing whose holder the first dispatch fills with MoRI's routing handle, and later dispatches on the Routing replay it (which combine's backward needs). Three things differ from what the contract needs and are handled in the adapter: MoRI v2 routing handles alias op-owned buffers (ROCm/mori#715), so each handle is cloned; MoRI forwards each token's global top-k, so it is translated to the contract's local, packed layout by a helper compiled on first use (~22 us vs ~125 us eager at 16k rows, K=8); and MoRI's kernels synchronize ranks on entry only, so two dispatches (or two combines) in a row are fenced with a one-element all_reduce, which is needed for interleaved routings. Only the flat layout is supported; expert_major raises NotImplementedError. MoRI's outputs are copied into the caller's buffers (op-owned buffers are overwritten by the next call).

Then the tests: the existing flat TOP_K=1 tests move unchanged into a _TokenSwitchFlatTests mixin (test ids unchanged), and TokenSwitchMoRITest runs them plus the contract tests, gated on mori and flydsl being importable on a ROCm GPU.

Alternatives considered: MoRI v1 IntraNode replay dispatch moves no payload on current main (ROCm/mori#714, fixed by ROCm/mori#675), and v2's hip backend has no replay, so v2 flydsl is the only MoRI path that supports combine's backward today. Returning views of MoRI's buffers instead of copying saves ~4% of a dispatch+combine pair at 2 ranks but is unsafe under autograd (the expert GEMM saves its input, and combine's backward re-dispatches on the same op first), so it is left for an opt-in follow-up like the NCCL symmetric-memory path.

Test Plan:

Run against an installed ROCm torch 2.15.0a0 with this branch's torch/distributed/_token_switch.py loaded in its place (the change is pure Python), stock MoRI 78b7a5f3 + flydsl 0.3.4.1, 2 MI355X GPUs:

```
HIP_VISIBLE_DEVICES=0,1 python run_ts_tests.py -v
HIP_VISIBLE_DEVICES= ROCR_VISIBLE_DEVICES= python run_ts_tests.py -v
```

With GPUs: 67 ran, OK, 44 skipped (TokenSwitchMoRITest 15 and TokenSwitchReferenceTest 8 ran; NCCL classes skip without USE_NCCL_EP). Without GPUs: 67 ran, OK, 59 skipped (reference 8/8, MoRI skips). An interleaved dispatch r1 / dispatch r2 / combine r1 / combine r2 + backward check at 64 tokens, hidden 128, top-k 4 goes from max forward error 5.14 / grad error 6.43 without the fence to 0.000 / 0.028 with it.

```
lintrunner -a --take PYFMT,RUFF,FLAKE8,CODESPELL,NEWLINE,SPACES,TABS,NOQA,TEST_HAS_MAIN,TEST_DEVICE_BIAS,DOCSTRING_LINTER,TYPEIGNORE torch/distributed/_token_switch.py test/distributed/test_token_switch.py
```

This change was authored with Claude (AI assistant).
MoRI has no expert-major dispatch, so TokenSwitchMoRI builds it on MoRI's flat dispatch. On the first dispatch on an expert_major Routing, a stable argsort over (local expert, receive row) of every (receive row, k) pair that targets a local expert assigns the slots, and that slot map is kept on the Routing so later dispatches (including combine's backward) reuse it. Dispatch gathers payload rows and the 1-D per-slot weights through the map; combine sums each receive row's slots in fp32 into MoRI's own combine input buffer (MoRI skips its staging copy when handed that buffer) and runs MoRI's combine. Slots are ordered by local expert, then receive row; NCCL EP orders within an expert by global source token, and the contract does not specify this order. A rank can receive up to recv_cap * min(top_k, experts_per_rank) slots, more than max_recv_tokens_per_rank, so the bound is exposed as max_expert_major_slots_per_rank and used by _alloc_dispatch_outputs.

Alternative considered: MoRI v2's StdMoE ConvertDispatchOutput. It only helps with slot assignment, pads every expert to a fixed capacity, orders slots within an expert with atomics (non-deterministic), reads op-owned buffers the next dispatch overwrites, needs enable_std_moe at op construction (which also changes combine's staging) and makes an extra payload copy; ConvertCombineInput folds in routing weights, which TokenSwitch's unweighted combine must not. A prototype using it measured ~6.3 ms vs ~3.1 ms for the first dispatch+combine.

Cost: copies run over the full slot capacity to avoid a host sync, so expert_major costs ~2.5x the flat layout (2 MI355X GPUs, 2048 tokens/rank, hidden 4096 bf16, top-k 8, 8 experts/rank: flat ~0.70 ms, expert_major ~1.65-1.79 ms per dispatch+combine; first dispatch costs the same as a replay).

Tests: upstream's two expert_major tests move from TokenSwitchNCCLTest into a _TokenSwitchExpertMajorTests mixin shared by NCCL and MoRI (bodies unchanged), plus two new top-k 2 tests there: slot count and per-expert grouping with the right sources and weights, re-dispatch keeping the slots, unweighted combine == K * x; and two interleaved expert_major Routings under autograd.

Test Plan:

Same harness as the previous commit (this branch's torch/distributed/_token_switch.py over an installed ROCm torch 2.15.0a0; stock MoRI 78b7a5f3 + flydsl 0.3.4.1):

```
HIP_VISIBLE_DEVICES=0,1 python run_ts_tests.py -v
HIP_VISIBLE_DEVICES=4,5,6,7 python run_ts_tests.py -v
HIP_VISIBLE_DEVICES= ROCR_VISIBLE_DEVICES= python run_ts_tests.py -v
```

2 and 4 GPUs: 75 ran, OK, 48 skipped (TokenSwitchMoRITest 19, including the 4 expert_major tests, and TokenSwitchReferenceTest 8 ran). No GPU: 75 ran, OK, 67 skipped. Interleaved dispatch/dispatch/combine/combine + backward at 64 tokens, hidden 128, top-k 4: max forward error 0.000 for both layouts, max grad error 0.024 (flat) / 0.062 (expert_major, bf16 rounding of 4x values).

```
lintrunner -a --take PYFMT,RUFF,FLAKE8,CODESPELL,NEWLINE,SPACES,TABS,NOQA,TEST_HAS_MAIN,TEST_DEVICE_BIAS,DOCSTRING_LINTER,TYPEIGNORE torch/distributed/_token_switch.py test/distributed/test_token_switch.py
```

This change was authored with Claude (AI assistant).
Review feedback: backends may lay out a flat row's top-k entries differently (expert-id sorted and packed, weight sorted and packed, or left in the token's top-k positions), and the contract should not pick one yet. The contract now says only what a row contains: the local ids of the receiving rank's experts among the token's top-k, -1 in the other entries, the matching weights, and 0 where the id is -1. test_contract_flat_dispatch_rows_and_topk compares each row as a set of (local expert, weight) pairs and checks the padding entries, and the reference backend now keeps entries in the token's top-k positions, which is simpler and exercises a non-packed layout.

Test Plan:

Same harness as before (this branch's torch/distributed/_token_switch.py over an installed ROCm torch 2.15.0a0):

```
HIP_VISIBLE_DEVICES= ROCR_VISIBLE_DEVICES= python run_upstream_ts_tests.py -v -k Reference
HIP_VISIBLE_DEVICES=0,1 python run_mori_contract_tests.py -v -k TokenSwitchMoRIUpstreamTest.test_contract
```

Reference backend (slot-preserving): 8 passed. TokenSwitchMoRI prototype (expert-id sorted and packed), 2 MI355X GPUs: 8 passed. A variant that forwards the source token's full global top-k still fails test_contract_flat_dispatch_rows_and_topk.

```
lintrunner -a --take PYFMT,RUFF,FLAKE8,CODESPELL,NEWLINE,SPACES,TABS,NOQA,TEST_HAS_MAIN,TEST_DEVICE_BIAS,DOCSTRING_LINTER,TYPEIGNORE torch/distributed/_token_switch.py test/distributed/test_token_switch.py
```

This change was authored with Claude (AI assistant).
…h.compile

With the contract no longer fixing the order of a flat row's out_topk_idx entries, TokenSwitchMoRI keeps MoRI's forwarded top-k positions: this rank's experts become local ids in place, the others -1 with weight 0. That needs no sort, so the torch.compile'd helper goes away along with its inductor dependency, its ~4 s compile on the first dispatch and per-shape recompiles. Cost at 16384 rows, top-k 8 on MI355X: 43.3 us eager vs 21.3 us if compiled (21.9 us for the previous compiled sort); a few percent of a dispatch at these sizes.

Test Plan:

```
HIP_VISIBLE_DEVICES=0,1 python run_ts_tests.py -v
HIP_VISIBLE_DEVICES= ROCR_VISIBLE_DEVICES= python run_ts_tests.py -v
```

2 GPUs: 75 ran, OK, 48 skipped (TokenSwitchMoRITest 19 and TokenSwitchReferenceTest 8 ran). No GPU: 75 ran, OK, 67 skipped. Interleaved dispatch/dispatch/combine/combine + backward check passes for both layouts (max forward error 0.000).

This change was authored with Claude (AI assistant).
The routing handle copy works around ROCm/mori#715. Once a MoRI release includes ROCm/mori#733, dispatch(..., snapshot=True) makes the copy unnecessary.

Authored with Claude.
@pytorch-bot

pytorch-bot Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

This PR adds `TokenSwitchMoRI`, an intranode MoRI EP v2 backend for
`TokenSwitch` with flat and expert_major layouts, and moves
`test_token_switch.py` into shared mixins. The review recommends Approve: the
blocking findings from the previous review are fixed and verified at HEAD, and
only non-blocking points remain.

Findings (4):

[minor] torch/distributed/_token_switch.py:750
Non-blocking, low confidence: the flat size bound comes from two different
config fields. The public `max_recv_tokens_per_rank` returns `cfg.max_recv`
(:622), and the base docstring says it "sizes full flat dispatch outputs". The
new check here requires `self._recv_cap` rows, which is
`cfg.effective_max_recv`; `_combine`, `_combine_backward` and
`_dispatch_backward` also use `_recv_cap`. The flat branch of
`_alloc_dispatch_outputs` does not take a max against `_recv_cap`. So if
`effective_max_recv > max_recv`, any buffer sized from the documented property
(e.g. `dispatch(..., ts.max_recv_tokens_per_rank)`, the shared
`_contract_out_buffers`) raises an error naming a number the API never exposes.
`test_dispatch_short_out_raises[flat]` builds its regex from
`max_recv_tokens_per_rank`, so it only passes when the two are equal. Fix:
return `_recv_cap` from `max_recv_tokens_per_rank`, or assert at construction
that the fields are equal. Also, as `TokenSwitchNCCL`'s message does, name the
property to size by in the error: `max_recv_tokens_per_rank` for flat,
`max_expert_major_slots_per_rank` for expert_major.

[minor] torch/distributed/_token_switch.py:260
Non-blocking: the expert_major sizing contract is still backend-specific. The
base `TokenSwitch.max_recv_tokens_per_rank` docstring and the shared comment in
`_CombineAutograd.backward` point to
`TokenSwitchMoRI.max_expert_major_slots_per_rank`, which exists only on MoRI, so
backend-agnostic code cannot size an expert_major `out=` buffer without
`getattr`. The narrowed "flat-layout" wording also does not describe NCCL, which
enforces `max_recv_tokens_per_rank` for both layouts. Because of the gap, sizing
happens twice: `_CombineAutograd.backward` allocates
`max(max_recv_tokens_per_rank, expert_shape[0])` rows, then MoRI's
`_combine_backward` allocates a second `new_zeros(need, H)` buffer and copies
back when the combine input was sliced. Fix: add an overridable per-layout bound
on `TokenSwitch` (e.g. `max_recv_slots(layout)`) defaulting to
`max_recv_tokens_per_rank`, and use it in the base docstring,
`_CombineAutograd.backward` and MoRI's `_alloc_dispatch_outputs`; the extra
buffer and MoRI-specific comment in shared code would go away.

[minor] test/distributed/test_token_switch.py:1536
Non-blocking: the new and moved MoRI-only tests are missing `@​
skip_if_lt_x_gpu(2)`: `test_dispatch_short_out_raises`,
`test_combine_backward_zeroes_unused_rows` (:1549),
`test_expert_major_slots_and_combine` (:1632) and
`test_expert_major_interleaved_autograd` (:1680). The `_TokenSwitchFlatTests`
and `_TokenSwitchExpertMajorTests` tests all carry the decorator.
`TokenSwitchMoRITest` takes its world size from the device count, and
`requires_mori` does not check GPU count. On a 1-GPU host, the flat fill routing
in `test_combine_backward_zeroes_unused_rows` uses expert ids `[0, 2]` with
`num_experts = 2`, so id 2 is out of range, and the "ranks 0 and 1" comment also
assumes at least 2 ranks.

[minor] test/distributed/test_token_switch.py:1546
Non-blocking: `test_dispatch_short_out_raises` only shortens `out_tokens`. The
new check loops over all three outputs (`_token_switch.py:751`), but a check on
`out_tokens` alone would also pass this test. NCCL's
`test_dispatch_requires_full_capacity` parametrizes over each output index; do
the same here.

Reviewed commit: 7ea16bd (NOT the current head a89d177)

Review run

🐛 Report a bad review

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/201225

Note: Links to docs will display an error until the docs builds have been completed.

❌ 1 New Failure, 15 Unrelated Failures

As of commit a89d177 with merge base e9fbc79 (image):

🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:

  • Triviality
    • Adds a new backend, TokenSwitchMoRI (~300 lines) in torch/distributed/_token_switch.py, with its own slot-mapping, fencing, and gradient-gather logic
    • New collective behavior (broadcast_object_list, all_reduce fence, all_gather_into_tensor) is not in any trivial class
  • Shared code
    • _CombineAutograd.backward now sizes its gradient buffer as max(ts.max_recv_tokens_per_rank, ctx.expert_shape[0]), which affects every backend
    • test_token_switch.py splits TokenSwitchNCCLTest into mixins and limits the get_num_recv_tokens assert in test_create_routing to NCCL
  • Test coverage
    • TokenSwitchMoRITest skips unless mori with flydsl imports (requires_mori), so CI never runs the new backend
  • Socialization
    • A maintainer comment asks @kawhil-amd to review or delegate, so a human review is already expected

reason: not_trivial
Reviewed commit: 19dd6cd (NOT the current head a89d177)

Inference job

🐛 Report a wrong verdict

NEW FAILURE - The following job has failed:

  • trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable) (gh)
    inductor/test_cudagraph_trees

    AI verdict: AI verdict: probably not related

    The test file failed at import because the unpinned redis&gt;=4.0.0 requirement resolved to redis-8.2.0. Under python -bb, its module-level frozenset((&quot;c&quot;, &quot;C&quot;, b&quot;c&quot;, b&quot;C&quot;)) raises a BytesWarning, which becomes an error. The PR only touches torch/distributed/_token_switch.py and its test, so it can't affect the redis version or the inductor import chain.

    Full reasoning on HUD →

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following jobs failed, but the AI CI Advisor judged the failures not to be evidence against this change:

  • trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable) (gh)
    dynamo/test_fake_distributed

    AI verdict: AI verdict: not related

    The failure is an import-time BytesWarning, turned into an error by python -bb, inside the newly installed third-party package redis 8.2.0. CI pulls that version because .ci/docker/requirements-ci.txt only asks for redis&gt;=4.0.0. The PR's own changes touch only torch/distributed/_token_switch.py and its test, neither of which is on the failing import path.

    Full reasoning on HUD →

  • trunk / win-vs2022-cpu-py3 / test (default, 10, 12, windows.4xlarge.nonephemeral) (gh)
    inductor/test_cutedsl_template

    AI verdict: AI verdict: not related

    The failure is an import-time crash in the newly released third-party redis 8.2.0. CI installs it unpinned (redis&gt;=4.0.0), and under python -bb importing it raises a BytesWarning. The PR only changes torch/distributed/_token_switch.py and its test, and trunk commits that don't include the PR fail with the same redis traceback.

    Full reasoning on HUD →

  • trunk / win-vs2022-cpu-py3 / test (default, 11, 12, windows.4xlarge.nonephemeral) (gh)
    inductor/test_deterministic

    AI verdict: AI verdict: not related

    The test fails because of a new upstream release of the redis package (8.2.0). Importing it raises a BytesWarning, and the tests run with -bb, so every test that imports inductor's remote_cache dies at import. Unrelated trunk commits fail the same way, and the PR only changes the distributed token_switch module and its test.

    Full reasoning on HUD →

  • trunk / win-vs2022-cpu-py3 / test (default, 12, 12, windows.4xlarge.nonephemeral) (gh)
    dynamo/test_list

    AI verdict: AI verdict: not related

    dynamo/test_list fails at import time because a newly released redis 8.2.0 raises a BytesWarning, and the tests run with python -bb, which turns that warning into an error. The baseline installed redis 8.1.0. Trunk commits from the same time fail across many Windows shards with the same error. The suspect only changes distributed token_switch files.

    Full reasoning on HUD →

  • trunk / win-vs2022-cpu-py3 / test (default, 5, 12, windows.4xlarge.nonephemeral) (gh)
    dynamo/test_fx_graph_runnable

    AI verdict: AI verdict: not related

    The test fails at import time: import redis raises BytesWarning: Comparison between bytes and string. The error comes from redis/connection.py:2080, where _CLIENT_FIRST_CHARS = frozenset((&quot;c&quot;, &quot;C&quot;, b&quot;c&quot;, b&quot;C&quot;)) runs while Python is started with -bb, so it looks like a newly released redis package. Trunk main commits without this PR show the same error, and the PR only touches distributed token_switch files.

    Full reasoning on HUD →

  • trunk / win-vs2022-cpu-py3 / test (default, 6, 12, windows.4xlarge.nonephemeral) (gh)
    inductor/test_aot_inductor_arrayref

    AI verdict: AI verdict: not related

    The failure is an import-time crash in the redis package. The Windows test setup installs it from an unpinned requirement (redis&gt;=4.0.0), which resolved to redis 8.2.0. Under Python's -bb flag, a module-level frozenset((&quot;c&quot;,&quot;C&quot;,b&quot;c&quot;,b&quot;C&quot;)) in that version raises BytesWarning as an error. The PR only touches the distributed token_switch files, so it cannot cause this, and unrelated trunk commits fail across Windows shards in the same window.

    Full reasoning on HUD →

  • trunk / win-vs2022-cpu-py3 / test (default, 8, 12, windows.4xlarge.nonephemeral) (gh)
    inductor/test_control_deps

    AI verdict: AI verdict: not related

    The failure is a BytesWarning raised under python -bb when an installed redis package is imported (redis/connection.py line 2080, _CLIENT_FIRST_CHARS = frozenset((&quot;c&quot;,&quot;C&quot;,b&quot;c&quot;,b&quot;C&quot;))). The same signature shows up on concurrent trunk commits. The PR only changes torch/distributed/_token_switch.py and its test, so the cause is an external dependency update.

    Full reasoning on HUD →

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

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

@pytorch-bot pytorch-bot Bot added ciflow/torchtitan Run TorchTitan integration tests module: rocm AMD GPU support for Pytorch labels Oct 16, 2026
@jeffdaily jeffdaily added the release notes: rocm mandatorylabel label Oct 16, 2026
Routing.handle is typed object, so TokenSwitchMoRI now narrows it to its own routing state with an isinstance check, which also reports a Routing from another backend clearly. The optional mori imports get the same missing-import ignore as the NCCL EP import, and the expert_major slot tensors are no longer Optional.

Test Plan:

```
lintrunner --take PYREFLY --all-files
lintrunner --take PYREFLY,FLAKE8,RUFF --paths-cmd 'echo torch/distributed/_token_switch.py'
python test/distributed/test_token_switch.py -v
```

Lint is clean (the unpatched file reproduces CI's 12 pyrefly errors). On 4x MI355X with MoRI main, TokenSwitchMoRITest 19/19 and TokenSwitchReferenceTest 8/8 pass twice.

Authored with Claude.
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.
@jeffdaily
jeffdaily marked this pull request as ready for review October 29, 2026 21:02
@jeffdaily
jeffdaily requested a review from crcrpar October 29, 2026 21:03
@jeffdaily

Copy link
Copy Markdown
Collaborator Author

@kawhil-amd please review or delegate. Thanks.

@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Oct 29, 2026

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

thanks jeff, can u add mori to the docker image too

also has this PR been tested on multinode with pollara NICs?

@jeffdaily
jeffdaily requested review from d4l3k and kwen2501 October 29, 2026 21:29
@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Nov 4, 2026
…mori-sync

# Conflicts:
#	test/distributed/test_token_switch.py
@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Nov 9, 2026
Decorating TokenSwitchMoRITest with instantiate_parametrized_tests raised AttributeError at import: the decorator walks dir(cls), finds the tests the mixins already expanded (they keep parametrize_fn), and tries to delete them from the host class. The two new parametrized tests move into their own decorated mixin, _TokenSwitchMoRIOnlyTests, like the file's other mixins.

The flat case of test_combine_backward_zeroes_unused_rows passed without the library fix, because rows past the receive count had never been written. It now fills the receive buffers of ranks 0 and 1 with a first dispatch, so stale rows exist.

Test Plan: on gfx950 (fleet mi355), 4 ranks and 2 ranks:

```
python test/distributed/test_token_switch.py -v
```

Authored with Claude.
@jeffdaily

Copy link
Copy Markdown
Collaborator Author

My agent came up with this analysis, but I've read and approved it.

The automated review's three blocking findings were real; fixed in 12fb044 and 7ea16bd.

  1. TokenSwitchMoRI._dispatch now raises ValueError when an out= buffer has fewer rows than the layout needs (receive capacity for flat, max_expert_major_slots_per_rank for expert_major), as TokenSwitchNCCL does, and the max_recv_tokens_per_rank docstring says it bounds the flat layout.
  2. Combine backward zeroes the gradient of rows the forward combine ignores (rows past the receive count in flat, unused slots in expert_major).
  3. test_expert_major_slots_and_combine and test_expert_major_interleaved_autograd are now MoRI-only, so the NCCL classes run the same tests as on main. Both did run on MoRI before (the PR body's test count was stale; updated).

New MoRI tests cover 1 and 2 in both layouts, and each fails without the library change. On gfx950 the file passes at 4 ranks and at 2 ranks: TokenSwitchMoRITest 38/38, TokenSwitchReferenceTest 13/13. Also taken from the non-blocking list: close() is idempotent, create_routing checks topk_idx is 2D, and _mori_available catches any exception. The remaining non-blocking items (dtype/hidden_dim validation, current-device dependence, an arch gate for ROCm/mori#794, backward cost) are follow-up work.

@github-actions github-actions Bot 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.

Automated review of 7ea16bd: nothing blocking; ready for human review.

This PR adds TokenSwitchMoRI, an intranode MoRI EP v2 backend for TokenSwitch with flat and expert_major layouts, and moves test_token_switch.py into shared mixins. The review recommends Approve: the blocking findings from the previous review are fixed and verified at HEAD, and only non-blocking points remain.

⚪ 4 non-blocking findings

need = self._recv_cap if flat else self._em_slots

Non-blocking, low confidence: the flat size bound comes from two different config fields. The public max_recv_tokens_per_rank returns cfg.max_recv (:622), and the base docstring says it "sizes full flat dispatch outputs". The new check here requires self._recv_cap rows, which is cfg.effective_max_recv; _combine, _combine_backward and _dispatch_backward also use _recv_cap. The flat branch of _alloc_dispatch_outputs does not take a max against _recv_cap. So if effective_max_recv &gt; max_recv, any buffer sized from the documented property (e.g. dispatch(..., ts.max_recv_tokens_per_rank), the shared _contract_out_buffers) raises an error naming a number the API never exposes. test_dispatch_short_out_raises\[flat\] builds its regex from max_recv_tokens_per_rank, so it only passes when the two are equal. Fix: return _recv_cap from max_recv_tokens_per_rank, or assert at construction that the fields are equal. Also, as TokenSwitchNCCL's message does, name the property to size by in the error: max_recv_tokens_per_rank for flat, max_expert_major_slots_per_rank for expert_major.


def max_recv_tokens_per_rank(self) -> int:

Non-blocking: the expert_major sizing contract is still backend-specific. The base TokenSwitch.max_recv_tokens_per_rank docstring and the shared comment in _CombineAutograd.backward point to TokenSwitchMoRI.max_expert_major_slots_per_rank, which exists only on MoRI, so backend-agnostic code cannot size an expert_major out= buffer without getattr. The narrowed "flat-layout" wording also does not describe NCCL, which enforces max_recv_tokens_per_rank for both layouts. Because of the gap, sizing happens twice: _CombineAutograd.backward allocates max(max_recv_tokens_per_rank, expert_shape\[0\]) rows, then MoRI's _combine_backward allocates a second new_zeros(need, H) buffer and copies back when the combine input was sliced. Fix: add an overridable per-layout bound on TokenSwitch (e.g. max_recv_slots(layout)) defaulting to max_recv_tokens_per_rank, and use it in the base docstring, _CombineAutograd.backward and MoRI's _alloc_dispatch_outputs; the extra buffer and MoRI-specific comment in shared code would go away.


def test_dispatch_short_out_raises(self, layout):

Non-blocking: the new and moved MoRI-only tests are missing @ skip_if_lt_x_gpu(2): test_dispatch_short_out_raises, test_combine_backward_zeroes_unused_rows (:1549), test_expert_major_slots_and_combine (:1632) and test_expert_major_interleaved_autograd (:1680). The _TokenSwitchFlatTests and _TokenSwitchExpertMajorTests tests all carry the decorator. TokenSwitchMoRITest takes its world size from the device count, and requires_mori does not check GPU count. On a 1-GPU host, the flat fill routing in test_combine_backward_zeroes_unused_rows uses expert ids \[0, 2\] with num_experts = 2, so id 2 is out of range, and the "ranks 0 and 1" comment also assumes at least 2 ranks.


ts.dispatch(routing, x, w, out=(out[0][: need - 1], out[1], out[2]))

Non-blocking: test_dispatch_short_out_raises only shortens out_tokens. The new check loops over all three outputs (_token_switch.py:751), but a check on out_tokens alone would also pass this test. NCCL's test_dispatch_requires_full_capacity parametrizes over each output index; do the same here.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

@github-actions
github-actions Bot dismissed their stale review November 18, 2026 16:11

Withdrawn: the automated review of 7ea16bd found nothing blocking.

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 18, 2026
@jeffdaily

Copy link
Copy Markdown
Collaborator Author

@kwen2501 @d4l3k this is ready for review. The conflict with #197194 is resolved, the automated review's blocking findings are fixed, and CI is green at 7ea16bd. Could one of you take a look?

@jeffdaily

Copy link
Copy Markdown
Collaborator Author

@functionstackx On the two questions in your review:

  • MoRI isn't in the CI images yet. Until it is, the MoRI tests skip in CI when mori with flydsl isn't importable, the same way the NCCL EP tests skip without their build. Adding it to the image is separate CI work, not part of this PR.
  • This backend is intranode only, so there is no multinode path to test here. It was validated on a single MI355X node at 2 and 4 ranks.

@kawhil-amd

Copy link
Copy Markdown

@kawhil-amd please review or delegate. Thanks.

LGTM

…mori-sync

Conflict in test/distributed/test_token_switch.py with pytorch#205504: kept this PR's flat-test docstring and applied pytorch#205504's backend_str(cls, device) signature to the TokenSwitchNCCL and TokenSwitchMoRI test classes.

Authored with Claude.
@jeffdaily

Copy link
Copy Markdown
Collaborator Author

@kawhil-amd thanks. I'll do both in a follow-up PR so this one can land: adding MoRI to the CI docker image (that forces an image rebuild, so it's better kept separate), and multinode testing. On Pollara: not yet. So far it's validated only on a single MI355X node at 2 and 4 GPUs. Multinode with Pollara NICs will be part of the follow-up.

@d4l3k d4l3k left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

lgtm. Would be nice to move vendor specific code into their own files

)


@dataclass

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

can we move the mori specific code to a new folder? maybe torch/distributed/_token_switch/mori.py ?

I'll also request the same from the nvidia folks

@jeffdaily
jeffdaily dismissed functionstackx’s stale review November 23, 2026 18:36

Both questions are answered above: MoRI in the CI docker image and multinode testing with Pollara NICs will come in a follow-up PR. The review has no other requested changes, so I'm dismissing it so it doesn't block the merge.

@jeffdaily

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 23, 2026
@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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable). Blocking jobs that the merge waited on for a Dr.CI or AI CI Advisor classification: 1.

Details for Dev Infra team

Raised by workflow job

@jeffdaily

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

pytorchmergebot pushed a commit that referenced this pull request Nov 24, 2026
…06366)

## Linked issue or supporting maintainer

Author has write access. Requested by @d4l3k in #201225.

## BC-breaking?

No

## Summary (human written only)

Follow-up to #201225. Addresses @d4l3k's review comment there by moving the MoRI backend out of the shared module into `torch/distributed/_token_switch/mori.py`, and addresses the four non-blocking findings of the automated review on that PR.

## Agent details (if applicable)

My agent came up with this analysis, but I've read and approved it.

The first commit is a pure move: `torch/distributed/_token_switch.py` becomes the package `torch/distributed/_token_switch/`, with Routing, the autograd functions, the TokenSwitch base and TokenSwitchNCCL unchanged in `__init__.py`, and TokenSwitchMoRI, its routing state and `_import_mori` moved verbatim to `mori.py`. `__init__.py` re-imports them at the bottom so existing imports work. The NCCL backend stays in `__init__.py`; @d4l3k is asking its owners to move it the same way.

The second commit fixes the review findings. `TokenSwitchMoRI.max_recv_tokens_per_rank` now returns the receive capacity its checks enforce (`effective_max_recv`, not `max_recv`). `max_expert_major_slots_per_rank` becomes a TokenSwitch property defaulting to `max_recv_tokens_per_rank` and overridden by MoRI, so shared code no longer names a MoRI attribute and MoRI's combine backward drops its second buffer. The MoRI-only tests get `@skip_if_lt_x_gpu(2)`, and `test_dispatch_short_out_raises` shortens each dispatch output in turn.

Test plan, on 4x MI355X (gfx950) with a ROCm nightly overlaid with this package and MoRI EP v2 + flydsl built from source:

```
python test/distributed/test_token_switch.py -v
lintrunner torch/distributed/_token_switch/__init__.py torch/distributed/_token_switch/mori.py test/distributed/test_token_switch.py
```

TokenSwitchMoRITest 41/41 pass (two runs), TokenSwitchReferenceTest passes, NCCL classes skip on ROCm.

Pull Request resolved: #206366
Approved by: https://github.com/pytorchgreenlight
pytorchmergebot pushed a commit that referenced this pull request Nov 30, 2026
## Linked issue or supporting maintainer

Supported by @jeffdaily

## BC-breaking?

No

## Summary (human written only)

The TokenSwitchMoRI tests from #201225 skip in CI because no CI image has MoRI. This adds MoRI to the ROCm CI images that run on MI300 and MI350. Single-node only; there are no multi-node ROCm CI runners yet.

## Agent details (if applicable)

My agent came up with this analysis, but I've read and approved it.

`install_rocm_mori.sh` builds MoRI from source, pinned in `ci_commit_pins/rocm-mori.txt` to v1.2.5, since the `amd_mori` wheels on PyPI are cp310/cp312 only and the images use Python 3.11. It fetches only the two submodules the build uses and installs only the build requirements missing from `requirements-ci.txt` (MoRI's `requirements-build.txt` would also add a pytest plugin). The build needs no GPU and no torch: MoRI JIT-compiles its kernels on first use, so the background precompile and the optional torch extension are off. No NIC provider (`USE_IONIC`/`USE_BNXT`) is built.

It does not install flydsl: MoRI's flydsl EP backend uses the flydsl 0.3.4.1 that `.ci/pytorch/test.sh` already installs on the ROCm multi-GPU distributed shards, where the MoRI tests run, so other jobs see no new flydsl. The 4-GPU MI350 shard does not install flydsl, so the MoRI tests still skip there.

It runs for `pytorch-linux-noble-rocm-n-py3.11` and `pytorch-linux-noble-rocm-preview-py3.11`. The jammy images run distributed tests only on MI210 and RX7900, which MoRI does not support.

Test plan, on an MI355X host with TheRock ROCm 10.1 wheels: the script's steps in a fresh Python 3.11 venv without torch, as at docker build time, build in about 20 s and `import mori.cco.cco` succeeds. The same build with a ROCm torch nightly and flydsl 0.3.4.1 passes TokenSwitchMoRITest 41/41 at 2 ranks, as on the 2-GPU CI runners, with a cold and a warm kernel cache. This PR's docker-builds CI exercises the image build itself, on ROCm 10.2.

```
HIP_VISIBLE_DEVICES=2,3 python test/distributed/test_token_switch.py -v
```

Pull Request resolved: #206534
Approved by: https://github.com/jeffdaily

Co-authored-by: Jeff Daily <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request GL/superseded GreenLight review is superseded by changes Merged module: rocm AMD GPU support for Pytorch open source ready for review Automated review passed, ready for a final review by a maintainer. release notes: rocm mandatorylabel triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants