PyTorch GPU训练报错:输入与权重设备类型不匹配求助
问题描述
- 已将输入数据移至GPU,但训练模型时仍报错:
Error: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same or input should be a MKLDNN tensor and weight is a dense tensor
- 检查发现模型和输入数据显示
device='cuda:0',但调用get_device()返回-1,尝试过.to(device)和.cuda()均无效。
解决方案
1. 确保批次数据全量转移GPU
不要只在Dataset初始化时处理设备转移,要保证每个批次的样本都正确移到GPU:
- 可在Dataset的
__getitem__方法中处理:
def __getitem__(self, idx): data = self.data[idx] label = self.labels[idx] return data.to(device), label.to(device)
- 或在训练循环中逐个批次转移:
for batch_data, batch_labels in dataloader: batch_data = batch_data.to(device) batch_labels = batch_labels.to(device) # 执行训练步骤
2. 校验模型所有参数的设备
部分子模块可能未被正确转移到GPU,遍历参数检查:
for name, param in model.named_parameters(): print(name, param.device)
若发现CPU参数,重新执行model = model.to(device),确保模型初始化后未新增未转移的子模块。
3. 排查get_device()返回-1的矛盾
get_device()返回-1说明张量实际在CPU,和显示的device='cuda:0'矛盾时:
- 用
tensor.is_cuda判断真实设备状态:
print(input_tensor.is_cuda) # 输出True才代表张量确实在GPU
- 若DataLoader设置了
num_workers>0,多进程加载可能导致设备转移失效,先将num_workers设为0测试:
dataloader = DataLoader(dataset, num_workers=0, batch_size=32)
4. 同步设备状态排除异步干扰
PyTorch异步操作可能导致设备状态显示异常,添加同步命令后再检查:
torch.cuda.synchronize() print(input_tensor.device) print(next(model.parameters()).device)
内容的提问来源于stack exchange,提问作者user17185383
相关产品推荐
相关产品推荐

