CUDA 流卫士¶
注意
这是一个原型功能,这意味着它处于早期反馈和测试阶段,其组件可能会发生变化。
概述¶
此模块引入了 CUDA Sanitizer,这是一个用于检测在不同流上运行的内核之间的同步错误的工具。
它存储对张量的访问信息,以确定它们是否同步。在 Python 程序中启用它并在检测到可能的数据竞争时,将打印详细警告并退出程序。
可以通过导入此模块并调用 enable_cuda_sanitizer()
或导出 TORCH_CUDA_SANITIZER
环境变量来启用它。
用法¶
以下是一个 PyTorch 中简单同步错误的示例
import torch
a = torch.rand(4, 2, device="cuda")
with torch.cuda.stream(torch.cuda.Stream()):
torch.mul(a, 5, out=a)
a
张量在默认流上初始化,并在没有同步方法的情况下在新流上修改。这两个内核将在同一个张量上并发运行,这可能会导致第二个内核在第一个内核能够写入数据之前读取未初始化的数据,或者第一个内核可能会覆盖第二个内核结果的一部分。当在命令行上使用
TORCH_CUDA_SANITIZER=1 python example_error.py
CSAN 打印以下输出
============================
CSAN detected a possible data race on tensor with data pointer 139719969079296
Access by stream 94646435460352 during kernel:
aten::mul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
writing to argument(s) self, out, and to the output
With stack trace:
File "example_error.py", line 6, in <module>
torch.mul(a, 5, out=a)
...
File "pytorch/torch/cuda/_sanitizer.py", line 364, in _handle_kernel_launch
stack_trace = traceback.StackSummary.extract(
Previous access by stream 0 during kernel:
aten::rand(int[] size, *, int? dtype=None, Device? device=None) -> Tensor
writing to the output
With stack trace:
File "example_error.py", line 3, in <module>
a = torch.rand(10000, device="cuda")
...
File "pytorch/torch/cuda/_sanitizer.py", line 364, in _handle_kernel_launch
stack_trace = traceback.StackSummary.extract(
Tensor was allocated with stack trace:
File "example_error.py", line 3, in <module>
a = torch.rand(10000, device="cuda")
...
File "pytorch/torch/cuda/_sanitizer.py", line 420, in _handle_memory_allocation
traceback.StackSummary.extract(
这提供了对错误来源的广泛见解
张量从 ID 为 0(默认流)和 94646435460352(新流)的流中访问不正确
张量通过调用
a = torch.rand(10000, device="cuda")
分配- 错误的访问是由操作符
a = torch.rand(10000, device="cuda")
在流 0 上torch.mul(a, 5, out=a)
在流 94646435460352 上
错误消息还会显示调用运算符的架构,以及一个注释,显示运算符的哪些参数对应于受影响的张量。
在示例中,可以看到张量
a
对应于参数self
、out
和调用运算符torch.mul
的output
值。
另请参阅
可以在 此处 查看受支持的 torch 运算符及其架构的列表。
可以通过强制新流等待默认流来修复此错误
with torch.cuda.stream(torch.cuda.Stream()):
torch.cuda.current_stream().wait_stream(torch.cuda.default_stream())
torch.mul(a, 5, out=a)
再次运行脚本时,没有报告错误。