Skip to content

[c10d] Fix cudaErrorStreamCaptureMerge with ProcessGroupNCCL in nested CUDA graph captures - #199439

Closed
galv wants to merge 7 commits into
mainfrom
fix-nccl-stream-merge
Closed

galv wants to merge 7 commits into
mainfrom
fix-nccl-stream-merge

Conversation

@galv

@galv galv commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

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.

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

cc @gujinghui @PenghuiCheng @XiaobingSuper @jianyuh @jgong5 @mingfeima @sanchitintel @ashokei @jingxu10 @min-jean-cho @yanbing-j @Guobing-Chen @Xia-Weiwen @snadampal @mcarilli @ezyang @eellison @penguinwu @BoyuanFeng

@galv
galv requested review from d4l3k, fduwjj and kapilsh as code owners October 2, 2026 05:23
@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/199439

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

✅ No Failures

As of commit 1ec31a0 with merge base 8bf2072 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot pytorch-bot Bot added the release notes: distributed (c10d) release notes category label Oct 2, 2026
@galv

galv commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

@claude review this PR. Note that you already did a review here: #191827 (comment)

@claude

claude Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

Claude finished @galv's task in 2m 34s —— View job


The fix only reaches the nccl-legacy backend, so the default "nccl" backend (nccl2) still has the bug from #191681; I recommend Needs Discussion before merging.

Full review

PR Review: #199439

Summary

The PR adds ProcessGroupNCCL::getNCCLStream, which picks a stream from a process-wide pool whenever the default NCCL stream belongs to a different capture than the current stream. Without it, NCCL inside a conditional-node body hits cudaErrorStreamCaptureMerge. The PR also adds replay-checked tests for one level of nesting, for 40 sequential and 40 nested torch.conds, and for streams outliving the process group. Of the earlier concerns, the process-wide pool fixes the stream-lifetime problem, and the tests now replay the graph and check values. The open problems are below: the default backend is not fixed, replay depends on a non-default NCCL env var, and idle-stream selection has a race.

Code Quality

  • The default nccl backend is not fixed. _register_builtin_nccl_backend (torch/distributed/distributed_c10d.py:1020) maps "nccl" to ProcessGroupNCCL2 unless TORCH_DIST_USE_NCCL2=0. nccl2 still sends every async op to one internal_stream_ per PG (nccl2/ProcessGroupNCCLUtils.cpp:522-536, getOperationStream), so it will hit the same capture merge. Every new test uses nccl-legacy (in test_c10d_nccl.py, NCCL_BACKEND = "nccl-legacy"), so CI never runs the default path. Either apply the same fix to ProcessGroupNCCL2::getOperationStream, or drop Fixes #191681 and say the fix is legacy-only.

  • Replay only works with a non-default NCCL setting. The PR description says correct replay needs NCCL_GRAPH_MIXING_SUPPORT=0, and both test classes force it in setUp. With NCCL's default of 1, users will now capture without an error and may then get wrong results or hangs at replay. That is arguably worse than the current clear capture error. At minimum:

    • document the requirement;
    • ideally, TORCH_WARN_ONCE or TORCH_CHECK in getNCCLStream when it takes the pool path and getCvarString({"NCCL_GRAPH_MIXING_SUPPORT"}, ...) is not "0".

    If NCCL itself can't support graph mixing together with conditional bodies, the PR should say why, or link the NCCL issue.

  • Priority is recomputed instead of copied. ProcessGroupNCCL.cpp:6226-6227 recomputes highPriority from options_ and the cvar, duplicating the logic at lines 3244 and 6268. Using defaultStream.priority() both as the pool key and as the argument to cudaStreamCreateWithPriority guarantees the pool stream matches the default stream. It also removes the separate cudaDeviceGetStreamPriorityRange and plain cudaStreamCreateWithFlags branches.

Thread Safety

  • Two captures can be handed the same idle stream (ProcessGroupNCCL.cpp:6230-6243). An "idle" stream (CaptureStatus::None) is picked under poolMutex, but it only joins the caller's capture later, in syncStream, after the lock is released. The pool is now process-wide and shared across PGs. So two threads doing nested captures at the same time, under thread_local or relaxed capture mode, can both receive the same idle stream. The second syncStream then merges the two captures, which is the error this PR is fixing. The per-PG pool in [c10d] Fix cudaErrorStreamCaptureMerge with NCCL in nested CUDA graph captures #191827 had a smaller version of the same window. Fix options:
    • make the stream join the capture while the lock is held, by recording an event on the current stream and waiting on it from the chosen stream inside the critical section;
    • or track ownership explicitly, e.g. a capture_id -> stream map that is cleared when the stream's capture status returns to None.

