# 运行时错误：CUDA错误：流正在捕获时不允许操作（streamCaptureInvalidated）

- **ID:** `cuda/stream-capture-invalid-scope`
- **领域:** cuda
- **类别:** runtime_error
- **错误码:** `cudaErrorStreamCaptureInvalidated`
- **验证级别:** ai_generated
- **修复率:** 81%

## 根因

流上正在进行CUDA图捕获，但尝试了捕获期间无效的操作（例如内存分配、主机端同步），导致捕获失效。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| CUDA 12.0 | active | — | — |
| PyTorch 2.1.0 | active | — | — |
| NVIDIA Driver 535.129.03 | active | — | — |

## 解决方案

1. ```
   Move all memory allocations and host-device synchronization outside the capture scope. Example: pre-allocate tensors before calling torch.cuda.CUDAGraph.begin_capture(), and use torch.cuda.synchronize() only after capture ends.
   ```
2. ```
   Use cudaStreamBeginCapture with cudaStreamCaptureModeGlobal to allow more operations, but ensure no host-side blocking calls occur during capture. In PyTorch, wrap the capture in a context manager that defers any print or sleep calls.
   ```

## 无效尝试

- **** — This disables cuDNN heuristics but does not fix the capture violation; the error will reoccur if capture is attempted again. (92% 失败率)
- **** — Thread configuration is unrelated to capture validity; the error is about operations allowed during capture. (98% 失败率)
