快捷方式

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 對應於呼叫運算子 torch.mul 的引數 selfoutoutput 值。

另請參閱

支援的 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()[source][source]

啟用 CUDA Sanitizer。

Sanitizer 將開始分析由 torch 函式呼叫的低級別 CUDA 呼叫是否存在同步錯誤。發現的所有資料競爭將列印到標準錯誤輸出,並附帶可疑原因的堆疊跟蹤。為了獲得最佳結果,應在程式的最開始啟用 Sanitizer。

文件

訪問 PyTorch 的完整開發者文件

檢視文件

教程

獲取面向初學者和高階開發者的深入教程

檢視教程

資源

查詢開發資源並獲得問題解答

檢視資源