梯度累加
在你已经达到计算资源上限的情况下,你的 batch size 仍然太小(比如 8),然后我们需要模拟一个更大的 batch size 来进行梯度下降,以提供一个良好的估计。
假设我们想要达到 128 的batch size大小。我们需要以 batch size 为 8 执行 16 个前向传播和向后传播,然后再执行一次优化步骤。
# clear last step
optimizer.zero_grad()
# 16 accumulated gradient steps
scaled_loss = 0
for accumulated_step_i in range(16):
out = model.forward()
loss = some_loss(out,y)
loss.backward()
scaled_loss += loss.item()
# update weights after 8 steps. effective batch = 8*16
optimizer.step()
# loss is now scaled up by the number of accumulated batches
actual_loss = scaled_loss / 16
保留的计算图
对模型加速的思考
尽管本指南将为你提供了一系列提高网络速度的技巧,但我还是要给你解释一下如何通过查找瓶颈来思考问题。
我将模型分成几个部分:
首先,我要确保在数据加载中没有瓶颈。为此,我使用了我所描述的现有数据加载解决方案,但是如果没有一种解决方案满足你的需要,请考虑离线处理和缓存到高性能数据存储中,比如h5py。
接下来看看你在训练步骤中要做什么。确保你的前向传播速度快,避免过多的计算以及最小化 CPU 和 GPU 之间的数据传输。最后,避免做一些会降低 GPU 速度的事情(本指南中有介绍)。
接下来,我试图最大化我的 batch size,这通常是受 GPU 内存大小的限制。现在,需要关注在使用大 的batch size 的时候如何在多个 GPUs 上分布并最小化延迟(比如,我可能会尝试着在多个gpu上使用8000 +的有效batch size)。
然而,你需要小心大的 batch size。针对你的具体问题,请查阅相关文献,看看人们都忽略了什么!
移动到多个GPUs中
有3种(也许更多?)方法来进行多GPU训练。
1)分batch训练
A) 拷贝模型到每个 GPU中,B) 给每个 GPU 一部分 batch
第一种方法被称为 “分batch训练”。该策略将模型复制到每个 GPU上,每个 GPU 获得 batch 的一部分。
# copy model on each GPU and give a fourth of the batch to each
model = DataParallel(model, devices=[0, 1, 2 ,3])
# out has 4 outputs (one for each gpu)
out = model(x.cuda(0))
2)将模型的不同部分放在不同的GPU上,batch按顺序移动
有时你的模型可能太大不能完全放到内存中。例如,带有编码器和解码器的序列到序列模型在生成输出时可能会占用 20GB RAM。在本例中,我们希望将编码器和解码器放在独立的 GPU上。
# each model is sooo big we can't fit both in memory
encoder_rnn.cuda(0)
decoder_rnn.cuda(1)
# run input through encoder on GPU 0
encoder_out = encoder_rnn(x.cuda(0))
# run output through decoder on the next GPU
out = decoder_rnn(encoder_out.cuda(1))
# normally we want to bring all outputs back to GPU 0
out = out.cuda(0)
3)两者混合
在上面的情况下,编码器和解码器仍然可以从并行化操作中获益。
# change these lines
self.encoder = RNN(...)
self.decoder = RNN(...)
# to these
# now each RNN is based on a different gpu set
self.encoder = DataParallel(self.encoder, devices=[0, 1, 2, 3])
self.decoder = DataParallel(self.encoder, devices=[4, 5, 6, 7])
# in forward...
out = self.encoder(x.cuda(0))
# notice inputs on first gpu in device
sout = self.decoder(out.cuda(4)) # <--- the 4 here
使用多个GPU时要考虑的注意事项:
- 如果模型已经在GPU上了,model.cuda()不会做任何事情。
- 总是把输入放在设备列表中的第一个设备上。
- 在设备之间传输数据是昂贵的,把它作为最后的手段。
- 优化器和梯度会被保存在 GPU 0上,因此,GPU 0上使用的内存可能会比其他 GPU 大得多
英文原文:
9 Tips For Training Lightning-Fast Neural Networks In Pytorch
中文翻译: