解决 PyTorch 报错 Expected all tensors to be on the same device 设备不一致修复
排查 PyTorch 报错 Expected all tensors to be on the same device, but found at least two devices: cuda:0 and cpu,统一张量与模型设备。
问题现象
在模型计算或损失函数调用时,控制台抛出设备不匹配的运行时异常:
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)
触发根因
PyTorch 严格要求在同一个算子内部参与数学运算的所有张量(Tensor)以及模型内部的权重参数(Parameter)必须驻留在完全相同的物理硬件设备上。如果模型权重已被转移到 GPU(cuda:0),而 DataLoader 产出的输入张量仍保留在主机的内存(cpu)中,或者自定义模块内部使用 torch.zeros() 临时创建了默认驻留 CPU 的张量,则运算立即崩溃。
解决步骤
1. 定义统一的全局物理设备抽象
在程序入口处统一配置 device 实例:
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = MyModel().to(device)
2. 在训练循环中显式转移输入数据
在取批次数据后,确保数据和标签均转入目标设备:
for batch_idx, (data, target) in enumerate(train_loader):
data = data.to(device, non_blocking=True)
target = target.to(device, non_blocking=True)
output = model(data)
loss = criterion(output, target)
3. 自定义模块中使用 register_buffer 或基于现有张量创建
在自定义 nn.Module 中创建辅助张量时,指定与权重相同的属性:
# 规范写法:基于输入张量的 device 和 dtype 创建,无需硬编码
mask = torch.zeros(batch_size, seq_len, device=inputs.device, dtype=inputs.dtype)
验证确认
执行带检查的单步前向传播测试:
assert next(model.parameters()).device == data.device
output = model(data)
print("Forward pass success on device:", output.device)
输出展示 Forward pass success on device: cuda:0,报错彻底消失。


