第13章計算の性能
13.5.6. Training13.5.6 訓練
Now we can implement multi-GPU training on a single minibatch. Its implementation is primarily based on the data parallelism approach described in this section. We will use the auxiliary functions we just discussed,
allreduce and split_and_load, to synchronize the data among multiple GPUs. Note that we do not need to write any specific code to achieve parallelism. Since the computational graph does not have any dependencies across devices within a minibatch, it is executed in parallel automatically.英語のヒント
これで、一つのミニバッチで複数GPUの訓練を実装できる。その実装は、主にこの節で説明したデータ並列のやり方にもとづく。複数のGPUのあいだでデータを同期させるため、いま論じた補助関数
allreduceとsplit_and_loadを使う。並列性を達成するために特別なコードを書く必要はないことに注意してほしい。ミニバッチの中では計算グラフに装置をまたぐ依存がないので、それは自動的に並列に実行される。def train_batch(X, y, device_params, devices, lr):
X_shards, y_shards = split_batch(X, y, devices)
# Loss is calculated separately on each GPU
ls = [loss(lenet(X_shard, device_W), y_shard).sum()
for X_shard, y_shard, device_W in zip(
X_shards, y_shards, device_params)]
for l in ls: # Backpropagation is performed separately on each GPU
l.backward()
# Sum all gradients from each GPU and broadcast them to all GPUs
with torch.no_grad():
for i in range(len(device_params[0])):
allreduce([device_params[c][i].grad for c in range(len(devices))])
# The model parameters are updated separately on each GPU
for param in device_params:
d2l.sgd(param, lr, X.shape[0]) # Here, we use a full-size batchNow, we can define the training function. It is slightly different from the ones used in the previous chapters: we need to allocate the GPUs and copy all the model parameters to all the devices. Obviously each batch is processed using the
train_batch function to deal with multiple GPUs. For convenience (and conciseness of code) we compute the accuracy on a single GPU, though this is inefficient since the other GPUs are idle.英語のヒント
では、訓練関数を定義できる。それは前の章で使ったものと少し違う。GPUを割り当て、モデルのすべてのパラメータをすべての装置にコピーする必要がある。当然、各バッチは、複数のGPUを扱うために
train_batch関数を使って処理される。便利さ(とコードの簡潔さ)のため、正解率は一つのGPUで計算するが、ほかのGPUが遊んでいるので、これは効率が悪い。def train(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)]
# Copy model parameters to `num_gpus` GPUs
device_params = [get_params(params, d) for d in devices]
num_epochs = 10
animator = d2l.Animator('epoch', 'test acc', xlim=[1, num_epochs])
timer = d2l.Timer()
for epoch in range(num_epochs):
timer.start()
for X, y in train_iter:
# Perform multi-GPU training for a single minibatch
train_batch(X, y, device_params, devices, lr)
torch.cuda.synchronize()
timer.stop()
# Evaluate the model on GPU 0
animator.add(epoch + 1, (d2l.evaluate_accuracy_gpu(
lambda x: lenet(x, device_params[0]), test_iter, devices[0]),))
print(f'test acc: {animator.Y[0][-1]:.2f}, {timer.avg():.1f} sec/epoch '
f'on {str(devices)}')Let’s see how well this works on a single GPU. We first use a batch size of 256 and a learning rate of 0.2.
英語のヒント
一つのGPUでこれがどれくらいうまくいくかを見よう。まず、バッチの大きさ256と学習率0.2を使う。
train(num_gpus=1, batch_size=256, lr=0.2)test acc: 0.83, 3.0 sec/epoch on [device(type='cuda', index=0)]By keeping the batch size and learning rate unchanged and increasing the number of GPUs to 2, we can see that the test accuracy roughly stays the same compared with the previous experiment. In terms of the optimization algorithms, they are identical. Unfortunately there is no meaningful speedup to be gained here: the model is simply too small; moreover we only have a small dataset, where our slightly unsophisticated approach to implementing multi-GPU training suffered from significant Python overhead. We will encounter more complex models and more sophisticated ways of parallelization going forward. Let’s see what happens nonetheless for Fashion-MNIST.
英語のヒント
バッチの大きさと学習率を変えずにGPUの数を2に増やすと、テストの正解率は前の実験と比べてほぼ同じままであることがわかる。最適化アルゴリズムの点では、それらは同一である。残念ながら、ここでは意味のある高速化は得られない。モデルが単に小さすぎるのである。さらに、データセットも小さく、複数GPUの訓練を実装するやや洗練されていないやり方が、Pythonの大きなオーバーヘッドに苦しんだ。今後、もっと複雑なモデルと、もっと洗練された並列化のやり方に出会う。それでも、Fashion-MNISTで何が起こるかを見よう。
train(num_gpus=2, batch_size=256, lr=0.2)test acc: 0.84, 2.8 sec/epoch on [device(type='cuda', index=0), device(type='cuda', index=1)]