Repository navigation
Conversation
🔗 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 FailureAs of commit 4067b68 with merge base 244fdb3 ( NEW FAILURE - The following job has failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
Repro of the original issue |
|
cc @galv |
|
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. |
|
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. |
| conditional_graph_capture_ids_.pop(); | ||
|
|
||
| TORCH_INTERNAL_ASSERT(!conditional_node_raw_streams_.empty()); | ||
| AT_CUDA_CHECK(cudaStreamDestroy(conditional_node_raw_streams_.top())); |
There was a problem hiding this comment.
you still need some RAII wrapper for stream, otherwise if capture hit an error you'll never get to this
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 So you could imagine doing something like this to do your proposal: However, it won't work if someone does something weird like this: ... 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 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.
215a218 to
4067b68
Compare
|
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. Another approach we could take here is simply to use a single stream for all the if nodes within a given graph? |
|
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! |
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). |
|
Looked into it a bit more. 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 |
Merge failedReason: Approvers from one of the following sets are needed:
|
|
@pytorchbot merge -i |
Merge startedYour 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 |
…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
…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
…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
… 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).
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
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_nodeusedgetStreamFromPool()to obtain a childstream for the conditional node capture. The stream pool has exactly 32
streams served round-robin. The parent capture stream (allocated by
torch.cuda.graph()viatorch.cuda.Stream()) also comes from this samepool. After 31 conditional node captures,
getStreamFromPool()wrapsaround and returns the same stream already in use for the parent capture,
causing
cudaStreamBeginCaptureToGraphto fail withcudaErrorIllegalState.Fix by creating a dedicated stream via
cudaStreamCreateWithFlags+getStreamFromExternalinstead of drawing from the shared pool. Thestream is destroyed in
end_capture_to_conditional_node, with cleanup inreset()for error paths.Test plan
test_cuda_graph_many_if_nodes_across_graphs: 40 separate graphs with one if-node eachtest_cuda_graph_many_if_nodes_in_one_graph: single graph with 40 if-nodes