Skip to content

Fix NCCL EP handle reuse and zero-copy window offsets. - #197194

Closed
crcrpar wants to merge 4 commits into
mainfrom
crpa/token_switch-fix
Closed

crcrpar wants to merge 4 commits into
mainfrom
crpa/token_switch-fix

Conversation

@crcrpar

@crcrpar crcrpar commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator

Reusing a TokenSwitchNCCL group across tests mixed HT FLAT handles that supplied RECV_EXPERT_COUNTER with ones that did not. That switched NCCL EP from the pec scan kernel to nopec, which then hit a CUDA illegal address on the next create_routing. Always bind a live int32 expert-counter buffer (caller-owned or internally allocated) and keep it on the handle for the metadata kernel's lifetime.

Zero-copy dispatch/combine also computed win_offset as data_ptr minus the data-buffer base, which skips the signal pad at the start of the NCCL window. Use get_window_offset() plus storage_offset.

Authored with Grok 4.6 Extra High.

@pytorch-bot

pytorch-bot Bot commented Sep 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:

The PR binds a live int32 expert counter to every HT FLAT NCCL EP handle and
keeps it alive on the handle, fixes the zero-copy win_offset so it no longer
lands in the signal pad, and adds a _cleanup_worker hook so tests release cached
TokenSwitchNCCL objects before destroy_process_group. Recommendation: Approve.
Both earlier blocking findings and the maintainer's comments are fixed at HEAD,
and every remaining point is non-blocking.

Findings (3):

[minor] torch/csrc/distributed/c10d/symm_mem/nccl_ep.cu:197
Non-blocking: the combined `recv_expert_counter` check tests `dim() == 1`, but
its message reports only dtype, device and numel. In the `torch.zeros((1, 1),
dtype=torch.int32)` case the test exercises, it prints "...1D int32 tensor on
cuda:N with 1 elements; got Int on cuda:N with 1 elements". Every field it shows
matches, so nothing tells the user the shape is wrong. It also raises
`RuntimeError`, while the `topk_idx` dtype check just above (:181) uses
`TORCH_CHECK_TYPE` and the `EpTensor` checks use `TORCH_CHECK_VALUE`. Fix: split
it into `TORCH_CHECK_TYPE` for dtype and `TORCH_CHECK_VALUE` for
dim/numel/device, print `expert_counter.sizes()`, and update
`test_create_routing_invalid_counts`, which expects `RuntimeError` for all five
cases.

[minor] torch/csrc/distributed/c10d/symm_mem/nccl_ep.cu:195
Non-blocking: the new `expert_counter` block (lines 195-219) uses 2-space
indentation. The rest of the function and file uses 4 spaces, and the
CLANGFORMAT lint does not cover `.cu` files.

[minor] torch/csrc/distributed/c10d/symm_mem/nccl_ep.cu:120
Non-blocking: `~NcclEpGroup` and `~NcclEpHandle` (lines 120-136) still call
`ncclEpGroupDestroy` / `ncclEpHandleDestroy` without a shutdown guard. The other
symm_mem allocation destructors check `should_skip_cuda_cleanup(device_idx)`
(`CUDASymmetricMemoryUtils.cpp:23`) before touching CUDA/NCCL during interpreter
finalization, e.g. `NCCLSymmetricMemory.cu:66` and `:366`,
`CUDASymmetricMemory.cu:98`. So a `TokenSwitchNCCL` held in a module-level
global, or one that outlives a failed test (`_cleanup_worker` runs only on a
clean exit), still calls into the library at shutdown. This PR did not introduce
the problem, but the guard is worth adding now that these destructors are being
hardened.

Reviewed commit: 1e3fd98 (NOT the current head 27ee711)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ No Failures

As of commit 27ee711 with merge base a4b3692 (image):
💚 Looks good so far! There are no failures yet. 💚

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

// shutdown). ncclEpGroupDestroy synchronizes and deregisters windows.
try {
ncclEpGroupDestroy(reinterpret_cast<ncclEpGroup_t>(group));
} catch (const std::exception&) {}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Should at least log to info, no?

