赞
踩
进行多GPU训练有几个主要原因:
提高训练速度: 使用多个GPU可以将模型的参数和训练数据分配到不同的GPU上并行处理,从而显著提高训练速度。每个GPU都可以处理一部分数据,同时进行反向传播和参数更新,使得整个训练过程更加高效。
处理更大的模型和数据集: 多GPU训练使得可以处理更大的模型和数据集,因为每个GPU都可以专注于处理部分模型参数和数据。这对于深度学习中复杂模型和大规模数据集的训练非常有益。
资源利用率提高: 利用多个GPU可以更充分地利用计算资源。在单个GPU上,可能存在计算资源的浪费,而多GPU训练可以更有效地利用这些资源。
实验迭代速度提高: 多GPU训练还有助于提高实验迭代速度。在深度学习中,通过更快地尝试不同的模型架构、超参数和数据处理方法,可以更快地找到最优的模型配置。
需要注意的是,多GPU训练也面临一些挑战,如数据同步、通信开销等问题,需要采用适当的并行训练策略来解决这些问题。
多GPU训练的核心不同的卡得到不同的样本个数,分别进行训练然后将得到的各自梯度进行相加
%matplotlib inline import torch from torch import nn from torch.nn import functional as F from d2l import torch as d2l # 以LeNet网络为例子 scale = 0.01 W1 = torch.randn(size=(20, 1, 3, 3)) * scale b1 = torch.zeros(20) W2 = torch.randn(size=(50, 20, 5, 5)) * scale b2 = torch.zeros(50) W3 = torch.randn(size=(800, 128)) * scale b3 = torch.zeros(128) W4 = torch.randn(size=(128, 10)) * scale b4 = torch.zeros(10) params = [W1, b1, W2, b2, W3, b3, W4, b4] def lenet(X, params): h1_conv = F.conv2d(input=X, weight=params[0], bias=params[1]) h1_activation = F.relu(h1_conv) h1 = F.avg_pool2d(input=h1_activation, kernel_size=(2, 2), stride=(2, 2)) h2_conv = F.conv2d(input=h1, weight=params[2], bias=params[3]) h2_activation = F.relu(h2_conv) h2 = F.avg_pool2d(input=h2_activation, kernel_size=(2, 2), stride=(2, 2)) h2 = h2.reshape(h2.shape[0], -1) h3_linear = torch.mm(h2, params[4]) + params[5] h3 = F.relu(h3_linear) y_hat = torch.mm(h3, params[6]) + params[7] return y_hat loss = nn.CrossEntropyLoss(reduction='none')
向多个设备分发参数
# 把一个参数复制到指定device的gpu上
def get_params(params, device): # params是list,用来存放各个参数
new_params = [p.clone().to(device) for p in params]
for p in new_params:
p.requires_grad_()
return new_params
new_params = get_params(params, d2l.try_gpu(0)) # 将params全部移动到cuda0上
print('b1 weight:', new_params[1])
print('b1 grad:', new_params[1].grad)
allreduce 函数将所有向量【将各个梯度的data相加然后复制回去】相加,并将结果广播给所有 GPU
def allreduce(data): # data是一个list[有几张卡就有几个list] for i in range(1, len(data)): # 把从1到后面cuda的数据全部复制到cuda0上,因为加法计算必须在同一张卡上操作 data[0][:] += data[i].to(data[0].device) # for结束后, data[0中存放的就是所有梯度相加的结果 for i in range(1, len(data)):# 将data[0]中的数据复制回各个gpu data[i] = data[0].to(data[i].device) # test 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]) """ output 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') """
将一个小批量数据均匀地分布在多个 GPU 上
# test data = torch.arange(20).reshape(4, 5) devices = [torch.device('cuda:0'), torch.device('cuda:1')] split = nn.parallel.scatter(data, devices) # .scatter直接均匀切割 print('input :', data) print('load into', devices) print('output:', split) """ output input : tensor([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) load into [device(type='cuda', index=0), device(type='cuda', index=1)] output: (tensor([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], device='cuda:0'), tensor([[10, 11, 12, 13, 14], [15, 16, 17, 18, 19]], device='cuda:1')) """
def split_batch(X, y, devices):
"""将`X`和`y`拆分到多个设备上"""
assert X.shape[0] == y.shape[0]
return (nn.parallel.scatter(X, devices),
nn.parallel.scatter(y, devices))
在一个小批量上实现多 GPU 训练
def train_batch(X, y, device_params, devices, lr): X_shards, y_shards = split_batch(X, y, devices) # 将小批量X和y均匀分布到各个gpu上 # 从小批量和共享的设备参数里拿到每个gpu上的小批量X,y和参数, # 再把得到的(X_shard, device_W)放到LeNet里面,和y_shard求损失并求和 # ls是list,每一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: l.backward() # 对每个gpu算梯度 with torch.no_grad(): for i in range(len(device_params[0])): # 这步结果是将每个设备参数的梯度存储的都是整体小批量的梯度 allreduce([device_params[c][i].grad for c in range(len(devices))]) # 对每个梯度做同步更新优化 for param in device_params: d2l.sgd(param, lr, X.shape[0])
定义训练函数
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)] # 主要区别在于要将参数复制到每个gpu上 device_params = [get_params(params, d) for d in devices] # 在训练之前将所有参数复制到每个gpu上 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: train_batch(X, y, device_params, devices, lr) torch.cuda.synchronize() # 同步一次 timer.stop() 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)}')
# 在单个GPU上运行
train(num_gpus=1, batch_size=256, lr=0.2)
# 增加为2个GPU
train(num_gpus=2, batch_size=256, lr=0.2)
理论上不会改变训练结果,也有可能分布式也不会变快,
主要:gpu增加了,batch_size没变,会导致gpu性能不能完全发挥,如果只是单纯增加batch_size,可能会导致acc降低,
所以一般可以将批量和lr一起提高一点
import torch from torch import nn from d2l import torch as d2l # 使用一个稍微大一点的模型 def resnet18(num_classes, in_channels=1): """稍加修改的 ResNet-18 模型。""" def resnet_block(in_channels, out_channels, num_residuals, first_block=False): blk = [] for i in range(num_residuals): if i == 0 and not first_block: blk.append( d2l.Residual(in_channels, out_channels, use_1x1conv=True, strides=2)) else: blk.append(d2l.Residual(out_channels, out_channels)) return nn.Sequential(*blk) net = nn.Sequential( nn.Conv2d(in_channels, 64, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(64), nn.ReLU()) net.add_module("resnet_block1", resnet_block(64, 64, 2, first_block=True)) net.add_module("resnet_block2", resnet_block(64, 128, 2)) net.add_module("resnet_block3", resnet_block(128, 256, 2)) net.add_module("resnet_block4", resnet_block(256, 512, 2)) net.add_module("global_avg_pool", nn.AdaptiveAvgPool2d((1, 1))) net.add_module("fc", nn.Sequential(nn.Flatten(), nn.Linear(512, num_classes))) return net net = resnet18(10) devices = d2l.try_all_gpus()
训练-主要就是DataParallel的使用
DataParallel接口隐含的实现了get_params/ allreduce/split_batch等函数的功能
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(m): if type(m) in [nn.Linear, nn.Conv2d]: nn.init.normal_(m.weight, std=0.01) net.apply(init_weights) # .DataParallel接口隐含的实现了get_params/ allreduce/split_batch等函数的功能 net = nn.DataParallel(net, device_ids=devices) # 把net复制到每个gpu上 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]) # 和前面实现一样,要先将数据都复制到同一块gpu上 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)}')
# 在单个GPU上训练网络
train(net, num_gpus=1, batch_size=256, lr=0.1)
# 使用 2 个 GPU 进行训练
train(net, num_gpus=2, batch_size=512, lr=0.2)
可以通过调整批量和学习率来提升训练速度
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。