在 CentOS 上使用 PyTorch 进行训练,一般流程如下(以服务器/无 GUI 环境为例):
sudo yum update -y
sudo yum install -y python3 python3-pip
查看版本:
python3 --version
pip3 install torch torchvision torchaudio
先确认 CUDA 版本:
nvidia-smi
然后到官网选择对应命令,例如 CUDA 11.8:
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
import torch
print(torch.__version__)
print(torch.cuda.is_available()) # GPU 应为 True
import torch
import torch.nn as nn
import torch.optim as optim
device = "cuda" if torch.cuda.is_available() else "cpu"
model = nn.Linear(10, 1).to(device)
optimizer = optim.SGD(model.parameters(), lr=0.01)
loss_fn = nn.MSELoss()
for epoch in range(100):
x = torch.randn(32, 10).to(device)
y = torch.randn(32, 1).to(device)
pred = model(x)
loss = loss_fn(pred, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print(epoch, loss.item())
运行:
python3 train.py
nohup python3 train.py > train.log 2>&1 &
查看日志:
tail -f train.log
pip3 install numpy pandas matplotlib
batch_sizetorch.cuda.empty_cache()建议使用 conda 或 pyenv 管理 Python。
如果你有:
可以告诉我,我可以直接给你 完整训练示例。