在 Ubuntu 上使用 PyTorch 调用 GPU,通常步骤如下:
nvidia-smi
能看到显卡信息说明驱动已安装。
nvidia-smi
右上角会显示 CUDA Version(驱动支持的最大版本)
去 https://pytorch.org 选择对应配置,例如:
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
cu118表示 CUDA 11.8,按你的驱动版本选择
import torch
print(torch.cuda.is_available()) # True 表示可用
print(torch.cuda.device_count()) # GPU 数量
print(torch.cuda.get_device_name(0))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = MyModel().to(device)
x = torch.randn(8, 3, 224, 224).to(device)
y = model(x)
device = torch.device("cuda:0")
可能原因:
解决:
pip uninstall torch
pip install torch --index-url https://download.pytorch.org/whl/cu118
model = torch.nn.DataParallel(model)
model.to(device)
(更推荐 torch.distributed)
import torch
import torch.nn as nn
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = nn.Linear(10, 2).to(device)
x = torch.randn(32, 10).to(device)
out = model(x)
print(out.device)
如果你愿意,可以告诉我:
我可以给你精确安装命令 ✅