torch.cuda.cudart

torch.cuda.cudart()[源代码]

获取CUDA运行时API模块。

此函数用于初始化CUDA运行时环境(如果尚未初始化),并返回CUDA运行时API模块(_cudart)。该模块提供了访问各种CUDA运行时功能的功能。

参数

返回值

CUDA运行时API模块(_cudart)

返回类型

模块

异常
  • RuntimeError – 在分叉的子进程中如果无法重新初始化 CUDA。

  • AssertionError – 如果 PyTorch 没有与 CUDA 一起编译,或 libcudart 函数不可用。

包含性能分析的 CUDA 操作示例:
>>> import torch
>>> from torch.cuda import cudart, check_error
>>> import os
>>>
>>> os.environ['CUDA_PROFILE'] = '1'
>>>
>>> def perform_cuda_operations_with_streams():
>>>     stream = torch.cuda.Stream()
>>>     with torch.cuda.stream(stream):
>>>         x = torch.randn(100, 100, device='cuda')
>>>         y = torch.randn(100, 100, device='cuda')
>>>         z = torch.mul(x, y)
>>>     return z
>>>
>>> torch.cuda.synchronize()
>>> print("====== Start nsys profiling ======")
>>> check_error(cudart().cudaProfilerStart())
>>> with torch.autograd.profiler.emit_nvtx():
>>>     result = perform_cuda_operations_with_streams()
>>>     print("CUDA operations completed.")
>>> check_error(torch.cuda.cudart().cudaProfilerStop())
>>> print("====== End nsys profiling ======")
要运行此示例并保存 profiling 信息,请执行:
>>> $ nvprof --profile-from-start off --csv --print-summary -o trace_name.prof -f -- python cudart_test.py

此命令对提供的脚本中的 CUDA 操作进行性能分析,并将结果保存到名为 trace_name.prof 的文件中。--profile-from-start off 选项确保性能分析在脚本中的 cudaProfilerStart 调用之后开始。--csv--print-summary 选项分别将性能输出格式化为 CSV 文件并打印摘要信息。-o 选项指定输出文件名,而 -f 选项则在输出文件已存在时强制覆盖。

本页目录