在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进行深度学习计算。