RuntimeError: indices should be either on cpu or on the same device as the indexed tensor (cpu)

前言

在训练代码(旋转目标框检测)出现以下错误提示:

RuntimeError: indices should be either on cpu or on the same device as the indexed tensor (cpu)

问题分析

出现这个错误通常是由于:部分在GPU上运行,部分在CPU上运行;

比如:a = at [j] ,这里本来是想将变量at中下标为j的元素赋值给变量a。

我们打印一下 at操作和 j 数据的情况:

at device: cpu

j device: cuda:0

所以报错啦~

解决方法

首先定位是哪一行代码出错了

扫描二维码关注公众号,回复: 14943162 查看本文章

然后,把那一行代码的变量打印一下:

print(f"at device: {at.device}")
print(f"j device: {j.device}")

再进行类型转换

  1. 可以将变量,从CPU转到GPU(cuda)中;
  2. 或者将变量,从GPU(cuda)转到CPU中;

这个取决于后续代码所需的类型,比如a = at [j]中,后续需要GPU类型的数据,那么我们把变量at转为GPU中即可:

at = at.to(j.device)
a = at[j]

如果at变量本来不是张量,不能直接转换,使用下面的方式实现: 

at_tensor = torch.tensor(at)
at_tensor = at_tensor.to(j.device)

a = at_tensor[j]

修改完成~

知识扩展

这个错误通常是由于以下原因之一:

  1. 张量和张量B不在同一个设备上(例如,一个在CPU上,一个在GPU上)。
  2. 张量A在CPU上,而张量B在GPU上。

由于 PyTorch 要求在同一操作中,张量A和张量B在同一个设备上,所以出现这个错误。要解决这个问题,可以将张量A转换为和张量B相同的设备上的张量。

可以使用以下代码将张量转换为CUDA张量(在GPU上):

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
tensor = tensor.to(device)

想将张量转换为CPU张量,可以使用以下代码:

tensor = tensor.cpu()

确保所有张量都在同一个设备上后,应该能够解决这个错误。

猜你喜欢

转载自blog.csdn.net/qq_41204464/article/details/130359266
cpu