if (handle) {
try {
ncclEpHandleDestroy(reinterpret_cast<ncclEpHandle_t>(handle));
} catch (const std::exception&){}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Same here

@crcrpar
crcrpar force-pushed the crpa/token_switch-fix branch from a2ada21 to 803c3f9 Compare September 17, 2026 04:10
@ezyang
ezyang requested a review from Skylion007 September 21, 2026 19:04
@ezyang ezyang added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Sep 21, 2026
@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this PR

@claude

claude Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 1m 59s —— View job


The window-offset fix is correct, but I'm asking for changes: the fix doesn't validate the counter tensor the caller passes in, the regression coverage depends on test order, and it only covers the flat layout.

PR review details

PR Review: #197194

Summary

The PR does three things:

  • Every HT FLAT handle now gets an int32 expert-counter buffer, so NCCL EP always runs the pec scan kernel.
  • The zero-copy win_offset now comes from get_window_offset() plus storage_offset.
  • The EP destructors now warn on errors instead of throwing.

The offset math is correct. rendezvous(t) keys on t.storage().data_ptr(), so offset_ is the storage base relative to the data buffer. Adding buffer_offset_ and storage_offset * element_size gives the right window offset, and it matches nccl_all_to_all_nd.cu:202. The problems are all in the expert-counter fix and in the tests.

Code Quality

  • nccl_ep.cu:212-213: the caller's recv_expert_counter is still bound without any checks. The fix assumes the counter is "a live int32 buffer" of num_local_experts elements, and the group now stores num_local_experts. Still, a caller can pass an int64 tensor, a tensor of the wrong length, or one on the wrong device, and it goes straight to the library. The library writes num_local_experts int32 values into it. A tensor that is too short gives an out-of-bounds device write, which is the same class of illegal-address failure this PR is fixing. Add these checks before counter.emplace:
    • TORCH_CHECK(expert_counter.scalar_type() == at::kInt)
    • TORCH_CHECK(expert_counter.numel() == group->num_local_experts)
    • the device matches topk_idx
  • nccl_ep.cu:184-192: the num_experts % world_size check runs after ncclEpCreateGroup has already succeeded. When the check fails, the error is only raised after a collective group was built and registered with NCCL. The destructor then has to tear it down, possibly after a partial setup on other ranks. Validate before calling get_nccl_comm and ncclEpCreateGroup.
  • nccl_ep.cu:122-156: the try/catch (const std::exception&)/catch (...) blocks are dead code. ncclEpGroupDestroy and ncclEpHandleDestroy are C APIs that return ncclResult_t. The comment itself says library-internal failures exit() rather than throw. The only other thing that could throw is TORCH_WARN inside warn_destroy_result, and that sits inside the same try. So each destructor can shrink to one warn_destroy_result(...) call, which removes about 24 lines of boilerplate that is repeated twice. If you do keep a guard, one catch (...) is enough.

Testing

  • No test pins down the regression that motivated this PR. The failing sequence was a FLAT handle created with RECV_EXPERT_COUNTER, then a FLAT handle created without it, on the same cached group. Today that sequence only happens because test_create_routing (with counts, line 110) runs before test_dispatch_symm_mem_tokens (no counts, line 494). That coverage depends on test order and the shared _cached_token_switch. Reordering, filtering with -k, or dropping the cache would silently lose it. Add one test that calls create_routing(topk_idx, counts, layout="flat"), then create_routing(topk_idx, layout="flat"), then dispatches.
  • Nothing checks that the zero-copy path is actually taken. _init now forces the NCCL backend. If make_ep_tensor falls back to EpTensor(t) (because dynamic_cast<NCCLSymmetricMemory*> fails), the *_symm_mem_tokens tests still pass through the device-pointer copy, so the offset fix is untested in that case. At minimum, assert symm_mem.get_backend(self.device) == "NCCL" after set_backend.
  • Test data never exercises the storage_offset term. Every symm_mem tensor in the tests starts at storage offset 0. A dispatch or combine on a view such as symm_mem.empty(2*N, ...)[N:] would cover the storage_offset() * element_size() part of the new formula.

Needs discussion (low confidence)

  • nccl_ep.cu:214: only Flat handles get an internally allocated counter. Handles for expert_major and rank_major created without counts (test lines 385, 425, 600) still go through the nopec path on the same reused group. The PR description says "mixing pec then nopec on a reused EP group" triggers the illegal address. If that state is per group and not per layout, the same crash could still happen for expert_major after flat. Please confirm whether the problem is specific to FLAT, and put the answer in the comment at line 207.

Recommendation

Request Changes

The main blockers are the missing validation of the caller's counter (line 212) and a regression test that doesn't depend on test order. The window-offset change can go in as is.

@crcrpar

crcrpar commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator Author

@claude could you review this again?

@claude

claude Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Claude encountered an error after 21s —— View job


I'll analyze this and get back to you.

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased crpa/token_switch-fix onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout crpa/token_switch-fix && git pull --rebase)

