Skip to content

[cuda graphs] Fix stream pool collision in conditional graph nodes - #185836

Closed
albanD wants to merge 1 commit into
pytorch:mainfrom
albanD:cc_fix_cudagraph_if_node_stream_collision
Closed

albanD wants to merge 1 commit into
pytorch:mainfrom
albanD:cc_fix_cudagraph_if_node_stream_collision

Conversation

@albanD

@albanD albanD commented Jun 1, 2026 •

Copy link
Copy Markdown
Collaborator

Author Notes

This was manual investigation and the simplest solution I could find. The overhead of creating a new stream shouldn't be a problem as this only happens during tracing. Either way, there is no way to get the pool to work if you ever have more than 32 if statement within a single cudagraph as they each need their own stream. Happy to update if I missed something though!
You can look at the test code for minimal repros of the problem.

Agent Notes

begin_capture_to_if_node used getStreamFromPool() to obtain a child
stream for the conditional node capture. The stream pool has exactly 32
streams served round-robin. The parent capture stream (allocated by
torch.cuda.graph() via torch.cuda.Stream()) also comes from this same
pool. After 31 conditional node captures, getStreamFromPool() wraps
around and returns the same stream already in use for the parent capture,
causing cudaStreamBeginCaptureToGraph to fail with
cudaErrorIllegalState.

Fix by creating a dedicated stream via cudaStreamCreateWithFlags +
getStreamFromExternal instead of drawing from the shared pool. The
stream is destroyed in end_capture_to_conditional_node, with cleanup in
reset() for error paths.

Test plan

  • test_cuda_graph_many_if_nodes_across_graphs: 40 separate graphs with one if-node each
  • test_cuda_graph_many_if_nodes_in_one_graph: single graph with 40 if-nodes

@albanD
albanD requested review from Aidyn-A, eqy and syed-ahmed as code owners June 1, 2026 18:20
@pytorch-bot

pytorch-bot Bot commented Jun 1, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure

As of commit 4067b68 with merge base 244fdb3 (image):

NEW FAILURE - The following job has failed:

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

@albanD albanD added the release notes: cuda release notes category label Jun 1, 2026
@ngimel

ngimel commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator

Repro of the original issue

"""
$ python repro.py
[...]
capture 30 ok
Traceback (most recent call last):
  File "/home/dhaziza/gb200_moe_sol/cudagraph_conditional_repro.py", line 27, in <module>
    g.begin_capture_to_if_node(pred)
torch.AcceleratorError: CUDA error: the operation cannot be performed in the present state
Search for `cudaErrorIllegalState' in https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__TYPES.html for more information.
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.
"""
import torch
pred = torch.zeros((), device="cuda", dtype=torch.bool)
x = torch.zeros((), device="cuda")
for i in range(128):
    g = torch.cuda.CUDAGraph()
    with torch.cuda.graph(g):
        g.begin_capture_to_if_node(pred)
        x.add_(1.0)
        g.end_capture_to_conditional_node()
    print(f"capture {i} ok", flush=True)

@ngimel

ngimel commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator

cc @galv

@albanD

albanD commented Jun 1, 2026 •

Copy link
Copy Markdown
Collaborator Author

EDIT: THIS REPRO IS FAKE, it is the same bug as above. Fixing the capture removes the error, see other comments below

Note that I also found another related repro:

import torch

pred = torch.zeros((), device="cuda", dtype=torch.bool)
x = torch.zeros((), device="cuda")
g = torch.cuda.CUDAGraph()
with torch.cuda.graph(g):
    for i in range(40):
        g.begin_capture_to_if_node(pred)
        x.add_(1.0)
        g.end_capture_to_conditional_node()
        print(f"if_node {i} ok", flush=True)

Which is just trying to create >32 if node in a single graph. It was failing with the same error.

@galv

galv commented Jun 1, 2026 •

Copy link
Copy Markdown
Collaborator

