第13章計算の性能
13.5.4. Data Synchronization13.5.4 データの同期
For efficient multi-GPU training we need two basic operations. First we need to have the ability to distribute a list of parameters to multiple devices and to attach gradients (
get_params). Without parameters it is impossible to evaluate the network on a GPU. Second, we need the ability to sum parameters across multiple devices, i.e., we need an allreduce function.英語のヒント
効率的な複数GPUでの訓練には、二つの基本的な演算が要る。第一に、パラメータのリストを複数の装置に配り、勾配を付ける能力が必要である(
get_params)。パラメータがなければ、GPUでネットワークを評価することはできない。第二に、複数の装置にわたってパラメータを足し合わせる能力が必要である。つまり、allreduce関数が要る。def get_params(params, device):
new_params = [p.to(device) for p in params]
for p in new_params:
p.requires_grad_()
return new_paramsLet’s try it out by copying the model parameters to one GPU.
英語のヒント
モデルのパラメータを一つのGPUにコピーして試してみよう。
new_params = get_params(params, d2l.try_gpu(0))
print('b1 weight:', new_params[1])
print('b1 grad:', new_params[1].grad)b1 weight: tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
device='cuda:0', requires_grad=True)
b1 grad: NoneSince we did not perform any computation yet, the gradient with regard to the bias parameter is still zero. Now let’s assume that we have a vector distributed across multiple GPUs. The following
allreduce function adds up all vectors and broadcasts the result back to all GPUs. Note that for this to work we need to copy the data to the device accumulating the results.英語のヒント
まだ何も計算していないので、バイアスのパラメータについての勾配はまだゼロである。では、複数のGPUに分散したベクトルがあるとしよう。次の
allreduce関数は、すべてのベクトルを足し合わせ、結果をすべてのGPUにブロードキャストして戻す。これがうまくいくには、結果を累積する装置にデータをコピーする必要があることに注意してほしい。def allreduce(data):
for i in range(1, len(data)):
data[0][:] += data[i].to(data[0].device)
for i in range(1, len(data)):
data[i][:] = data[0].to(data[i].device)Let’s test this by creating vectors with different values on different devices and aggregate them.
英語のヒント
異なる装置で異なる値のベクトルを作り、それらを集めて、これを試そう。
data = [torch.ones((1, 2), device=d2l.try_gpu(i)) * (i + 1) for i in range(2)]
print('before allreduce:\n', data[0], '\n', data[1])
allreduce(data)
print('after allreduce:\n', data[0], '\n', data[1])before allreduce:
tensor([[1., 1.]], device='cuda:0')
tensor([[2., 2.]], device='cuda:1')
after allreduce:
tensor([[3., 3.]], device='cuda:0')
tensor([[3., 3.]], device='cuda:1')