pytorch在GPU中部署神经网络

科普贴:深度学习中GPU和显存分析

1.pytorch的数据类型

torch.dtype是表示torch.Tensor的数据类型的对象。PyTorch有八种不同的数据类型:
在这里插入图片描述

2.动态实时监控GPU的使用

在MobaXterm输入命令:watch --color -n1 gpustat -cpu
在这里插入图片描述

3.torch.device

torch.device代表将torch.Tensor分配到的设备的对象。
(1)python中代码设置可用的GPU设备
import os
os.environ[“CUDA_VISIBLE_DEVICES”] = “0,1,2,3”
(2)构造torch.device
cuda0 = torch.device(‘cuda:0’)
cuda1 = torch.device(‘cuda:1’)
cuda2 = torch.device(‘cuda:2’)
#‘cuda:X’:X是tensor上传的设备的编号
#If you use ‘cuda’ only, Tensors/models will be sent to the default(current) device. (default= 0)

4.pytorch中使用GPU

pytorch中使用GPU十分简单,重点是以下两个方面:
(1)传入device的必须是tensor(且为相同类型的tensor,如longTensor)
(2)模型以及批量数据创建好后需传入device
代码示例:

import torch
import torch.nn as nn

input_size = 5
output_size = 2

class Model(nn.Module):

    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("[In Model]: device",torch.cuda.current_device() ," input size", input.size()," output size", output.size())
        return output
        
device = torch.device('cuda:0')

model = Model(input_size, output_size)
model=model.to(device)

x = torch.Tensor(2,5)
x = x.to(device)
y = model(x)

这里需要注意的是,仅仅调用Tensor.to()只会在GPU上返回一个新的copy,并不会对原来的引用造成变化,因此需要通过赋值rewrite。

4.pytorch之Dataparallel解析

上述只是对单个GPU的使用方法,对于多个GPU,pytorch也提供了封装好的接口——DataParallel,只需要将model 对象放入容器中即可:

model = nn.DataParallel(model)
if torch.cuda.is_available():
   model.cuda()
  input_data.cuda()
output = model(input_var) 

而其并行处理机制是,首先将模型加载到主 GPU 上,然后再将模型复制到各个指定的从 GPU 中,然后将输入数据按 batch 维度进行划分,具体来说就是每个 GPU 分配到的数据 batch 数量是总输入数据的 batch 除以指定 GPU 个数。每个 GPU 将针对各自的输入数据独立进行 forward 计算,最后将各个 GPU 的 loss 进行求和,再用反向传播更新单个 GPU 上的模型参数,再将更新后的模型参数复制到剩余指定的 GPU 中,这样就完成了一次迭代计算。所以该接口还要求输入数据的 batch 数量要不小于所指定的 GPU 数量。
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值