以下内容为Pytorch官网教程的翻译简化和一些自己的总结:
在拥有多个GPU时,可通过nn.DataParallel()实现并行训练模型
首先创建GPU设备:
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
创建模型并迁移至GPU:
model = Model(input_size, output_size)
if torch.cuda.device_count() > 1:
model = nn.DataParallel(model) # 将模型转换为并行模型
# 迁移至GPU设备
model.to(device)
将数据张量也迁移至设备,输入模型中:
for data in rand_loader:
input = data.to(device) # 张量迁移至GPU设备
output = model(input)
DataParallel会自动将数据划分到各GPU,并分配计算任务给各GPU上的多个模型。如若Batch Size为30,当有2个GPU时各模型输入的Batch Size为15;当有8个GPU时,其中7个Batch Size为4,一个Batch Size为2。每个模型完成任务后,DataParallel收集并合并计算结果。