常规解决方案
从报错问题描述中可以找到错误原因
- 输入的数据类型为
torch.cuda.FloatTensor
,说明输入数据在GPU中 - 模型参数的数据类型为
torch.FloatTensor
,说明模型还在CPU
问题原因搞清楚了,模型没加载到CPU,在代码中加一行语句就可以了
model = model.cuda()
model = model.to('cuda')
model.cuda()
model.to('cuda')
上面四行任选一,还有其他未列出的表述方法,都可以将模型加载到GPU。
反之Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the
问题来源是输入数据没有加载到GPU,解决方法为
tensor = tensor.cuda()
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博客