一、解决方案
找出在cpu的tensor,然后把这些在cpu上的tensor转移到同一cuda上。
import torch
device = torch.device('cuda:0') # 假如我使用的GPU为cuda:0
tensor.to(device) # 将tensor转移到cuda上
以上是网上的解决方案,思路确实没错,但是上面的代码犯了一个小错,就是tensor.to(device)它会返回一个新的tensor地址,如果我们只是执行这行代码,那么tensor实际上还是在cpu上,因为我们没有保存转移到GPU上后的tensor地址。
正确姿势
import torch
device = torch.device('cuda:0') # 假如我使用的GPU为cuda:0
tensor = tensor.to(device) # 将tensor转移到cuda上
二、参考
RuntimeError: Expected all tensors to be on the same device...
本文纠正了关于将CPU上的PyTorch tensor转移到CUDA设备的常见误解,指出仅使用tensor.to(device)不会自动更新原始tensor的引用。正确的做法是直接赋值,如tensor=tensor.to(device),确保tensor在GPU上。避免RuntimeError: Expected all tensors to be on the same device错误。

4万+

被折叠的 条评论
为什么被折叠?