I'm alright with this. FYI, cudaStreamCreate() does a take a lock, but it's not like people use more than one thread during stream capture anyway, so you should not worry about that.

The other thing you should be aware of is this: If your conditional node's body graph uses more than one stream (e.g., becuase it has a fork), this workaround won't help. This is because your torch.cuda.Stream() call won't know that it's creating a stream that is going to particpate in stream capture. Thus, you cannot use the trick of creating a brand new cudaStream_t. There is not enough information. So I do think that the proper solution is to get rid of the round-robining over streams at some point, but that's hard and I don't know how to do it properly. Maybe we can just increase the ring buffer from 32 streams to a configurable value instead if anyone encounters this niche issue.

Comment thread aten/src/ATen/cuda/CUDAGraph.cpp Outdated
conditional_graph_capture_ids_.pop();

TORCH_INTERNAL_ASSERT(!conditional_node_raw_streams_.empty());
AT_CUDA_CHECK(cudaStreamDestroy(conditional_node_raw_streams_.top()));

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.

you still need some RAII wrapper for stream, otherwise if capture hit an error you'll never get to this

@albanD

albanD commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator Author

The other option here is to completely disable the stream pool during graph capture.
The benefit is that this would also work for sub-stream that @galv mentions.
Any other downside? Maybe profiler?

@ngimel @galv any strong opinion?

@galv

galv commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator

The other option here is to completely disable the stream pool during graph capture.

The problem with that is that "graph capture" is not some sort of "process global" state. Rather, your current stream in pytorch may or may not be doing stream capture. You can query that via torch.cuda.is_current_stream_capturing(). One cudaStreamEndCapture() is called, all of these streams will no longer be in capture mode.

So you could imagine doing something like this to do your proposal:

class Stream:
    def __init__():
        if torch.cuda.is_current_stream_capturing():
             # don't use pool. Always allocate a fresh new cudaStream_t
        else:
             # do use pool

However, it won't work if someone does something weird like this:

def my_workload_that_is_being_captured():
     assert torch.cuda.is_current_stream_capturing()
     with torch.cuda.stream(torch.cuda.Stream()):
          assert not torch.cuda.is_current_stream_capturing()
          # do some work eagerly. We've considered this at one point for https://github.com/pytorch/pytorch/pull/170590
          torch.cuda.current_stream().synchronize()
          next_stream_to_capture = torch.cuda.Stream() # removing one level of indentation would fix my concern.
     next_stream_to_capture.wait_stream(torch.cuda.current_stream())
     # next_stream_to_capture is now in capture mode. However, it was allocated from the pool of 32 streams! Thus, it could already be capturing!

... Now that I write this out, I suppose what I am worried about is rather niche, and doesn't really affect correctness unless you are using a lot of streams. So maybe your heuristic is fine. Your heuristic also ensures that we don't accidentally stream capture work that we intended to do eagerly, though fortunately that will be caught by torch.cuda.current_stream().synchronize() failing.

Having said that, though, I'm perfectly fine with merging your PR as-is once the RAII issue is fixed since it's unlikely to be harmful. Meanwhile, I might be missing a potential concern with your suggestion.

`begin_capture_to_if_node` used `getStreamFromPool()` to obtain a child
stream for the conditional node capture. The stream pool has exactly 32
streams served round-robin. The parent capture stream (allocated by
`torch.cuda.graph()` via `torch.cuda.Stream()`) also comes from this same
pool. After 31 conditional node captures, `getStreamFromPool()` wraps
around and returns the same stream already in use for the parent capture,
causing `cudaStreamBeginCaptureToGraph` to fail with
`cudaErrorIllegalState`.

Fix by creating a dedicated stream via `cudaStreamCreateWithFlags` +
`getStreamFromExternal` instead of drawing from the shared pool. The
stream is destroyed in `end_capture_to_conditional_node`, with cleanup in
`reset()` for error paths.

Test Plan:

