Skip to content

Enable NCCLSymmetricMemory (RCCL) symmetric-memory support on ROCm - #192524

Closed
abhilashKaturu wants to merge 41 commits into
pytorch:mainfrom
ROCm:abhilash-rccl-symmem-rocm-enable
Closed

abhilashKaturu wants to merge 41 commits into
pytorch:mainfrom
ROCm:abhilash-rccl-symmem-rocm-enable

Conversation

@abhilashKaturu

@abhilashKaturu abhilashKaturu commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR enables NCCLSymmetricMemory on ROCm. ROCm cannot reuse the CUDA path: HIP graph capture, RCCL window registration, and the device reduce APIs do not behave the same way. The changes below are the smallest set that make allocation, rendezvous, capture, and the three device ops work on the tested RCCL stack.

Almost all of the C++ under torch/csrc is USE_ROCM-guarded. Five changes are not, and do change CUDA behavior; they are listed under "Changes that affect the default path". NCCL_HAS_SYMMEM_DEVICE_SUPPORT on CUDA stays at NCCL 2.28.0.

Problem

NCCLSymmetricMemory was CUDA-only. Opening the same gates on ROCm is not enough:

  • RCCL ncclMemAlloc without CUMEM falls back to hipMalloc. Capture rejects that.
  • A synchronous hipMemset or hipMemcpy during Global capture returns HIP 906 and kills the capture (901).
  • An async memset recorded on the capturing stream becomes a graph node and can wipe a peer signal pad on every replay.
  • RCCL 2.30.4 window registration fails during capture. 2.30.7 succeeds.
  • A fused multi-destination reduce-scatter launch faults with HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION on gfx942 and gfx950.
  • A retained handle after process-group destroy launched a barrier kernel through a dead communicator and hit HSA_STATUS_ERROR_MEMORY_FAULT.

Solution

On ROCm, a per-device NCCLDevCommManager snapshots RCCL device-API support when a communicator registers. Without that support a handle is host-only. Fresh windows use CUMEM plus an async zero on a non-captured setup stream wherever RCCL supports capture-time allocation. Peer tables upload on the same stream, under a Relaxed capture-mode guard, so rendezvous returns with initialized device pointers. Device comms are created once per op and cached. Reduce-scatter launches one kernel per destination. ProcessGroupNCCL retires its registry entry through a hook that NCCLComm runs at the start of abort() and destroy(), and every ROCm accessor that can reach a communicator checks that its registration is still live. A handle whose communicator is gone raises; it is not rebuilt against a successor.

On ROCm the feature needs RCCL >= 2.30.4 and an nccl_device.h that compiles in a host translation unit, which CMake probes. Capture-time allocation additionally needs RCCL >= 2.30.7. There is no GPU- or ROCm-version-specific floor.

Design choices

nccl_device.h presence is not enough. A host C++ TU cannot compile every RCCL that ships the header, so cmake/External/rccl.cmake try-compiles the installed header and defines RCCL_DEVICE_HEADER_HOST_COMPATIBLE when it passes. On ROCm, NCCL_HAS_SYMMEM_DEVICE_SUPPORT requires that probe and RCCL >= 2.30.4. The condition is written !defined(USE_ROCM) || (...), so CUDA's threshold stays at NCCL 2.28.0. hipcc needs CUDA's extended-lambda macro and a local __half operator+ because PyTorch defines __HIP_NO_HALF_OPERATORS__.

Device API support is a runtime snapshot; without it the handle is host-only. RCCL reports deviceApiSupport=0 unless both NCCL_CUMEM_ENABLE and NCCL_WIN_ENABLE are set before communicator init. register_comm records ncclCommQueryProperties against that communicator identity, so setting the env vars later does not upgrade an existing comm. Rendezvous on such a comm still registers the window, so host-side collectives on the buffer work; the peer-pointer accessors and barrier() raise with a message naming the missing condition. test_host_only_rendezvous_without_device_api_support covers this.

Capability, not capture state, selects the allocation path. The CUMEM + setup-stream path is correct outside capture too, so keying on capture_allocation_supported() gives one path on a supported stack. HIP only reports capture state for the current stream, so this PR adds no process-wide capture query: the CUMEM path runs under the Relaxed guard, performs no capture-illegal host wait, and writes the pad and peer tables as host-side setup rather than graph nodes. The current-stream TORCH_CHECK on the other path is a diagnostic for stacks that cannot allocate under capture, not the safety mechanism.

TORCH_NCCL_SYMM_MEM_DISABLE_CAPTURE_ALLOC=1 keeps the plain path. It is read inside capture_allocation_supported(), so it selects ncclMemAlloc plus synchronous memset for allocation and a synchronous cudaMemcpy for the rendezvous peer-table upload. That is the allocate-then-capture fallback for stacks that cannot allocate under capture, and it is how the two allocation paths were compared: both arms produce the same peer digest, which is what justifies keying on capability rather than on capture state.

One shared setup stream per device. Signal-pad zero and peer-table H2D need a stream that is not the capturing stream. It is created when the first comm with capture-allocation support registers, so every alloc and rendezvous reuses it rather than creating one per call. It is created regardless of the kill switch, and its use is serialized.

A host-side wait is illegal under Global capture, even on a non-captured stream. Moving the H2D copy off the capturing stream is not enough. cudaStreamSynchronize on the setup stream still returns HIP 900. alloc() therefore wraps its whole ncclMemAlloc / async-zero / synchronize sequence in CUDAStreamCaptureModeGuard{Relaxed}, and rendezvous does the same for the peer-table upload. The peer tables and signal pad are immutable for the object's lifetime, so they are initialized on the setup stream and are not recorded as graph nodes. hipStreamWaitEvent would also work, but it would only guarantee the tables are ready before later device work, not when rendezvous returns on the host.

Fresh capture allocation requires RCCL >= 2.30.7. Direct window registration during Global capture succeeds on 2.30.7 (mode stays Global, capture stays active). 2.30.4 fails in worker-side synchronization. The check is made at compile time and against ncclGetVersion() at registration. Older RCCL still works if the tensor is allocated and rendezvoused before capture.

ncclDevCommCreate is a direct call, then cached per op. First create during Global capture succeeds on 2.30.7, keeps Global mode and an active capture, and the captured graph replays. All-to-all and reduce-scatter each create a devcomm once and cache it under their own op key. There is no extra ROCm-only capture guard around create. The symmetric-memory barrier uses the signal pads directly and needs no devcomm.

RCCL leaks Relaxed mode on window deregister and device-comm destroy. Direct ncclCommWindowDeregister and ncclDevCommDestroy change the caller's capture thread mode from Global to Relaxed. Destroy during an active capture also invalidates the capture. Both calls sit in a balanced CUDAStreamCaptureModeGuard{Relaxed} so the caller gets its mode back.

The manager destructor keeps cudaDeviceSynchronize. HIP returns 900 for that wait under an active capture in both Global and Relaxed thread mode, so a Relaxed guard would not make teardown capture-safe. This enablement does not change destructor synchronization.

Reduce-scatter is serialized per destination, not fused. The fused launch faults on gfx942 and gfx950 with RCCL 2.30.7. Row tiles that write one destination are safe. ROCm drives the existing shared kernel with a one-slot ReduceScatterOffsetsInfo rather than getting a kernel of its own. With n_owned == 1 the barrier index collapses to blockIdx.x, so the per-destination launches are expected to agree bit for bit with a fused launch of the same shape.

dst_block_size stays a uint16_t. The shared kernel layout is the CUDA struct and sizes above 65535 do not fit that field. This PR keeps the layout and validates the size on the host instead; see "Changes that affect the default path" for why that check is not ROCm-scoped.

On ROCm, retirement runs inside NCCLComm, before RCCL sees the abort or destroy. initNCCLComm registers the collective comm and installs a pre-invalidate hook on the NCCLComm as one step under the comm's own mutex, which abort() and destroy() also take, so an invalidation cannot land in between. The hook captures the group uid, the ncclComm_t (because abort() nulls the handle), and the registration generation, and NCCLComm::destroy() / abort() run it first (NCCLUtils.cpp:362, :379). Retirement only erases registry entries and makes no RCCL call, so it is safe on every abort path, including watchdog and wait-timeout aborts. The generation is what tells our entry apart from a successor that is handed the same ncclComm_t address. Because the hook covers every teardown path, the ~ProcessGroupNCCL unregister loop is compiled out on ROCm (ProcessGroupNCCL.cpp:1614); on CUDA that loop is unchanged. nccl2 already retired before destroy and abort; it now also retires on a failed split or shrink (see below).

