分类专栏: PyTorch
- 测试环境:Python3.6 + Pytorch1.1
在pytorch中,使用多GPU训练网络需要用到 【nn.DataParallel】:
-
gpu_ids = [0, 1, 2, 3]
-
device = t.device("cuda:0" if t.cuda.is_available() else "cpu") # 只能单GPU运行
-
net = LeNet()
-
if len(gpu_ids) > 1:
-
net = nn.DataParallel(net, device_ids=gpu_ids)
-
net = net.to(device)
而使用单GPU训练网络:
-
device = t.device("cuda:0" if t.cuda.is_available() else "cpu") # 只能单GPU运行
-
net = LeNet().to(device)
由于多GPU训练使用了 nn.DataParallel(net, device_ids=gpu_ids) 对网络进行封装,因此在原始网络结构中添加了一层module。网络结构如下:
-
DataParallel(
-
(module): LeNet(
-
(conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))
-
(conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
-
(fc1): Linear(in_features=400, out_features=120, bias=True)
-
(fc2): Linear(in_features=120, out_features=84, bias=True)
-
(fc3): Linear(in_features=84, out_features=10, bias=True)
-
)
-
)
而不使用多GPU训练的网络结构如下:
-
LeNet(
-
(conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))
-
(conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
-
(fc1): Linear(in_features=400, out_features=120, bias=True)
-
(fc2): Linear(in_features=120, out_features=84, bias=True)
-
(fc3): Linear(in_features=84, out_features=10, bias=True)
-
)
由于在测试模型时不需要用到多GPU测试,因此在保存模型时应该把module层去掉。如下:
-
if len(gpu_ids) > 1:
-
t.save(net.module.state_dict(), "model.pth")
-
else:
-
t.save(net.state_dict(), "model.pth")