【pytorch】简单例子演示 nn.DataParallel 单机多卡训练

导入模块与参数设置

import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader

# Parameters and DataLoaders
input_size = 5
output_size = 2

batch_size = 30
data_size = 100
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device

device(type=‘cuda’, index=0)

虚拟数据集

制作一个假的(随机的)数据集。你只需要实现getitem

class RandomDataset(Dataset):

    def __init__(self, size, length):
        self.len = length
        self.data = torch.randn(length, size)

    def __getitem__(self, index):
        return self.data[index]

    def __len__(self):
        return self.len

rand_loader = DataLoader(dataset=RandomDataset(input_size, data_size),
                         batch_size=batch_size, shuffle=True)

简单的模型

在这个演示中,我们的模型只是得到一个输入,执行一个线性运算,然后给出一个输出。然而,你可以在任何模型上使用DataParallel(CNN、RNN、Capsule Net等)。

我们在模型内部放置了一个打印语句来监控输入和输出张量的大小。请注意在批处理等级0时打印的内容。

class Model(nn.Module):
    # Our model

    def __init__(self, input_size, output_size):
        super(Model, self).__init__()
        self.fc = nn.Linear(input_size, output_size)

    def forward(self, input):
        output = self.fc(input)
        print("\tIn Model: input size", input.size(),
              "output size", output.size())

        return output

创建模型和DataParallel

这是本教程的核心部分。首先,我们需要制作一个模型实例并检查我们是否有多个GPU。如果我们有多个GPU,我们可以使用nn.DataParallel来包装我们的模型。然后我们可以通过model.to(device)将我们的模型放在GPU上。

model = Model(input_size, output_size)
if torch.cuda.device_count() > 1:
  print("Let's use", torch.cuda.device_count(), "GPUs!")
  # dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
  model = nn.DataParallel(model)

model.to(device)

Let’s use 4 GPUs!
DataParallel(
(module): Model(
(fc): Linear(in_features=5, out_features=2, bias=True)
)
)

运行模型

现在我们可以看到输入和输出张量的大小。

for data in rand_loader:
    input = data.to(device)
    output = model(input)
    print("Outside: input size", input.size(),
          "output_size", output.size())
	In Model: input size torch.Size([8, 5]) output size torch.Size([8, 2])
	In Model: input size torch.Size([8, 5]) output size torch.Size([8, 2])
	In Model: input size torch.Size([8, 5]) output size torch.Size([8, 2])
	In Model: input size torch.Size([6, 5]) output size torch.Size([6, 2])
Outside: input size torch.Size([30, 5]) output_size torch.Size([30, 2])
	In Model: input size torch.Size([8, 5]) output size torch.Size([8, 2])
	In Model: input size torch.Size([8, 5]) output size torch.Size([8, 2])
	In Model: input size torch.Size([8, 5]) output size torch.Size([8, 2])
	In Model: input size torch.Size([6, 5]) output size torch.Size([6, 2])
Outside: input size torch.Size([30, 5]) output_size torch.Size([30, 2])
	In Model: input size torch.Size([8, 5]) output size torch.Size([8, 2])
	In Model: input size torch.Size([8, 5]) output size torch.Size([8, 2])
	In Model: input size torch.Size([8, 5]) output size torch.Size([8, 2])
	In Model: input size torch.Size([6, 5]) output size torch.Size([6, 2])
Outside: input size torch.Size([30, 5]) output_size torch.Size([30, 2])
	In Model: input size torch.Size([3, 5]) output size torch.Size([3, 2])
	In Model: input size torch.Size([3, 5]) output size torch.Size([3, 2])
	In Model: input size torch.Size([3, 5]) output size torch.Size([3, 2])
	In Model: input size torch.Size([1, 5]) output size torch.Size([1, 2])
Outside: input size torch.Size([10, 5]) output_size torch.Size([10, 2])

补充内容

关于损失函数

如果损失函数是在模型外定义的(大多数情况),则这种方法会加重主卡(一般是 cuda:0 )的负担,因为模型的损失是由主卡来计算的,如果要减轻主卡的负担,可以将损失函数写在模型内部。

如以下的模型结构:

class Model(nn.Module):
    def __init__(self):
    	...
    def forward(self, x):
    	...
    def loss_func(self, y, y_pred):
    	...

然后在训练的 for 循环中,将

loss = model.loss(y, y_pred)

修改成

loss = model.module.loss(y, y_pred)

即可

关于模型保存和重新读取

如果将模型直接保存,读取的时候需要:

# 如果使用并行训练,需要使用下面的代码加载模型参数
model = torch.nn.DataParallel(model) 							# 先转换成并行对象
torch.backends.cudnn.benchmark = True
model.load_state_dict(torch.load('./model_Parallel.pth')) 	# 读取并行对象的参数
model = model.module 											# 将模型从并行对象中取出

也可以在保存的时候,先取出并行对象中的模型,然后保存模型参数:

model = model.module
torch.save(model.state_dict(), './model_root.pth')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值