标签:contex stride multi lua 同步 ogr html bsp div
假设一台机器上有k个GPU。给定需要训练的模型,每个GPU将分别独立维护一份完整的模型参数。
在模型训练的任意一次迭代中,给定一个小批量,我们将该批量中的样本划分成k份并分给每个GPU一份。
然后,每个GPU将分别根据自己分到的训练数据样本和自己维护的模型参数计算模型参数的梯度。
接下来,我们把k个GPU上分别计算得到的梯度相加,从而得到当前的小批量梯度。
之后,每个GPU都使用这个小批量梯度分别更新自己维护的那一份完整的模型参数。
使用“卷积神经网络——从零开始”里的LeNet来作为本节的样例:
# 初始化模型参数。
scale = 0.01
W1 = nd.random.normal(scale=scale, shape=(20, 1, 3, 3))
b1 = nd.zeros(shape=20)
W2 = nd.random.normal(scale=scale, shape=(50, 20, 5, 5))
b2 = nd.zeros(shape=50)
W3 = nd.random.normal(scale=scale, shape=(800, 128))
b3 = nd.zeros(shape=128)
W4 = nd.random.normal(scale=scale, shape=(128, 10))
b4 = nd.zeros(shape=10)
params = [W1, b1, W2, b2, W3, b3, W4, b4]
# 定义模型。
def lenet(X, params):
h1_conv = nd.Convolution(data=X, weight=params[0], bias=params[1],
kernel=(3, 3), num_filter=20)
h1_activation = nd.relu(h1_conv)
h1 = nd.Pooling(data=h1_activation, pool_type="avg", kernel=(2, 2),
stride=(2, 2))
h2_conv = nd.Convolution(data=h1, weight=params[2], bias=params[3],
kernel=(5, 5), num_filter=50)
h2_activation = nd.relu(h2_conv)
h2 = nd.Pooling(data=h2_activation, pool_type="avg", kernel=(2, 2),
stride=(2, 2))
h2 = nd.flatten(h2)
h3_linear = nd.dot(h2, params[4]) + params[5]
h3 = nd.relu(h3_linear)
y_hat = nd.dot(h3, params[6]) + params[7]
return y_hat
# 交叉熵损失函数。
loss = gloss.SoftmaxCrossEntropyLoss()
下面函数将模型参数[参数一,参数二,……]复制到某个特定GPU,并标记梯度求解:
def get_params(params, ctx):
new_params = [p.copyto(ctx) for p in params]
for p in new_params:
p.attach_grad()
return new_params
以下函数可以把各个GPU上的同一参数数据加起来,然后再广播到所有GPU上:
def allreduce(data): # 输入为list,包含位于不同设备上的同一参数
for i in range(1, len(data)):
data[0][:] += data[i].copyto(data[0].context) # 将i位复制到0位设备上,并加给0位
for i in range(1, len(data)):
data[0].copyto(data[i]) # 使用累计后的0位替换i位
给定一个批量的数据样本,以下函数可以划分它们并复制到各个GPU上:
def split_and_load(data, ctx):
n, k = data.shape[0], len(ctx)
m = n // k
assert m * k == n, ‘# examples is not divided by # devices.‘
return [data[i * m: (i + 1) * m].as_in_context(ctx[i]) for i in range(k)]
将完整的模型参数复制到多个GPU上,并在每次迭代时对单个小批量上进行多GPU训练:
def train(num_gpus, batch_size, lr):
train_iter, test_iter = gb.load_data_fashion_mnist(batch_size)
ctx = [mx.gpu(i) for i in range(num_gpus)] # 设备代号list
print(‘running on:‘, ctx)
# 将模型参数复制到 num_gpus 个 GPU 上。
gpu_params = [get_params(params, c) for c in ctx] # 每个元素为一个设备上的参数
for epoch in range(1, 6):
start = time()
for X, y in train_iter:
# 对单个小批量上进行多 GPU 训练。
train_batch(X, y, gpu_params, ctx, lr)
nd.waitall()
print(‘epoch %d, time: %.1f sec‘ % (epoch, time() - start))
# 在 GPU0 上验证模型。
net = lambda x: lenet(x, gpu_params[0])
test_acc = gb.evaluate_accuracy(test_iter, net, ctx[0])
print(‘validation accuracy: %.4f‘ % test_acc)
实现单个小批量上的多GPU训练:
def train_batch(X, y, gpu_params, ctx, lr):
# 划分小批量数据样本并复制到各个 GPU 上。
gpu_Xs = split_and_load(X, ctx)
gpu_ys = split_and_load(y, ctx)
# 在各个 GPU 上计算损失。
with autograd.record():
ls = [loss(lenet(gpu_X, gpu_W), gpu_y) # 不同设备上的loss对象
for gpu_X, gpu_y, gpu_W in zip(gpu_Xs, gpu_ys, gpu_params)]
# 在各个 GPU 上反向传播。
for l in ls:
l.backward()
# 把各个 GPU 上的梯度加起来,然后再广播到所有 GPU 上。
for i in range(len(gpu_params[0])): # gpu_params[0]:位于设备0上的全部参数
allreduce([gpu_params[c][i].grad for c in range(len(ctx))]) # 汇总梯度并广播
# 在各个 GPU 上更新自己维护的那一份完整的模型参数。
for param in gpu_params: # 各个设备分别更新
gb.sgd(param, lr, X.shape[0])
标签:contex stride multi lua 同步 ogr html bsp div
原文地址:https://www.cnblogs.com/hellcat/p/9091191.html