```
python -m pytest test/test_cuda.py -xvs -k "test_cuda_graph_many_if_nodes"
```

Both tests pass: 40 separate graphs with one if-node each, and a single
graph with 40 if-nodes.

Authored by Claude.
@albanD
albanD force-pushed the cc_fix_cudagraph_if_node_stream_collision branch from 215a218 to 4067b68 Compare June 2, 2026 18:43
@albanD

albanD commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

FYI from more investigation @galv , my repro above is fake :/

import torch
from cuda.core import Device, StreamOptions

pred = torch.zeros((), device="cuda", dtype=torch.bool)
x = torch.zeros((), device="cuda")

g = torch.cuda.CUDAGraph()
# Create a stream via cuda.core (not from torch's pool) to avoid the
# capture-stream vs if-node-stream collision shown in foo.py.
dev = Device(0)
dev.set_current()
_owner = dev.create_stream(options=StreamOptions(nonblocking=True))
stream = torch.cuda.Stream(stream_ptr=int(_owner.handle))
with torch.cuda.stream(stream):
    g.capture_begin()
    capture_addr = torch.cuda.current_stream().cuda_stream
    print(f"capture stream: {capture_addr:#x}")
    for i in range(40):
        g.begin_capture_to_if_node(pred)
        if_stream = torch.cuda.current_stream().cuda_stream
        print(f"if_node {i}: stream={if_stream:#x}", flush=True)
        x.add_(1.0)
        g.end_capture_to_conditional_node()
    g.capture_end()

print("\nAll if_nodes captured successfully")

This passes all right without this PR.
So different if node can actually re-use the same stream.

Another approach we could take here is simply to use a single stream for all the if nodes within a given graph?

@albanD

albanD commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

Either way, this PR is a net win compared to the current state so will be landing it now that the RAII is fixed. And will do more improvements as follow up!

@albanD albanD added the ciflow/trunk Trigger trunk jobs on your pull request label Jun 2, 2026
@galv

galv commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator

Another approach we could take here is simply to use a single stream for all the if nodes within a given graph?

The problem with that is that you might be nesting if nodes within each other, so you cannot reuse nested conditionals in this case. To give an idea of when this might happen, we still don't have torch.switch() support #182902 yet, so the only way to get a N-way conditional operation is to nest torch.cond().

I would prefer a more general solution, either creating fresh new streams if the current stream is capturing (as you suggested earlier) or simply doing away with the the fixed size ring buffer of 32 cuda streams (which seems scary becuase it might cause subtle performance changes for users).

@albanD

albanD commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator Author

Looked into it a bit more.
The problem with updating all stream being created is the lifetime. As we would either leak them forever or require a concept the c10::Stream that actually owns the undelying cudaStream_t.

Will go ahead with this PR as is and look for these as follow ups

ROCm failure looks unrelated as this doesn't touch Future.

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: Approvers from one of the following sets are needed:

  • Metamates (8Keep, aditvenk, AmesingFlank, andrewor14, andyanwang, ...)
  • Core Reviewers (mruberry, lezcano, Skylion007, ngimel, peterbell10, ...)
  • Core Maintainers (soumith, gchanan, ezyang, malfet, albanD, ...)
Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@albanD

albanD commented Jun 9, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: trunk / linux-jammy-rocm-py3.10-mi355 / test (distributed, 4, 4, linux.rocm.gpu.gfx950.2)

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

jemitche1 pushed a commit to jemitche1/pytorch that referenced this pull request Jun 13, 2026
…ytorch#185836)

## Author Notes

This was manual investigation and the simplest solution I could find. The overhead of creating a new stream shouldn't be a problem as this only happens during tracing. Either way, there is no way to get the pool to work if you ever have more than 32 if statement within a single cudagraph as they each need their own stream. Happy to update if I missed something though!
You can look at the test code for minimal repros of the problem.

## Agent Notes

`begin_capture_to_if_node` used `getStreamFromPool()` to obtain a child
stream for the conditional node capture. The stream pool has exactly 32
streams served round-robin. The parent capture stream (allocated by
`torch.cuda.graph()` via `torch.cuda.Stream()`) also comes from this same
pool. After 31 conditional node captures, `getStreamFromPool()` wraps
around and returns the same stream already in use for the parent capture,
causing `cudaStreamBeginCaptureToGraph` to fail with
`cudaErrorIllegalState`.

Fix by creating a dedicated stream via `cudaStreamCreateWithFlags` +
`getStreamFromExternal` instead of drawing from the shared pool. The
stream is destroyed in `end_capture_to_conditional_node`, with cleanup in
`reset()` for error paths.

## Test plan

- `test_cuda_graph_many_if_nodes_across_graphs`: 40 separate graphs with one if-node each
- `test_cuda_graph_many_if_nodes_in_one_graph`: single graph with 40 if-nodes
Pull Request resolved: pytorch#185836
Approved by: https://github.com/galv, https://github.com/ngimel
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…ytorch#185836)

## Author Notes

This was manual investigation and the simplest solution I could find. The overhead of creating a new stream shouldn't be a problem as this only happens during tracing. Either way, there is no way to get the pool to work if you ever have more than 32 if statement within a single cudagraph as they each need their own stream. Happy to update if I missed something though!
You can look at the test code for minimal repros of the problem.

## Agent Notes

`begin_capture_to_if_node` used `getStreamFromPool()` to obtain a child
stream for the conditional node capture. The stream pool has exactly 32
streams served round-robin. The parent capture stream (allocated by
`torch.cuda.graph()` via `torch.cuda.Stream()`) also comes from this same
pool. After 31 conditional node captures, `getStreamFromPool()` wraps
around and returns the same stream already in use for the parent capture,
causing `cudaStreamBeginCaptureToGraph` to fail with
`cudaErrorIllegalState`.

Fix by creating a dedicated stream via `cudaStreamCreateWithFlags` +
`getStreamFromExternal` instead of drawing from the shared pool. The
stream is destroyed in `end_capture_to_conditional_node`, with cleanup in
`reset()` for error paths.

## Test plan

- `test_cuda_graph_many_if_nodes_across_graphs`: 40 separate graphs with one if-node each
- `test_cuda_graph_many_if_nodes_in_one_graph`: single graph with 40 if-nodes
Pull Request resolved: pytorch#185836
Approved by: https://github.com/galv, https://github.com/ngimel
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ytorch#185836)

## Author Notes

This was manual investigation and the simplest solution I could find. The overhead of creating a new stream shouldn't be a problem as this only happens during tracing. Either way, there is no way to get the pool to work if you ever have more than 32 if statement within a single cudagraph as they each need their own stream. Happy to update if I missed something though!
You can look at the test code for minimal repros of the problem.

## Agent Notes

`begin_capture_to_if_node` used `getStreamFromPool()` to obtain a child
stream for the conditional node capture. The stream pool has exactly 32
streams served round-robin. The parent capture stream (allocated by
`torch.cuda.graph()` via `torch.cuda.Stream()`) also comes from this same
pool. After 31 conditional node captures, `getStreamFromPool()` wraps
around and returns the same stream already in use for the parent capture,
causing `cudaStreamBeginCaptureToGraph` to fail with
`cudaErrorIllegalState`.

Fix by creating a dedicated stream via `cudaStreamCreateWithFlags` +
`getStreamFromExternal` instead of drawing from the shared pool. The
stream is destroyed in `end_capture_to_conditional_node`, with cleanup in
`reset()` for error paths.

## Test plan

- `test_cuda_graph_many_if_nodes_across_graphs`: 40 separate graphs with one if-node each
- `test_cuda_graph_many_if_nodes_in_one_graph`: single graph with 40 if-nodes
Pull Request resolved: pytorch#185836
Approved by: https://github.com/galv, https://github.com/ngimel
RohitRathore1 added a commit to RohitRathore1/pytorch that referenced this pull request Aug 12, 2026
… 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).
huangjingwei pushed a commit to Ascend/pytorch that referenced this pull request Nov 20, 2026
Co-authored-by: guanam<[email protected]>



# message auto-generated for no-merge-commit merge:
!49725 merge feat/cond-child-stream-external into master

[fix] support dedicated cond streams and external stream operations

Created-by: LyriCheng
Commit-by: guanam
Merged-by: ascend-robot
Description: # 【合入来源】

- [ ] 需求
- [x] 问题单
- [ ] issue/工单
- [ ] 重构优化
- [ ] 资料更新

# 【修改方案】

cond 分支子流取自共享轮转流池,根捕获流同出一池,嵌套足够深时回绕取到一条正在捕获的流,`AclmdlRICaptureToModelRIBegin` 报 107027。

1. 分支子流改为 `AclrtCreateStreamWithConfig` 自建,经 `getStreamFromExternal` 包装,由 `OwnedNPUStream` RAII 持有,分支体结束与 `reset()` 时销毁。标志位沿用池流的 `ACL_STREAM_FAST_LAUNCH | ACL_STREAM_FAST_SYNC`。改的是 `begin_capture_to_conditional_node()`,IF 与 WHILE 共用该入口,两者同时生效。
2. 自建流经包装后即外部流,因此解除图捕获路径上的外部流校验:`capture_begin/capture_end`、捕获状态与 capture id 查询、`NPUEvent::record/block`、`LaunchRecordEventTask/LaunchWaitEventTask`、`NPUStream::query/synchronize`、`record_stream`、HCCL/LCCL 集合通信的当前流。

外部流的任务队列行为不变:保持 `repo.reset()`,逐流队列的拒绝检查保留,`emptyAllNPUStream()` 不增加外部流遍历。

# 【资料变更】

更新 `ExternalStream` 的支持范围与生命周期约束:`record_stream` 关联的 Tensor 和异步拷贝使用的 pinned Host buffer 在释放时仍可能记录事件,仅在释放前同步一次不足以保证可以销毁裸流。

# 【接口变更】

无签名变更。外部流的逐流队列、task group、super kernel scope、callback 与 report 限制保留。

# 【注意点】

- **不支持 `ExternalStream + PER_STREAM_QUEUE=1`**,已写入 `ExternalStream` 文档。
- 已 rebase 到含 [!49379](https://gitcode.com/Ascend/pytorch/merge_requests/49379)(torch.while_loop)的 master。该 MR 已提供 `set_conditional_handle_for_current_node()` 与 WHILE 的句柄跟踪,本 MR 不再重复实现。
- 对标上游 [pytorch/pytorch#185836](https://github.com/pytorch/pytorch/pull/185836)(已合入上游主线)。该设计有一处上游已登记、但修法尚未合入的缺陷:分支体内对 pinned Host 内存做 `non_blocking` 拷贝,且该张量在分支体结束之后才释放时会崩溃。**本 MR 不引入未合入的修法,该问题作为已知遗留问题随本 MR 合入**,规避办法是分支体内不使用 pinned 内存的异步拷贝,或保证相关张量在分支体结束前释放。不含 cond 的图捕获不创建子流,不受影响。

# 【功能验证】

双卡 NPU:默认队列流测试 26/26,HCCL/LCCL 2/2,关闭任务队列的直接下发 6/6,回归时间窗内 native 日志 ERROR 0。合并目标分支后的完整 lintrunner 检查通过。cond 场景需支持 conditional model capture 的硬件,单独验证。

# 【CheckList】

- [x] 代码注释完备,正确记录错误日志
- [x] 代码实现进行了返回值、空指针等校验
- [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等
- [ ] PR持续集成流水线(CI)执行通过,代码检查无异常


See merge request: Ascend/pytorch!49725
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: cuda release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants