Skip to content

[symm_mem] Route multicast setup through the PG when PG rendezvous is… - #192623

Closed
ngimel wants to merge 1 commit into
mainfrom
ngimel/symm-mem-pg-multicast-exchange
Closed

ngimel wants to merge 1 commit into
mainfrom
ngimel/symm-mem-pg-multicast-exchange

Conversation

@ngimel

@ngimel ngimel commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

… enabled

use_pg_for_symm_mem_rendezvous moved the RendezvousRequest and block handle exchanges off the TCPStore, since the store gets overloaded during rendezvous at large rank counts, but multicast setup was left behind: the multicast handle exchange, the per-rank success flag, and the barrier after peer handles are imported hit the store. This routes tthem through the process group when the option is set. The multicast handle uses a real broadcast (pg_broadcast) rather than the store path's allgather-and-keep-element-0. The POSIX-fd path is unchanged, exchanging the multicast fd over ipc_channel as before.

The barrier moves too as for large jobs the aggregate request rate from all groups is problematic rather than any single exchange; The success flag is carried as uint8_t because pg_all_gather memcpys into its result vector and std::vector<bool> packs bits, leaving no usable data() to copy into.
test_rendezvous_via_pg_allgather asserted an exact allgather count, so it now derives the expected range from whether the handle got a multicast pointer.

Test Plan:

On 2x GB200 (NVLink fabric handles, multicast supported):

python test/distributed/test_symmetric_memory.py -v

134 tests, 1 pre-existing failure (LoweringTest.test_custom_op_symm_mem_realization, an alloc_id size mismatch that also reproduces without this change and passes in isolation). The NCCL flight recorder around a PG rendezvous confirms nothing is left on the store, and multimem_all_gather_out over the resulting pointer confirms the PG-exchanged multicast handle works:

nccl ops: ['nccl:_all_gather_base',    # RendezvousRequest
           'nccl:_all_gather_base',    # block handles
           'nccl:all_reduce_barrier',  # post-import barrier
           'nccl:broadcast',           # multicast handle
           'nccl:_all_gather_base']    # multicast success flag

This PR was authored with the assistance of an AI coding agent (Claude Code).

… enabled

`use_pg_for_symm_mem_rendezvous` moved the RendezvousRequest and block handle
exchanges off the TCPStore, since the store gets overloaded during rendezvous at
large rank counts, but multicast setup was left behind: the multicast handle
exchange, the per-rank success flag, and the barrier after peer handles are
imported all still hit the store. This routes the three of them through the
process group when the option is set. The multicast handle uses a real
broadcast (`pg_broadcast`, new alongside `pg_all_gather`) rather than the store
path's allgather-and-keep-element-0, which is what the existing
`TODO implement storeExchange.broadcast` worked around; rank 0 is the only
producer, so an allgather would just waste bandwidth. The POSIX-fd path is
unchanged, exchanging the multicast fd over `ipc_channel` as before.

The barrier moves too. There is one TCPStore per job, shared by every rank and
by all the symmetric memory groups rendezvousing against it, so what overloads
it is the aggregate request rate rather than any single exchange; `Store::barrier`
is an add plus a wait from every rank, which is no better in that respect than
the allgathers it sits between. The success flag is carried as `uint8_t` because
`pg_all_gather` memcpys into its result vector and `std::vector<bool>` packs
bits, leaving no usable `data()` to copy into.
`test_rendezvous_via_pg_allgather` asserted an exact allgather count, so it now
derives the expected range from whether the handle got a multicast pointer.

Test Plan:

On 2x GB200 (NVLink fabric handles, multicast supported):

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

134 tests, 1 pre-existing failure (`LoweringTest.test_custom_op_symm_mem_realization`,
an `alloc_id` size mismatch that also reproduces without this change and passes
in isolation). The NCCL flight recorder around a PG rendezvous confirms nothing
is left on the store, and `multimem_all_gather_out` over the resulting pointer
confirms the PG-exchanged multicast handle works:

```
nccl ops: ['nccl:_all_gather_base',    # RendezvousRequest
           'nccl:_all_gather_base',    # block handles
           'nccl:all_reduce_barrier',  # post-import barrier
           'nccl:broadcast',           # multicast handle
           'nccl:_all_gather_base']    # multicast success flag
```

This PR was authored with the assistance of an AI coding agent (Claude Code).
@ngimel
ngimel requested review from d4l3k, fduwjj and kapilsh as code owners August 9, 2026 01:51
@pytorch-bot

pytorch-bot Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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 96987ba with merge base 061ace3 (image):

CRCR (non-blocking) - The following CRCR downstream CI job failed but is non-blocking:

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

@ngimel
ngimel requested review from ezyang, kapilsh and kwen2501 and removed request for d4l3k, fduwjj and kapilsh August 9, 2026 01:51
if (work != nullptr) {
work->wait();
}
}

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.

claude: Tell me why we have to new add new functions for these

@ezyang

ezyang commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

@claude Answer claude questions. Also let's argue why the specific PGOptions in the new functions are correct, as well as the wait/cpu strategy.

@claude

claude Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

Claude finished @ezyang's task in 9m 59s —— View job


Answered both inline questions and laid out the reasoning for the BroadcastOptions/BarrierOptions fields and the asyncOp=false + blocking-.cpu() strategy; two small nits at the end.

Details

1. CUDASymmetricMemoryUtils.hpp:28 — "Is the old comment no longer true now?"

Still true, and you spotted it yourself: it moved. The sentence about staging on device_idx and the H2D/D2H copies being negligible is now on the shared helper at CUDASymmetricMemoryUtils.cpp:36-39, because it applies to all three PG paths (allgather, broadcast, and — for the device-pinning half of it — barrier), not just the allgather. It also gained the actual reason for staging on device, which the header comment never stated: the group may only have a CUDA backend, so a CPU tensor dispatches to a backend that isn't registered.

2. CUDASymmetricMemoryUtils.cpp:121 — "Tell me why we have to add new functions for these"

Three separate things landed here; the justification is different for each.

stage_bytes_to_device is not new functionality — it is the body of the old pg_all_gather_bytes staging block, extracted because pg_broadcast_bytes needs the identical from_blob + .to(cuda) dance. Two callers, one behavior. If you'd rather not have the helper, the alternative is duplicating five lines.

pg_broadcast / pg_broadcast_bytes could be avoided: pg_all_gather + take element 0 works, and that is exactly what the store path does at CUDASymmetricMemory.cu:646 behind // TODO implement storeExchange.broadcast. I'll be honest that the bandwidth argument is thin — a CUmemFabricHandle is 64 bytes, so even at 1k ranks the allgather is 64KB. The real reasons are (a) the sentinel logic immediately below it (memcmp(&recv_handle, &invalidator, ...)) reads much better against a value that was actually broadcast from the producer than against gathered_handles[0], where the other world_size - 1 entries are meaningless padding every reader has to reason about, and (b) it retires a TODO rather than porting it to a second transport. If you want the smaller diff, say so and I'll collapse it to pg_all_gather(...)[0].

pg_barrier wraps ProcessGroup::barrier, which already exists — but three fields have to be set together and each one is load-bearing (argued below). At the single call site that is a ~10-line block of option plumbing that has nothing to do with rendezvous logic, and it sits naturally next to pg_all_gather/pg_broadcast as the third "route this through the PG, pinned to device_idx" primitive. It is used once today, so inlining it at CUDASymmetricMemory.cu:882 is defensible; I kept it out of line because the option-setting is the part that is easy to get subtly wrong and worth commenting once.

3. Why the specific PGOptions are correct

BroadcastOptions.rootRank = root, rootTensor left at 0. NCCL computes root = opts.rootRank + opts.rootTensor (ProcessGroupNCCL.cpp:4721); with one tensor per vector, rootTensor must be 0, which is the default. rootRank is group-local, and the producer side (if (rank == 0) at CUDASymmetricMemory.cu:614) uses the group-local rank from the same PG, so root and producer agree by construction.

BarrierOptions.device and .device_ids are both required — they are consumed by different layers, and neither substitutes for the other.

  • opts.device is read only by ProcessGroup::barrier (ProcessGroup.hpp:884-903) to pick the device of a dummy tensor whose sole purpose is to route the c10d::barrier dispatch to the CUDA key. Without it the fallback chain tests backendType_ == BackendType::NCCL; use_pg is gated on hasBackendForDeviceType(CUDA) (CUDASymmetricMemory.cu:801-802), not on backendType_ == NCCL, so a PG whose default backend registered as CUSTOM reaches this code, falls to the CPU branch, dispatches to barrierCPU, and throws in getBackend(DeviceType::CPU). So device is what makes this correct for any CUDA backend, not just one literally named nccl.
  • opts.device_ids is the only channel that actually reaches NCCL: barrierCUDA discards the tensor entirely (Ops.cpp:622, at::Tensor /* unused */), and ProcessGroupNCCL::barrier picks its device from opts.device_ids[0] or else calls guessDeviceId() (ProcessGroupNCCL.cpp:5336-5342). guessDeviceId falls back to globalRank() % localDeviceCount_ with a "this can cause a hang" warning. We know the exact right answer (block->device_idx), and a wrong guess here is precisely a hang, so passing it is not optional.
  • timeout deliberately left at kUnsetTimeout so rendezvous inherits the PG's configured timeout rather than inventing one.

4. Why the wait/CPU strategy is correct

asyncOp = false everywhere. In NCCL this means the collective is enqueued on the caller's current stream rather than an internal ncclStream, no cross-stream syncStream is issued, no tensor stashing happens, and collective() returns nullptr (ProcessGroupNCCL.cpp:3799-3806, 3840-3850, 3938). That is the right choice because of what happens on both ends of the collective:

  • Input side: stage_bytes_to_device H2D-copies from an unpinned stack object (&local_req, &mc_exported_handle, &success_flag). Unpinned H2D takes the memcpy_and_sync path (Copy.cu:488), which is cudaMemcpyAsync + cudaStreamSynchronize (c10/cuda/CUDAFunctions.h:111-112). So the device buffer is fully populated before the collective is even enqueued, and the caller's stack object is safe to let die. This is not incidental — a pinned/non_blocking staging copy here would be a use-after-scope.
  • Output side: the result is consumed by out_buf.cpu() / bufs[0].cpu(), an unpinned D2H that hits the same memcpy_and_sync. Because asyncOp=false put the collective on the current stream, that copy is already correctly ordered after it, and the cudaStreamSynchronize inside it is what makes the bytes visible to the host. There is no Work to wait on and none is needed — the D2H is the wait, and it is one we have to pay regardless.

With asyncOp=true we would instead get an internal stream, a syncStream in, a work->wait(), and allocator stashing — strictly more synchronization for identical semantics. The .cpu() D2H makes every one of these exchanges a full host-side round trip anyway, which is exactly the semantics the StoreExchange code it replaces had, so nothing upstream needs to change.

pg_barrier must block the CPU, not just order streams. ProcessGroupNCCL::barrier with asyncOp=false does the allreduce on the current stream and then currentStream.synchronize(), returning nullptr (ProcessGroupNCCL.cpp:5372-5378). Host blocking is required, not merely convenient: everything the barrier guards is host-side driver work, not stream work — close(block_handle) right after it, then cuMulticastCreate / cuMemImportFromShareableHandle / cuMulticastBindMem. Stream ordering would not delay any of those by one instruction. And when it returns, every peer has entered the allreduce, i.e. finished importing and mapping peer handles — the same guarantee storeExchange.barrier gave.

if (work != nullptr) work->wait() is not dead defensiveness. NCCL returns nullptr in sync mode, but ProcessGroup::barrier is virtual and use_pg only requires some CUDA backend; a custom CUDA backend may ignore asyncOp and hand back a real Work. Unconditionally dereferencing would segfault on NCCL, unconditionally skipping would silently drop the barrier on such a backend. The null-check is the only form that is correct for both.

Two nits

  • CUDASymmetricMemory.cu:602: auto store = group->getStore(); is now unconditional but only used in the two non-use_pg branches. Harmless (getStore() is cheap), just slightly misleading about what the PG path touches.
  • pg_broadcast's doc says val is "ignored" on non-root ranks, but stage_bytes_to_device still H2D-copies sizeof(T) bytes out of it on every rank. Fine for the one caller (McHandleType mc_exported_handle{} is value-initialized), but "ignored" would read better as "its contents are not used, though it must be initialized".
| branch `ngimel/symm-mem-pg-multicast-exchange`

@ngimel

ngimel commented Aug 9, 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 Aug 9, 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

@kapilsh kapilsh 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! I was wondering if we should just make the ues_pg path default and get rid of storeExchange path unless it still provides some value?

cc @d4l3k

ankitbhrdwj pushed a commit to ankitbhrdwj/pytorch that referenced this pull request Aug 12, 2026
pytorch#192623)

… enabled

`use_pg_for_symm_mem_rendezvous` moved the RendezvousRequest and block handle exchanges off the TCPStore, since the store gets overloaded during rendezvous at large rank counts, but multicast setup was left behind: the multicast handle exchange, the per-rank success flag, and the barrier after peer handles are imported hit the store. This routes tthem through the process group when the option is set. The multicast handle uses a real broadcast (`pg_broadcast`) rather than the store path's allgather-and-keep-element-0. The POSIX-fd path is unchanged, exchanging the multicast fd over `ipc_channel` as before.

The barrier moves too as for large jobs the aggregate request rate from all groups is problematic rather than any single exchange; The success flag is carried as `uint8_t` because `pg_all_gather` memcpys into its result vector and `std::vector<bool>` packs bits, leaving no usable `data()` to copy into.
`test_rendezvous_via_pg_allgather` asserted an exact allgather count, so it now derives the expected range from whether the handle got a multicast pointer.

Test Plan:

On 2x GB200 (NVLink fabric handles, multicast supported):

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

134 tests, 1 pre-existing failure (`LoweringTest.test_custom_op_symm_mem_realization`, an `alloc_id` size mismatch that also reproduces without this change and passes in isolation). The NCCL flight recorder around a PG rendezvous confirms nothing is left on the store, and `multimem_all_gather_out` over the resulting pointer confirms the PG-exchanged multicast handle works:

```
nccl ops: ['nccl:_all_gather_base',    # RendezvousRequest
           'nccl:_all_gather_base',    # block handles
           'nccl:all_reduce_barrier',  # post-import barrier
           'nccl:broadcast',           # multicast handle
           'nccl:_all_gather_base']    # multicast success flag
```

This PR was authored with the assistance of an AI coding agent (Claude Code).
Pull Request resolved: pytorch#192623
Approved by: https://github.com/ezyang
@github-actions
github-actions Bot deleted the ngimel/symm-mem-pg-multicast-exchange branch November 1, 2026 01:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/h100-symm-mem ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: distributed (c10d) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants