thop profile函数遇到nn.DataParallel()时的错误

问题描述:

在神经网络中,常用 From thop import profile 来计算FLOPs和Parameters来作为神经网络模型的评价指标。我在使用该函数时程序报如下错误:RuntimeError: module must have its parameters and buffers on device cuda:0 (device_ids[0]) but found one of them on device: cpu

 解决方式:

我在CSDN上查了半天没有遇到类似的问题,于是上了thop的github官网,企图在issue里找到答案,结果在真给我找到了。issue的网站如下:https://github.com/Lyken17/pytorch-OpCounter/issues/131

我们只需要将源代码:

if torch.cuda.device_count() > 1:
    model = nn.DataParallel(model)

input = torch.randn(1, 8, 224, 224).to(device)
flops, params = profile(model, inputs = (input, ))

修改为:

if torch.cuda.device_count() > 1:
    model = nn.DataParallel(model)

input = torch.randn(1, 8, 224, 224).to(device)
flops, params = profile(model.module, inputs = (input, ))

问题就完美解决了。

另外需要注意的是,如果是用GPU加载模型,则需要在input后面加上to(device),否则会出现RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same报错

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值