Retirement does not call ncclDevCommDestroy. It is collective (it deregisters the devcomm's resource window), so it cannot run on the unilateral abort path. The registry drops the entries, and comm teardown reclaims those windows: RCCL's commFree always runs ncclDevrFinalize, and NCCL's runs it for every comm with symmetric support, which ncclDevCommCreate requires. GIN contexts are not reclaimed that way, so this holds for single-node symmetric memory.

Stale handles are rejected, not rebuilt. Once a handle's registration is retired, every checked accessor raises ... is stale because its RCCL communicator was destroyed or replaced. Free the tensor and allocate a new one after initializing the successor process group. Re-rendezvous is included: a cached handle (NCCLSymmetricMemory.cu:876) and another pointer into the same allocation (:905) both check liveness before reuse. An earlier revision rebuilt such a handle against a same-name successor. That rebuild starts a collective window registration based on rank-local registry state, and its test hung once in 13 runs in destroy_process_group on MI355X with RCCL 2.31.2. It did not reproduce in 264 runs on MI300X with RCCL 2.31.2 or in 6 CI runs, no stack was captured, and it was not root-caused, so this PR drops the rebuild. test_stale_handle_rejected_across_same_name_restart covers the replacement contract: the old handle raises from barrier, put_signal, wait_signal, and re-rendezvous, while a freshly allocated tensor on the successor works.

Liveness checks are ROCm-only. The use-after-destroy hazard is not ROCm-specific, but the check relies on every producer retiring before it invalidates its comm, which stock ProcessGroupNCCL does only on ROCm, so CUDA accessors are unchanged. Checked: the four peer-pointer accessors and barrier() (which also require device API support), put_signal, wait_signal, get_window, has_multicast_support, get_group_name, and the two CFT handle accessors. get_group_name() checks because resolving a communicator from a name is the hazard. get_window_offset(), get_offset(), get_buffer_size(), get_rank(), get_world_size(), and get_device() do not: they return immutable scalars, and callers that use the offset go through get_window(). The window destructor deregisters only if its exact registration, pointer and generation, is still live. These checks cover use after teardown, not use that races a concurrent abort.

Host-side CFT is not enabled on ROCm. NCCL_HAS_HOST_CFT gains !defined(USE_ROCM) because host-side CFT has not been validated on RCCL. SymmMemCftHandleTest skips on ROCm.

Allocation size is rounded to NCCL_WIN_REQUIRED_ALIGNMENT on ROCm only. An unrounded backing allocation produced wrong put_wait_signal data and a teardown timeout. Registration uses the same rounded extent. CUDA sizes are not changed.

Changes that affect the default path

Five changes here are not under USE_ROCM and do change CUDA behavior. Listing them explicitly because the rest of the PR is ROCm-scoped and a reviewer should not have to grep for the exceptions.

  • initNCCLComm publishes only the collective comm. Every comm initNCCLComm created was registered under getGroupUid(), last write wins, so a lazily created 2-rank send/recv comm could replace the group's collective comm, and symmetric memory on that group would then resolve to a comm that does not span the group. Registration now runs only if (!singleP2POp) (ProcessGroupNCCL.cpp:3326). On CUDA, a group that has only ever created a P2P comm therefore has no registry entry, and rendezvous on it raises get_comm's "host communicator ... not found" error instead of using the P2P comm. No dedicated test.

  • Reduce-scatter silently truncated blocks larger than 65535. ReduceScatterOffsetsInfo::dst_block_size is a uint16_t and the host wrote static_cast<uint16_t>(owned_sizes[j]) with no bound; the only prior check was on block count. A taller shard reduced owned_sizes[j] % 65536 rows and returned wrong data with no error. Now a host-side TORCH_CHECK (nccl_reduce_scatter_offset.cu:345), placed before the ROCm/CUDA launch split so both paths get it. The inputs this rejects are exactly the ones that were already producing wrong results. test_reduce_scatter_offset_rejects_oversized_block asserts both that the first oversized block raises and that the largest block that still fits reduces correctly.

  • Cached device comms survived a communicator replacement. register_comm is last-write-wins, but a cached ncclDevComm is built from one specific host comm. When a successor process group registered a different comm under the same uid, get_devcomm kept handing kernels devcomms naming a comm the registry no longer owned, and ~NCCLDevCommManager would pass the successor's comm to ncclDevCommDestroy alongside a predecessor-built devcomm. register_comm now evicts that group's devcomms on replacement (nccl_devcomm_manager.hpp:261); re-publishing the same pointer is not a replacement. Identity is the pointer, so on CUDA, where ~ProcessGroupNCCL keeps the entry of a destroyed comm, a successor at a recycled ncclComm_t address still skips the eviction; nccl2 and ROCm retire before invalidating, which rules that out. Covered by NCCLDevCommManagerTest.ReplacementRegistrationEvictsDevComms, which also asserts that a bystander group's devcomm survives and that a predecessor's late retirement cannot unpublish its successor.

  • The one-sided ops dereferenced an unchecked dynamic_cast. nccl_put_signal and nccl_wait_signal are schema'd over the SymmetricMemory base class, so a handle from another backend is a legal argument, and both used the cast result without testing it. Now TORCH_CHECKed (nccl_extension.cu:375, :410), matching the sibling ops. Covered by NCCLOneSidedOpHandleTypeTest::test_one_sided_ops_reject_foreign_handle.

  • nccl2 left the parent registered when split or shrink failed. On failure both cleared nccl_comm_ without retiring, leaving the registry pointing at a parent the failed call may have aborted. Both now call retireComm() first (nccl2/ProcessGroupNCCL.cpp:399, nccl2/ShrinkNCCL.cpp:100). No test: it needs a split or shrink that fails.

Also visible on CUDA, but not behavioral:

  • The two ops copy the cached ncclDevComm instead of binding a reference into the registry (nccl_all_to_all_nd.cu:183, nccl_reduce_scatter_offset.cu:221), since eviction can now erase the entry. get_devcomm's signature is unchanged; its comment now says the reference dangles after replacement.
  • NCCLComm gains preInvalidateHook_ on every platform, so the class layout does not depend on USE_ROCM. It is only set and run on ROCm.
  • nccl_dev_cap.hpp only adds ROCm terms, so the CUDA truth values of NCCL_HAS_SYMMEM_DEVICE_SUPPORT and NCCL_HAS_HOST_CFT are unchanged. The NCCL_HAS_DEVCOMM / NCCL_HAS_ONE_SIDED_API hunk merges two byte-identical #if conditions.
  • #include <vector_types.h> is dropped from NCCLSymmetricMemory.cu; nothing there uses a CUDA vector type, and the header does not exist on ROCm.
  • _is_nccl_symmem_available() is new and only used by the test suite to pick a skip predicate. The rest of the init.cpp hunk is clang-format reflow of existing lambdas.

Tests

test/distributed/test_nccl.py no longer carries a blanket TEST_WITH_ROCM skip on the symmetric-memory classes. It is replaced by narrower gates, all no-ops on CUDA:

  • skip_if_rccl_symmem_not_compiled: the build-time result, exposed to Python as _is_nccl_symmem_available().
  • skip_if_rccl_lt_2_30_4: the RCCL host device-API floor.
  • skip_if_rccl_lt_2_31_2: test_put_wait_signal and test_nccl_symmem_signal_rank_out_of_bounds, which are validated only on RCCL 2.31.2.
  • Tests that allocate during capture skip on RCCL < 2.30.7.

New coverage:

  • NCCLSymmetricMemoryLifecycleTest (ROCm-only, 8 items, each on nccl and nccl-legacy; only nccl-legacy goes through stock ProcessGroupNCCL): a retained handle is rejected after abort, after a wait-timeout abort, and after a watchdog abort, and across a same-name restart as described above.
  • NCCLSymmetricMemoryCapabilityGateTest (ROCm-only, 3 items): the host-only path without device API support, capture allocation rejected when CUMEM/WIN are enabled after init, and the kill switch.
  • NCCLSymmetricMemorySubgroupTest (ROCm-only, 1 item): subgroup-first rendezvous in a fresh process.
  • NCCLSymmetricMemoryRestartTest (not ROCm-gated, 2 items): allocation after a default-PG restart, and a successor PG surviving its predecessor's teardown.
  • NCCLOneSidedOpHandleTypeTest (not ROCm-gated, 1 item): one-sided ops reject a non-NCCL handle.
  • NCCLSymmetricMemoryTest::test_reduce_scatter_offset_rejects_oversized_block (not ROCm-gated), plus the ROCm-only capture cases test_nccl_symmem_capture_allocation_kill_switch and NCCLSymmetricMemoryNccl2Test::test_nccl_symmem_fresh_cuda_graph.
  • NCCLDevCommManagerTest (C++): ReplacementRegistrationEvictsDevComms on both platforms, and three ROCm-only generation-token cases.

Two CI changes, both to shared config:

  • .ci/pytorch/test.sh:590: the H100 sm90-symm filter widens from NCCLSymmetricMemoryTest to "NCCLSymmetricMemoryTest or NCCLOneSidedOpHandleTypeTest or NCCLSymmetricMemoryRestartTest", so the CUDA-visible fixes run on CUDA hardware with P2P.
  • .ci/pytorch/test.sh:1907: cpp/NCCLDevCommManagerTest runs in the distributed C++ block shared by CUDA and ROCm on shard 1. On a ROCm build without device support the binary contains one GTEST_SKIP case. This branch is rebased onto Fix C++ tests silently not running on ROCm CI #199440; before it, every ROCm C++ test in that block collected 0 items and still reported success.

Still skipped on ROCm: test_nccl_symmem_rendezvous_subgroup (RCCL hangs in ncclRmaCeInit's bootstrap barrier when WORLD already holds a window) and SymmMemCftHandleTest (host-side CFT is not enabled on ROCm).

Validation

CI on this head

Read from the uploaded test-reports XML and the per-test C++ logs on f07e71b.

Job GPU test_nccl.py symmetric-memory items cpp/NCCLDevCommManagerTest
rocm-preview linux-noble-rocm-preview-py3.12-mi350 gfx950 51 passed, 5 skipped 11 passed
trunk linux-noble-rocm-py3.11-mi350 gfx950 56 skipped 1 skipped
periodic-rocm-mi300 linux-noble-rocm-py3.11-mi300 gfx942 56 skipped 1 skipped
periodic-rocm-mi200 linux-jammy-rocm-py3.11-mi200 gfx90a 56 skipped 1 skipped
trunk linux-jammy-cuda13.2-py3.11-gcc11 T4 56 skipped (no P2P) 8 passed
sm90-symm CUDA 13.2 H100 36 passed, 2 skipped not run

Preview's 5 skips are the two signal tests (CI ships RCCL 2.30.7), the two SymmMemCftHandleTest cases, and the subgroup test. All 8 NCCLSymmetricMemoryLifecycleTest items pass there, including the same-name restart on both backends. The other three ROCm labels skip 51 items on the build-time gate (their RCCL is older than 2.30.4 or its nccl_device.h fails the host-compile probe), plus 3 on RCCL < 2.30.7 and 2 on CFT, and their gtest binary holds only the GTEST_SKIP case. Preview is therefore the only ROCm label with live coverage. Widening that is a matter of the trunk and periodic images carrying a qualifying RCCL, not of test gating.

On H100 the sm90-symm filter selects 38 items. The oversized-block, foreign-handle, and both restart cases are among the 36 that pass; the two skips are test_multicast_ptr (NCCL_NVLS_ENABLE=0 on that runner) and the ROCm-only test_nccl_symmem_capture_allocation_kill_switch. On T4 the gtest runs the 7 existing cases and ReplacementRegistrationEvictsDevComms; the three generation-token cases are ROCm-only.

Locally

8x MI300X (gfx942), HIP 7.17.26383, RCCL 2.31.2, via run_test.py as CI invokes it, on the same patch before the rebase:

  • distributed/test_nccl.py: all 56 symmetric-memory items collected, 53 passed and 3 skipped (subgroup and the two CFT cases). The signal tests run here because RCCL is 2.31.2.
  • test_stale_handle_rejected_across_same_name_restart: 100 runs across four GPU pairs, both backends per run, no failure or hang.
  • cpp/NCCLDevCommManagerTest: 11 passed.
  • lintrunner clean on the changed files.

Measurements CI does not reproduce

The two-arm allocation digest comparison, the in-capture alloc/rendezvous/replay probe, and the per-config reduce-scatter kernel comparison were run on an 8x MI355X box (HIP 7.16.26344, RCCL 2.30.7, torch.version.rocm 10.1.0). They are recorded in the evidence notes and available on request.

Fixes #168480
Authored with the assistance of an AI coding assistant.

Co-authored by @chinmaydk99

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

@pytorch-bot

pytorch-bot Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure

As of commit 6868f14 with merge base 4858fc7 (image):

NEW FAILURE - The following job has failed:

  • trunk / linux-noble-rocm-py3.11-mi350 / test (default, 1, 8, amd-dpx-linux.rocm.gpu.gfx950.1) (gh)
    test/inductor/test_torchinductor_dynamic_shapes.py::DynamicShapesGPUTests::test_conv2d_backward_parametrized_dilation_1_stride_2_padding_1_kernel_1_channels_groups3_nhwc_False_dynamic_shapes_cuda

    AI verdict: AI verdict: inconclusive

    The failure is a reproducible numerical mismatch in inductor conv2d backward on MI350. The suspect PR only touches RCCL symmetric-memory, distributed c10d code, an RCCL cmake check and distributed test lists, none of which is on that code path. But the test passed at the merge base and no alternative cause (concurrent commit, trunk failures, runner fault) could be confirmed, so this is left as unsure.

    Full reasoning on HUD →

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

@pytorch-bot pytorch-bot Bot added ciflow/h100-symm-mem module: rocm AMD GPU support for Pytorch release notes: distributed (c10d) release notes category labels Aug 7, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@jithunnair-amd jithunnair-amd added ciflow/trunk Trigger trunk jobs on your pull request keep-going Don't stop on first failure, keep running tests until the end ci-no-td Do not run TD on this PR labels Aug 10, 2026
@chinmaydk99
chinmaydk99 force-pushed the abhilash-rccl-symmem-rocm-enable branch from 5e9ce4e to 79d2691 Compare August 18, 2026 05:02
@jithunnair-amd jithunnair-amd added ciflow/rocm-preview Trigger unit tests CI on a preview build of ROCm from theRock on MI300 ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/periodic-rocm-mi300 Trigger "distributed" config CI on ROCm MI300/MI325 ciflow/inductor-rocm-mi300 Trigger "inductor" config CI on ROCm MI300/MI325 labels Aug 18, 2026
@chinmaydk99

Copy link
Copy Markdown
Contributor

@pytorchbot rebase

@chinmaydk99
chinmaydk99 force-pushed the abhilash-rccl-symmem-rocm-enable branch from 35f5715 to 5695d15 Compare August 24, 2026 20:47
@linux-foundation-easycla

linux-foundation-easycla Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

@chinmaydk99
chinmaydk99 force-pushed the abhilash-rccl-symmem-rocm-enable branch 3 times, most recently from 0afb27f to 5e5525b Compare August 27, 2026 14:32
@jithunnair-amd jithunnair-amd added ciflow/rocm-mi200 Trigger "default" config CI on ROCm MI200 ciflow/periodic-rocm-mi200 Trigger "distributed" config CI on ROCm MI200 ciflow/inductor-rocm-mi200 Trigger "inductor" config CI on ROCm MI200 labels Aug 28, 2026
@chinmaydk99
chinmaydk99 force-pushed the abhilash-rccl-symmem-rocm-enable branch 3 times, most recently from af5b5c6 to 11bfb07 Compare September 2, 2026 19:35
chinmaydk99 added a commit to ROCm/pytorch that referenced this pull request Sep 3, 2026
@pragupta
pragupta marked this pull request as ready for review September 10, 2026 17:23
@pragupta
pragupta requested a review from d4l3k as a code owner September 10, 2026 17:23
State why the ROCm build defines __CUDACC_EXTENDED_LAMBDA__ and a __half
operator+ before including RCCL's device headers, and when each can go: RCCL
gates its reduce/copy API on nvcc's extended-lambda macro, which hipcc never
defines (RCCL's own DeviceApiMPITests.cpp defines it the same way), and its
generic OpSum<T> adds with `a + b`, which PyTorch's __HIP_NO_HALF_OPERATORS__
disables for __half. Comment-only change.
On ROCm, the RCCL 2.30.4 floor and the nccl_device.h host-compile probe
gated NCCL_HAS_SYMMEM_SUPPORT, so where the probe fails (RCCL 2.30.4 on
ROCm 10.0) the NCCL symmetric-memory backend compiled out entirely. Where
it compiled in, rendezvous rejected communicators without device API
support. RCCL reports that support only with cuMem enabled, and it
auto-enables cuMem only on gfx1250, so on MI300 and MI350 that was any
process group created without NCCL_CUMEM_ENABLE=1. Both broke FSDP's
symmetric-memory path and TORCH_SYMMMEM=NCCL, which work host-only on main.

Gate only the device API on the floor and the probe. Rendezvous records
device API support instead of requiring it; without it the handle stays
host-only, skips the peer-pointer setup, and the peer-pointer accessors
and barrier raise. _is_nccl_symmem_available() reports the device API on
ROCm, so the device-API test classes keep skipping where it is compiled
out.
It hung intermittently in destroy_process_group on ROCm 10.2 (RCCL 2.31.2).
Rendezvous on a handle whose RCCL communicator was retired now raises
instead of rebuilding the window against a same-name successor. The
rebuild started a collective window registration from rank-local
registry state, and its test hung intermittently in teardown. The error
tells the caller to free the tensor and allocate a new one after
initializing the successor process group.

Restore same-name restart coverage as
test_stale_handle_rejected_across_same_name_restart, and run
cpp/NCCLDevCommManagerTest in the distributed C++ block shared by CUDA
and ROCm so its ROCm-only cases execute in CI.
…UIRED_ALIGNMENT

RCCL defines NCCL_WIN_REQUIRED_ALIGNMENT from 2.28 on. The two ROCm
rounding sites used it under a plain USE_ROCM guard, so building against
RCCL 2.27.x failed with "use of undeclared identifier", which is why this
PR was reverted.

Gate both sites on the macro as well. RCCL older than 2.28 keeps main's
unrounded size; the rounding is only needed by the device-API paths,
which require RCCL >= 2.30.4 and therefore always have the macro.
@chinmaydk99
chinmaydk99 force-pushed the abhilash-rccl-symmem-rocm-enable branch from eff3138 to 6868f14 Compare October 26, 2026 17:54
@jithunnair-amd jithunnair-amd added the ciflow/periodic-rocm-mi350 Trigger "distributed_4gpu" config (only runs distributed tests that need >2GPUs) CI on ROCm MI350 label Oct 26, 2026

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

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

The #ifdef NCCL_WIN_REQUIRED_ALIGNMENT guard addresses the revert cause, and the earlier review points still hold at this head. Two things before this re-lands:

  1. On rocm-preview mi350 (RCCL 2.32.3, job 121776888358), test_stale_handle_rejected_across_same_name_restart_backend_name_nccl segfaulted in hipMemRetainAllocationHandle under ncclMemFree in the NCCLAllocation destructor (NCCLSymmetricMemory.cu:74), right after del old_handle, tensor; gc.collect() (test_nccl.py:1824-1827), and rank 1 hung at the following barrier. test_allocation_after_default_pg_restart also exited with -11 in the same job, and ncclMemFree failed in NCCLAllocation dtor: unhandled cuda error appears in other tests. Both passed only on retry; RCCL 2.30.7 jobs are clean. Please root-cause this (and file it against RCCL if it is an RCCL 2.32.3 bug) before the re-land, since freeing the tensor is exactly what the new stale-handle error tells users to do.
  2. The revert was for an internal build against an older RCCL, which OSS CI cannot reproduce. @huydhn, could you check that this head builds internally before it is merged?

@chinmaydk99

Copy link
Copy Markdown
Contributor

@jeffdaily with regards to your first review point. Since we have moved preview wheel to Oct 27th, this issue will have been resolved.

This is a HIP runtime bug, not RCCL or this PR, and it is already fixed upstream by ROCm/rocm-systems#13562 (ROCM-33022). Releasing a VMM handle imported with hipMemImportFromShareableHandle could free memory the handle only borrowed. RCCL imports and releases each peer's buffer when it registers a symmetric window, so later frees and unmaps of that memory crash. The preview image's ROCm 10.2.0a20261014 falls inside the affected nightlies, 10.2.0a20261010 through 10.2.0a20261020. The RCCL 2.30.7 jobs run ROCm 10.1, which predates the bug, so the RCCL version only correlated with it.

Reproduced on MI355X with this job's torch wheel and ROCm:

  • With the job's HIP, 1 to 2 of the 10 symmetric-memory lifecycle and restart tests fail per run, with the same segfault and ncclMemFree failed warnings.
  • With the same wheel and RCCL but HIP and ROCr from the 10.3.0a20261026 nightly, all 10 pass in each of 3 runs.
  • A torch-free repro using only RCCL calls crashes on the affected HIP even in the documented order (deregister the window, free the buffer, destroy the communicator), and never crashes without a symmetric window. Swapping in only libamdhip64 from each nightly brackets the bug to the range above.

So there is nothing to file against RCCL and no change needed in this PR. The fix on the CI side is moving the rocm-preview image to ROCm 10.2.0a20261022 or later; release/therock-10.2 already has the fix.

Drafted with AI assistance; reviewed by me.

@meta-codesync

meta-codesync Bot commented Oct 27, 2026

Copy link
Copy Markdown

@huydhn has imported this pull request. If you are a Meta employee, you can view this in D127921940.

@huydhn

huydhn commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

@chinmaydk99 FYI, the internal failure earlier looks fixed. I don't see it showing up on the imported diff anymore.

@jithunnair-amd

Copy link
Copy Markdown
Collaborator

@claude Analyze CI failures and check if the failures are related to the changes in the PR. Ignore the PR size(LOC) warning since the PR predates the size limit change

@claude

claude Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Claude finished @jithunnair-amd's task in 1m 34s —— View job


Neither CI failure on 6868f140 is caused by this PR. Leaving out the PR size check you said to ignore, only one real failure is left: a conv2d backward numerics mismatch in inductor on MI350. This PR changes nothing on that code path.

Details
  • Fetch CI status
  • Inspect failing job logs
  • Determine relation to PR changes

Failing jobs

Workflow / job Failure Related?
Lint / pr-sanity-checks PR size check (nonretryable) Ignored, as you asked
trunk / linux-noble-rocm-py3.11-mi350 / test (default, 1, 8) (job) test_conv2d_backward_parametrized_dilation_1_stride_2_padding_1_kernel_1_channels_groups3_nhwc_False_dynamic_shapes_cuda No

All other jobs in the trunk run passed. That includes all 3 ROCm MI350 distributed shards, all 10 CUDA distributed shards (which run test_nccl.py and the new cpp/NCCLDevCommManagerTest), and every build.

The MI350 inductor failure

FAILED CONSISTENTLY: test/inductor/test_torchinductor_dynamic_shapes.py::DynamicShapesGPUTests::test_conv2d_backward_parametrized_dilation_1_stride_2_padding_1_kernel_1_channels_groups3_nhwc_False_dynamic_shapes_cuda
AssertionError: Tensor-likes are not close!
Mismatched elements: 7786 / 31232 (24.9%)
Greatest absolute difference: 14.69253921508789 at index (1, 43, 5, 15) (up to 6e-05 allowed)
Greatest relative difference: 302.4363708496094 at index (0, 58, 3, 7) (up to 0.001 allowed)
  • It reproduces. The mismatch is identical across every rerun in the job. Dr. CI reported the same test failing on an earlier attempt of this run (job 121772681182), so this is deterministic numerics, not a flake.
  • It is not on any code path the PR touches. The test checks a grouped conv2d backward (groups=3, stride 2, 1x1 kernel, NCHW) compiled by inductor against eager. On ROCm, eager conv backward goes through MIOpen. The PR's C++ changes are all in torch/csrc/distributed/c10d/ (symm_mem, ProcessGroupNCCL, NCCLUtils), plus the RCCL CMake probe, test_nccl.py and the c10d C++ tests. None of these is in the conv, inductor or MIOpen stack.
  • The CMake change can't leak into conv. The rccl.cmake probe only adds RCCL_DEVICE_HEADER_HOST_COMPATIBLE to the __caffe2_nccl INTERFACE target, so only code that links RCCL sees it. The PR description also says this image fails the probe, so the new symm-mem device code isn't compiled on trunk MI350 at all.
  • The test.sh changes don't reach the default shard. They only affect the sm90-symm filter and the distributed C++ test block; default shard 1 doesn't use either.

Likely cause: a MIOpen or ROCm regression on gfx950 for this grouped-conv shape in the trunk MI350 image, or a change that landed on main after the merge base. Dr. CI says the test passed at the merge base, so the most likely cause is a newer image or a concurrent commit. One caveat: I could not query HUD to see whether this test is already red on main for MI350. Checking that, or the disable-test issue list, would confirm it.

Recommendation

Treat this failure as unrelated: merge with -i, or wait for a fix or disable on main. It doesn't need a code change in this PR. The symmetric-memory items that blocked the last re-land (the RCCL 2.32.3 / HIP free crash and the internal build) are not in this CI signal; @huydhn reported the internal build is fixed.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: trunk / linux-noble-rocm-py3.11-mi350 / test (default, 1, 8, amd-dpx-linux.rocm.gpu.gfx950.1)

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

dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…ytorch#192524)

## Summary

This PR enables `NCCLSymmetricMemory` on ROCm. ROCm cannot reuse the CUDA path: HIP graph capture, RCCL window registration, and the device reduce APIs do not behave the same way. The changes below are the smallest set that make allocation, rendezvous, capture, and the three device ops work on the tested RCCL stack.

Almost all of the C++ under `torch/csrc` is `USE_ROCM`-guarded. Five changes are not, and do change CUDA behavior; they are listed under "Changes that affect the default path". `NCCL_HAS_SYMMEM_DEVICE_SUPPORT` on CUDA stays at NCCL 2.28.0.

## Problem

`NCCLSymmetricMemory` was CUDA-only. Opening the same gates on ROCm is not enough:

- RCCL `ncclMemAlloc` without CUMEM falls back to `hipMalloc`. Capture rejects that.
- A synchronous `hipMemset` or `hipMemcpy` during Global capture returns HIP 906 and kills the capture (901).
- An async memset recorded on the capturing stream becomes a graph node and can wipe a peer signal pad on every replay.
- RCCL 2.30.4 window registration fails during capture. 2.30.7 succeeds.
- A fused multi-destination reduce-scatter launch faults with `HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION` on gfx942 and gfx950.
- A retained handle after process-group destroy launched a barrier kernel through a dead communicator and hit `HSA_STATUS_ERROR_MEMORY_FAULT`.

## Solution

On ROCm, a per-device `NCCLDevCommManager` snapshots RCCL device-API support when a communicator registers. Without that support a handle is host-only. Fresh windows use CUMEM plus an async zero on a non-captured setup stream wherever RCCL supports capture-time allocation. Peer tables upload on the same stream, under a Relaxed capture-mode guard, so rendezvous returns with initialized device pointers. Device comms are created once per op and cached. Reduce-scatter launches one kernel per destination. `ProcessGroupNCCL` retires its registry entry through a hook that `NCCLComm` runs at the start of `abort()` and `destroy()`, and every ROCm accessor that can reach a communicator checks that its registration is still live. A handle whose communicator is gone raises; it is not rebuilt against a successor.

On ROCm the feature needs RCCL >= 2.30.4 and an `nccl_device.h` that compiles in a host translation unit, which CMake probes. Capture-time allocation additionally needs RCCL >= 2.30.7. There is no GPU- or ROCm-version-specific floor.

## Design choices

**`nccl_device.h` presence is not enough.** A host C++ TU cannot compile every RCCL that ships the header, so `cmake/External/rccl.cmake` try-compiles the installed header and defines `RCCL_DEVICE_HEADER_HOST_COMPATIBLE` when it passes. On ROCm, `NCCL_HAS_SYMMEM_DEVICE_SUPPORT` requires that probe and RCCL >= 2.30.4. The condition is written `!defined(USE_ROCM) || (...)`, so CUDA's threshold stays at NCCL 2.28.0. hipcc needs CUDA's extended-lambda macro and a local `__half operator+` because PyTorch defines `__HIP_NO_HALF_OPERATORS__`.

**Device API support is a runtime snapshot; without it the handle is host-only.** RCCL reports `deviceApiSupport=0` unless both `NCCL_CUMEM_ENABLE` and `NCCL_WIN_ENABLE` are set before communicator init. `register_comm` records `ncclCommQueryProperties` against that communicator identity, so setting the env vars later does not upgrade an existing comm. Rendezvous on such a comm still registers the window, so host-side collectives on the buffer work; the peer-pointer accessors and `barrier()` raise with a message naming the missing condition. `test_host_only_rendezvous_without_device_api_support` covers this.

**Capability, not capture state, selects the allocation path.** The CUMEM + setup-stream path is correct outside capture too, so keying on `capture_allocation_supported()` gives one path on a supported stack. HIP only reports capture state for the current stream, so this PR adds no process-wide capture query: the CUMEM path runs under the Relaxed guard, performs no capture-illegal host wait, and writes the pad and peer tables as host-side setup rather than graph nodes. The current-stream `TORCH_CHECK` on the other path is a diagnostic for stacks that cannot allocate under capture, not the safety mechanism.

**`TORCH_NCCL_SYMM_MEM_DISABLE_CAPTURE_ALLOC=1` keeps the plain path.** It is read inside `capture_allocation_supported()`, so it selects `ncclMemAlloc` plus synchronous memset for allocation *and* a synchronous `cudaMemcpy` for the rendezvous peer-table upload. That is the allocate-then-capture fallback for stacks that cannot allocate under capture, and it is how the two allocation paths were compared: both arms produce the same peer digest, which is what justifies keying on capability rather than on capture state.

**One shared setup stream per device.** Signal-pad zero and peer-table H2D need a stream that is not the capturing stream. It is created when the first comm with capture-allocation support registers, so every alloc and rendezvous reuses it rather than creating one per call. It is created regardless of the kill switch, and its use is serialized.

**A host-side wait is illegal under Global capture, even on a non-captured stream.** Moving the H2D copy off the capturing stream is not enough. `cudaStreamSynchronize` on the setup stream still returns HIP 900. `alloc()` therefore wraps its whole `ncclMemAlloc` / async-zero / synchronize sequence in `CUDAStreamCaptureModeGuard{Relaxed}`, and rendezvous does the same for the peer-table upload. The peer tables and signal pad are immutable for the object's lifetime, so they are initialized on the setup stream and are not recorded as graph nodes. `hipStreamWaitEvent` would also work, but it would only guarantee the tables are ready before later device work, not when rendezvous returns on the host.

**Fresh capture allocation requires RCCL >= 2.30.7.** Direct window registration during Global capture succeeds on 2.30.7 (mode stays Global, capture stays active). 2.30.4 fails in worker-side synchronization. The check is made at compile time and against `ncclGetVersion()` at registration. Older RCCL still works if the tensor is allocated and rendezvoused before capture.

**`ncclDevCommCreate` is a direct call, then cached per op.** First create during Global capture succeeds on 2.30.7, keeps Global mode and an active capture, and the captured graph replays. All-to-all and reduce-scatter each create a devcomm once and cache it under their own op key. There is no extra ROCm-only capture guard around create. The symmetric-memory barrier uses the signal pads directly and needs no devcomm.

**RCCL leaks Relaxed mode on window deregister and device-comm destroy.** Direct `ncclCommWindowDeregister` and `ncclDevCommDestroy` change the caller's capture thread mode from Global to Relaxed. Destroy during an active capture also invalidates the capture. Both calls sit in a balanced `CUDAStreamCaptureModeGuard{Relaxed}` so the caller gets its mode back.

**The manager destructor keeps `cudaDeviceSynchronize`.** HIP returns 900 for that wait under an active capture in both Global and Relaxed thread mode, so a Relaxed guard would not make teardown capture-safe. This enablement does not change destructor synchronization.

**Reduce-scatter is serialized per destination, not fused.** The fused launch faults on gfx942 and gfx950 with RCCL 2.30.7. Row tiles that write one destination are safe. ROCm drives the existing shared kernel with a one-slot `ReduceScatterOffsetsInfo` rather than getting a kernel of its own. With `n_owned == 1` the barrier index collapses to `blockIdx.x`, so the per-destination launches are expected to agree bit for bit with a fused launch of the same shape.

**`dst_block_size` stays a `uint16_t`.** The shared kernel layout is the CUDA struct and sizes above 65535 do not fit that field. This PR keeps the layout and validates the size on the host instead; see "Changes that affect the default path" for why that check is not ROCm-scoped.

**On ROCm, retirement runs inside `NCCLComm`, before RCCL sees the abort or destroy.** `initNCCLComm` registers the collective comm and installs a pre-invalidate hook on the `NCCLComm` as one step under the comm's own mutex, which `abort()` and `destroy()` also take, so an invalidation cannot land in between. The hook captures the group uid, the `ncclComm_t` (because `abort()` nulls the handle), and the registration generation, and `NCCLComm::destroy()` / `abort()` run it first (`NCCLUtils.cpp:362`, `:379`). Retirement only erases registry entries and makes no RCCL call, so it is safe on every abort path, including watchdog and wait-timeout aborts. The generation is what tells our entry apart from a successor that is handed the same `ncclComm_t` address. Because the hook covers every teardown path, the `~ProcessGroupNCCL` unregister loop is compiled out on ROCm (`ProcessGroupNCCL.cpp:1614`); on CUDA that loop is unchanged. nccl2 already retired before destroy and abort; it now also retires on a failed split or shrink (see below).

**Retirement does not call `ncclDevCommDestroy`.** It is collective (it deregisters the devcomm's resource window), so it cannot run on the unilateral abort path. The registry drops the entries, and comm teardown reclaims those windows: RCCL's `commFree` always runs `ncclDevrFinalize`, and NCCL's runs it for every comm with symmetric support, which `ncclDevCommCreate` requires. GIN contexts are not reclaimed that way, so this holds for single-node symmetric memory.

**Stale handles are rejected, not rebuilt.** Once a handle's registration is retired, every checked accessor raises `... is stale because its RCCL communicator was destroyed or replaced. Free the tensor and allocate a new one after initializing the successor process group.` Re-rendezvous is included: a cached handle (`NCCLSymmetricMemory.cu:876`) and another pointer into the same allocation (`:905`) both check liveness before reuse. An earlier revision rebuilt such a handle against a same-name successor. That rebuild starts a collective window registration based on rank-local registry state, and its test hung once in 13 runs in `destroy_process_group` on MI355X with RCCL 2.31.2. It did not reproduce in 264 runs on MI300X with RCCL 2.31.2 or in 6 CI runs, no stack was captured, and it was not root-caused, so this PR drops the rebuild. `test_stale_handle_rejected_across_same_name_restart` covers the replacement contract: the old handle raises from `barrier`, `put_signal`, `wait_signal`, and re-rendezvous, while a freshly allocated tensor on the successor works.

**Liveness checks are ROCm-only.** The use-after-destroy hazard is not ROCm-specific, but the check relies on every producer retiring before it invalidates its comm, which stock `ProcessGroupNCCL` does only on ROCm, so CUDA accessors are unchanged. Checked: the four peer-pointer accessors and `barrier()` (which also require device API support), `put_signal`, `wait_signal`, `get_window`, `has_multicast_support`, `get_group_name`, and the two CFT handle accessors. `get_group_name()` checks because resolving a communicator from a name is the hazard. `get_window_offset()`, `get_offset()`, `get_buffer_size()`, `get_rank()`, `get_world_size()`, and `get_device()` do not: they return immutable scalars, and callers that use the offset go through `get_window()`. The window destructor deregisters only if its exact registration, pointer and generation, is still live. These checks cover use after teardown, not use that races a concurrent abort.

**Host-side CFT is not enabled on ROCm.** `NCCL_HAS_HOST_CFT` gains `!defined(USE_ROCM)` because host-side CFT has not been validated on RCCL. `SymmMemCftHandleTest` skips on ROCm.

**Allocation size is rounded to `NCCL_WIN_REQUIRED_ALIGNMENT` on ROCm only.** An unrounded backing allocation produced wrong `put_wait_signal` data and a teardown timeout. Registration uses the same rounded extent. CUDA sizes are not changed.

## Changes that affect the default path

Five changes here are not under `USE_ROCM` and do change CUDA behavior. Listing them explicitly because the rest of the PR is ROCm-scoped and a reviewer should not have to grep for the exceptions.

- **`initNCCLComm` publishes only the collective comm.** Every comm `initNCCLComm` created was registered under `getGroupUid()`, last write wins, so a lazily created 2-rank send/recv comm could replace the group's collective comm, and symmetric memory on that group would then resolve to a comm that does not span the group. Registration now runs only `if (!singleP2POp)` (`ProcessGroupNCCL.cpp:3326`). On CUDA, a group that has only ever created a P2P comm therefore has no registry entry, and rendezvous on it raises `get_comm`'s "host communicator ... not found" error instead of using the P2P comm. No dedicated test.

- **Reduce-scatter silently truncated blocks larger than 65535.** `ReduceScatterOffsetsInfo::dst_block_size` is a `uint16_t` and the host wrote `static_cast<uint16_t>(owned_sizes[j])` with no bound; the only prior check was on block *count*. A taller shard reduced `owned_sizes[j] % 65536` rows and returned wrong data with no error. Now a host-side `TORCH_CHECK` (`nccl_reduce_scatter_offset.cu:345`), placed before the ROCm/CUDA launch split so both paths get it. The inputs this rejects are exactly the ones that were already producing wrong results. `test_reduce_scatter_offset_rejects_oversized_block` asserts both that the first oversized block raises and that the largest block that still fits reduces correctly.

- **Cached device comms survived a communicator replacement.** `register_comm` is last-write-wins, but a cached `ncclDevComm` is built from one specific host comm. When a successor process group registered a different comm under the same uid, `get_devcomm` kept handing kernels devcomms naming a comm the registry no longer owned, and `~NCCLDevCommManager` would pass the successor's comm to `ncclDevCommDestroy` alongside a predecessor-built devcomm. `register_comm` now evicts that group's devcomms on replacement (`nccl_devcomm_manager.hpp:261`); re-publishing the same pointer is not a replacement. Identity is the pointer, so on CUDA, where `~ProcessGroupNCCL` keeps the entry of a destroyed comm, a successor at a recycled `ncclComm_t` address still skips the eviction; nccl2 and ROCm retire before invalidating, which rules that out. Covered by `NCCLDevCommManagerTest.ReplacementRegistrationEvictsDevComms`, which also asserts that a bystander group's devcomm survives and that a predecessor's late retirement cannot unpublish its successor.

- **The one-sided ops dereferenced an unchecked `dynamic_cast`.** `nccl_put_signal` and `nccl_wait_signal` are schema'd over the `SymmetricMemory` base class, so a handle from another backend is a legal argument, and both used the cast result without testing it. Now `TORCH_CHECK`ed (`nccl_extension.cu:375`, `:410`), matching the sibling ops. Covered by `NCCLOneSidedOpHandleTypeTest::test_one_sided_ops_reject_foreign_handle`.

- **nccl2 left the parent registered when split or shrink failed.** On failure both cleared `nccl_comm_` without retiring, leaving the registry pointing at a parent the failed call may have aborted. Both now call `retireComm()` first (`nccl2/ProcessGroupNCCL.cpp:399`, `nccl2/ShrinkNCCL.cpp:100`). No test: it needs a split or shrink that fails.

Also visible on CUDA, but not behavioral:

- The two ops copy the cached `ncclDevComm` instead of binding a reference into the registry (`nccl_all_to_all_nd.cu:183`, `nccl_reduce_scatter_offset.cu:221`), since eviction can now erase the entry. `get_devcomm`'s signature is unchanged; its comment now says the reference dangles after replacement.
- `NCCLComm` gains `preInvalidateHook_` on every platform, so the class layout does not depend on `USE_ROCM`. It is only set and run on ROCm.
- `nccl_dev_cap.hpp` only adds ROCm terms, so the CUDA truth values of `NCCL_HAS_SYMMEM_DEVICE_SUPPORT` and `NCCL_HAS_HOST_CFT` are unchanged. The `NCCL_HAS_DEVCOMM` / `NCCL_HAS_ONE_SIDED_API` hunk merges two byte-identical `#if` conditions.
- `#include <vector_types.h>` is dropped from `NCCLSymmetricMemory.cu`; nothing there uses a CUDA vector type, and the header does not exist on ROCm.
- `_is_nccl_symmem_available()` is new and only used by the test suite to pick a skip predicate. The rest of the `init.cpp` hunk is clang-format reflow of existing lambdas.

## Tests

`test/distributed/test_nccl.py` no longer carries a blanket `TEST_WITH_ROCM` skip on the symmetric-memory classes. It is replaced by narrower gates, all no-ops on CUDA:

- `skip_if_rccl_symmem_not_compiled`: the build-time result, exposed to Python as `_is_nccl_symmem_available()`.
- `skip_if_rccl_lt_2_30_4`: the RCCL host device-API floor.
- `skip_if_rccl_lt_2_31_2`: `test_put_wait_signal` and `test_nccl_symmem_signal_rank_out_of_bounds`, which are validated only on RCCL 2.31.2.
- Tests that allocate during capture skip on RCCL < 2.30.7.

New coverage:

- `NCCLSymmetricMemoryLifecycleTest` (ROCm-only, 8 items, each on `nccl` and `nccl-legacy`; only `nccl-legacy` goes through stock `ProcessGroupNCCL`): a retained handle is rejected after abort, after a wait-timeout abort, and after a watchdog abort, and across a same-name restart as described above.
- `NCCLSymmetricMemoryCapabilityGateTest` (ROCm-only, 3 items): the host-only path without device API support, capture allocation rejected when CUMEM/WIN are enabled after init, and the kill switch.
- `NCCLSymmetricMemorySubgroupTest` (ROCm-only, 1 item): subgroup-first rendezvous in a fresh process.
- `NCCLSymmetricMemoryRestartTest` (**not** ROCm-gated, 2 items): allocation after a default-PG restart, and a successor PG surviving its predecessor's teardown.
- `NCCLOneSidedOpHandleTypeTest` (**not** ROCm-gated, 1 item): one-sided ops reject a non-NCCL handle.
- `NCCLSymmetricMemoryTest::test_reduce_scatter_offset_rejects_oversized_block` (**not** ROCm-gated), plus the ROCm-only capture cases `test_nccl_symmem_capture_allocation_kill_switch` and `NCCLSymmetricMemoryNccl2Test::test_nccl_symmem_fresh_cuda_graph`.
- `NCCLDevCommManagerTest` (C++): `ReplacementRegistrationEvictsDevComms` on both platforms, and three ROCm-only generation-token cases.

Two CI changes, both to shared config:

- `.ci/pytorch/test.sh:590`: the H100 `sm90-symm` filter widens from `NCCLSymmetricMemoryTest` to `"NCCLSymmetricMemoryTest or NCCLOneSidedOpHandleTypeTest or NCCLSymmetricMemoryRestartTest"`, so the CUDA-visible fixes run on CUDA hardware with P2P.
- `.ci/pytorch/test.sh:1907`: `cpp/NCCLDevCommManagerTest` runs in the distributed C++ block shared by CUDA and ROCm on shard 1. On a ROCm build without device support the binary contains one `GTEST_SKIP` case. This branch is rebased onto pytorch#199440; before it, every ROCm C++ test in that block collected 0 items and still reported success.

Still skipped on ROCm: `test_nccl_symmem_rendezvous_subgroup` (RCCL hangs in `ncclRmaCeInit`'s bootstrap barrier when WORLD already holds a window) and `SymmMemCftHandleTest` (host-side CFT is not enabled on ROCm).

## Validation

### CI on this head

Read from the uploaded `test-reports` XML and the per-test C++ logs on [`f07e71b`](pytorch@f07e71b).

| Job | GPU | `test_nccl.py` symmetric-memory items | `cpp/NCCLDevCommManagerTest` |
|---|---|---|---|
| [rocm-preview](https://github.com/pytorch/pytorch/actions/runs/37410391165) `linux-noble-rocm-preview-py3.12-mi350` | gfx950 | **51 passed, 5 skipped** | [**11 passed**](https://github.com/pytorch/pytorch/actions/runs/37410391165/job/112119195812) |
| [trunk](https://github.com/pytorch/pytorch/actions/runs/37410384883) `linux-noble-rocm-py3.11-mi350` | gfx950 | 56 skipped | [1 skipped](https://github.com/pytorch/pytorch/actions/runs/37410384883/job/112125954872) |
| [periodic-rocm-mi300](https://github.com/pytorch/pytorch/actions/runs/37410383794) `linux-noble-rocm-py3.11-mi300` | gfx942 | 56 skipped | [1 skipped](https://github.com/pytorch/pytorch/actions/runs/37410383794/job/112125941200) |
| [periodic-rocm-mi200](https://github.com/pytorch/pytorch/actions/runs/37410386548) `linux-jammy-rocm-py3.11-mi200` | gfx90a | 56 skipped | [1 skipped](https://github.com/pytorch/pytorch/actions/runs/37410386548/job/112128613809) |
| [trunk](https://github.com/pytorch/pytorch/actions/runs/37410384883) `linux-jammy-cuda13.2-py3.11-gcc11` | T4 | 56 skipped (no P2P) | [8 passed](https://github.com/pytorch/pytorch/actions/runs/37410384883/job/112110745550) |
| [`sm90-symm`](https://github.com/pytorch/pytorch/actions/runs/37410384954/job/112111113881) CUDA 13.2 | H100 | 36 passed, 2 skipped | not run |

Preview's 5 skips are the two signal tests (CI ships RCCL 2.30.7), the two `SymmMemCftHandleTest` cases, and the subgroup test. All 8 `NCCLSymmetricMemoryLifecycleTest` items pass there, including the same-name restart on both backends. The other three ROCm labels skip 51 items on the build-time gate (their RCCL is older than 2.30.4 or its `nccl_device.h` fails the host-compile probe), plus 3 on RCCL < 2.30.7 and 2 on CFT, and their gtest binary holds only the `GTEST_SKIP` case. Preview is therefore the only ROCm label with live coverage. Widening that is a matter of the trunk and periodic images carrying a qualifying RCCL, not of test gating.

On H100 the `sm90-symm` filter selects 38 items. The oversized-block, foreign-handle, and both restart cases are among the 36 that pass; the two skips are `test_multicast_ptr` (`NCCL_NVLS_ENABLE=0` on that runner) and the ROCm-only `test_nccl_symmem_capture_allocation_kill_switch`. On T4 the gtest runs the 7 existing cases and `ReplacementRegistrationEvictsDevComms`; the three generation-token cases are ROCm-only.

### Locally

8x MI300X (gfx942), HIP 7.17.26383, RCCL 2.31.2, via `run_test.py` as CI invokes it, on the same patch before the rebase:

- `distributed/test_nccl.py`: all 56 symmetric-memory items collected, 53 passed and 3 skipped (subgroup and the two CFT cases). The signal tests run here because RCCL is 2.31.2.
- `test_stale_handle_rejected_across_same_name_restart`: 100 runs across four GPU pairs, both backends per run, no failure or hang.
- `cpp/NCCLDevCommManagerTest`: 11 passed.
- `lintrunner` clean on the changed files.

### Measurements CI does not reproduce

The two-arm allocation digest comparison, the in-capture alloc/rendezvous/replay probe, and the per-config reduce-scatter kernel comparison were run on an 8x MI355X box (HIP 7.16.26344, RCCL 2.30.7, `torch.version.rocm` 10.1.0). They are recorded in the evidence notes and available on request.

Fixes pytorch#168480
Authored with the assistance of an AI coding assistant.

Co-authored by @chinmaydk99

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

Co-authored-by: Chinmay Kuchinad <[email protected]>
pytorchmergebot pushed a commit that referenced this pull request Nov 5, 2026
…03291)

## Linked issue or supporting maintainer

Fixes #202797
Fixes #200247

Supported by @jeffdaily

## BC-breaking?

No.

## Summary (human written only)

The symmetric-memory lifecycle tests hold rank 0's collective for 10 s with `torch.cuda._sleep`, but the cycle count was calibrated from a single cold launch timed on the host, so the hold came out several seconds short and sometimes under the peer's 2 s timeout. Use the existing `get_cycles_per_ms()` helper, which times with device events and averages several samples.

## Agent details (if applicable)

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

Since #192524 relanded on 10-28, `NCCLSymmetricMemoryLifecycleTest` has been flaky on the ROCm CI MI350 runners (about 161 failures in 5000 runs; MI300 0 in about 500). The `watchdog_abort` variants fail with "watchdog never aborted the comm" and the `wait_timeout` variants with "RuntimeError not raised"; both mean rank 0's collective reached rank 1 before rank 1's 2 s timeout.

`_hold_back_collectives(10)` is meant to hold rank 0's collective for 10 s. It converted seconds to `torch.cuda._sleep` cycles by timing one 10^7-cycle launch with host `synchronize()` calls, and that launch was the first one, so launch overhead inflated `seconds_per_cycle` and every hold came out short. On an MI355X the hold measured 6.0-7.0 s (median 6.49 s) with the shader clock steady at about 2385 MHz, and about 4% of calibrations took 13-22 ms instead of 4-7 ms, which gave holds of 1.97 s and 2.35 s; those two runs were the failures. On an MI300X the hold was 4.6-8.6 s, so it stayed above 2 s.

The hold now uses `get_cycles_per_ms()` from `common_utils`, as other distributed tests do (`test_c10d_nccl2.py`, `test_c10d_fault_tolerance.py`). It times `_sleep` with device events and takes the trimmed mean of 10 samples, so first-launch overhead and an occasional slow sample drop out. An untimed warm-up launch before the old calibration also fixed it (20 of 20 class runs on the MI355X, median hold 10.01 s), but it kept a single host-timed sample and duplicated the helper.

Test plan:

```
python test/distributed/test_nccl.py -k NCCLSymmetricMemoryLifecycleTest -v
```

On an MI355X (SPX) at the same base, the unpatched class failed 8 of 160 tests in 20 runs, all with one of the two signatures above. With the change, 40 of 40 class runs passed (320 tests). In 10 more instrumented runs the 10 s hold measured a median 9.95 s; 36 of 40 holds were 9.87-10.40 s, and the other 4 (4.1-9.2 s, still above the 2 s timeout) happened while an unrelated process from another container was running on rank 0's GPU, which slows every calibration launch.

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

Co-authored-by: Jeff Daily <[email protected]>
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…ytorch#192524)

## Summary

This PR enables `NCCLSymmetricMemory` on ROCm. ROCm cannot reuse the CUDA path: HIP graph capture, RCCL window registration, and the device reduce APIs do not behave the same way. The changes below are the smallest set that make allocation, rendezvous, capture, and the three device ops work on the tested RCCL stack.

Almost all of the C++ under `torch/csrc` is `USE_ROCM`-guarded. Five changes are not, and do change CUDA behavior; they are listed under "Changes that affect the default path". `NCCL_HAS_SYMMEM_DEVICE_SUPPORT` on CUDA stays at NCCL 2.28.0.

## Problem

`NCCLSymmetricMemory` was CUDA-only. Opening the same gates on ROCm is not enough:

- RCCL `ncclMemAlloc` without CUMEM falls back to `hipMalloc`. Capture rejects that.
- A synchronous `hipMemset` or `hipMemcpy` during Global capture returns HIP 906 and kills the capture (901).
- An async memset recorded on the capturing stream becomes a graph node and can wipe a peer signal pad on every replay.
- RCCL 2.30.4 window registration fails during capture. 2.30.7 succeeds.
- A fused multi-destination reduce-scatter launch faults with `HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION` on gfx942 and gfx950.
- A retained handle after process-group destroy launched a barrier kernel through a dead communicator and hit `HSA_STATUS_ERROR_MEMORY_FAULT`.

## Solution

On ROCm, a per-device `NCCLDevCommManager` snapshots RCCL device-API support when a communicator registers. Without that support a handle is host-only. Fresh windows use CUMEM plus an async zero on a non-captured setup stream wherever RCCL supports capture-time allocation. Peer tables upload on the same stream, under a Relaxed capture-mode guard, so rendezvous returns with initialized device pointers. Device comms are created once per op and cached. Reduce-scatter launches one kernel per destination. `ProcessGroupNCCL` retires its registry entry through a hook that `NCCLComm` runs at the start of `abort()` and `destroy()`, and every ROCm accessor that can reach a communicator checks that its registration is still live. A handle whose communicator is gone raises; it is not rebuilt against a successor.

On ROCm the feature needs RCCL >= 2.30.4 and an `nccl_device.h` that compiles in a host translation unit, which CMake probes. Capture-time allocation additionally needs RCCL >= 2.30.7. There is no GPU- or ROCm-version-specific floor.

## Design choices

**`nccl_device.h` presence is not enough.** A host C++ TU cannot compile every RCCL that ships the header, so `cmake/External/rccl.cmake` try-compiles the installed header and defines `RCCL_DEVICE_HEADER_HOST_COMPATIBLE` when it passes. On ROCm, `NCCL_HAS_SYMMEM_DEVICE_SUPPORT` requires that probe and RCCL >= 2.30.4. The condition is written `!defined(USE_ROCM) || (...)`, so CUDA's threshold stays at NCCL 2.28.0. hipcc needs CUDA's extended-lambda macro and a local `__half operator+` because PyTorch defines `__HIP_NO_HALF_OPERATORS__`.

**Device API support is a runtime snapshot; without it the handle is host-only.** RCCL reports `deviceApiSupport=0` unless both `NCCL_CUMEM_ENABLE` and `NCCL_WIN_ENABLE` are set before communicator init. `register_comm` records `ncclCommQueryProperties` against that communicator identity, so setting the env vars later does not upgrade an existing comm. Rendezvous on such a comm still registers the window, so host-side collectives on the buffer work; the peer-pointer accessors and `barrier()` raise with a message naming the missing condition. `test_host_only_rendezvous_without_device_api_support` covers this.

**Capability, not capture state, selects the allocation path.** The CUMEM + setup-stream path is correct outside capture too, so keying on `capture_allocation_supported()` gives one path on a supported stack. HIP only reports capture state for the current stream, so this PR adds no process-wide capture query: the CUMEM path runs under the Relaxed guard, performs no capture-illegal host wait, and writes the pad and peer tables as host-side setup rather than graph nodes. The current-stream `TORCH_CHECK` on the other path is a diagnostic for stacks that cannot allocate under capture, not the safety mechanism.

**`TORCH_NCCL_SYMM_MEM_DISABLE_CAPTURE_ALLOC=1` keeps the plain path.** It is read inside `capture_allocation_supported()`, so it selects `ncclMemAlloc` plus synchronous memset for allocation *and* a synchronous `cudaMemcpy` for the rendezvous peer-table upload. That is the allocate-then-capture fallback for stacks that cannot allocate under capture, and it is how the two allocation paths were compared: both arms produce the same peer digest, which is what justifies keying on capability rather than on capture state.

**One shared setup stream per device.** Signal-pad zero and peer-table H2D need a stream that is not the capturing stream. It is created when the first comm with capture-allocation support registers, so every alloc and rendezvous reuses it rather than creating one per call. It is created regardless of the kill switch, and its use is serialized.

**A host-side wait is illegal under Global capture, even on a non-captured stream.** Moving the H2D copy off the capturing stream is not enough. `cudaStreamSynchronize` on the setup stream still returns HIP 900. `alloc()` therefore wraps its whole `ncclMemAlloc` / async-zero / synchronize sequence in `CUDAStreamCaptureModeGuard{Relaxed}`, and rendezvous does the same for the peer-table upload. The peer tables and signal pad are immutable for the object's lifetime, so they are initialized on the setup stream and are not recorded as graph nodes. `hipStreamWaitEvent` would also work, but it would only guarantee the tables are ready before later device work, not when rendezvous returns on the host.

**Fresh capture allocation requires RCCL >= 2.30.7.** Direct window registration during Global capture succeeds on 2.30.7 (mode stays Global, capture stays active). 2.30.4 fails in worker-side synchronization. The check is made at compile time and against `ncclGetVersion()` at registration. Older RCCL still works if the tensor is allocated and rendezvoused before capture.

**`ncclDevCommCreate` is a direct call, then cached per op.** First create during Global capture succeeds on 2.30.7, keeps Global mode and an active capture, and the captured graph replays. All-to-all and reduce-scatter each create a devcomm once and cache it under their own op key. There is no extra ROCm-only capture guard around create. The symmetric-memory barrier uses the signal pads directly and needs no devcomm.

**RCCL leaks Relaxed mode on window deregister and device-comm destroy.** Direct `ncclCommWindowDeregister` and `ncclDevCommDestroy` change the caller's capture thread mode from Global to Relaxed. Destroy during an active capture also invalidates the capture. Both calls sit in a balanced `CUDAStreamCaptureModeGuard{Relaxed}` so the caller gets its mode back.

**The manager destructor keeps `cudaDeviceSynchronize`.** HIP returns 900 for that wait under an active capture in both Global and Relaxed thread mode, so a Relaxed guard would not make teardown capture-safe. This enablement does not change destructor synchronization.

**Reduce-scatter is serialized per destination, not fused.** The fused launch faults on gfx942 and gfx950 with RCCL 2.30.7. Row tiles that write one destination are safe. ROCm drives the existing shared kernel with a one-slot `ReduceScatterOffsetsInfo` rather than getting a kernel of its own. With `n_owned == 1` the barrier index collapses to `blockIdx.x`, so the per-destination launches are expected to agree bit for bit with a fused launch of the same shape.

**`dst_block_size` stays a `uint16_t`.** The shared kernel layout is the CUDA struct and sizes above 65535 do not fit that field. This PR keeps the layout and validates the size on the host instead; see "Changes that affect the default path" for why that check is not ROCm-scoped.

**On ROCm, retirement runs inside `NCCLComm`, before RCCL sees the abort or destroy.** `initNCCLComm` registers the collective comm and installs a pre-invalidate hook on the `NCCLComm` as one step under the comm's own mutex, which `abort()` and `destroy()` also take, so an invalidation cannot land in between. The hook captures the group uid, the `ncclComm_t` (because `abort()` nulls the handle), and the registration generation, and `NCCLComm::destroy()` / `abort()` run it first (`NCCLUtils.cpp:362`, `:379`). Retirement only erases registry entries and makes no RCCL call, so it is safe on every abort path, including watchdog and wait-timeout aborts. The generation is what tells our entry apart from a successor that is handed the same `ncclComm_t` address. Because the hook covers every teardown path, the `~ProcessGroupNCCL` unregister loop is compiled out on ROCm (`ProcessGroupNCCL.cpp:1614`); on CUDA that loop is unchanged. nccl2 already retired before destroy and abort; it now also retires on a failed split or shrink (see below).

**Retirement does not call `ncclDevCommDestroy`.** It is collective (it deregisters the devcomm's resource window), so it cannot run on the unilateral abort path. The registry drops the entries, and comm teardown reclaims those windows: RCCL's `commFree` always runs `ncclDevrFinalize`, and NCCL's runs it for every comm with symmetric support, which `ncclDevCommCreate` requires. GIN contexts are not reclaimed that way, so this holds for single-node symmetric memory.

**Stale handles are rejected, not rebuilt.** Once a handle's registration is retired, every checked accessor raises `... is stale because its RCCL communicator was destroyed or replaced. Free the tensor and allocate a new one after initializing the successor process group.` Re-rendezvous is included: a cached handle (`NCCLSymmetricMemory.cu:876`) and another pointer into the same allocation (`:905`) both check liveness before reuse. An earlier revision rebuilt such a handle against a same-name successor. That rebuild starts a collective window registration based on rank-local registry state, and its test hung once in 13 runs in `destroy_process_group` on MI355X with RCCL 2.31.2. It did not reproduce in 264 runs on MI300X with RCCL 2.31.2 or in 6 CI runs, no stack was captured, and it was not root-caused, so this PR drops the rebuild. `test_stale_handle_rejected_across_same_name_restart` covers the replacement contract: the old handle raises from `barrier`, `put_signal`, `wait_signal`, and re-rendezvous, while a freshly allocated tensor on the successor works.

**Liveness checks are ROCm-only.** The use-after-destroy hazard is not ROCm-specific, but the check relies on every producer retiring before it invalidates its comm, which stock `ProcessGroupNCCL` does only on ROCm, so CUDA accessors are unchanged. Checked: the four peer-pointer accessors and `barrier()` (which also require device API support), `put_signal`, `wait_signal`, `get_window`, `has_multicast_support`, `get_group_name`, and the two CFT handle accessors. `get_group_name()` checks because resolving a communicator from a name is the hazard. `get_window_offset()`, `get_offset()`, `get_buffer_size()`, `get_rank()`, `get_world_size()`, and `get_device()` do not: they return immutable scalars, and callers that use the offset go through `get_window()`. The window destructor deregisters only if its exact registration, pointer and generation, is still live. These checks cover use after teardown, not use that races a concurrent abort.

**Host-side CFT is not enabled on ROCm.** `NCCL_HAS_HOST_CFT` gains `!defined(USE_ROCM)` because host-side CFT has not been validated on RCCL. `SymmMemCftHandleTest` skips on ROCm.

**Allocation size is rounded to `NCCL_WIN_REQUIRED_ALIGNMENT` on ROCm only.** An unrounded backing allocation produced wrong `put_wait_signal` data and a teardown timeout. Registration uses the same rounded extent. CUDA sizes are not changed.

## Changes that affect the default path

Five changes here are not under `USE_ROCM` and do change CUDA behavior. Listing them explicitly because the rest of the PR is ROCm-scoped and a reviewer should not have to grep for the exceptions.

- **`initNCCLComm` publishes only the collective comm.** Every comm `initNCCLComm` created was registered under `getGroupUid()`, last write wins, so a lazily created 2-rank send/recv comm could replace the group's collective comm, and symmetric memory on that group would then resolve to a comm that does not span the group. Registration now runs only `if (!singleP2POp)` (`ProcessGroupNCCL.cpp:3326`). On CUDA, a group that has only ever created a P2P comm therefore has no registry entry, and rendezvous on it raises `get_comm`'s "host communicator ... not found" error instead of using the P2P comm. No dedicated test.

- **Reduce-scatter silently truncated blocks larger than 65535.** `ReduceScatterOffsetsInfo::dst_block_size` is a `uint16_t` and the host wrote `static_cast<uint16_t>(owned_sizes[j])` with no bound; the only prior check was on block *count*. A taller shard reduced `owned_sizes[j] % 65536` rows and returned wrong data with no error. Now a host-side `TORCH_CHECK` (`nccl_reduce_scatter_offset.cu:345`), placed before the ROCm/CUDA launch split so both paths get it. The inputs this rejects are exactly the ones that were already producing wrong results. `test_reduce_scatter_offset_rejects_oversized_block` asserts both that the first oversized block raises and that the largest block that still fits reduces correctly.

- **Cached device comms survived a communicator replacement.** `register_comm` is last-write-wins, but a cached `ncclDevComm` is built from one specific host comm. When a successor process group registered a different comm under the same uid, `get_devcomm` kept handing kernels devcomms naming a comm the registry no longer owned, and `~NCCLDevCommManager` would pass the successor's comm to `ncclDevCommDestroy` alongside a predecessor-built devcomm. `register_comm` now evicts that group's devcomms on replacement (`nccl_devcomm_manager.hpp:261`); re-publishing the same pointer is not a replacement. Identity is the pointer, so on CUDA, where `~ProcessGroupNCCL` keeps the entry of a destroyed comm, a successor at a recycled `ncclComm_t` address still skips the eviction; nccl2 and ROCm retire before invalidating, which rules that out. Covered by `NCCLDevCommManagerTest.ReplacementRegistrationEvictsDevComms`, which also asserts that a bystander group's devcomm survives and that a predecessor's late retirement cannot unpublish its successor.

- **The one-sided ops dereferenced an unchecked `dynamic_cast`.** `nccl_put_signal` and `nccl_wait_signal` are schema'd over the `SymmetricMemory` base class, so a handle from another backend is a legal argument, and both used the cast result without testing it. Now `TORCH_CHECK`ed (`nccl_extension.cu:375`, `:410`), matching the sibling ops. Covered by `NCCLOneSidedOpHandleTypeTest::test_one_sided_ops_reject_foreign_handle`.

- **nccl2 left the parent registered when split or shrink failed.** On failure both cleared `nccl_comm_` without retiring, leaving the registry pointing at a parent the failed call may have aborted. Both now call `retireComm()` first (`nccl2/ProcessGroupNCCL.cpp:399`, `nccl2/ShrinkNCCL.cpp:100`). No test: it needs a split or shrink that fails.

Also visible on CUDA, but not behavioral:

- The two ops copy the cached `ncclDevComm` instead of binding a reference into the registry (`nccl_all_to_all_nd.cu:183`, `nccl_reduce_scatter_offset.cu:221`), since eviction can now erase the entry. `get_devcomm`'s signature is unchanged; its comment now says the reference dangles after replacement.
- `NCCLComm` gains `preInvalidateHook_` on every platform, so the class layout does not depend on `USE_ROCM`. It is only set and run on ROCm.
- `nccl_dev_cap.hpp` only adds ROCm terms, so the CUDA truth values of `NCCL_HAS_SYMMEM_DEVICE_SUPPORT` and `NCCL_HAS_HOST_CFT` are unchanged. The `NCCL_HAS_DEVCOMM` / `NCCL_HAS_ONE_SIDED_API` hunk merges two byte-identical `#if` conditions.
- `#include <vector_types.h>` is dropped from `NCCLSymmetricMemory.cu`; nothing there uses a CUDA vector type, and the header does not exist on ROCm.
- `_is_nccl_symmem_available()` is new and only used by the test suite to pick a skip predicate. The rest of the `init.cpp` hunk is clang-format reflow of existing lambdas.

## Tests

`test/distributed/test_nccl.py` no longer carries a blanket `TEST_WITH_ROCM` skip on the symmetric-memory classes. It is replaced by narrower gates, all no-ops on CUDA:

- `skip_if_rccl_symmem_not_compiled`: the build-time result, exposed to Python as `_is_nccl_symmem_available()`.
- `skip_if_rccl_lt_2_30_4`: the RCCL host device-API floor.
- `skip_if_rccl_lt_2_31_2`: `test_put_wait_signal` and `test_nccl_symmem_signal_rank_out_of_bounds`, which are validated only on RCCL 2.31.2.
- Tests that allocate during capture skip on RCCL < 2.30.7.

New coverage:

- `NCCLSymmetricMemoryLifecycleTest` (ROCm-only, 8 items, each on `nccl` and `nccl-legacy`; only `nccl-legacy` goes through stock `ProcessGroupNCCL`): a retained handle is rejected after abort, after a wait-timeout abort, and after a watchdog abort, and across a same-name restart as described above.
- `NCCLSymmetricMemoryCapabilityGateTest` (ROCm-only, 3 items): the host-only path without device API support, capture allocation rejected when CUMEM/WIN are enabled after init, and the kill switch.
- `NCCLSymmetricMemorySubgroupTest` (ROCm-only, 1 item): subgroup-first rendezvous in a fresh process.
- `NCCLSymmetricMemoryRestartTest` (**not** ROCm-gated, 2 items): allocation after a default-PG restart, and a successor PG surviving its predecessor's teardown.
- `NCCLOneSidedOpHandleTypeTest` (**not** ROCm-gated, 1 item): one-sided ops reject a non-NCCL handle.
- `NCCLSymmetricMemoryTest::test_reduce_scatter_offset_rejects_oversized_block` (**not** ROCm-gated), plus the ROCm-only capture cases `test_nccl_symmem_capture_allocation_kill_switch` and `NCCLSymmetricMemoryNccl2Test::test_nccl_symmem_fresh_cuda_graph`.
- `NCCLDevCommManagerTest` (C++): `ReplacementRegistrationEvictsDevComms` on both platforms, and three ROCm-only generation-token cases.

Two CI changes, both to shared config:

- `.ci/pytorch/test.sh:590`: the H100 `sm90-symm` filter widens from `NCCLSymmetricMemoryTest` to `"NCCLSymmetricMemoryTest or NCCLOneSidedOpHandleTypeTest or NCCLSymmetricMemoryRestartTest"`, so the CUDA-visible fixes run on CUDA hardware with P2P.
- `.ci/pytorch/test.sh:1907`: `cpp/NCCLDevCommManagerTest` runs in the distributed C++ block shared by CUDA and ROCm on shard 1. On a ROCm build without device support the binary contains one `GTEST_SKIP` case. This branch is rebased onto pytorch#199440; before it, every ROCm C++ test in that block collected 0 items and still reported success.

Still skipped on ROCm: `test_nccl_symmem_rendezvous_subgroup` (RCCL hangs in `ncclRmaCeInit`'s bootstrap barrier when WORLD already holds a window) and `SymmMemCftHandleTest` (host-side CFT is not enabled on ROCm).

## Validation

### CI on this head

Read from the uploaded `test-reports` XML and the per-test C++ logs on [`f07e71b`](pytorch@f07e71b).

| Job | GPU | `test_nccl.py` symmetric-memory items | `cpp/NCCLDevCommManagerTest` |
|---|---|---|---|
| [rocm-preview](https://github.com/pytorch/pytorch/actions/runs/37410391165) `linux-noble-rocm-preview-py3.12-mi350` | gfx950 | **51 passed, 5 skipped** | [**11 passed**](https://github.com/pytorch/pytorch/actions/runs/37410391165/job/112119195812) |
| [trunk](https://github.com/pytorch/pytorch/actions/runs/37410384883) `linux-noble-rocm-py3.11-mi350` | gfx950 | 56 skipped | [1 skipped](https://github.com/pytorch/pytorch/actions/runs/37410384883/job/112125954872) |
| [periodic-rocm-mi300](https://github.com/pytorch/pytorch/actions/runs/37410383794) `linux-noble-rocm-py3.11-mi300` | gfx942 | 56 skipped | [1 skipped](https://github.com/pytorch/pytorch/actions/runs/37410383794/job/112125941200) |
| [periodic-rocm-mi200](https://github.com/pytorch/pytorch/actions/runs/37410386548) `linux-jammy-rocm-py3.11-mi200` | gfx90a | 56 skipped | [1 skipped](https://github.com/pytorch/pytorch/actions/runs/37410386548/job/112128613809) |
| [trunk](https://github.com/pytorch/pytorch/actions/runs/37410384883) `linux-jammy-cuda13.2-py3.11-gcc11` | T4 | 56 skipped (no P2P) | [8 passed](https://github.com/pytorch/pytorch/actions/runs/37410384883/job/112110745550) |
| [`sm90-symm`](https://github.com/pytorch/pytorch/actions/runs/37410384954/job/112111113881) CUDA 13.2 | H100 | 36 passed, 2 skipped | not run |

Preview's 5 skips are the two signal tests (CI ships RCCL 2.30.7), the two `SymmMemCftHandleTest` cases, and the subgroup test. All 8 `NCCLSymmetricMemoryLifecycleTest` items pass there, including the same-name restart on both backends. The other three ROCm labels skip 51 items on the build-time gate (their RCCL is older than 2.30.4 or its `nccl_device.h` fails the host-compile probe), plus 3 on RCCL < 2.30.7 and 2 on CFT, and their gtest binary holds only the `GTEST_SKIP` case. Preview is therefore the only ROCm label with live coverage. Widening that is a matter of the trunk and periodic images carrying a qualifying RCCL, not of test gating.

On H100 the `sm90-symm` filter selects 38 items. The oversized-block, foreign-handle, and both restart cases are among the 36 that pass; the two skips are `test_multicast_ptr` (`NCCL_NVLS_ENABLE=0` on that runner) and the ROCm-only `test_nccl_symmem_capture_allocation_kill_switch`. On T4 the gtest runs the 7 existing cases and `ReplacementRegistrationEvictsDevComms`; the three generation-token cases are ROCm-only.

### Locally

8x MI300X (gfx942), HIP 7.17.26383, RCCL 2.31.2, via `run_test.py` as CI invokes it, on the same patch before the rebase:

- `distributed/test_nccl.py`: all 56 symmetric-memory items collected, 53 passed and 3 skipped (subgroup and the two CFT cases). The signal tests run here because RCCL is 2.31.2.
- `test_stale_handle_rejected_across_same_name_restart`: 100 runs across four GPU pairs, both backends per run, no failure or hang.
- `cpp/NCCLDevCommManagerTest`: 11 passed.
- `lintrunner` clean on the changed files.

### Measurements CI does not reproduce

The two-arm allocation digest comparison, the in-capture alloc/rendezvous/replay probe, and the per-config reduce-scatter kernel comparison were run on an 8x MI355X box (HIP 7.16.26344, RCCL 2.30.7, `torch.version.rocm` 10.1.0). They are recorded in the evidence notes and available on request.

Fixes pytorch#168480
Authored with the assistance of an AI coding assistant.

Co-authored by @chinmaydk99

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

Co-authored-by: Chinmay Kuchinad <[email protected]>
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…torch#203291)

## Linked issue or supporting maintainer

Fixes pytorch#202797
Fixes pytorch#200247

Supported by @jeffdaily

## BC-breaking?

No.

## Summary (human written only)

The symmetric-memory lifecycle tests hold rank 0's collective for 10 s with `torch.cuda._sleep`, but the cycle count was calibrated from a single cold launch timed on the host, so the hold came out several seconds short and sometimes under the peer's 2 s timeout. Use the existing `get_cycles_per_ms()` helper, which times with device events and averages several samples.

## Agent details (if applicable)

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

Since pytorch#192524 relanded on 10-28, `NCCLSymmetricMemoryLifecycleTest` has been flaky on the ROCm CI MI350 runners (about 161 failures in 5000 runs; MI300 0 in about 500). The `watchdog_abort` variants fail with "watchdog never aborted the comm" and the `wait_timeout` variants with "RuntimeError not raised"; both mean rank 0's collective reached rank 1 before rank 1's 2 s timeout.

`_hold_back_collectives(10)` is meant to hold rank 0's collective for 10 s. It converted seconds to `torch.cuda._sleep` cycles by timing one 10^7-cycle launch with host `synchronize()` calls, and that launch was the first one, so launch overhead inflated `seconds_per_cycle` and every hold came out short. On an MI355X the hold measured 6.0-7.0 s (median 6.49 s) with the shader clock steady at about 2385 MHz, and about 4% of calibrations took 13-22 ms instead of 4-7 ms, which gave holds of 1.97 s and 2.35 s; those two runs were the failures. On an MI300X the hold was 4.6-8.6 s, so it stayed above 2 s.

The hold now uses `get_cycles_per_ms()` from `common_utils`, as other distributed tests do (`test_c10d_nccl2.py`, `test_c10d_fault_tolerance.py`). It times `_sleep` with device events and takes the trimmed mean of 10 samples, so first-launch overhead and an occasional slow sample drop out. An untimed warm-up launch before the old calibration also fixed it (20 of 20 class runs on the MI355X, median hold 10.01 s), but it kept a single host-timed sample and duplicated the helper.

Test plan:

```
python test/distributed/test_nccl.py -k NCCLSymmetricMemoryLifecycleTest -v
```

On an MI355X (SPX) at the same base, the unpatched class failed 8 of 160 tests in 20 runs, all with one of the two signatures above. With the change, 40 of 40 class runs passed (320 tests). In 10 more instrumented runs the 10 s hold measured a median 9.95 s; 36 of 40 holds were 9.87-10.40 s, and the other 4 (4.1-9.2 s, still above the 2 s timeout) happened while an unrelated process from another container was running on rank 0's GPU, which slows every calibration launch.

Pull Request resolved: pytorch#203291
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

ci-no-td Do not run TD on this PR ciflow/docker ciflow/h100-symm-mem ciflow/inductor-rocm-mi200 Trigger "inductor" config CI on ROCm MI200 ciflow/inductor-rocm-mi300 Trigger "inductor" config CI on ROCm MI300/MI325 ciflow/periodic-rocm-mi200 Trigger "distributed" config CI on ROCm MI200 ciflow/periodic-rocm-mi300 Trigger "distributed" config CI on ROCm MI300/MI325 ciflow/periodic-rocm-mi350 Trigger "distributed_4gpu" config (only runs distributed tests that need >2GPUs) CI on ROCm MI350 ciflow/rocm-mi200 Trigger "default" config CI on ROCm MI200 ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/rocm-preview Trigger unit tests CI on a preview build of ROCm from theRock on MI300 ciflow/trunk Trigger trunk jobs on your pull request keep-going Don't stop on first failure, keep running tests until the end Merged module: rocm AMD GPU support for Pytorch open source release notes: distributed (c10d) release notes category Reverted skip-pr-sanity-checks 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.

[P1] TestModule: test/distributed/test_nccl.py::NCCLSymmetricMemoryTest

8 participants