在 Linux 下使用 PyTorch 调用 GPU,通常需要完成环境准备、代码修改、验证三步。下面给你一个清晰、实用的说明。
nvidia-smi
如果能看到 GPU 信息(如型号、显存、CUDA 版本),说明驱动已安装。
如果命令不存在,需要先安装 NVIDIA 驱动。
nvidia-smi
右上角会显示 CUDA Version: 12.x
推荐使用官方命令:
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
⚠️ 不要只用
pip install torch,默认可能是 CPU 版
import torch
print(torch.cuda.is_available()) # True 表示可用
print(torch.cuda.device_count()) # GPU 数量
print(torch.cuda.get_device_name(0))
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)
model = torch.nn.DataParallel(model)
或使用更推荐的:
model = torch.compile(model) # PyTorch 2.x
torch.cuda.is_available() 返回 False可能原因:
解决:
pip uninstall torch
pip install torch --index-url https://download.pytorch.org/whl/cu121
batch_sizetorch.cuda.empty_cache()with torch.cuda.amp.autocast():
output = model(x)
import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
x = torch.randn(1000, 1000).to(device)
y = x @ x
print(y.device)
如果你愿意,可以告诉我:
我可以给你一条完全对应你环境的安装命令。