评价此页

torch.cuda.cudart#

torch.cuda.cudart()[source]#

获取 CUDA 运行时 API 模块。

此函数在 CUDA 运行时环境尚未初始化时进行初始化,并返回 CUDA 运行时 API 模块 (_cudart)。 CUDA 运行时 API 模块提供了对各种 CUDA 运行时函数的访问。

参数

None

返回

CUDA 运行时 API 模块 (_cudart)。

返回类型

模块

引发
  • RuntimeError – 如果在 fork 的子进程中无法重新初始化 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 ======")
要运行此示例并保存性能分析信息,请执行
>>> $ 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 选项强制覆盖已存在的输出文件。