Pytorch参数注册和nn.ModuleList nn.ModuleDict的问题

作者:luputo 时间:2021-02-10 23:43:06 

参考自官方文档

参数注册

尝试自己写GoogLeNet时碰到的问题,放在字典中的参数无法自动注册,所谓的注册,就是当参数注册到这个网络上时,它会随着你在外部调用net.cuda()后自动迁移到GPU上,而没有注册的参数则不会随着网络迁到GPU上,这就可能导致输入在GPU上而参数不在GPU上,从而出现错误,为了说明这个现象。

举一个有点铁憨憨的例子:

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.weight = torch.rand((3,4)) # 这里其实可以直接用nn.Linear,但为了举例这里先憨憨一下
    
    def forward(self,x):
        return F.linear(x,self.weight)

if __name__ == "__main__":
    batch_size = 10
    dummy = torch.rand((batch_size,4))
    net = Net()
    print(net(dummy))

上面的代码可以成功运行,因为所有的数值都是放在CPU上的,但是,一旦我们要把模型移到GPU上时

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.weight = torch.rand((3,4))
    
    def forward(self,x):
        return F.linear(x,self.weight)

if __name__ == "__main__":
    batch_size = 10
    dummy = torch.rand((batch_size,4)).cuda()
    net = Net().cuda()
    print(net(dummy))

运行后就会出现

...
RuntimeError: Expected object of backend CUDA but got backend CPU for argument #2 'mat2'

这就是因为self.weight没有随着模型一起移到GPU上的原因,此时我们查看模型的参数,会发现并没有self.weight

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.weight = torch.rand((3,4))
    
    def forward(self,x):
        return F.linear(x,self.weight)

if __name__ == "__main__":
    net = Net()
    for parameter in net.parameters():
        print(parameter)

上面的代码没有输出,因为net根本没有参数

那么为了让net有参数,我们需要手动地将self.weight注册到网络上

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.weight = nn.Parameter(torch.rand((3,4))) # 被注册的参数必须是nn.Parameter类型
        self.register_parameter('weight',self.weight) # 手动注册参数
        
    
    def forward(self,x):
        return F.linear(x,self.weight)

if __name__ == "__main__":
    net = Net()
    for parameter in net.parameters():
        print(parameter)

    batch_size = 10
    net = net.cuda()
    dummy = torch.rand((batch_size,4)).cuda()
    print(net(dummy))

此时网络的参数就有了输出,同时会随着一起迁到GPU上,输出就类似这样

Parameter containing:
tensor([...])
tensor([...])

不过后来我实验了以下,好像只写nn.Parameter不写register也可以被默认注册

nn.ModuleList和nn.ModuleDict

有时候我们为了图省事,可能会这样写网络

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.linears = [nn.Linear(4,4),nn.Linear(4,4),nn.Linear(4,2)]
    
    def forward(self,x):
        for linear in self.linears:
            x = linear(x)
            x = F.relu(x)
        return x

if __name__ == '__main__':
    net = Net()
    for parameter in net.parameters():
        print(parameter)  

     

同样,输出网络的参数啥也没有,这意味着当调用net.cuda时,self.linears里面的参数不会一起走到GPU上去

此时我们可以在__init__方法中手动对self.parameters()迭代然后把每个参数注册,但更好的方法是,pytorch已经为我们提供了nn.ModuleList,用来代替python内置的list,放在nn.ModuleList中的参数将会自动被正确注册

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.linears = nn.ModuleList([nn.Linear(4,4),nn.Linear(4,4),nn.Linear(4,2)])
    
    def forward(self,x):
        for linear in self.linears:
            x = linear(x)
            x = F.relu(x)
        return x

if __name__ == '__main__':
    net = Net()
    for parameter in net.parameters():
        print(parameter)        

此时就有输出了

Parameter containing:
tensor(...)
Parameter containing:
tensor(...)
...

nn.ModuleDict也是类似,当我们需要把参数放在一个字典里的时候,能够用的上,这里直接给一个官方的例子看一看就OK

class MyModule(nn.Module):
    def __init__(self):
        super(MyModule, self).__init__()
        self.choices = nn.ModuleDict({
                'conv': nn.Conv2d(10, 10, 3),
                'pool': nn.MaxPool2d(3)
        })
        self.activations = nn.ModuleDict([
                ['lrelu', nn.LeakyReLU()],
                ['prelu', nn.PReLU()]
        ])

    def forward(self, x, choice, act):
        x = self.choices[choice](x)
        x = self.activations[act](x)
        return x

需要注意的是,虽然直接放在python list中的参数不会自动注册,但如果只是暂时放在list里,随后又调用了nn.Sequential把整个list整合起来,参数仍然是会自动注册的

另外一点要注意的是ModuleList和ModuleDict里面只能放Module的子类,也就是nn.Conv,nn.Linear这样的,但不能放nn.Parameter,如果要放nn.Parameter,用nn.ParameterList即可,用法和nn.ModuleList一样

来源:https://blog.csdn.net/luo3300612/article/details/97815207

标签:Pytorch,参数注册,nn.ModuleList,nn.ModuleDict
0
投稿

猜你喜欢

  • JavaScript正则表达式的简单应用:高亮显示

    2008-07-20 12:46:00
  • Python爬虫之用Xpath获取关键标签实现自动评论盖楼抽奖(二)

    2021-02-11 00:58:03
  • python turtle绘图命令及案例

    2022-04-29 10:26:58
  • ASP+JAVAScript:复杂表单的动态生成与验证

    2007-10-06 21:51:00
  • Python接口自动化之接口依赖

    2021-09-03 15:53:09
  • pandas dataframe drop函数介绍

    2023-07-11 17:19:17
  • Python实现连接dr校园网示例详解

    2022-09-20 05:00:45
  • Yii配置与使用memcached缓存的方法

    2023-11-05 06:34:45
  • Python队列RabbitMQ 使用方法实例记录

    2021-01-30 22:38:26
  • JS target与currentTarget区别说明

    2023-08-22 20:14:40
  • 如何绝对获知浏览器类型?

    2009-12-16 18:58:00
  • python3实现ftp服务功能(客户端)

    2023-05-28 00:36:31
  • php生成随机数/生成随机字符串的方法小结【5种方法】

    2023-09-05 20:23:21
  • Python中的布尔类型bool

    2023-08-11 13:10:00
  • SQL SERVER数据库开发之触发器的应用

    2008-06-23 13:09:00
  • 动态导航设计

    2008-09-21 13:40:00
  • 特效代码:弹出一个淡入淡出的提示框

    2008-05-22 17:11:00
  • Python学习笔记之装饰器

    2021-03-03 02:02:48
  • Python基于回溯法子集树模板解决取物搭配问题实例

    2023-11-20 04:46:53
  • python config文件的读写操作示例

    2022-04-05 07:42:11
  • asp之家 网络编程 m.aspxhome.com