torch.cuda.cudart#
- torch.cuda.cudart()[原始碼]#
獲取 CUDA 執行時 API 模組。
此函式將在 CUDA 執行時環境尚未初始化時進行初始化,並返回 CUDA 執行時 API 模組 (_cudart)。CUDA 執行時 API 模組提供了對各種 CUDA 執行時函式的訪問。
- 引數
None –
- 返回
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 ======")
- 要執行此示例並儲存效能分析資訊,請執行
>>> $ 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 選項強制覆蓋已存在的輸出檔案。