解决RuntimeError: Expected all tensors to be on the same device, but found at least two devices,

目录

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

2.错误:Tensor for argument #2 ‘mat1’ is on CPU, but expected it to be on GPU (while checking arguments for addmm)


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

原因:参与运算的两个或多个变量,有的在CPU上,有的在GPU上

解决:

  1. 首先找到报错的行,看看计算时都用到哪些变量或者数据,然后在调试模式下使用.is_cuda这个属性去查看到底哪些是在GPU上,哪些是在CPU上,然后把它们统一都放在CPU,或者统一放在GPU上就可以。
  2. 如果增加了变量,需要将新增加的变量也搬到GPU上去
g.ndata['norm'] = norm.unsqueeze(1)
g = g.to(device)

2.错误:Tensor for argument #2 ‘mat1’ is on CPU, but expected it to be on GPU (while checking arguments for addmm)

为了使模型在GPU上进行计算,需要将变量和模型都增加.to(device),都搬到GPU上去即可

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

g = g.to(device)

model=model.to(device)

你可能感兴趣的:(机器学习)