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).
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/198963
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 4561b9c with merge base a970aa8 ( BROKEN TRUNK - The following job failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
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).
| its top-k experts live there. ``out_topk_idx`` holds that rank's local expert | ||
| ids in ascending order, packed to the front, padded with -1; | ||
| ``out_topk_weights`` is aligned with it and padded with 0. |
There was a problem hiding this comment.
Regarding out_topk_idx, I am not sure if we'd want to limit its ordering right now.
There are three possibilities:
Expert-ID-sorted, packed to the front: [1, 2, -1, -1]
Weight-sorted, packed to the front: [2, 1, -1, -1]
Slot preserving: [-1, 1, 2, -1]
Different backends may have different implementations today.
There was a problem hiding this comment.
Appreciate the suggestion here to relax the contract. My agent made the following change based on your feedback:
Claude (AI assistant) drafted the change summary:
The latest commit (378c14a) drops the ordering requirement. The contract now only says what a flat row contains (the receiving rank's local expert ids from the token's top-k, -1 in the other entries, the matching weights, and 0 where the id is -1) and leaves the order within a row to the backend. test_contract_flat_dispatch_rows_and_topk compares each row as a set, and the reference backend now keeps entries in the token's top-k positions (your third layout), so a non-packed layout is exercised too.
| class TokenSwitchReferenceTest(_TokenSwitchContractTests, MultiProcContinuousTest): | ||
| """Runs the contract tests on the gloo reference backend (no GPU, no EP library).""" | ||
|
|
||
| world_size = 2 | ||
| contract_dtype = torch.float32 | ||
| _cached_contract_token_switch: _ReferenceTokenSwitch | None = None |
There was a problem hiding this comment.
I see that _ReferenceTokenSwitch allows these contract tests to run in CPU-only CI. Could you clarify what signal we expect from testing the reference implementation itself? Since it is test-only, I’m wondering whether this primarily validates the test harness rather than a production backend, and whether that coverage justifies the additional CI cost (on GPU instances)
There was a problem hiding this comment.
IMHO some CI here is better than no CI, so it's an improvement, especially since it will keep us aligned with the design intent if the contract or the shared base class changes.
Claude (AI assistant) drafted the explanation:
The signal is coverage of the shared code rather than of a production backend. Every other TokenSwitch test is skipped in CI because no job builds with USE_NCCL_EP, so _DispatchAutograd and _CombineAutograd, which every backend inherits and which this PR changes, have no CI coverage today; the reference backend is the only thing exercising them. It also keeps the contract tests honest: they run somewhere in CI, so a broken contract test is caught even though NCCL cannot run them there. The cost is 8 tests, about 4 s in total on 2 CPU processes with gloo and no GPU work, though they run wherever this file runs. If you would still rather not carry it, I can drop TokenSwitchReferenceTest and keep the contract tests for the real backends.
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).
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 4 checks: Lint / quick-checks / lint, Lint / workflow-checks / lint, torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_features_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8), trunk / linux-jammy-aarch64-py3.11 / build Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
Merge failedReason: 7 mandatory check(s) failed. The first few are:
Dig deeper by viewing the failures on hud |
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 1 checks: torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_features_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8) Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
## 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
We're adding a ROCm MoRI backend for TokenSwitch. While working on the implementation, it baked some implicit semantics from the NCCL EP behavior into TokenSwitchNCCL. This PR establishes the API and behavior contract on its own, with new CI coverage, that will pave the way for the new TokenSwitchMoRI implementation.
Claude (AI assistant) drafted the following description of the change: