快捷方式

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 对应于参数 selfout 和调用运算符 torch.muloutput 值。

另请参阅

可以在 此处 查看受支持的 torch 运算符及其架构的列表。

可以通过强制新流等待默认流来修复此错误

with torch.cuda.stream(torch.cuda.Stream()):
    torch.cuda.current_stream().wait_stream(torch.cuda.default_stream())
    torch.mul(a, 5, out=a)

再次运行脚本时,没有报告错误。

API 参考

torch.cuda._sanitizer.enable_cuda_sanitizer()[源代码]

启用 CUDA Sanitizer。

Sanitizer 将开始分析 torch 函数调用的低级 CUDA 调用,以查找同步错误。找到的所有数据竞争都将打印到标准错误输出,以及可疑原因的堆栈跟踪。为了获得最佳效果,应在程序一开始就启用 sanitizer。

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取适合初学者和高级开发者的深入教程

查看教程

资源

查找开发资源并获得问题的解答

查看资源