本地电脑的配置达不到深度学习模型训练的要求,GPU云服务器按使用时间计费,配置灵活,为我们训练复杂模型提供了一个解决办法。
下面以《Dive into Deep Learning》(动手学深度学习)第2版 第7.1小节 《深度卷积神经网络(AlexNet)》 为例,介绍如何在GPU云服务器上训练模型,并参考第5.5小节《读写文件》,将训练好的模型参数保存到文件,供以后使用。
- 准备GPU云服务器
选择云服务器硬件配置,根据具体任务选择CPU,内存大小,硬盘容量,显卡种类和显存大小
操作系统选择ubuntu 24.04(一般提供的都是linux,因为免费。选1个自己熟悉的发行版)
运行nvidia-smi,确认已经安装了cuda。 - 安装环境和依赖
下载并安装miniconda
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
conda命令已经加入PATH,为了使其生效,执行:
source ~/.bashrc
同意tos
conda tos accept –override-channels –channel https://repo.anaconda.com/pkgs/main
conda tos accept –override-channels –channel https://repo.anaconda.com/pkgs/r
创建环境并激活
conda create –n py39 python=3.9 -y
注意:有时候会报错。复制粘贴以上命令后,-和=,这些符号需要在命令行删除后重新打字!
conda activate py39
安装依赖
conda install pytorch==1.12.0 torchvision==0.13.0 cudatoolkit=11.3 -c pytorch
pip install d2l==0.17.6
conda install -c conda-forge mkl=2024.0.0 -y
否则会报错:
ImportError: /root/miniconda3/envs/py39/lib/python3.9/site-packages/torch/lib/libtorch_cpu.so: undefined symbol: iJIT_NotifyEvent
pip install numpy==1.26.4
pip uninstall numpy==1.26.4
pip install numpy==1.21.5
• 3. 新建python文件并执行
新建一个目录并进入
mkdir pytorch_train && cd $_
vim alexnet.py,内容如下:
# 7.1 AlexNet
import matplotlib
# Patch the missing private method to match the standard public .get method
if not hasattr(matplotlib.rcParams, '_get'):
matplotlib.rcParams._get = matplotlib.rcParams.get
import torch
from torch import nn
from d2l import torch as d2l
import matplotlib.pyplot as plt
net = nn.Sequential(
# 这里使用一个11*11的更大窗口来捕捉对象。
# 同时,步幅为4,以减少输出的高度和宽度。
# 另外,输出通道的数目远大于LeNet
nn.Conv2d(1, 96, kernel_size=11, stride=4, padding=1), nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2),
# 减小卷积窗口,使用填充为2来使得输入与输出的高和宽一致,且增大输出通道数
nn.Conv2d(96, 256, kernel_size=5, padding=2), nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2),
# 使用三个连续的卷积层和较小的卷积窗口。
# 除了最后的卷积层,输出通道的数量进一步增加。
# 在前两个卷积层之后,汇聚层不用于减少输入的高度和宽度
nn.Conv2d(256, 384, kernel_size=3, padding=1), nn.ReLU(),
nn.Conv2d(384, 384, kernel_size=3, padding=1), nn.ReLU(),
nn.Conv2d(384, 256, kernel_size=3, padding=1), nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Flatten(),
# 这里,全连接层的输出数量是LeNet中的好几倍。使用dropout层来减轻过拟合
nn.Linear(6400, 4096), nn.ReLU(),
nn.Dropout(p=0.5),
nn.Linear(4096, 4096), nn.ReLU(),
nn.Dropout(p=0.5),
# 最后是输出层。由于这里使用Fashion-MNIST,所以用类别数为10,而非论文中的1000
nn.Linear(4096, 10))
X = torch.randn(1, 1, 224, 224)
for layer in net:
X=layer(X)
print(layer.__class__.__name__,'output shape:\t',X.shape)
batch_size = 128
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size, resize=224)
lr, num_epochs = 0.01, 10
d2l.train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())
plt.show()
plt.savefig("alexnet_train.png")
# save model params
torch.save(net.state_dict(), "alexnet.params")
执行程序,标准输出和错误输出都定向到文件并在后台执行(防止ssh连接意外断开时程序未执行完就退出)
nohup python alexnet.py > output.log 2>&1 &
查看执行情况:
tail -f output.log
执行完毕,可以看到生成的损失和正确率的绘图文件alexnet_train.png和模型参数文件alexnet.params。