用pytorch包搭建神经网络时,经常遇到GPU和CPU的指定问题,有时候明明指定了GPU(cuda)却依然会报错,下面将这些常见的错误整理出来。
问题一
RuntimeError: Expected object of device type cuda but got device type cpu for argument #2 ‘target’
除了上面博文提到的三种情况以外,还有一种可能是变量的设备指定方式有问题,如下:
device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu")
a.to(device) # 第一种方式
a = a.to(device) # 第二种方式
上面第一种方式是无效的,必须用第二种方式才能真正将a送入cuda中。
问题二
RuntimeError: expected device cpu but got device cuda:0
这种情况除了这篇博文说的左右两边类型不一致,更多可能是右边某个参数忘记指定设备了,比如:
a = a.to(device)
b = b.to(device)
d = a + b + c
这个时候如果c没有指定类型为device就会报上面的错误,实际中要仔细检查一下是不是每个变量的类型都指定为相同设备了。
(后续若遇到类似问题再继续更新)
问题三
RuntimeError: Expected object of backend CUDA but got backend CPU for sequence element 14 in sequence argument at position #1 ‘tensors’