RuntimeError: Expected object of device type cuda but got device type cpu for argument #2 'target'
RuntimeError: Expected object of device type cuda but got device type cpu for argument #2 ‘target’ in call to _thnn_binary_cross_entropy_forward出错误背景:Pytorch中想使用 CUDA 对程序计算进行加速错误的意思:object 的 devic...
·
RuntimeError: Expected object of device type cuda but got device type cpu for argument #2 ‘target’ in call to _thnn_binary_cross_entropy_forward
出错误背景:Pytorch 中想使用 CUDA 对程序计算进行加速
错误的意思:object 的 device 类型期望得到的是 cuda 类型,但是实际上的类型确实 cpu 类型,在调用二分类交叉熵损失进行前向计算的时候
检查下面几点:
- 模型是否放到了CUDA上
model = model.to(device)或model = model.cuda(device) - 输入数据是否放到了CUDA上
data = data.to(device)或data = data.cuda(device) - 模型内部新建的张量是否放到了CUDA上
p = torch.tensor([1]).to(device)或p = torch.tensor([1]).cuda(device)
一般情况下应该是忘记了第三点,而根据提示也可以知道,在进行二分类交叉熵损失进行前向计算的过程中,存在没有放到cuda上的张量,找到他,fix it !!!
其中:device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”)
或者:写一个方法,来判断是否有cuda,然后决定是否放上去:
def trans_to_cuda(variable):
if torch.cuda.is_available():
return variable.cuda()
else:
return variable
# 调用:
model = trans_to_cuda(model)
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)