@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this PR

@claude

claude Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 1m 22s —— View job


The follow-up commits fix every blocker from my last review, and only minor items are left, so I recommend approving.

PR review details

What changed since the last review

Earlier finding Status
Caller-supplied recv_expert_counter wasn't checked ✅ Now checks 1D, int32, matching device and numel == num_local_experts (nccl_ep.cu:193-208)
num_experts % world_size was checked after ncclEpCreateGroup ✅ Now checked before get_nccl_comm
try/catch in destructors did nothing ✅ Replaced by warn_destroy_result with TORCH_WARN (also answers @Skylion007's "should at least log" comment)
Regression coverage depended on test order ✅ test_create_routing_with_then_without_counts
Nothing confirmed the zero-copy path ran ✅ _init sets the NCCL backend and asserts it
The storage_offset term wasn't tested ✅ test_dispatch_symm_mem_tokens_storage_offset, including a check that the bytes before the view stay untouched
Was the fix FLAT-only? ✅ The comment at nccl_ep.cu:188-190 now explains: expert-major uses the library's own counter, and rank-major is LL-only

Correctness

  • Window offset: correct. rendezvous(t) keys on t.storage().data_ptr() (SymmetricMemory.cpp:296). get_window_offset() returns buffer_offset_ + offset_ (NCCLSymmetricMemory.cu:473-477). Adding storage_offset * element_size gives the tensor's byte offset in the window, including the signal pad.
  • Counter lifetime: correct. NcclEpHandle now owns recv_expert_counter, so the buffer handed to the library stays alive as long as the handle.
  • I didn't add a contiguity check for the counter: EpTensor's constructor already requires is_contiguous().

Minor / nits (none blocking)

  1. nccl_ep.cu:198: the numel == check is stricter than it needs to be, and the shape isn't documented.
    • The library writes exactly num_local_experts int32 values, so numel() >= num_local_experts would be enough to prevent out-of-bounds writes.
    • The old tests passed a buffer of length world_size. With ==, any caller doing the same now gets an error.
    • _token_switch is private, so == is acceptable. Either way, please state the expected shape ((num_experts // world_size,), int32, same device as topk_idx) in the create_routing docstring in torch/distributed/_token_switch.py.
  2. nccl_ep.cu:188-190: this works around a library bug. The illegal address in nopec after pec on a reused group is an NCCL EP problem. If there's an upstream issue, link it in the comment so the workaround can be removed once it's fixed.
  3. nccl_ep.cu:214: there's a small per-call cost. at::zeros adds one allocation and one memset launch to every FLAT create_routing without counts. That's fine for routing setup; flagging it only in case create_routing sits on a hot path.
  4. test_token_switch.py:171: the test assumes one local expert. torch.zeros(2, ...) is only invalid because the test uses num_experts == world_size. Deriving the bad length from that, e.g. num_local_experts + 1, would keep the test correct if the config changes.
  5. Combine has no storage-offset test. The new view test covers dispatch only, and test_combine_symm_mem_tokens (line 631) still uses offset-0 tensors. Combine goes through the same make_ep_tensor path, so this is low risk.

Recommendation

Approve. I read the code but didn't run the tests here (they need multiple H100s). Dr. CI shows no failures on 4cd88f65.

@pytorch-bot pytorch-bot Bot added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 30, 2026
github-actions[bot]

This comment was marked as outdated.

@crcrpar
crcrpar force-pushed the crpa/token_switch-fix branch from 4cd88f6 to 1e3fd98 Compare November 5, 2026 07:41
@pytorch-bot pytorch-bot Bot added the ciflow/torchtitan Run TorchTitan integration tests label Nov 5, 2026

@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 1e3fd98: nothing blocking; ready for human review.

The PR binds a live int32 expert counter to every HT FLAT NCCL EP handle and keeps it alive on the handle, fixes the zero-copy win_offset so it no longer lands in the signal pad, and adds a _cleanup_worker hook so tests release cached TokenSwitchNCCL objects before destroy_process_group. Recommendation: Approve. Both earlier blocking findings and the maintainer's comments are fixed at HEAD, and every remaining point is non-blocking.

⚪ 3 non-blocking findings

Non-blocking: the combined recv_expert_counter check tests dim() == 1, but its message reports only dtype, device and numel. In the torch.zeros((1, 1), dtype=torch.int32) case the test exercises, it prints "...1D int32 tensor on cuda:N with 1 elements; got Int on cuda:N with 1 elements". Every field it shows matches, so nothing tells the user the shape is wrong. It also raises RuntimeError, while the topk_idx dtype check just above (:181) uses TORCH_CHECK_TYPE and the EpTensor checks use TORCH_CHECK_VALUE. Fix: split it into TORCH_CHECK_TYPE for dtype and TORCH_CHECK_VALUE for dim/numel/device, print expert_counter.sizes(), and update test_create_routing_invalid_counts, which expects RuntimeError for all five cases.


if (recv_expert_counter.has_value()) {

Non-blocking: the new expert_counter block (lines 195-219) uses 2-space indentation. The rest of the function and file uses 4 spaces, and the CLANGFORMAT lint does not cover .cu files.


NcclEpGroup::~NcclEpGroup() {

Non-blocking: ~NcclEpGroup and ~NcclEpHandle (lines 120-136) still call ncclEpGroupDestroy / ncclEpHandleDestroy without a shutdown guard. The other symm_mem allocation destructors check should_skip_cuda_cleanup(device_idx) (CUDASymmetricMemoryUtils.cpp:23) before touching CUDA/NCCL during interpreter finalization, e.g. NCCLSymmetricMemory.cu:66 and :366, CUDASymmetricMemory.cu:98. So a TokenSwitchNCCL held in a module-level global, or one that outlives a failed test (_cleanup_worker runs only on a clean exit), still calls into the library at shutdown. This PR did not introduce the problem, but the guard is worth adding now that these destructors are being hardened.

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 5, 2026 07:52

Withdrawn: the automated review of 1e3fd98 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 5, 2026

@kwen2501 kwen2501 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Looks good. The expert-counter validation and handle ownership of the counter, zero-copy window offset calculation, and clean-exit teardown ordering look correct. Reviewed at 1e3fd98; multi-GPU tests were not run as part of this review.

@crcrpar

crcrpar commented Nov 6, 2026

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 6, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: Approvers from one of the following sets are needed:

  • Metamates (aditvenk, andrewor14, angelayi, anshul-si, aorenste, ...)
  • Greenlight Review Bot (pytorchgreenlight)
  • Core Reviewers (mruberry, lezcano, Skylion007, ngimel, peterbell10, ...)
  • Core Maintainers (soumith, gchanan, ezyang, malfet, albanD, ...)
Details for Dev Infra team

Raised by workflow job

Failing merge rule: Core Maintainers

crcrpar and others added 4 commits November 9, 2026 10:14
Reusing a `TokenSwitchNCCL` group across tests mixed HT FLAT handles
that supplied `RECV_EXPERT_COUNTER` with ones that did not. That
switched NCCL EP from the pec scan kernel to nopec, which then hit a
CUDA illegal address on the next `create_routing`. Always bind a live
`int32` expert-counter buffer (caller-owned or internally allocated) and
keep it on the handle for the metadata kernel's lifetime. Store
`num_local_experts` on the group so a missing caller counter can
allocate that buffer.

Zero-copy dispatch/combine also computed `win_offset` as data_ptr minus
the data-buffer base, which skips the signal pad at the start of the
NCCL window. Use `get_window_offset()` plus storage_offset. Tests call
`symm_mem.set_backend("NCCL")` so that path is actually exercised.

Test Plan:
```
python test/distributed/test_token_switch.py -v
```
28 tests OK on nccl and nccl2.

Authored with Grok 4.6 Extra High.
Signed-off-by: Masaki Kozuki <[email protected]>
Authored with Grok 4.6 Extra High.
Signed-off-by: Masaki Kozuki <[email protected]>
NCCL EP writes per-expert counts into the caller's tensor, but the
wrapper accepted tensors with an invalid shape, dtype, size, or device.
Validate the counter before binding it so a short buffer cannot cause an
out-of-bounds device write. Check expert divisibility before creating
the collective group and simplify deconstructor error handling.

Authored with GPT-6 Sol Medium
Signed-off-by: Masaki Kozuki <[email protected]>
…h in tests

The review bot flagged two things on this PR. First,
TokenSwitch.create_routing documented per_expert_token_counts as
"length >= local experts", but nccl_ep_create_handle now requires exactly
num_experts // world_size elements, so a caller following the docstring would
hit a RuntimeError. The docstring now states the exact length, matching the
check and test_create_routing_invalid_counts.

Second, the warn-in-destructor path in nccl_ep.cu was justified by cached
TokenSwitch objects outliving destroy_process_group, which is a test
lifetime bug rather than something the C++ should paper over. The cached
switches live in class attributes that MultiProcContinuousTest never clears
before destroying the process group. Add a no-op _cleanup_worker() hook that
runs in each worker just before destroy_process_group, and override it in
TokenSwitchNCCLTest and TokenSwitchRoutingDtypeTest to drop the cached
switches. The destructors keep warning instead of throwing as a defensive
fallback, and the comment no longer claims to handle a torn-down comm.

An alternative was to clear the caches in a final test method, but that
depends on test ordering, so a worker-level hook is more robust. The hook is
in the shared common_distributed.py, a small addition that other
MultiProcContinuousTest users can ignore.

Test Plan:

```
ninja -C build _nccl_ep
python test/distributed/test_token_switch.py -v
```

Ran on a 4x GB200 node: 93 tests, OK, none skipped, including the new
counter-validation, handle-reuse and storage-offset tests.

ruff check and ruff format --check pass on the changed Python files.

This change was authored with an AI assistant (Claude Code).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@crcrpar
crcrpar force-pushed the crpa/token_switch-fix branch from 1e3fd98 to 27ee711 Compare November 9, 2026 01:17
@eqy

eqy commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator

@claude is this ready to land?

@claude

claude Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Claude finished @eqy's task in 39s —— View job


Yes, it looks ready to land: it has three approvals (kwen2501, fduwjj, kapilsh), CI at HEAD 27ee711 is green, and nothing blocking is open. Someone should retry @pytorchbot merge.

Details

Status

  • Approvals: kwen2501 and fduwjj approved on 11-06, and kapilsh approved on 11-10. kapilsh's approval came after the 11-09 rebase onto a4b3692.
  • CI: all 9 workflows on the current head passed, including trunk, pull, Lint, BC Lint, TSan, torchtitan-test and the H100 symm-mem job. Dr. CI shows no failures.
  • Review findings: every blocking item from earlier reviews has been addressed:
    • the caller's counter is now validated;
    • the num_experts % world_size check happens before the group is created;
    • the regression test no longer depends on test order;
    • the zero-copy path is asserted and storage_offset is covered;
    • the docstring now says the counter needs exactly num_experts // world_size elements;
    • a _cleanup_worker hook drops the cached TokenSwitch before destroy_process_group.

Why the 11-06 merge attempt failed

The bot rejected the merge on 11-06, saying it needed approvers from the Metamates, Core Reviewers or Core Maintainers sets, and listed Core Maintainers as the failing rule. I can't see from here why kwen2501 and fduwjj didn't satisfy it. The PR now has a third approval and a fresh green run, so retry @pytorchbot merge. If it fails again, the error will name the rule that is blocking. One possible cause: the PR touches the shared torch/testing/_internal/common_distributed.py (adds the _cleanup_worker hook), which may fall under a different approver rule.

Non-blocking leftovers (fine as follow-ups)

  • nccl_ep.cu:191-217:
    • the combined recv_expert_counter check tests dim() == 1 but its error message never prints the shape, and it uses plain TORCH_CHECK where the nearby checks use the _TYPE/_VALUE variants;
    • the new block is indented with 2 spaces while the rest of the file uses 4.
  • nccl_ep.cu:120-136: the destructors still don't check should_skip_cuda_cleanup the way other symm_mem destructors do. This was already the case before this PR.

I only read the code; I didn't run the multi-GPU tests. The author's test plan reports 93 tests passing on 4x GB200.

@crcrpar

crcrpar commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/h100-symm-mem ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged open source ready for review Automated review passed, ready for a final review by a maintainer. release notes: distributed (c10d) release notes category 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.

9 participants