Expected one of xxx device type 解决方法

问题

出错代码:

DEVICE = torch.device(‘gpu’ if torch.cuda.is_available() else ‘cpu’)

报错信息:

RuntimeError: Expected one of cpu, cuda, xpu, mkldnn, opengl, opencl,
ideep, hip, ve, ort, mlc, xla, lazy, vulkan, meta, hpu device type at
start of device string: gpu

原理

无法识别“gpu”这个字符串,只能识别“cpu, cuda, xpu, mkldnn, opengl, opencl, ideep, hip, ve, ort, mlc, xla, lazy, vulkan, meta, hpu”这样的字符串

解决

将“gpu”改为训练用的设备字符串,我用的是cuda,所以写为

device = torch.device(‘cuda’ if torch.cuda.is_available() else ‘cpu’)

参考文章:https://blog.csdn.net/u014264373/article/details/87640753

衍生问题

出错代码:

if torch.cuda.is_available():#是否可以gpu加速
correct += (predict.gpu() == labels.gpu()).sum()
else:
correct += (predict == labels).sum()

报错信息:

AttributeError: ‘Tensor’ object has no attribute ‘gpu’

原理

device选择的加速设备名称是Tensor的合法属性。由于我使用的设备是cuda,则gpu应该改为cuda。

解决

将“gpu”改为训练用的设备字符串。根据使用的设备名确定修改的属性名称。

if torch.cuda.is_available():#是否可以gpu加速
correct += (predict.cuda() == labels.cuda()).sum()
else:
correct += (predict == labels).sum()

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

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

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年8月22日
下一篇 2023年8月22日

相关推荐