评价此页

CUDA 流消毒器#

创建于: 2022 年 09 月 09 日 | 最后更新于: 2022 年 10 月 31 日

注意

这是一个原型功能,意味着它处于早期阶段,供反馈和测试,并且其组件可能会发生变化。

概述#

此模块介绍了 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` 对应于算子 torch.mul 的参数 `self`、`out` 以及 `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)

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

API 参考#

torch.cuda._sanitizer.enable_cuda_sanitizer()[源]#

启用 CUDA Sanitizer。

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