Repository navigation
Conversation
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.
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". ✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:
Findings (4): Reviewed commit: 🔗 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 FailuresAs of commit a89d177 with merge base e9fbc79 ( 🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:
reason: NEW FAILURE - The following job has failed:
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:
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. |
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.
|
@kawhil-amd please review or delegate. Thanks. |
…mori-sync # Conflicts: # test/distributed/test_token_switch.py
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.
|
My agent came up with this analysis, but I've read and approved it.
|
There was a problem hiding this comment.
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
pytorch/torch/distributed/_token_switch.py
Line 750 in 7ea16bd
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.
pytorch/torch/distributed/_token_switch.py
Line 260 in 7ea16bd
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.
pytorch/test/distributed/test_token_switch.py
Line 1536 in 7ea16bd
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.
pytorch/test/distributed/test_token_switch.py
Line 1546 in 7ea16bd
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
Withdrawn: the automated review of 7ea16bd found nothing blocking.
|
@functionstackx On the two questions in your review:
|
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.
|
@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
left a comment
There was a problem hiding this comment.
lgtm. Would be nice to move vendor specific code into their own files
| ) | ||
|
|
||
|
|
||
| @dataclass |
There was a problem hiding this comment.
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
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.
|
@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 |
Merge failedReason: 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 teamRaised by workflow job |
|
@pytorchbot merge -i |
…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
## 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]>
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.
TokenSwitchMoRIimplements theTokenSwitchcontract 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_rankbounds the slot count). The firstdispatchon aRoutingcomputes the layout and later dispatches replay it.Backward. Since #201642, backends implement
_combine_backwardand_dispatch_backwardthemselves, and dispatch backward also returnstopk_weightsgradients.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.backwardsizes its gradient buffer asmax(max_recv_tokens_per_rank, rows of the combine input); MoRI's expert_major input can have up tomax_expert_major_slots_per_rankrows. NCCL inputs never exceedmax_recv_tokens_per_rank, so NCCL is unchanged.test_token_switch.py, the shared flat-layout mixin now holds [TokenSwitch] Supporttopk_weightsgradients #201642's weight-gradient tests (they get the backend from the test class instead of constructingTokenSwitchNCCL), so they run for MoRI too. Parametrized tests are expanded on the mixins that define them, which movesTokenSwitchNCCLTest's twoexplicit_rendezvoustests into an NCCL-only mixin.test_create_routingchecks the NCCL EP handle's receive count only forTokenSwitchNCCL, andTokenSwitchMoRI.create_routingraises the sametopk_idxdtypeTypeErroras NCCL.MoRI workarounds, in the code with comments.
snapshot=Truefor this; a TODO marks the copy for removal once a MoRI release includes it.all_reduceonly 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
TokenSwitchMoRIcurrently works on MI355X but not MI300X. ROCm/mori#795 adds a tuned MI300X table.Tests.
TokenSwitchMoRITestruns the flat, expert_major and contract test suites plus MoRI-only tests (38 tests) on 2+ GPUs. It skips whenmoriwith flydsl is not importable, which includes current CI images, the same way the NCCL EP tests skip withoutUSE_NCCL_EP.Test Plan. MI355X, 4 ranks and 2 ranks, torch nightly 2.16.0.dev20261117+rocm10.1 with this PR's
_token_switch.pyin place of the installed module, MoRI main e73ccc539 built from source, flydsl 0.5.0:Each run:
TokenSwitchMoRITest38/38 passed,TokenSwitchReferenceTest13/13 passed, NCCL EP classes skipped (noUSE_NCCL_EPbuild). Lint (default linters andlintrunner --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