在 CentOS 上优化 PyTorch 的性能,通常可以从 系统环境、PyTorch 安装方式、硬件利用、代码与训练策略 几个层面来做。下面给你一个比较系统、可落地的优化清单。
yum update -y
优化文件描述符和内存:
# /etc/security/limits.conf
* soft nofile 1048576
* hard nofile 1048576
systemctl stop firewalld
systemctl disable firewalld
如果是 CPU 训练或推理:
pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cpu
或安装 Intel Extension for PyTorch(强烈推荐):
pip install intel-extension-for-pytorch
启用:
import intel_extension_for_pytorch as ipex
model = ipex.optimize(model)
✅ 可提升 CPU 推理 1.5–3 倍
torch.set_num_threads(N)
torch.set_num_interop_threads(M)
建议:
num_threads = 物理核数interop_threads = 1~2查看 CPU:
lscpu
yum install -y cpupower-utils
cpupower frequency-set -g performance
nvidia-smi
PyTorch 版本必须匹配 CUDA:
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.enabled = True
model = torch.nn.DataParallel(model)
# 或
model = torch.nn.parallel.DistributedDataParallel(model)
推荐 DDP(更快、更稳定)
torch.compile(PyTorch 2.x)model = torch.compile(model)
✅ A100 / 3090 上常见提升 10–30%
from torch.cuda.amp import autocast, GradScaler
with autocast():
output = model(x)
DataLoader(
dataset,
batch_size=64,
num_workers=8,
pin_memory=True,
prefetch_factor=4
)
✅ num_workers ≈ CPU 核心数
print.cpu()torch.utils.checkpoint 省显存.pt / WebDataset / LMDBtorch.save(dataset, "cache.pt")
watch -n 1 nvidia-smi
htop
with torch.profiler.profile() as prof:
train()
print(prof.key_averages().table())
| 优化项 | 提升幅度 |
|---|---|
| IPEX (CPU) | 1.5–3× |
| AMP | 1.5–2× |
| torch.compile | 10–30% |
| DDP | 线性加速 |
| DataLoader 调优 | 20–50% |
你可以直接告诉我:
“CentOS 7 + RTX 3090 + PyTorch 训练图像模型,怎么优化?”