项目场景:
学习pytorch途中将cpu代码转移到gpu上时遇到的一些错误
问题描述
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!
原因分析:
在将代码从cpu转移到gpu时,一定要注意模型和数据都要转移,即模型和数据都要在gpu上,因为模型转移比较方便,只需要模型实例化的时候转移就可以了,所以大多数情况都是数据没转移过去,我这里遇到的问题就是模型转移到gpu了,但是部分数据为转移到gpu,所以报错。
解决方案:
通过调试找到报错的位置,然后看数据的device是否在gpu上,也就是cuda上,找到之后将数据转移到gpu上即可。
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"Using {device} device")
怎样转移呢?将上面这两行代码加到开头,然后在需要转移的数据或者模型调用.to(device)即可。比如:
model = GCNN().to(device) #模型转移
for step,(A,B) in enumerate(data_loader):
# 将数据转移到gpu上
if torch.cuda.is_available():
A=A.to(device)
B=B.to(device)