Ubuntu上PyTorch性能优化实战指南
一 环境配置与版本匹配
ubuntu-drivers autoinstall 或官方 PPA 安装,重启后用 nvidia-smi 验证驱动与 CUDA Runtime 是否正常显示。nvcc --version 与 torch.version.cuda 交叉核对。cudatoolkit=11.3),避免源码编译带来的不确定性与性能损失。import torch
print("torch:", torch.__version__, "cuda:", torch.version.cuda)
print("cuda available:", torch.cuda.is_available())
print("device name:", torch.cuda.get_device_name(0) if torch.cuda.is_available() else "CPU")
以上步骤能显著降低因版本不匹配导致的慢速或报错风险,并为后续优化打底。二 训练阶段的高收益优化
from torch.cuda.amp import autocast, GradScaler
scaler = GradScaler()
for x, y in loader:
x, y = x.cuda(non_blocking=True), y.cuda(non_blocking=True)
optimizer.zero_grad(set_to_none=True)
with autocast():
out = model(x)
loss = criterion(out, y)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
with torch.profiler.profile(
activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA],
schedule=torch.profiler.schedule(wait=1, warmup=1, active=3),
on_trace_ready=lambda prof: prof.export_chrome_trace("trace.json"),
record_shapes=True
) as prof:
for step, (x, y) in enumerate(loader):
# 训练步骤
prof.step()
这些手段通常能在不改动模型结构的前提下带来显著提速与显存节省。
三 数据 IO 与预处理优化
loader = DataLoader(dataset, batch_size=..., num_workers=8,
pin_memory=True, prefetch_factor=2, persistent_workers=True)
df -h /dev/shm
# 需要更大共享内存时,可在 /etc/fstab 调整 tmpfs size 后重挂载
IO 优化往往是最“立竿见影”的环节,特别在大规模图像/视频训练中。
四 显存与内存管理
export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:32,有助于减少显存碎片、缓解 OOM 与频繁申请/释放带来的抖动。五 常见问题与排查清单
nvidia-smi、nvcc --version、torch.cuda.is_available() 与 torch.version.cuda 进行“三件套”自检,确保驱动、CUDA、cuDNN 与 PyTorch 版本一致。