第13章計算の性能
13.6.3. Training13.6.3 訓練
As before, the training code needs to perform several basic functions for efficient parallelism:
英語のヒント
前と同じように、訓練のコードは、効率的な並列化のためにいくつかの基本的な機能を果たす必要がある。
- Network parameters need to be initialized across all devices.
英語のヒント
ネットワークのパラメータを、すべての装置で初期化する必要がある。 - While iterating over the dataset minibatches are to be divided across all devices.
英語のヒント
データセットを反復するあいだ、ミニバッチをすべての装置に分ける。 - We compute the loss and its gradient in parallel across devices.
英語のヒント
損失とその勾配を、装置にわたって並列に計算する。 - Gradients are aggregated and parameters are updated accordingly.
英語のヒント
勾配を集め、それに応じてパラメータを更新する。
In the end we compute the accuracy (again in parallel) to report the final performance of the network. The training routine is quite similar to implementations in previous chapters, except that we need to split and aggregate data.
英語のヒント
最後に、ネットワークの最終的な性能を報告するため、(やはり並列に)正解率を計算する。訓練のルーチンは、データを分けて集める必要があることを除けば、前の章の実装とよく似ている。
def train(net, num_gpus, batch_size, lr):
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
devices = [d2l.try_gpu(i) for i in range(num_gpus)]
def init_weights(module):
if type(module) in [nn.Linear, nn.Conv2d]:
nn.init.normal_(module.weight, std=0.01)
net.apply(init_weights)
# Set the model on multiple GPUs
net = nn.DataParallel(net, device_ids=devices)
trainer = torch.optim.SGD(net.parameters(), lr)
loss = nn.CrossEntropyLoss()
timer, num_epochs = d2l.Timer(), 10
animator = d2l.Animator('epoch', 'test acc', xlim=[1, num_epochs])
for epoch in range(num_epochs):
net.train()
timer.start()
for X, y in train_iter:
trainer.zero_grad()
X, y = X.to(devices[0]), y.to(devices[0])
l = loss(net(X), y)
l.backward()
trainer.step()
timer.stop()
animator.add(epoch + 1, (d2l.evaluate_accuracy_gpu(net, test_iter),))
print(f'test acc: {animator.Y[0][-1]:.2f}, {timer.avg():.1f} sec/epoch '
f'on {str(devices)}')Let’s see how this works in practice. As a warm-up we train the network on a single GPU.
英語のヒント
これが実際にどう働くかを見よう。準備運動として、一つのGPUでネットワークを訓練する。
train(net, num_gpus=1, batch_size=256, lr=0.1)test acc: 0.91, 12.2 sec/epoch on [device(type='cuda', index=0)]Next we use 2 GPUs for training. Compared with LeNet evaluated in Section 13.5, the model for ResNet-18 is considerably more complex. This is where parallelization shows its advantage. The time for computation is meaningfully larger than the time for synchronizing parameters. This improves scalability since the overhead for parallelization is less relevant.
英語のヒント
次に、2個のGPUを訓練に使う。13.5節で評価したLeNetと比べて、ResNet-18のモデルはかなり複雑である。ここで並列化が利点を示す。計算の時間が、パラメータを同期させる時間よりはっきり大きい。並列化のオーバーヘッドがあまり重要でなくなるので、これによりスケーラビリティが改善する。
train(net, num_gpus=2, batch_size=512, lr=0.2)test acc: 0.73, 7.5 sec/epoch on [device(type='cuda', index=0), device(type='cuda', index=1)]