Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

问题描述:

这类问题属于tensor关于内存的问题,就是说进行运算的tensor放在了不同的设备上。

Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

 注意,也有其他的错误表达:

Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor)

上述表面意思是:输入类型属于在CPU上,而权重类型属于在GPU上。

解决方案:

就一句话,跟踪步骤指定设备

比如现在我有一块代码:

Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

main函数部分: 

Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

运行报错:

Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

我先在代码最上方加一句:

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

然后怎么跟踪步骤呢?在红框位置单击:

Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

你肯定会问为什么是这里?首先红框底下都是底层运算,先不会考虑这里的运算涉及到不同的设备(麻烦),而上面是先跳到main(),再到tst这个函数里面,运行到logits=model(img)这里出现的问题。

点击,修改输入参数img到GPU设备上,即

logits = model(img.to(device))

再运行,报错位置变了,说明上个位置问题解决了,但仍然报错如下:

Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

 点击红框位置,原因类似上面,修改这一行代码为:

loss = criterion(logits, label.to(device))

 注意,这里前面的logits已经是to(device)的结果,不用再to(device)

再运行,报错位置又变了,但仍然报错如下:

Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

应该不用我讲了,直接点击红框位置,修改代码如下:

top1_acc = torch.eq(pred, label.to(device)).sum().item() / len(img)

 这里加to(device)的位置有点难,但是大家记住原始的问题,是输入不在device(GPU)上,所以我们需要修改的是输入(函数的参数)让其to(device)。

然后,再运行,成功。

总结:

看代码报错信息和位置(读错误真的很重要),一步步找device不同的代码修改。遇到类似的问题才能举一反三。

希望对你有帮助。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年2月25日
下一篇 2023年2月25日

相关推荐