Testing

  • The 40-sequential test doesn't test what its docstring says. test_nccl_cudagraph_many_nested_captures claims to "Replay more conditional nodes than the 32-stream pool can hold". But its 40 torch.conds are sequential: each body capture ends before the next begins, so one idle pool stream is reused 40 times. Only test_nccl_cudagraph_nested_conditionals holds more than 32 captures open at once. Either fix the docstring or drop this test, since num_cond_nodes=1 plus the nested test cover the paths.
  • The lifetime test may pass even without the fix (low confidence). test_cudagraph_stream_outlives_process_group relies on a cudaEventRecord against a destroyed stream misbehaving visibly. That is undefined behavior and may pass silently on the old per-PG pool. Confirm it actually fails on [c10d] Fix cudaErrorStreamCaptureMerge with NCCL in nested CUDA graph captures #191827's version, for example under compute-sanitizer, or note that it is a best-effort regression test.
  • Test classes are split and duplicated. ProcessGroupNCCLCaptureStreamTest (test_c10d_nccl.py) and ProcessGroupNCCLConditionalGraphTest (test_c10d_ops_nccl.py) have identical setUp, world-size, skip decorators and init boilerplate, in different files. The same is true of _test_nested_capture and test_nccl_cudagraph_nested_conditionals within one file. Put them in one class with a shared init helper. Each one also spawns fresh processes, which torch/distributed/CLAUDE.md discourages for expensive multi-GPU tests. That is justified here by NCCL caching the env var, but it is a reason to keep the number of test methods small.

Recommendation

Needs Discussion

The PR fixes only nccl-legacy, yet claims to fix #191681. Correct replay depends on an env var users won't know to set. Also resolve the idle-stream race before relying on the process-wide pool.

@galv galv added ciflow/trunk Trigger trunk jobs on your pull request ci-no-td Do not run TD on this PR labels Oct 2, 2026
@galv

galv commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator Author

Replay only works with a non-default NCCL setting.

Any code that doesn't set NCCL_GRAPH_MIXING_SUPPORT=0 will fail with an error at cudaGraphInstantiate() time, so this isn't a concern. An explicit warning about event record and wait nodes not being supported inside of conditional nodes will be part of the error message. This work also allows us to use child graph nodes in pytorch with NCCL as well, which I may be interested in for other reasons. Non-conditional child graphs are allowed to use event record nodes internally. I don't think this is a concern.

@galv

galv commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

I was unaware of the legacy nccl vs nccl2 distinction, which apparently showed up at the end of August, after the original PR. I will need to take some time to understand that.

@ngimel

ngimel commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Default backend is nccl2 now, so it's ok for fixes to only go into nccl2 backend

@galv galv added the module: cuda graphs Ability to capture and then replay streams of CUDA kernels label Oct 2, 2026
@janeyx99 janeyx99 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Oct 6, 2026
@galv
galv force-pushed the fix-nccl-stream-merge branch from daa69e8 to 95ee8e9 Compare October 9, 2026 21:03
galv and others added 4 commits October 22, 2026 23:24
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]>
Remove race condition by joining stream before returning it from
getNCCLStreamForCapture().

Copy priority of defaultStream rather than reconstructing it.

Remove redundant test code.

Parameterize over nccl-legacy and nccl2, though I may just remove the
nccl-legacy support if it isn't in use any more.
@galv
galv force-pushed the fix-nccl-stream-merge branch from 95ee8e9 to f6485b4 Compare October 23, 2026 07:20
@pytorch-bot pytorch-bot Bot added the module: mkldnn Related to Intel IDEEP or oneDNN (a.k.a. mkldnn) integration label Oct 23, 2026
Previous changes were just too hard to read.
@galv
galv force-pushed the fix-nccl-stream-merge branch from f6485b4 to 2e43a0b Compare October 23, 2026 07:28
@galv

galv commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

@RohitRathore1 @d4l3k and @ngimel this is good for review now.

@galv
galv requested review from RohitRathore1 and ngimel October 23, 2026 07:30
@galv

galv commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator Author

@claude review this PR

