pytorch多GPU训练方式 Multi GPU

1、首先定义模型

import torch.nn as nn

class Net(nn.Module):
    def __init__(self):
        pass
    def forward(self, x):
        pass

2、利用DataParallel分布式存储数据和模型

gpuID = '0,1,2,3,4,5,6,7'
device_ids = [int(id) for id in gpuID.split(',')]

import os
os.environ['CUDA_VISIBLE_DEVICES'] = gpuID

device = torch.device('cuda: 0')

import torch
model = Net()
model = torch.nn.DataParallel(model, device_ids=device_ids)
model.to(device)
criterion.to(device)

input, output = input.to(device), output.to(device)

output_ = model(input)

loss = criterion(output, output_)

3、查看nvidia-smi命令即可发现模型训练已经自动分配在全部显卡上

4、貌似指定偶数块GPU没问题,实验过程中,如果指定奇数块GPU,如4,5,6,发现模型只占用了4,5号GPU;而指定4,5,6,7时,模型会占用4,5,6,7号GPU。没搞懂原因。搞懂了,跟batchsize有关。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值