RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!
我原本的代码在未添加 GPU 支持时能够正常运行,但在添加 GPU 支持后,出现了如下错误:
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_CUDA_addmm)
该错误信息表明,部分数据位于 GPU 上,而部分数据位于 CPU 上,由于数据未处于同一设备,从而导致程序出错。
经过排查,定位到存在问题的代码行如下:
predicted = model(torch.from_numpy(x_train).requires_grad_()).data.numpy().to(device)
此处的 to(device)
指定的是 GPU 设备。这行代码报错的原因在于,x_train
是经过 NumPy 处理的数据,而 NumPy 数据无法直接使用 GPU。因此,需要将 x_train
转换为张量(Tensor)形式,并指定其使用 GPU 设备。
将出错的代码修改为:
predicted = model(torch.tensor(x_train).to(device).requires_grad_())