Skip to content

Fix C++ tests silently not running on ROCm CI - #199440

Closed
pablo-garay wants to merge 4 commits into
pytorch:mainfrom
ROCm:jeffdaily/rocm-cpp-gtests-run
Closed

pablo-garay wants to merge 4 commits into
pytorch:mainfrom
ROCm:jeffdaily/rocm-cpp-gtests-run

Conversation

@pablo-garay

@pablo-garay pablo-garay commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

ROCm CI reports its C++ gtests as passing while running none of them: every cpp/* test in the ROCm shard logs shows 0 items.

pytest-cpp skips a binary whose --help fails, pytest exits 5, and run_test.py treats 5 as success. On ROCm the build/bin binaries fail --help with exit 127: their RUNPATH is build/lib under the build job's /__w workspace, which does not exist in the ROCm test container.

  • run_test.py: when a C++ test exits 5, fail it if the binary's --help fails, and print the error. Binaries that start but define no tests still pass.
  • test.sh: put torch/lib on LD_LIBRARY_PATH for the two build/bin runs, test_aten and static_runtime_test.

test_api, test_jit and test_cpp_rpc run from the installed torch/bin and failed --help with "libaotriton_v2.so.0.14.1: cannot open shared object file": test.sh symlinked libtorch* into torch/bin, so libtorch_hip.so loaded through the symlink had $ORIGIN = torch/bin and could not find its dependencies in torch/lib. Those symlinks predate the $ORIGIN/../lib RUNPATH from #136627; this removes them for test_libtorch, the distributed C++ tests and test_rpc (test_aot_compilation and test_vulkan keep theirs, since those binaries never got that RUNPATH).

Test Plan:

# in the ROCm test image: exit 127; with torch/lib on LD_LIBRARY_PATH: 8 tests collected
build/bin/basic --help
# fails now with "--help failed with exit code 127"; zero-test binaries still pass
CPP_TESTS_DIR=/tmp/fakebin python test/run_test.py --cpp -i cpp/broken_test
CPP_TESTS_DIR=build/bin python test/run_test.py --cpp -i cpp/c10_ConstexprCrc_test cpp/c10_StreamGuard_test cpp/basic

On gfx950 all 19 shard-1 C++ tests pass when they actually run.

Authored with the assistance of Claude (AI).

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

ROCm CI has not been running any of its C++ gtests while reporting them as passing. The test binaries are linked with a RUNPATH of build/lib in the build job's workspace, /__w/pytorch/pytorch, but _rocm-test.yml runs the tests in a container that mounts the workspace at /var/lib/jenkins/workspace. There libtorch, libtorch_cpu, libtorch_hip and libc10 cannot be found, so every binary exits 127 before main(). pytest-cpp recognizes a gtest by running it with --help, so it collects nothing, pytest exits 5 ("no tests ran"), and run_test.py maps exit code 5 to success. The symlinks test_aten creates next to the binaries do not help, because nothing puts that directory on the loader path. CUDA is unaffected only because its tests run in the same /__w workspace the build used.

test.sh now puts the installed torch/lib on LD_LIBRARY_PATH for the ATen and libtorch C++ runs, as test_libtorch_profiler and test_inductor_aoti_cpp already do. The loader searches LD_LIBRARY_PATH before RUNPATH, so the binaries start wherever the build ran.

run_test.py now treats a C++ test that collects nothing as a failure, so a binary that cannot start fails the job instead of passing. To make that possible it skips the `-m serial` pass for C++ tests: pytest-cpp items carry no markers, so that pass always collected nothing and was the one place exit code 5 was expected for a C++ test.

Moving the ROCm test jobs into the build's workspace, as the no-DinD work does, would also fix the loader path for those jobs, but not the silent zero-collection, and not for the jobs that stay on DinD.

Test Plan:

With the binaries from a ROCm CI build artifact, in a ROCm CI image where /__w does not exist, and LD_LIBRARY_PATH set to the SDK lib directory as CI sets it: `ldd build/bin/basic` reports libtorch, libtorch_cpu, libtorch_hip and libc10 not found, `build/bin/basic --help` exits 127, and pytest-cpp collects nothing. With the installed torch/lib prepended to LD_LIBRARY_PATH, `--help` exits 0 and pytest-cpp collects all 8 tests:

```
LD_LIBRARY_PATH=$TORCH_LIB_DIR:$SDK_LIB python -m pytest build/bin/basic --collect-only -q
```

A binary that cannot start now fails instead of passing, under both the parallel schedule and the serial one ROCm runners use (before this change both exit 0):

```
CPP_TESTS_DIR=/tmp/fakebin python test/run_test.py --cpp -i cpp/broken_test
PYTORCH_TEST_RUN_EVERYTHING_IN_SERIAL=1 CPP_TESTS_DIR=/tmp/fakebin python test/run_test.py --cpp -i cpp/broken_test
```

Real gtests still pass, with one pytest run per test instead of two:

```
CPP_TESTS_DIR=build/bin python test/run_test.py --cpp --verbose -i cpp/basic cpp/Dict_test
PYTORCH_TEST_RUN_EVERYTHING_IN_SERIAL=1 CPP_TESTS_DIR=build/bin python test/run_test.py --cpp --verbose -i cpp/basic cpp/Dict_test
```

On gfx950, the ATen and libtorch C++ tests that ROCm default shard 1 runs, all of which collected nothing on ROCm CI, pass under the fixed run_test.py (19 binaries; test_api needs TORCH_CPP_TEST_MNIST_PATH for its two MNIST tests, as CI sets it):

```
PYTORCH_TEST_RUN_EVERYTHING_IN_SERIAL=1 CPP_TESTS_DIR=build/bin python test/run_test.py --cpp --verbose --keep-going -i cpp/Dict_test cpp/apply_utils_test cpp/atest cpp/basic cpp/broadcast_test cpp/cpu_generator_test cpp/dlconvertor_test cpp/extension_backend_test cpp/lazy_tensor_test cpp/legacy_vmap_test cpp/native_test cpp/operators_test cpp/scalar_tensor_test cpp/scalar_test cpp/static_runtime_test cpp/tensor_iterator_test cpp/test_api cpp/undefined_tensor_test cpp/wrapdim_test
```

```
lintrunner --skip CLANGTIDY test/run_test.py .ci/pytorch/test.sh
```

This change was developed with the assistance of an AI assistant (Claude).
Review follow-up. Failing every C++ test that collects nothing was too broad: c10_StreamGuard_test and c10_ConstexprCrc_test define no tests on any platform, and the Windows libtorch job runs every binary in torch/test, so they would have turned Windows red. run_test.py now treats exit code 5 from a C++ test as a failure only when the binary's own --help also fails, and prints that output, so the loader error that pytest-cpp swallows shows up in the CI log. The serial-pass skip is no longer needed and is reverted.

In test.sh the loader path is now scoped to the two runs that use build/bin binaries, test_aten and static_runtime_test, instead of being exported for everything after test_libtorch. Binaries under the installed torch/bin carry an $ORIGIN RUNPATH and do not need it.

Test Plan:

On gfx950, in both the parallel and the serial schedule:

```
CPP_TESTS_DIR=/tmp/fakebin python test/run_test.py --cpp -i cpp/broken_test
PYTORCH_TEST_RUN_EVERYTHING_IN_SERIAL=1 CPP_TESTS_DIR=/tmp/fakebin python test/run_test.py --cpp -i cpp/broken_test
CPP_TESTS_DIR=build/bin python test/run_test.py --cpp --verbose -i cpp/c10_ConstexprCrc_test cpp/c10_StreamGuard_test cpp/basic
PYTORCH_TEST_RUN_EVERYTHING_IN_SERIAL=1 CPP_TESTS_DIR=build/bin python test/run_test.py --cpp --verbose -i cpp/c10_ConstexprCrc_test cpp/c10_StreamGuard_test cpp/basic
```

The unrunnable binary fails and prints "--help failed with exit code 127"; the two zero-test binaries pass, and basic runs its 8 tests.

```
lintrunner -a test/run_test.py .ci/pytorch/test.sh
```

This change was developed with the assistance of an AI assistant (Claude).
@pablo-garay
pablo-garay requested a review from a team as a code owner October 2, 2026 05:42
@pytorch-bot pytorch-bot Bot added the module: rocm AMD GPU support for Pytorch label Oct 2, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ 4 Pending, 3 Unrelated Failures

As of commit 1dba898 with merge base 38cca96 (image):

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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

@jithunnair-amd jithunnair-amd added ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category labels Oct 2, 2026
soulitzer added a commit that referenced this pull request Oct 2, 2026
The first day of shadow runs on pytorch/pytorch (347 runs, 01:53-14:10 UTC on
2026-10-02) found three problems.

1. Ten eligible PRs were never analyzed. The labeler adds several labels to a
new PR in the same second, and every label event queued a run in the same
per-PR concurrency group. GitHub keeps one pending run per group, so a later
label's run replaced the pending `open source` run and then skipped itself.
For example, "Remove unused parameters in autograd" got five runs at
07:12:28: both eligible runs were cancelled and the other three skipped. Now
only entry events (the `open source` label and ready_for_review) share the
per-PR group; every other event gets its own group keyed by run id. Entry
events still run one at a time per PR.

2. Four runs (#199436, #199440, #199463, #199484) failed with Claude Code's
`error_max_structured_output_retries`: the worker produced no schema-valid
output within the default 5 attempts. Many successful runs also needed a retry
(4 turns instead of 2). MAX_STRUCTURED_OUTPUT_RETRIES is now 25. Every attempt
is a turn, so --max-turns goes from 5 to 30. A failed run cost about $0.02 per
attempt, so --max-budget-usd goes from 0.50 to 1.50. When the SDK errors like
this, the action writes no execution log and leaves `execution_file` empty.
Stage 2c then opened `Path("")`, which is `.`, and recorded
"IsADirectoryError" as the processing error. It now records "Claude action
wrote no execution log".

3. Eight runs failed the evidence-excerpt check. One cut a long line short (the
case that started this change, #199425). Five skipped lines
inside an excerpt (#197857, #199447, #199471, #199472, #199497). Two turned an
unchanged context line, which also appeared in the `@@` hunk header, into a
fake `-`/`+` pair (#199453, #199461). The worker prompt now says to keep
excerpts short by choosing a shorter run of adjacent lines, never by skipping
or cutting lines, and never to turn unchanged lines or hunk-header text into
changed lines. The validator stays strict: a mismatched excerpt can't be told
apart from an invented one, and a failed run falls back to human triage. The
replay below shows the wording fixes the hunk-header pattern but only partly
helps the other two, so a structural follow-up is still needed.

The same change is being made to pytorch/pytorch and pytorch/ciforge.

Test Plan:

```
cd scripts/auto_pr_triage && python -m unittest discover -p 'test_*.py'
actionlint .github/workflows/auto-pr-triage.yml
```

The worker was replayed locally (claude-sonnet-4-6, --effort low, the CI
flags and the old 5-attempt limits) on the exact inputs of three failed runs:
each run's patch at its analyzed head_sha and CODEOWNERS at its workflow_sha.
Outputs were checked with validate_result. Evidence-excerpt failures:

| PR (pattern)                         | old worker.md | new worker.md |
|--------------------------------------|---------------|---------------|
| #199461 (fake -/+ from hunk header)  | 2/3           | 0/3           |
| #197857 (skipped comment lines)      | 4/4           | 2/3           |
| #199425 (cut a long comment line)    | 2/5           | 3/5           |

The remaining failures still drop two comment lines from the middle of an
excerpt (#197857) or stop a long comment line at the end of a sentence
(#199425).

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

ghstack-source-id: d937117
Pull-Request-resolved: #199428
soulitzer added a commit that referenced this pull request Oct 2, 2026
The first day of shadow runs on pytorch/pytorch (347 runs, 01:53-14:10 UTC on
2026-10-02) found three problems.

1. Ten eligible PRs were never analyzed. The labeler adds several labels to a
new PR in the same second, and every label event queued a run in the same
per-PR concurrency group. GitHub keeps one pending run per group, so a later
label's run replaced the pending `open source` run and then skipped itself.
For example, "Remove unused parameters in autograd" got five runs at
07:12:28: both eligible runs were cancelled and the other three skipped. Now
only entry events (the `open source` label and ready_for_review) share the
per-PR group; every other event gets its own group keyed by run id. Entry
events still run one at a time per PR.

2. Four runs (#199436, #199440, #199463, #199484) failed with Claude Code's
`error_max_structured_output_retries`: the worker produced no schema-valid
output within the default 5 attempts. Many successful runs also needed a retry
(4 turns instead of 2). MAX_STRUCTURED_OUTPUT_RETRIES is now 25. Every attempt
is a turn, so --max-turns goes from 5 to 30. A failed run cost about $0.02 per
attempt, so --max-budget-usd goes from 0.50 to 1.50. When the SDK errors like
this, the action writes no execution log and leaves `execution_file` empty.
Stage 2c then opened `Path("")`, which is `.`, and recorded
"IsADirectoryError" as the processing error. It now records "Claude action
wrote no execution log".

3. Eight runs failed the evidence-excerpt check. One cut a long line short (the
case that started this change, #199425). Five skipped lines inside an excerpt
(#197857, #199447, #199471, #199472, #199497). Two turned an unchanged line,
which also appeared in the `@@` hunk header, into a fake `-`/`+` pair (#199453,
#199461).

The worker prompt still asks for whole, adjacent lines, and now also says never
to cut or skip lines or to turn unchanged lines or hunk-header text into
changed lines. A local replay showed that wording alone does not stop the
model from dropping comment lines or stopping a long line at the end of a
sentence, so the validator is relaxed as a safety net. Every excerpt line must
still come from the file's patch, in patch order, but lines may be skipped in
between, and a line may stop early if it keeps some text after its marker.
Every character shown still comes from the patch, so the model still cannot
add text; what we give up is that an excerpt may show two lines without the
lines between them. A fake `-`/`+` pair is still rejected, because it claims an
unchanged line changed.

We also considered having the model cite patch line ranges and extracting the
excerpt in the controller, which removes these failures by construction. The
relaxed check fixes almost all of them with a much smaller change.

The same change is being made to pytorch/pytorch and pytorch/ciforge.

Test Plan:

```
cd scripts/auto_pr_triage && python -m unittest discover -p 'test_*.py'
actionlint .github/workflows/auto-pr-triage.yml
```

The worker was replayed locally (claude-sonnet-4-6, --effort low, the CI
flags and the old 5-attempt limits) on the exact inputs of the eight runs that
failed the excerpt check: each run's patch at its analyzed head_sha and
CODEOWNERS at its workflow_sha. Outputs were checked with validate_result.

| Prompt and check                     | Excerpt failures |
|--------------------------------------|------------------|
| old worker.md, old check (3 PRs)     | 8/12             |
| new worker.md, old check (3 PRs)     | 5/11             |
| new worker.md, relaxed check (8 PRs) | 1/21             |

Re-checking the eight original CI outputs with the relaxed check, six pass.
The two that still fail (#199453, #199461), and the one replay failure
(#199453), are all the fake `-`/`+` pair, which stays rejected. An extra
prompt example aimed at that pattern made it worse in a replay, so it is not
included.

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

ghstack-source-id: 546c754
Pull-Request-resolved: #199428
pytorchmergebot pushed a commit that referenced this pull request Oct 2, 2026
…99428)

The first day of shadow runs on pytorch/pytorch (347 runs, 01:53-14:10 UTC on
2026-10-02) found three problems.

1. Ten eligible PRs were never analyzed. The labeler adds several labels to a
new PR in the same second, and every label event queued a run in the same
per-PR concurrency group. GitHub keeps one pending run per group, so a later
label's run replaced the pending `open source` run and then skipped itself.
For example, "Remove unused parameters in autograd" got five runs at
07:12:28: both eligible runs were cancelled and the other three skipped. Now
only entry events (the `open source` label and ready_for_review) share the
per-PR group; every other event gets its own group keyed by run id. Entry
events still run one at a time per PR.

2. Four runs (#199436, #199440, #199463, #199484) failed with Claude Code's
`error_max_structured_output_retries`: the worker produced no schema-valid
output within the default 5 attempts. Many successful runs also needed a retry
(4 turns instead of 2). MAX_STRUCTURED_OUTPUT_RETRIES is now 25. Every attempt
is a turn, so --max-turns goes from 5 to 30. A failed run cost about $0.02 per
attempt, so --max-budget-usd goes from 0.50 to 1.50. When the SDK errors like
this, the action writes no execution log and leaves `execution_file` empty.
Stage 2c then opened `Path("")`, which is `.`, and recorded
"IsADirectoryError" as the processing error. It now records "Claude action
wrote no execution log".

3. Eight runs failed the evidence-excerpt check. One cut a long line short (the
case that started this change, #199425). Five skipped lines inside an excerpt
(#197857, #199447, #199471, #199472, #199497). Two turned an unchanged line,
which also appeared in the `@@` hunk header, into a fake `-`/`+` pair (#199453,
#199461).

The worker prompt still asks for whole, adjacent lines, and now also says never
to cut or skip lines or to turn unchanged lines or hunk-header text into
changed lines. A local replay showed that wording alone does not stop the
model from dropping comment lines or stopping a long line at the end of a
sentence, so the validator is relaxed as a safety net. Every excerpt line must
still come from the file's patch, in patch order, but lines may be skipped in
between, and a line may stop early if it keeps some text after its marker.
Every character shown still comes from the patch, so the model still cannot
add text; what we give up is that an excerpt may show two lines without the
lines between them. A fake `-`/`+` pair is still rejected, because it claims an
unchanged line changed.

We also considered having the model cite patch line ranges and extracting the
excerpt in the controller, which removes these failures by construction. The
relaxed check fixes almost all of them with a much smaller change.

The same change is being made to pytorch/pytorch and pytorch/ciforge.

Test Plan:

```
cd scripts/auto_pr_triage && python -m unittest discover -p 'test_*.py'
actionlint .github/workflows/auto-pr-triage.yml
```

The worker was replayed locally (claude-sonnet-4-6, --effort low, the CI
flags and the old 5-attempt limits) on the exact inputs of the eight runs that
failed the excerpt check: each run's patch at its analyzed head_sha and
CODEOWNERS at its workflow_sha. Outputs were checked with validate_result.

| Prompt and check                     | Excerpt failures |
|--------------------------------------|------------------|
| old worker.md, old check (3 PRs)     | 8/12             |
| new worker.md, old check (3 PRs)     | 5/11             |
| new worker.md, relaxed check (8 PRs) | 1/21             |

Re-checking the eight original CI outputs with the relaxed check, six pass.
The two that still fail (#199453, #199461), and the one replay failure
(#199453), are all the fake `-`/`+` pair, which stays rejected. An extra
prompt example aimed at that pattern made it worse in a replay, so it is not
included.

This PR was authored with an AI assistant (Claude Code).
Pull Request resolved: #199428
Approved by: https://github.com/janeyx99
@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Oct 2, 2026
On ROCm, test_api, test_jit and test_cpp_rpc fail `--help` with "libaotriton_v2.so.0.14.1: cannot open shared object file". test.sh symlinks libtorch* into torch/bin, so the test binary loads libtorch_hip.so through that symlink, glibc sets its $ORIGIN to torch/bin, and its own dependencies in torch/lib (AOTriton, and before that libcaffe2_nvrtc.so, which pytorch#106712 patched with one more symlink) are not found.

The symlinks were added in pytorch#62797 because the installed test binaries had no RUNPATH; pytorch#136627 gave them $ORIGIN/../lib, so they are no longer needed. This removes them for test_libtorch, the distributed C++ tests and test_rpc. test_aot_compilation and test_vulkan keep theirs: test_mobile_nnc, aot_model_compiler_test and the vulkan tests never got that RUNPATH.

Test Plan:

With the torch/bin and torch/lib from this PR's mi350 wheel and CI's LD_LIBRARY_PATH: with the symlinks, `test_api --help` exits 127 with the CI error; without them, test_api, test_jit, test_lazy, test_cpp_rpc and the c10d store and process-group tests start, pytest-cpp collects 1024 and 588 tests from test_api and test_jit, and FunctionalTest.Conv1d (the libcaffe2_nvrtc.so case) passes on gfx950:

```
torch/bin/test_api --gtest_filter='FunctionalTest.Conv1d*'
python -m pytest torch/bin/test_api --collect-only -q
```

This change was developed with the assistance of an AI assistant (Claude).
@pytorch-bot

pytorch-bot Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

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

@jeffdaily jeffdaily added ciflow/trunk Trigger trunk jobs on your pull request and removed ciflow/trunk Trigger trunk jobs on your pull request labels Oct 2, 2026
jeffdaily
jeffdaily previously approved these changes Oct 2, 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.

ROCm now runs the installed C++ tests instead of collecting nothing: on mi350, test_api, test_jit, static_runtime_test, test_cpp_rpc and the store tests ran and passed, and the CUDA default shards that run test_libtorch stayed green without the torch/bin symlinks. The remaining red is the dynamo_wrapped test_autograd failure seen on other PRs.

Drafted with AI assistance (Claude); reviewed by me.

@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 2 checks: pull / linux-jammy-py3.11-clang21 / test (dynamo_wrapped, 5, 6, mt-l-x86iavx512-8-64), trunk / dynamo-unittest / dynamo-test (3.11) / test (dynamo_wrapped, 7, 7, mt-l-x86iavx512-8-64)

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

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorch-bot

pytorch-bot Bot commented Oct 5, 2026

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

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

Approving the reland: cpp/test_aoti_inference is dropped from test_inductor_aoti_cpp until #199776 packages its library and data. On 1dba898 the CUDA inductor_cpp_wrapper shards are green, and on mi350 test_api, test_jit, static_runtime_test and test_cpp_rpc ran and passed. The remaining red is dynamo_wrapped, the unstable inductor_aoti_fallback shards, and an image-pull lint failure.

Drafted with AI assistance (Claude); reviewed by me.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

pytorchmergebot pushed a commit that referenced this pull request Oct 6, 2026
…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 #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`](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 #168480
Authored with the assistance of an AI coding assistant.

Co-authored by @chinmaydk99

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

Co-authored-by: Chinmay Kuchinad <[email protected]>
pytorchmergebot pushed a commit that referenced this pull request Oct 7, 2026
…rseForward (#199922)

`RNNTest.BidirectionalLSTMReverseForward_CUDA` in `cpp/test_api` fails consistently on ROCm MI210 (`linux-jammy-rocm-py3.11-mi200`, original run plus 2 reruns), e.g. https://github.com/pytorch/pytorch/actions/runs/37407982276/job/112113883767:

```
test/cpp/api/rnn.cpp:544: Failure
Expected equality of these values:
  std::get<0>(std::get<1>(bi_output))[1][0][0].item<float>()
    Which is: -0.240088522
  std::get<0>(std::get<1>(reverse_output))[0][0][0].item<float>()
    Which is: -0.240088537
```

**Root cause:** the ROCm 6.3 upgrade (#142152) switched the per-timestep output comparison in this test to `ASSERT_NEAR` with `tolerance = 1e-5`, but left the final hidden/cell state (`h_n`/`c_n`) checks as exact `ASSERT_EQ`. Those checks never actually ran on ROCm because `test_api` collected 0 tests there until #199440 ("Fix C++ tests silently not running on ROCm CI") landed. Now that it runs, `h_n` differs by ~1.5e-8 (float32 rounding). The reverse-direction `h_n` is the same value as the last reverse output the loop already compares with tolerance, so the exact check is inconsistent within the test itself.

**Fix:** use `ASSERT_NEAR` with the test's existing `tolerance` for the `h_n` and `c_n` checks. No new tolerance is introduced; CPU and CUDA behavior is unaffected beyond allowing the same 1e-5 slack already used for outputs.

**Testing:** the observed difference (1.5e-8) is well within the existing 1e-5 tolerance; relying on ROCm CI for the C++ test run.

This PR was authored with the help of an AI assistant.

Pull Request resolved: #199922
Approved by: https://github.com/jeffdaily
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…torch#199428)

The first day of shadow runs on pytorch/pytorch (347 runs, 01:53-14:10 UTC on
2026-10-02) found three problems.

1. Ten eligible PRs were never analyzed. The labeler adds several labels to a
new PR in the same second, and every label event queued a run in the same
per-PR concurrency group. GitHub keeps one pending run per group, so a later
label's run replaced the pending `open source` run and then skipped itself.
For example, "Remove unused parameters in autograd" got five runs at
07:12:28: both eligible runs were cancelled and the other three skipped. Now
only entry events (the `open source` label and ready_for_review) share the
per-PR group; every other event gets its own group keyed by run id. Entry
events still run one at a time per PR.

2. Four runs (pytorch#199436, pytorch#199440, pytorch#199463, pytorch#199484) failed with Claude Code's
`error_max_structured_output_retries`: the worker produced no schema-valid
output within the default 5 attempts. Many successful runs also needed a retry
(4 turns instead of 2). MAX_STRUCTURED_OUTPUT_RETRIES is now 25. Every attempt
is a turn, so --max-turns goes from 5 to 30. A failed run cost about $0.02 per
attempt, so --max-budget-usd goes from 0.50 to 1.50. When the SDK errors like
this, the action writes no execution log and leaves `execution_file` empty.
Stage 2c then opened `Path("")`, which is `.`, and recorded
"IsADirectoryError" as the processing error. It now records "Claude action
wrote no execution log".

3. Eight runs failed the evidence-excerpt check. One cut a long line short (the
case that started this change, pytorch#199425). Five skipped lines inside an excerpt
(pytorch#197857, pytorch#199447, pytorch#199471, pytorch#199472, pytorch#199497). Two turned an unchanged line,
which also appeared in the `@@` hunk header, into a fake `-`/`+` pair (pytorch#199453,
pytorch#199461).

The worker prompt still asks for whole, adjacent lines, and now also says never
to cut or skip lines or to turn unchanged lines or hunk-header text into
changed lines. A local replay showed that wording alone does not stop the
model from dropping comment lines or stopping a long line at the end of a
sentence, so the validator is relaxed as a safety net. Every excerpt line must
still come from the file's patch, in patch order, but lines may be skipped in
between, and a line may stop early if it keeps some text after its marker.
Every character shown still comes from the patch, so the model still cannot
add text; what we give up is that an excerpt may show two lines without the
lines between them. A fake `-`/`+` pair is still rejected, because it claims an
unchanged line changed.

We also considered having the model cite patch line ranges and extracting the
excerpt in the controller, which removes these failures by construction. The
relaxed check fixes almost all of them with a much smaller change.

The same change is being made to pytorch/pytorch and pytorch/ciforge.

Test Plan:

```
cd scripts/auto_pr_triage && python -m unittest discover -p 'test_*.py'
actionlint .github/workflows/auto-pr-triage.yml
```

The worker was replayed locally (claude-sonnet-4-6, --effort low, the CI
flags and the old 5-attempt limits) on the exact inputs of the eight runs that
failed the excerpt check: each run's patch at its analyzed head_sha and
CODEOWNERS at its workflow_sha. Outputs were checked with validate_result.

| Prompt and check                     | Excerpt failures |
|--------------------------------------|------------------|
| old worker.md, old check (3 PRs)     | 8/12             |
| new worker.md, old check (3 PRs)     | 5/11             |
| new worker.md, relaxed check (8 PRs) | 1/21             |

Re-checking the eight original CI outputs with the relaxed check, six pass.
The two that still fail (pytorch#199453, pytorch#199461), and the one replay failure
(pytorch#199453), are all the fake `-`/`+` pair, which stays rejected. An extra
prompt example aimed at that pattern made it worse in a replay, so it is not
included.

This PR was authored with an AI assistant (Claude Code).
Pull Request resolved: pytorch#199428
Approved by: https://github.com/janeyx99
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
ROCm CI reports its C++ gtests as passing while running none of them: every `cpp/*` test in the ROCm shard logs shows `0 items`.

pytest-cpp skips a binary whose `--help` fails, pytest exits 5, and run_test.py treats 5 as success. On ROCm the build/bin binaries fail `--help` with exit 127: their RUNPATH is build/lib under the build job's /__w workspace, which does not exist in the ROCm test container.

- run_test.py: when a C++ test exits 5, fail it if the binary's `--help` fails, and print the error. Binaries that start but define no tests still pass.
- test.sh: put torch/lib on LD_LIBRARY_PATH for the two build/bin runs, test_aten and static_runtime_test.

`test_api`, `test_jit` and `test_cpp_rpc` run from the installed torch/bin and failed `--help` with "libaotriton_v2.so.0.14.1: cannot open shared object file": test.sh symlinked libtorch* into torch/bin, so libtorch_hip.so loaded through the symlink had `$ORIGIN` = torch/bin and could not find its dependencies in torch/lib. Those symlinks predate the `$ORIGIN/../lib` RUNPATH from pytorch#136627; this removes them for test_libtorch, the distributed C++ tests and test_rpc (test_aot_compilation and test_vulkan keep theirs, since those binaries never got that RUNPATH).

Test Plan:

```
# in the ROCm test image: exit 127; with torch/lib on LD_LIBRARY_PATH: 8 tests collected
build/bin/basic --help
# fails now with "--help failed with exit code 127"; zero-test binaries still pass
CPP_TESTS_DIR=/tmp/fakebin python test/run_test.py --cpp -i cpp/broken_test
CPP_TESTS_DIR=build/bin python test/run_test.py --cpp -i cpp/c10_ConstexprCrc_test cpp/c10_StreamGuard_test cpp/basic
```

On gfx950 all 19 shard-1 C++ tests pass when they actually run.

Authored with the assistance of Claude (AI).

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

Co-authored-by: Jeff Daily <[email protected]>
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
This reverts commit 5db6f55.

Reverted pytorch#199440 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#199440 (comment)))
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
ROCm CI reports its C++ gtests as passing while running none of them: every `cpp/*` test in the ROCm shard logs shows `0 items`.

pytest-cpp skips a binary whose `--help` fails, pytest exits 5, and run_test.py treats 5 as success. On ROCm the build/bin binaries fail `--help` with exit 127: their RUNPATH is build/lib under the build job's /__w workspace, which does not exist in the ROCm test container.

- run_test.py: when a C++ test exits 5, fail it if the binary's `--help` fails, and print the error. Binaries that start but define no tests still pass.
- test.sh: put torch/lib on LD_LIBRARY_PATH for the two build/bin runs, test_aten and static_runtime_test.

`test_api`, `test_jit` and `test_cpp_rpc` run from the installed torch/bin and failed `--help` with "libaotriton_v2.so.0.14.1: cannot open shared object file": test.sh symlinked libtorch* into torch/bin, so libtorch_hip.so loaded through the symlink had `$ORIGIN` = torch/bin and could not find its dependencies in torch/lib. Those symlinks predate the `$ORIGIN/../lib` RUNPATH from pytorch#136627; this removes them for test_libtorch, the distributed C++ tests and test_rpc (test_aot_compilation and test_vulkan keep theirs, since those binaries never got that RUNPATH).

Test Plan:

```
# in the ROCm test image: exit 127; with torch/lib on LD_LIBRARY_PATH: 8 tests collected
build/bin/basic --help
# fails now with "--help failed with exit code 127"; zero-test binaries still pass
CPP_TESTS_DIR=/tmp/fakebin python test/run_test.py --cpp -i cpp/broken_test
CPP_TESTS_DIR=build/bin python test/run_test.py --cpp -i cpp/c10_ConstexprCrc_test cpp/c10_StreamGuard_test cpp/basic
```

On gfx950 all 19 shard-1 C++ tests pass when they actually run.

Authored with the assistance of Claude (AI).

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

Co-authored-by: Jeff Daily <[email protected]>
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 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]>
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…rseForward (pytorch#199922)

`RNNTest.BidirectionalLSTMReverseForward_CUDA` in `cpp/test_api` fails consistently on ROCm MI210 (`linux-jammy-rocm-py3.11-mi200`, original run plus 2 reruns), e.g. https://github.com/pytorch/pytorch/actions/runs/37407982276/job/112113883767:

```
test/cpp/api/rnn.cpp:544: Failure
Expected equality of these values:
  std::get<0>(std::get<1>(bi_output))[1][0][0].item<float>()
    Which is: -0.240088522
  std::get<0>(std::get<1>(reverse_output))[0][0][0].item<float>()
    Which is: -0.240088537
```

**Root cause:** the ROCm 6.3 upgrade (pytorch#142152) switched the per-timestep output comparison in this test to `ASSERT_NEAR` with `tolerance = 1e-5`, but left the final hidden/cell state (`h_n`/`c_n`) checks as exact `ASSERT_EQ`. Those checks never actually ran on ROCm because `test_api` collected 0 tests there until pytorch#199440 ("Fix C++ tests silently not running on ROCm CI") landed. Now that it runs, `h_n` differs by ~1.5e-8 (float32 rounding). The reverse-direction `h_n` is the same value as the last reverse output the loop already compares with tolerance, so the exact check is inconsistent within the test itself.

**Fix:** use `ASSERT_NEAR` with the test's existing `tolerance` for the `h_n` and `c_n` checks. No new tolerance is introduced; CPU and CUDA behavior is unaffected beyond allowing the same 1e-5 slack already used for outputs.

**Testing:** the observed difference (1.5e-8) is well within the existing 1e-5 tolerance; relying on ROCm CI for the C++ test run.

This PR was authored with the help of an AI assistant.

Pull Request resolved: pytorch#199922
Approved by: https://github.com/jeffdaily
desertfire added a commit that referenced this pull request Oct 22, 2026
Fixes  #199776.

`test_aoti_inference` has collected no tests in CI since #164277. That change
moved model generation from build time to test time and dropped the rebuild
in the test job, but the binary still depended on its build directory,
`build/test_aoti_inference`, which the build job does not ship (only `build/lib`
and `build/bin` are): `libaoti_custom_class.so` was built there, the generated
data is written there, and `compile_model.py` loaded the library from its cwd,
which only worked because that cwd was the same directory. The binary failed
to start, pytest-cpp skipped it, and run_test.py counted "no tests collected"
as a pass; #199440 made that a failure and dropped the test from
`test_inductor_aoti_cpp`.

`aoti_custom_class` is now built into the default `build/lib`, which is shipped
and already on the binary's RUNPATH. Its path is passed to the test as
`AOTI_CUSTOM_CLASS_LIB` and from there to `compile_model.py` on the command
line. The test creates the data directory before generating into it. The
remaining build-time paths (data directory, test sources) still resolve in the
test job because CI builds and tests in the same workspace path; making them
fully relocatable (relative to the binary or via an env var) is a larger
change that only matters if the test moves to a job where those paths differ.

`test_inductor_aoti_cpp` also runs in the CPU `inductor_aoti_fallback` job, so
`test.py` now skips its CUDA-only models when CUDA is unavailable, and the
files-exist check only requires `script_model_cuda.pt` in CUDA/ROCm builds;
otherwise every test process would regenerate all the data on CPU.

Test Plan:

Built with the test enabled on macOS arm64 (CPU). Apple ld rejects
`-Wl,--no-as-needed`, so that flag was dropped locally for this build only. To
mirror a CI test job, `build/test_aoti_inference` was moved aside before
running, so the test had to create it and generate all data itself:

```
BUILD_AOT_INDUCTOR_TEST=1 pip install -e . -v --no-build-isolation
mv build/test_aoti_inference /tmp/
cd test && ../build/bin/test_aoti_inference
```

All 9 CPU tests pass (with the previous commit's consts cpp fix). CUDA tests and
the run_test.py path were not run locally; CI covers them via the a10g
`inductor_cpp_wrapper` job.

This PR was authored with the assistance of Claude (AI).

ghstack-source-id: e244a0a
Pull-Request: #201699
desertfire added a commit that referenced this pull request Oct 22, 2026
Fixes  #199776.

`test_aoti_inference` has collected no tests in CI since #164277. That change
moved model generation from build time to test time and dropped the rebuild
in the test job, but the binary still depended on its build directory,
`build/test_aoti_inference`, which the build job does not ship (only `build/lib`
and `build/bin` are): `libaoti_custom_class.so` was built there, the generated
data is written there, and `compile_model.py` loaded the library from its cwd,
which only worked because that cwd was the same directory. The binary failed
to start, pytest-cpp skipped it, and run_test.py counted "no tests collected"
as a pass; #199440 made that a failure and dropped the test from
`test_inductor_aoti_cpp`.

`aoti_custom_class` is now built into the default `build/lib`, which is shipped
and already on the binary's RUNPATH. Its path is passed to the test as
`AOTI_CUSTOM_CLASS_LIB` and from there to `compile_model.py` on the command
line. The test creates the data directory before generating into it. The
remaining build-time paths (data directory, test sources) still resolve in the
test job because CI builds and tests in the same workspace path; making them
fully relocatable (relative to the binary or via an env var) is a larger
change that only matters if the test moves to a job where those paths differ.

`test_inductor_aoti_cpp` also runs in the CPU `inductor_aoti_fallback` job, so
`test.py` now skips its CUDA-only models when CUDA is unavailable, and the
files-exist check only requires `script_model_cuda.pt` when a GPU is visible,
matching the generators; otherwise every test process would regenerate all the
data on CPU, or on a CUDA build without a visible GPU.

Test Plan:

Built with the test enabled on macOS arm64 (CPU). Apple ld rejects
`-Wl,--no-as-needed`, so that flag was dropped locally for this build only. To
mirror a CI test job, `build/test_aoti_inference` was moved aside before
running, so the test had to create it and generate all data itself:

```
BUILD_AOT_INDUCTOR_TEST=1 pip install -e . -v --no-build-isolation
mv build/test_aoti_inference /tmp/
cd test && ../build/bin/test_aoti_inference
```

All 9 CPU tests pass (with the previous commit's consts cpp fix). CUDA tests and
the run_test.py path were not run locally; CI covers them via the a10g
`inductor_cpp_wrapper` job.

This PR was authored with the assistance of Claude (AI).

ghstack-source-id: 6b2be4d
Pull-Request: #201699
desertfire added a commit that referenced this pull request Oct 26, 2026
Fixes  #199776.

`test_aoti_inference` has collected no tests in CI since #164277. That change
moved model generation from build time to test time and dropped the rebuild
in the test job, but the binary still depended on its build directory,
`build/test_aoti_inference`, which the build job does not ship (only `build/lib`
and `build/bin` are): `libaoti_custom_class.so` was built there, the generated
data is written there, and `compile_model.py` loaded the library from its cwd,
which only worked because that cwd was the same directory. The binary failed
to start, pytest-cpp skipped it, and run_test.py counted "no tests collected"
as a pass; #199440 made that a failure and dropped the test from
`test_inductor_aoti_cpp`.

`aoti_custom_class` is now built into the default `build/lib`, which is shipped
and already on the binary's RUNPATH. Its path is passed to the test as
`AOTI_CUSTOM_CLASS_LIB` and from there to `compile_model.py` on the command
line. The test creates the data directory before generating into it. The
remaining build-time paths (data directory, test sources) still resolve in the
test job because CI builds and tests in the same workspace path; making them
fully relocatable (relative to the binary or via an env var) is a larger
change that only matters if the test moves to a job where those paths differ.

`test_inductor_aoti_cpp` also runs in the CPU `inductor_aoti_fallback` job, so
`test.py` now skips its CUDA-only models when CUDA is unavailable, and the
files-exist check only requires `script_model_cuda.pt` when a GPU is visible,
matching the generators; otherwise every test process would regenerate all the
data on CPU, or on a CUDA build without a visible GPU.

Test Plan:

Built with the test enabled on macOS arm64 (CPU). Apple ld rejects
`-Wl,--no-as-needed`, so that flag was dropped locally for this build only. To
mirror a CI test job, `build/test_aoti_inference` was moved aside before
running, so the test had to create it and generate all data itself:

```
BUILD_AOT_INDUCTOR_TEST=1 pip install -e . -v --no-build-isolation
mv build/test_aoti_inference /tmp/
cd test && ../build/bin/test_aoti_inference
```

All 9 CPU tests pass (with the previous commit's consts cpp fix). CUDA tests and
the run_test.py path were not run locally; CI covers them via the a10g
`inductor_cpp_wrapper` job.

This PR was authored with the assistance of Claude (AI).

ghstack-source-id: 572755e
Pull-Request: #201699
desertfire added a commit that referenced this pull request Oct 26, 2026
Fixes  #199776.

`test_aoti_inference` has collected no tests in CI since #164277. That change
moved model generation from build time to test time and dropped the rebuild
in the test job, but the binary still depended on its build directory,
`build/test_aoti_inference`, which the build job does not ship (only `build/lib`
and `build/bin` are): `libaoti_custom_class.so` was built there, the generated
data is written there, and `compile_model.py` loaded the library from its cwd,
which only worked because that cwd was the same directory. The binary failed
to start, pytest-cpp skipped it, and run_test.py counted "no tests collected"
as a pass; #199440 made that a failure and dropped the test from
`test_inductor_aoti_cpp`.

`aoti_custom_class` is now built into the default `build/lib`, which is shipped
and already on the binary's RUNPATH. Its path is passed to the test as
`AOTI_CUSTOM_CLASS_LIB` and from there to `compile_model.py` on the command
line. The test creates the data directory before generating into it. The
remaining build-time paths (data directory, test sources) still resolve in the
test job because CI builds and tests in the same workspace path; making them
fully relocatable (relative to the binary or via an env var) is a larger
change that only matters if the test moves to a job where those paths differ.

`test_inductor_aoti_cpp` also runs in the CPU `inductor_aoti_fallback` job, so
`test.py` now skips its CUDA-only models when CUDA is unavailable, and the
files-exist check only requires `script_model_cuda.pt` when a GPU is visible,
matching the generators; otherwise every test process would regenerate all the
data on CPU, or on a CUDA build without a visible GPU.

Test Plan:

Built with the test enabled on macOS arm64 (CPU). Apple ld rejects
`-Wl,--no-as-needed`, so that flag was dropped locally for this build only. To
mirror a CI test job, `build/test_aoti_inference` was moved aside before
running, so the test had to create it and generate all data itself:

```
BUILD_AOT_INDUCTOR_TEST=1 pip install -e . -v --no-build-isolation
mv build/test_aoti_inference /tmp/
cd test && ../build/bin/test_aoti_inference
```

All 9 CPU tests pass (with the previous commit's consts cpp fix). CUDA tests and
the run_test.py path were not run locally; CI covers them via the a10g
`inductor_cpp_wrapper` job.

This PR was authored with the assistance of Claude (AI).

ghstack-source-id: 78e521f
Pull-Request: #201699
pytorchmergebot pushed a commit that referenced this pull request Oct 26, 2026
…1699)

Fixes  #199776.

`test_aoti_inference` has collected no tests in CI since #164277. That change
moved model generation from build time to test time and dropped the rebuild
in the test job, but the binary still depended on its build directory,
`build/test_aoti_inference`, which the build job does not ship (only `build/lib`
and `build/bin` are): `libaoti_custom_class.so` was built there, the generated
data is written there, and `compile_model.py` loaded the library from its cwd,
which only worked because that cwd was the same directory. The binary failed
to start, pytest-cpp skipped it, and run_test.py counted "no tests collected"
as a pass; #199440 made that a failure and dropped the test from
`test_inductor_aoti_cpp`.

`aoti_custom_class` is now built into the default `build/lib`, which is shipped
and already on the binary's RUNPATH. Its path is passed to the test as
`AOTI_CUSTOM_CLASS_LIB` and from there to `compile_model.py` on the command
line. The test creates the data directory before generating into it. The
remaining build-time paths (data directory, test sources) still resolve in the
test job because CI builds and tests in the same workspace path; making them
fully relocatable (relative to the binary or via an env var) is a larger
change that only matters if the test moves to a job where those paths differ.

`test_inductor_aoti_cpp` also runs in the CPU `inductor_aoti_fallback` job, so
`test.py` now skips its CUDA-only models when CUDA is unavailable, and the
files-exist check only requires `script_model_cuda.pt` when a GPU is visible,
matching the generators; otherwise every test process would regenerate all the
data on CPU, or on a CUDA build without a visible GPU.

Test Plan:

Built with the test enabled on macOS arm64 (CPU). Apple ld rejects
`-Wl,--no-as-needed`, so that flag was dropped locally for this build only. To
mirror a CI test job, `build/test_aoti_inference` was moved aside before
running, so the test had to create it and generate all data itself:

```
BUILD_AOT_INDUCTOR_TEST=1 pip install -e . -v --no-build-isolation
mv build/test_aoti_inference /tmp/
cd test && ../build/bin/test_aoti_inference
```

All 9 CPU tests pass (with the previous commit's consts cpp fix). CUDA tests and
the run_test.py path were not run locally; CI covers them via the a10g
`inductor_cpp_wrapper` job.

This PR was authored with the assistance of Claude (AI).
Pull Request resolved: #201699
Approved by: https://github.com/angelayi
pytorchmergebot pushed a commit that referenced this pull request Oct 28, 2026
…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 #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`](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 #168480
Authored with the assistance of an AI coding assistant.

Co-authored by @chinmaydk99

Pull Request resolved: #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 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]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triaged This is a label only to be used by the auto triage bot ci-no-td Do not run TD on this PR ciflow/inductor ciflow/trunk Trigger trunk jobs on your pull request Merged module: rocm AMD GPU support for Pytorch open source Reverted topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants