Pytorch基础问题RuntimeError: Expected all tensors to be on the same device

Pytorch基础问题RuntimeError: Expected all tensors to be on the same device

Introduction

今天让 Claude 4 Sonnet 给我写Nogo的reinforcement learning的训练代码,结果就直接报错:

RuntimeError: Expected all tensors to be on the same device

我平时不怎么注意细节,为了养成不依赖LLM的好习惯,以后对报错写博客记录一下

Main part

这个错误RuntimeError: Expected all tensors to be on the same device通常出现在把不同设备(比如 CPU 和 GPU)上的张量放在一起进行操作时:

import torch
# 一个张量在 CPU 上
a = torch.tensor([1.0, 2.0])
# 一个张量在 GPU 上(假设有 CUDA)
b = torch.tensor([3.0, 4.0]).to("cuda")

# 尝试把它们加起来会报错
c = a + b  # RuntimeError: Expected all tensors to be on the same device

解决方法是用.to()或.cuda()等方法把它们放到同一个设备上。

torch.device

还是上述代码

print(a.device)
print(b.device)
#打印结果:
# cpu
# cuda:0

设置device

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

一般默认是第一块即cuda:0

但也可以指定具体哪一个:

# 把张量放在第1个GPU(编号0)
a = torch.tensor([1.0, 2.0]).to("cuda:0")
# 放在第2个GPU(编号1)
b = torch.tensor([3.0, 4.0]).to("cuda:1")

当然用我的笔记本必然报错:

RuntimeError: CUDA error: invalid device ordinal**

多卡的时候可以打印一下数量

print(torch.cuda.device_count())

torch.tensor().to()

torch.tensor().to()是 PyTorch 中将张量转移到指定设备(如 CPU 或 GPU)上的方法。

这个函数可以用来显式地将数据放到某个设备上,以便后续运算不报错。

dvc=torch.device("cuda" if torch.cuda.is_available() else "cpu")
#设置指定显卡

a = torch.tensor([1.0, 2.0]).to(dvc)
b = torch.tensor([3.0, 4.0]).to(dvc)
print(a.device)
print(b.device)
c = a + b
print(c)
#打印结果:
# cuda:0
# cuda:0
# tensor([4., 6.], device='cuda:0')

Summary

显示调用张量位置是个好习惯,尤其是多卡训练的情况

  1. 排查错误的关键线索

多卡环境下最常见的错误是:

RuntimeError: Expected all tensors to be on the same device

如果你在关键位置加上.device显示,可以快速发现是谁跑偏了。

  1. 防止设备错配(如模型在 GPU0,数据在 GPU1)
print("model on:", next(model.parameters()).device)
print("inputs on:", inputs.device)

这些信息一眼就能看出是否匹配。

  1. 帮助调试和日志记录

在训练日志中打印 device 信息,比如:

print(f"Epoch {epoch}: input.device={inputs.device}, label.device={labels.device}")

可以让你在远程服务器、异步运行、多卡调度环境中更清楚程序状态。