Skip to content

[c10d] Fix cudaErrorStreamCaptureMerge with NCCL in nested CUDA graph captures - #191827

Closed
RohitRathore1 wants to merge 1 commit into
pytorch:mainfrom
RohitRathore1:fix-nccl-cudagraph-nested-capture
Closed

RohitRathore1 wants to merge 1 commit into
pytorch:mainfrom
RohitRathore1:fix-nccl-cudagraph-nested-capture

Conversation

@RohitRathore1

@RohitRathore1 RohitRathore1 commented Aug 1, 2026 •

Copy link
Copy Markdown
Collaborator

Using NCCL inside a parent CUDA graph capture and then again inside a nested child capture (e.g. a torch.cond() branch body) fails with cudaErrorStreamCaptureMerge. The communicator's dedicated ncclStream is already capturing into the parent graph, so when the child capture tries to join it through an event wait, CUDA rejects the cross-capture dependency.

getNCCLStream() now compares the current stream's capture id against the one the default nccl stream is bound to. In the common cases (no capture, or same capture) it returns the default stream as before. If the ids differ, it hands out a dedicated stream for that capture from a small per-device pool, and once a capture ends its stream is retired and reused by the next nested capture.

getStreamFromPool() doesn't work here: the default nccl stream comes from that same 32-stream round-robin pool, so it could hand back a stream that is already capturing into the parent graph (cudagraph conditional nodes hit the same problem, see #185836). The pool streams are therefore created raw, honoring TORCH_NCCL_HIGH_PRIORITY and is_high_priority_stream, and owned by an RAII wrapper (modeled on at::cuda::CUDAGraph::OwnedCUDAStream) that destroys them with the process group. Destroying retired streams eagerly instead would be unsafe: pointToPoint() records tensors on the nccl stream via CUDACachingAllocator::recordStream, and a block that outlives the capture would later record an event on the destroyed stream. Pool access is guarded by its own mutex, taken only on the nested-capture path.

Note this only unblocks capture. Instantiating a graph with NCCL inside a conditional body still trips over the event nodes NCCL records for stream syncing, which is a separate limitation.

Fixes #191681

Test Plan

Two new regression tests: test_nccl_cudagraph_nested_capture (NCCL in a parent capture followed by NCCL inside a torch.cond() body) and test_nccl_cudagraph_many_nested_captures (40 conditional nodes, going past the 32-stream pool limit and exercising stream retire/reuse). Ran those plus the full op suite on 2x H200:

python test/distributed/test_c10d_ops_nccl.py -k cudagraph
python test/distributed/test_c10d_ops_nccl.py

All 34 tests pass (2 version-gated skips unrelated to this change).

Written with the help of an AI coding assistant.

@pytorch-bot pytorch-bot Bot added the release notes: distributed (c10d) release notes category label Aug 1, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit f9182d4 with merge base 86b1148 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 3, 2026
@d4l3k
d4l3k requested a review from dolpm August 10, 2026 23:53
@d4l3k

d4l3k commented Aug 10, 2026

Copy link
Copy Markdown
Member

@dolpm can you review?

}
}
bool force_high = getCvarBool(TORCH_NCCL_HIGH_PRIORITY, false);
auto stream = at::cuda::getStreamFromPool(

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.

would this limit you to 32 child graphs? We already had to fix it in cudagraph integration itself #185836

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

aah, correct. getStreamFromPool is limited to 32 streams, so this would break with >32 conditional nodes. Let me switch to cudaStreamCreateWithFlags + getStreamFromExternal like #185836 did, and manage the raw stream lifetime in ncclCaptureStreams_.

@RohitRathore1
RohitRathore1 force-pushed the fix-nccl-cudagraph-nested-capture branch from 49eadf6 to feb957b Compare August 12, 2026 07:48
… captures

Using NCCL inside a parent CUDA graph capture and then again inside a
nested child capture (e.g. a torch.cond() branch body) fails with
cudaErrorStreamCaptureMerge. The communicator's dedicated ncclStream is
already capturing into the parent graph, so when the child capture tries
to join it through an event wait, CUDA rejects the cross-capture
dependency.

getNCCLStream() now compares the current stream's capture id against the
one the default nccl stream is bound to. In the common cases (no capture,
or same capture) it returns the default stream as before. If the ids
differ, it hands out a dedicated stream for that capture from a small
per-device pool, and once a capture ends its stream is retired and reused
by the next nested capture.

getStreamFromPool() doesn't work here: the default nccl stream comes from
that same 32-stream round-robin pool, so it could hand back a stream that
is already capturing into the parent graph (cudagraph conditional nodes
hit the same problem, see pytorch#185836). The pool streams are therefore
created raw, honoring TORCH_NCCL_HIGH_PRIORITY and
is_high_priority_stream, and owned by an RAII wrapper (modeled on
at::cuda::CUDAGraph::OwnedCUDAStream) that destroys them with the process
group. Destroying retired streams eagerly instead would be unsafe:
pointToPoint() records tensors on the nccl stream via
CUDACachingAllocator::recordStream, and a block that outlives the capture
would later record an event on the destroyed stream. Pool access is
guarded by its own mutex, taken only on the nested-capture path.

Note this only unblocks capture. Instantiating a graph with NCCL inside a
conditional body still trips over the event nodes NCCL records for stream
syncing, which is a separate limitation.

Fixes pytorch#191681

Test Plan:

Two new regression tests: test_nccl_cudagraph_nested_capture (NCCL in a
parent capture followed by NCCL inside a torch.cond() body) and
test_nccl_cudagraph_many_nested_captures (40 conditional nodes, going
past the 32-stream pool limit and exercising stream retire/reuse). Ran
those plus the full op suite on 2x H200:

```
python test/distributed/test_c10d_ops_nccl.py -k cudagraph
python test/distributed/test_c10d_ops_nccl.py
```

All 34 tests pass (2 version-gated skips unrelated to this change).
@RohitRathore1
RohitRathore1 force-pushed the fix-nccl-cudagraph-nested-capture branch from feb957b to f9182d4 Compare August 12, 2026 09:39
@RohitRathore1

Copy link
Copy Markdown
Collaborator Author

@ngimel would you mind to give one more look, thanks!

@ngimel

ngimel commented Aug 18, 2026

Copy link
Copy Markdown
Collaborator

@claude review this PR. Pay attention to not breaking or changing existing functionality, be brief, flag only real issues, ignore nits

@claude

claude Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Claude finished @ngimel's task in 24m 56s —— View job


Reviewed the diff — the capture-id dispatch preserves the existing fast path correctly, but the tests never instantiate or replay the graph, so it's not clear the linked issue is actually fixed end-to-end rather than moved to a later error.

Full review

Does this actually fix #191681?

Both new tests end at graph.reset() and deliberately skip instantiate()/replay(), and the PR body says instantiation still fails on the event nodes NCCL records. So from a user's point of view the nested-capture-with-NCCL case goes from failing at capture (cudaErrorStreamCaptureMerge) to failing at instantiate — no working scenario is enabled or tested.

If that's the intent (a prerequisite for a follow-up rather than a user-visible fix), the PR should say so and the "Fixes #191681" should probably become a partial reference. If the intent is to fix the issue, there needs to be a test that instantiates and replays and checks numerics.

Relatedly: the remaining limitation looks like it comes from the same place this PR only half-fixed. ncclEvents_ is still one event per device key, shared across the parent and every nested capture:

// ProcessGroupNCCL.cpp:3786, :4241
syncStream(device, ncclEvents_[key], ncclStream);

The PR gives each capture its own stream but keeps a single event that gets recorded into whichever capture is currently active. Was a per-capture event (parallel to the per-capture stream) tried? That seems like the piece that would make instantiate work, and it would make the fix complete rather than half.

Hot path cost for every user

getNCCLStream() (ProcessGroupNCCL.cpp:6161) issues a cudaStreamGetCaptureInfo on every async collective and every P2P op, including the overwhelmingly common no-capture case. collective() and collectiveCoalesced() have already computed capture_status a few lines above the call site (:3744, :3942), so passing it in and early-returning on CaptureStatus::None keeps the non-capture path at zero added driver calls. pointToPoint()/endCoalescing() compute it slightly later and would need it hoisted. Small per-op, but it's on the critical path for small-message eager collectives, which is exactly where c10d overhead is already scrutinized.

Fix this →

CUDAGuard is created after the capture queries

// :6165-6166  -- queries happen here
auto currentStream = at::cuda::getCurrentCUDAStream(device.index());
auto curInfo = c10::cuda::captureInfoMayInitCtx(currentStream.stream());
...
// :6196  -- guard only set up down here
at::cuda::CUDAGuard gpuGuard(device.index());

This is the exact hazard the existing comment at :3740 warns about ("Guard must be created before currentStreamCaptureStatusMayInitCtx; otherwise, extra CUDA context could be created on device 0"). It matters because endCoalescing() calls getNCCLStream() at :3623 with no outer guard in scope. Move the guard to the top of the function.

Stream priority doesn't match the default NCCL stream

C10_CUDA_CHECK(cudaDeviceGetStreamPriorityRange(&least_priority, &greatest_priority));
C10_CUDA_CHECK(cudaStreamCreateWithPriority(&raw_stream, cudaStreamNonBlocking, greatest_priority));

The default NCCL stream comes from getStreamFromPool(high), whose priority is clamped to PyTorch's max_compile_time_stream_priorities (4), i.e. -3. The raw CUDA range can be wider (e.g. -5), so on such devices a nested-capture stream gets a stricter priority than the stream it stands in for. Use at::cuda::CUDAStream::priority_range() (c10/cuda/CUDAStream.h:162), which applies the same clamp.

Fix this →

Things I checked that look correct

  • Existing behavior is preserved: not capturing, or current stream and NCCL stream in the same capture, both return ncclStreams_.at(key) unchanged. The asyncOp=false path still uses the current stream.
  • Capture ids are unique per capture (CUDAGraph.cpp:590 reads a distinct id for each child), so keying active on them is sound, and the retire sweep runs on every miss, so stale entries can't accumulate.
  • std::vector<OwnedCUDAStream> only needs the move constructor for reallocation, so the deleted move-assignment is fine.
  • The reasoning for not eagerly destroying retired streams (the recordStream in pointToPoint() at :4331) is right. Note the same hazard still exists at PG teardown if a recorded block outlives the process group — narrower, and it matches what CUDAGraph does with its conditional-node streams, so probably acceptable, but it isn't eliminated.

I did not build or run anything; this is a read-only review.

| Branch: `fix-nccl-cudagraph-nested-capture`

t = all_reduce(tensor)
torch.cond(predicate, true_branch, false_branch, (t,))

# The graph is intentionally not instantiated: conditional-node bodies

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.

so this PR doesn't actually allow anything that wasn't allowed before, what's the motivation then?

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.

I agree this is the main oversight with this PR, though, I'm otherwise happy with it.

The agent that did this is aware that cudaGraphInstantiate() will fail due to event record nodes inside of a conditional node in the cuda graph, but it doesn't understand that running with NCCL_GRAPH_MIXING_SUPPORT=0 will remove those event record nodes.

Running the test inside of a separate process with NCCL_GRAPH_MIXING_SUPPORT=0 should work based on my understanding of things.

I will modify this PR myself to actually instantiate and run the graph to make sure that the intended behavior is exercised.

There can come a world in which we don't need NCCL_GRAPH_MIXING_SUPPORT=0, though I won't elaborate further beyond the fact that we can "hoist" external event record and wait nodes outside of the conditional node without affecting correctness. But that world has not come yet today, and it's not clear whose responsibility that is, since NCCL doesn't have access to the full cuda graph topology during stream capture, even though NCCL would be the ideal software to own doing that.

The reason why I would like to merge this work is that I have a pytorch conference poster that mentions that we can use torch.while_loop() to run dropless MoE inside of a cuda graph at inference time (we discussed this last year IIRC). It cannot do that until this code is merged.

galv added a commit that referenced this pull request Oct 9, 2026
Build on PR #191827 to prevent cudaErrorStreamCaptureMerge when NCCL
runs in both an enclosing CUDA graph capture and a conditional-node
body.

There were a few issues with that PR.

First of all, as identified in
#191827 (comment),
the tests did not actually verify that the constructed graphs were
functionally correct by running them. The underlying problem can be
worked around by running nccl with the environment variable setting
NCCL_GRAPH_MIXING_SUPPORT=0.

The original PR #191827 also failed to test that more than 32 nested
torch.cond()'s would work properly, which was the original motivation
for having a separate pool of streams from the normal stream
pool. test_nccl_cudagraph_nested_conditionals now tests this.

There was another problem with the separate pool of streams. This pool
was originally an instance variable of the ProcessGroup
object. Destroying it would destroy the underlying cudaStream_t's, but
recordStream() is run on some tensors as part of ProcessGroupNCCL's
internal implementation. Once these tensors are destroyed, a
cudaEventRecord() will be called on these now deleted cudaStream_t's,
causing undefined behavior if the user has already destroyed the
process group. The obvious solution is to make sure that
cudaStream_t's in this pool are alive for the entirety of the
process. I don't think this will cause any serious mutex contention
problems, since usage of multiple process groups concurrently from
multiple CPU threads is not common these
days. test_cudagraph_stream_outlives_process_group tests that the
behavior is correct.

Test Plan
---------
Built an editable Release configuration with CUDA 13.3 and NCCL 2.30.7
for two A100 GPUs. The full operation suite passed 33 tests with two
existing FP8 skips; both lifetime variants passed. Setting graph mixing
to 1 in the parent deliberately verifies that the fresh-worker fixtures
override it to 0. The toolkit library path lets NVRTC locate its
builtins for the pre-existing complex-tensor comparison test.

```bash
timeout -k 5s 240s env CUDA_VISIBLE_DEVICES=0,1 OMP_NUM_THREADS=1 \
    NCCL_GRAPH_MIXING_SUPPORT=1 \
    TORCH_DIST_USE_NCCL2=0 TORCH_NCCL_WAIT_TIMEOUT_DUMP_MILSEC=0 \
    LD_LIBRARY_PATH="/home/scratch.dgalvez_ent/cuda-installs/cuda-13.3.1/lib64${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" \
    .venv/bin/python test/distributed/test_c10d_ops_nccl.py -v \
    > agent_space/test_nccl_ops_process_wide_pool_with_nvrtc.log 2>&1

timeout -k 5s 180s env CUDA_VISIBLE_DEVICES=0,1 OMP_NUM_THREADS=1 \
    NCCL_GRAPH_MIXING_SUPPORT=1 \
    TORCH_NCCL_WAIT_TIMEOUT_DUMP_MILSEC=0 \
    .venv/bin/python test/distributed/test_c10d_nccl.py \
    ProcessGroupNCCLCaptureStreamTest -v \
    > agent_space/test_stream_lifetime_after_build.log 2>&1

env PYTHONPATH=$PWD/agent_space/lint_deps PATH=$PWD/.venv/bin:$PATH \
    MAX_JOBS=4 spin lint -a -- --skip CLANGTIDY \
    test/distributed/test_c10d_ops_nccl.py \
    test/distributed/test_c10d_nccl.py \
    torch/csrc/distributed/c10d/ProcessGroupNCCL.cpp \
    torch/csrc/distributed/c10d/ProcessGroupNCCL.hpp \
    > agent_space/lint_before_commit.log 2>&1
```

Clang-tidy is excluded because of previously identified findings in
unchanged code. The remaining targeted linters pass.

Prepared with assistance from Codex.

Co-authored-by: Rohit Singh Rathaur <[email protected]>
galv added a commit that referenced this pull request Oct 23, 2026
Build on PR #191827 to prevent cudaErrorStreamCaptureMerge when NCCL
runs in both an enclosing CUDA graph capture and a conditional-node
body.

There were a few issues with that PR.

First of all, as identified in
#191827 (comment),
the tests did not actually verify that the constructed graphs were
functionally correct by running them. The underlying problem can be
worked around by running nccl with the environment variable setting
NCCL_GRAPH_MIXING_SUPPORT=0.

The original PR #191827 also failed to test that more than 32 nested
torch.cond()'s would work properly, which was the original motivation
for having a separate pool of streams from the normal stream
pool. test_nccl_cudagraph_nested_conditionals now tests this.

There was another problem with the separate pool of streams. This pool
was originally an instance variable of the ProcessGroup
object. Destroying it would destroy the underlying cudaStream_t's, but
recordStream() is run on some tensors as part of ProcessGroupNCCL's
internal implementation. Once these tensors are destroyed, a
cudaEventRecord() will be called on these now deleted cudaStream_t's,
causing undefined behavior if the user has already destroyed the
process group. The obvious solution is to make sure that
cudaStream_t's in this pool are alive for the entirety of the
process. I don't think this will cause any serious mutex contention
problems, since usage of multiple process groups concurrently from
multiple CPU threads is not common these
days. test_cudagraph_stream_outlives_process_group tests that the
behavior is correct.

Test Plan
---------
Built an editable Release configuration with CUDA 13.3 and NCCL 2.30.7
for two A100 GPUs. The full operation suite passed 33 tests with two
existing FP8 skips; both lifetime variants passed. Setting graph mixing
to 1 in the parent deliberately verifies that the fresh-worker fixtures
override it to 0. The toolkit library path lets NVRTC locate its
builtins for the pre-existing complex-tensor comparison test.

```bash
timeout -k 5s 240s env CUDA_VISIBLE_DEVICES=0,1 OMP_NUM_THREADS=1 \
    NCCL_GRAPH_MIXING_SUPPORT=1 \
    TORCH_DIST_USE_NCCL2=0 TORCH_NCCL_WAIT_TIMEOUT_DUMP_MILSEC=0 \
    LD_LIBRARY_PATH="/home/scratch.dgalvez_ent/cuda-installs/cuda-13.3.1/lib64${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" \
    .venv/bin/python test/distributed/test_c10d_ops_nccl.py -v \
    > agent_space/test_nccl_ops_process_wide_pool_with_nvrtc.log 2>&1

timeout -k 5s 180s env CUDA_VISIBLE_DEVICES=0,1 OMP_NUM_THREADS=1 \
    NCCL_GRAPH_MIXING_SUPPORT=1 \
    TORCH_NCCL_WAIT_TIMEOUT_DUMP_MILSEC=0 \
    .venv/bin/python test/distributed/test_c10d_nccl.py \
    ProcessGroupNCCLCaptureStreamTest -v \
    > agent_space/test_stream_lifetime_after_build.log 2>&1

env PYTHONPATH=$PWD/agent_space/lint_deps PATH=$PWD/.venv/bin:$PATH \
    MAX_JOBS=4 spin lint -a -- --skip CLANGTIDY \
    test/distributed/test_c10d_ops_nccl.py \
    test/distributed/test_c10d_nccl.py \
    torch/csrc/distributed/c10d/ProcessGroupNCCL.cpp \
    torch/csrc/distributed/c10d/ProcessGroupNCCL.hpp \
    > agent_space/lint_before_commit.log 2>&1
```

Clang-tidy is excluded because of previously identified findings in
unchanged code. The remaining targeted linters pass.

Prepared with assistance from Codex.

Co-authored-by: Rohit Singh Rathaur <[email protected]>
pytorchmergebot pushed a commit that referenced this pull request Oct 24, 2026
…d CUDA graph captures (#199439)

This is built on PR #191827.

There were a few issues with that PR.

First of all, as identified in
#191827 (comment), the tests did not actually verify that the constructed graphs were functionally correct by running them. The underlying problem can be worked around by running nccl with the environment variable setting NCCL_GRAPH_MIXING_SUPPORT=0.

The original PR #191827 also failed to test that more than 32 nested torch.cond()'s would work properly, which was the original motivation for having a separate pool of streams from the normal stream pool. test_nccl_cudagraph_nested_conditionals now tests this.

There was another problem with the separate pool of streams. This pool was originally an instance variable of the ProcessGroup object. Destroying it would destroy the underlying cudaStream_t's, but recordStream() is run on some tensors as part of ProcessGroupNCCL's internal implementation. Once these tensors are destroyed, a cudaEventRecord() will be called on these now deleted cudaStream_t's, causing undefined behavior if the user has already destroyed the process group. The obvious solution is to make sure that cudaStream_t's in this pool are alive for the entirety of the process. I don't think this will cause any serious mutex contention problems, since usage of multiple process groups concurrently from multiple CPU threads is not common these
days. test_cudagraph_stream_outlives_process_group tests that the behavior is correct.

Test Plan
---------
Built an editable Release configuration with CUDA 13.3 and NCCL 2.30.7 for two A100 GPUs. The full operation suite passed 33 tests with two existing FP8 skips; both lifetime variants passed. Setting graph mixing to 1 in the parent deliberately verifies that the fresh-worker fixtures override it to 0. The toolkit library path lets NVRTC locate its builtins for the pre-existing complex-tensor comparison test.

```bash
timeout -k 5s 240s env CUDA_VISIBLE_DEVICES=0,1 OMP_NUM_THREADS=1 \
    NCCL_GRAPH_MIXING_SUPPORT=1 \
    TORCH_DIST_USE_NCCL2=0 TORCH_NCCL_WAIT_TIMEOUT_DUMP_MILSEC=0 \
    LD_LIBRARY_PATH="/home/scratch.dgalvez_ent/cuda-installs/cuda-13.3.1/lib64${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" \
    .venv/bin/python test/distributed/test_c10d_ops_nccl.py -v \
    > agent_space/test_nccl_ops_process_wide_pool_with_nvrtc.log 2>&1

timeout -k 5s 180s env CUDA_VISIBLE_DEVICES=0,1 OMP_NUM_THREADS=1 \
    NCCL_GRAPH_MIXING_SUPPORT=1 \
    TORCH_NCCL_WAIT_TIMEOUT_DUMP_MILSEC=0 \
    .venv/bin/python test/distributed/test_c10d_nccl.py \
    ProcessGroupNCCLCaptureStreamTest -v \
    > agent_space/test_stream_lifetime_after_build.log 2>&1

env PYTHONPATH=$PWD/agent_space/lint_deps PATH=$PWD/.venv/bin:$PATH \
    MAX_JOBS=4 spin lint -a -- --skip CLANGTIDY \
    test/distributed/test_c10d_ops_nccl.py \
    test/distributed/test_c10d_nccl.py \
    torch/csrc/distributed/c10d/ProcessGroupNCCL.cpp \
    torch/csrc/distributed/c10d/ProcessGroupNCCL.hpp \
    > agent_space/lint_before_commit.log 2>&1
```

Clang-tidy is excluded because of previously identified findings in unchanged code. The remaining targeted linters pass.

Prepared with assistance from Codex.

Fixes #191681

Pull Request resolved: #199439
Approved by: https://github.com/ngimel

Co-authored-by: Rohit Singh Rathaur <[email protected]>
@galv

galv commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Fixed by #199439

@galv galv closed this Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

open source release notes: distributed (c10d) release notes category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

6 participants