【问题标题】:PyTorch: RuntimeError: Function MulBackward0 returned an invalid gradient at index 0 - expected type torch.cuda.FloatTensor but got torch.FloatTensorPyTorch:RuntimeError:函数 MulBackward0 在索引 0 处返回无效梯度 - 预期类型为 torch.cuda.FloatTensor 但得到了 torch.FloatTensor
【发布时间】:2019-08-30 11:08:18
【问题描述】:

我不明白这个错误告诉我什么。在a different post 中也解决了同样的问题,但没有有用的解决方案。

Traceback (most recent call last):
  File "train.py", line 252, in <module>
    main()
  File "train.py", line 231, in main
    train(net, training_dataset, targets, device, criterion, optimizer, epoch, args.epochs)
  File "train.py", line 103, in train
    loss.backward()
  File "/home/hb119056/.local/lib/python3.6/site-packages/torch/tensor.py", line 107, in backward
    torch.autograd.backward(self, gradient, retain_graph, create_graph)
  File "/home/hb119056/.local/lib/python3.6/site-packages/torch/autograd/__init__.py", line 93, in backward
    allow_unreachable=True)  # allow_unreachable flag
RuntimeError: Function MulBackward0 returned an invalid gradient at index 0 - expected type torch.cuda.FloatTensor but got torch.FloatTensor

这是我的代码中的相应段。

outputs = net(x, indices)
outputs = outputs.transpose(0, 1)
prob = F.normalize(outputs, p=1, dim=1).detach()
target = torch.from_numpy(np.load(file_dir + '/points/points{:03}.npy'.format(i))).to(device)
rv = torch.zeros(12 * outputs.shape[0])

for j in [x for x in range(10) if x != i]:
    source = torch.from_numpy(np.load(file_dir + '/points/points{:03}.npy'.format(j))).to(device)
    rv = factor.ransac(source, target, prob, n_iter, tol, device) # self-written

predicted = factor.predict(source, rv, outputs, device) # self-written
loss = criterion(predicted, target.type(torch.FloatTensor).to(device))
loss.backward() # error occurs here
optimizer.step()

非常感谢任何帮助,提前谢谢!

【问题讨论】:

标签: python pytorch backpropagation


【解决方案1】:

尝试改变 loss = criterion(predicted, target.type(torch.FloatTensor).to(device))loss = criterion(predicted, target.to(device).float())

【讨论】:

  • 你不是故意打电话给zero_grad吗?不确定这是否相关。无论如何,可以尝试使用类型打印预测和目标的设备(在移动它之后)
  • 在代码 sn-p 开始之前,我正在调用 zero_grad。嗯移动后两个设备都是cuda:0,类型是torch.cuda.FloatTensor
  • 好吧,也许这是您面临的一个非常具体的问题
【解决方案2】:

改变这一行:

loss = criterion(predicted, target.type(torch.FloatTensor).to(device))

predicted = predicted.to(device)
target=target.type(predicted.type()).to(predicted.device)
loss = criterion(predicted, target)

【讨论】:

  • 这是您答案第一行的错误TypeError: dtype must be a type, str, or dtype object
  • 我又试了一次,现在错误又和一开始一样了。
  • 嗯。我再次更新。顺便说一句,我不确定你的 predictedtarget 是什么类型。 device 的值是多少。
  • 修改target后,两台设备都是cuda:0,类型是torch.cuda.FloatTensor
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2018-12-07
  • 1970-01-01
  • 2018-08-30
  • 2018-12-29
  • 1970-01-01
相关资源
最近更新 更多