在Linux下,PyTorch可以通過CUDA來利用NVIDIA GPU進行加速計算。以下是PyTorch與CUDA配合使用的步驟:
安裝CUDA Toolkit:
安裝cuDNN(如果需要):
安裝PyTorch with CUDA支持:
pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113
這里的cu113
表示CUDA 11.3版本,你需要根據實際安裝的CUDA版本進行替換。驗證安裝:
import torch
print(torch.cuda.is_available()) # 應該輸出True,如果GPU可用且PyTorch已正確安裝
print(torch.cuda.current_device()) # 輸出當前使用的GPU設備ID
print(torch.cuda.get_device_name(0)) # 輸出第一個GPU設備的名稱
編寫和運行CUDA加速的PyTorch代碼:
torch.cuda
模塊來指定在GPU上運行張量和模型。device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
tensor = torch.randn(10, 10).to(device)
model = YourModel().to(device)
通過以上步驟,你可以在Linux系統下成功配置和使用PyTorch與CUDA進行深度學習計算。