“Ubuntu + PyTorch 最佳实践”通常指在 Ubuntu 系统上安装、配置和使用 PyTorch 时,被广泛认可、稳定且高效的一套做法。下面按「环境搭建 → 安装 → 使用 → 训练/部署 → 常见坑」给你梳理一份实用版。
ubuntu-drivers devices
sudo ubuntu-drivers autoinstall
nvidia-smi
避免系统 Python 被污染
方案 A(推荐):conda
conda create -n torch python=3.10
conda activate torch
方案 B:venv
python -m venv venv
source venv/bin/activate
去:https://pytorch.org
示例(CUDA 12.1):
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
import torch
print(torch.cuda.is_available())
print(torch.__version__)
project/
├── data/
├── models/
├── train.py
├── eval.py
├── config.yaml
├── requirements.txt
└── README.md
device = "cuda" if torch.cuda.is_available() else "cpu"
model.to(device)
torch.manual_seed(42)
torch.cuda.amp(混合精度)scaler = torch.cuda.amp.GradScaler()
with torch.cuda.amp.autocast():
output = model(x)
DataLoader 设置DataLoader(
dataset,
batch_size=32,
num_workers=4,
pin_memory=True
)
torch.compile(PyTorch 2.x)model = torch.compile(model)
watch -n 1 nvidia-smi
tensorboard 或 wandbtorch.quantization❌ 用系统 Python 直接装
❌ pip 和 conda 混用
❌ CUDA 版本和 PyTorch 不匹配
❌ num_workers 太大导致卡死
❌ 忘记 model.eval()
Ubuntu + PyTorch 最佳实践 = 干净环境 + 官方 CUDA 匹配 + 虚拟环境 + GPU 验证 + 工程化结构
如果你愿意,我可以: