Pytorch出现RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor)

常规解决方案

从报错问题描述中可以找到错误原因

  • 输入的数据类型为torch.cuda.FloatTensor,说明输入数据在GPU中
  • 模型参数的数据类型为torch.FloatTensor,说明模型还在CPU

问题原因搞清楚了,模型没加载到CPU,在代码中加一行语句就可以了

  1. model = model.cuda()
  2. model = model.to('cuda')
  3. model.cuda()
  4. model.to('cuda')

上面四行任选一,还有其他未列出的表述方法,都可以将模型加载到GPU。

反之Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the问题来源是输入数据没有加载到GPU,解决方法为

  1. tensor = tensor.cuda()
  2. tensor = tensor.to('cuda')

任选任选~

但是要注意直接tensor.to('cuda')等方法不行,

原因:

Module.to() 是一个“in-place”方法,tensor.to() 函数不是。tensor.to() 这个函数功能是产生一个新的tensor,并不会改变原数据。

疑难杂症

有时已经写了将模型和输入数据加载到GPU的语句,但还是报了这个错误。

检查模型和输入加载位置
模型

print(next(model.parameters()).is_cuda)

输入数据

print(tensor.device)

如果print(next(model.parameters()).is_cuda)的输出结果为False,那说明该模块没有放在gpu上。例如:我在__init__中用List包装了一些层,

self.group_list.append(MRF(dim_in, dim_out))
    for i in range(mrf_num - 1):
        group = MRF(dim_out, dim_out)
        self.group_list.append(group)

forword中调用时group时next(group.parameters()).is_cuda为False

那么在应该再加一句:
self.group_lists=nn.Sequential(*list([m for m in self.group_list]))

self.group_list.append(MRF(dim_in, dim_out))
    for i in range(mrf_num - 1):
        group = MRF(dim_out, dim_out)
        self.group_list.append(group)
self.group_lists=nn.Sequential(*list([m for m in self.group_list]))

此时再运行next(group.parameters()).is_cuda为True。

参考:1.https://www.iotword.com/2424.html

2. https://www.cnblogs.com/nmpanda/p/13047451.html

3. Pytorch出现RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) sh... - 简书4. Pytorch避坑之:RuntimeError: Input type(torch.cuda.FloatTensor) and weight type(torch.FloatTensor) shoul_暖仔会飞的博客-CSDN博客
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值