@galv galv changed the title [c10d] Fix cudaErrorStreamCaptureMerge with ProcessGroupNCL in nested CUDA graph captures [c10d] Fix cudaErrorStreamCaptureMerge with ProcessGroupNCCL in nested CUDA graph captures Oct 23, 2026
@claude

claude Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Claude finished @galv's task in 1m 57s —— View job


The pool logic looks correct and both earlier maintainer requests are in (flat map, isCaptureContext). I recommend Request Changes for two reasons: test_cudagraph_stream_outlives_process_group never exercises the recordStream lifetime problem it is meant to guard, and the fast-path check queries the same stream's capture state three times.

Full review

PR Review: #199439

Summary

On nccl2, ProcessGroupNCCL::getOperationStream now sends async collectives to a stream from a process-wide pool when internal_stream_ is already in a different active capture. It also adds replay-checked tests for one nested capture, for 40 nested torch.conds, and for multiple process group generations. Both maintainer comments are addressed: the pool uses ska::flat_hash_map, and the fast path uses CUDACachingAllocator::isCaptureContext, as suggested in #197857. The earlier concerns about the backend, the env var, priority and the idle-stream race are all resolved. Three issues remain, listed below.

Testing

  • test_cudagraph_stream_outlives_process_group does not test what its comments say. The only recordStream call in nccl2/ is the cross-device local_outputs case in all_gather (nccl2/ProcessGroupNCCL.cpp:1196). The test uses batch_isend_irecv on same-device tensors, so del send, recv never makes an event record against a pool stream. With a per-PG pool that is destroyed in ~ProcessGroupNCCL, the test would most likely still pass. So the "Tensor deallocation must remain safe after process group destruction" comment, and the rationale at ProcessGroupNCCLUtils.cpp:124-126, do not describe what nccl2 actually does. Pick one:

    • make the test hit a path that really records a use of the pool stream, for example a Tensor.record_stream(...) inside the conditional body;
    • or rename the test and fix both comments to say what it covers: reusing pool streams across PG generations and both priority keys.

    The process-lifetime pool is still a reasonable design, since a WorkNCCL holds the raw cudaStream_t. The point is that the stated reason and the regression test should match.

Code Quality

  • The same capture state is queried three times (ProcessGroupNCCLUtils.cpp:618-626). isCaptureContext(device) already returns whether getCurrentCUDAStream(device), which is current_stream, is capturing (CUDACachingAllocator.cpp:4084-4091, and the default in CUDACachingAllocator.h:171). So || !isStreamCapturingMayInitCtx(current_stream.stream()) can never change the result, and captureInfoMayInitCtx(current_stream) then asks a third time. Drop the middle check:
    if (C10_LIKELY(!c10::cuda::CUDACachingAllocator::isCaptureContext(device))) {
      return sync_stream(internal_stream);
    }
    Also, getStreamForThisCapture re-queries current_stream, which the caller already did; passing cur_info.id in removes that query too.
  • The sync_stream lambda is written twice (ProcessGroupNCCLUtils.cpp:138-142 and :610-614). Either have getStreamForThisCapture take the caller's lambda as a callable (the sync must happen inside the lock, so it can't simply return the stream), or define it once as a file-local helper taking (event, from, to).
  • The comments in getStreamForThisCapture need cleanup (ProcessGroupNCCLUtils.cpp:118-126, 151-157):

Recommendation

Request Changes

The lifetime regression test and its comment claim coverage the code doesn't provide; fix the test or rename it. The redundant capture check is a one-line cleanup on the path this PR is specifically meant to keep fast.

@galv

galv commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator Author

claude comments were right. Pushed some small fixes.

@ngimel

ngimel commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator

Pretty sure submodule updates are unintended

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

Don't land with submodule updates

Restore the PR base revisions after stale local submodule checkouts were
staged into the review-fix commit. Align the local checkouts as well to
avoid reintroducing these unrelated dependency changes.

Test Plan:
```bash
spin quicklint -- -a third_party/flash-attention third_party/ideep
git diff --cached --check --ignore-submodules=none
```
Verified both pins against the base side of PR #199439's diff.

Prepared with assistance from an AI coding assistant.
@galv

galv commented Oct 24, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

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

Labels

ci-no-td Do not run TD on this PR ciflow/trunk Trigger trunk jobs on your pull request Merged module: cuda graphs Ability to capture and then replay streams of CUDA kernels module: mkldnn Related to Intel IDEEP or oneDNN (a.k.a. mkldnn) integration 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