在 Linux 上 PyTorch 运行慢,通常不是“Linux 本身慢”,而是环境、配置或使用方式出了问题。下面按常见原因 → 排查方法 → 解决建议来说明。
即使你有显卡,PyTorch 也可能默认在 CPU 上运行。
检查:
import torch
print(torch.cuda.is_available())
print(torch.cuda.device_count())
解决:
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
device = "cuda" if torch.cuda.is_available() else "cpu"
model.to(device)
x = x.to(device)
很多 pip 默认装的是 CPU 版(尤其无 GPU 的服务器)。
检查:
torch.__version__
如果含 +cpu,就是 CPU 版。
解决: 重新安装 GPU 版本(见上)
CPU 预处理慢,GPU 在“等数据”。
表现:
解决:
DataLoader(
dataset,
batch_size=...,
num_workers=8,
pin_memory=True,
prefetch_factor=4
)
GPU 适合大批量并行。
现象:
解决:
batch_sizetorch.cuda.amp(混合精度)with torch.cuda.amp.autocast():
output = model(x)
在训练循环里大量用 Python loop 或 numpy 很慢。
错误示例:
for i in range(n):
x[i] = numpy_func(x[i])
解决:
torch.backends.cudnn.benchmark = True
(数据尺寸固定时非常有效)
多 CPU 服务器可能跨 NUMA 访问内存,很慢。
检查:
numactl --hardware
解决:
numactl --cpunodebind=0 --membind=0 python train.py
free -h
如果 swap 在涨,说明内存爆了。
nvidia-smi # GPU 是否在工作
htop # CPU / 内存
torch.cuda.is_available()
你可以告诉我:
torch.cuda.is_available() 结果nvidia-smi 截图或 GPU 利用率我可以直接帮你定位是哪一步慢。