【问题标题】:type dependence of 'backward ' in pytorchpytorch中'backward'的类型依赖
【发布时间】:2020-10-13 06:40:28
【问题描述】:
x = torch.ones(1, requires_grad=True)
print(x)
y = x + 2.
print(y)
y.backward()
print(x.grad)

-->结果>>>>>

tensor([1.], requires_grad=True)
tensor([3.], grad_fn=<AddBackward0>)
tensor([1.])

这里没有问题。但是,如果我改变类型,我会得到

x = torch.ones(1, requires_grad=True)
x = x.double()
print(x)
y = x + 2.
y = y.double()
print(y)
y.backward()
print(x.grad)

-->结果>>>>>

tensor([1.], dtype=torch.float64, grad_fn=<CopyBackwards>)
tensor([3.], dtype=torch.float64, grad_fn=<AddBackward0>)
None

/usr/local/lib/python3.6/dist-packages/torch/tensor.py:746: UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad attribute won't be populated during autograd.backward(). If you indeed want the gradient for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. If you access the non-leaf Tensor by mistake, make sure you access the leaf Tensor instead. See github.com/pytorch/pytorch/pull/30531 for more informations.
  warnings.warn("The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad "

==============================

有什么区别? 'backward'有'type'限制吗?

【问题讨论】:

    标签: pytorch


    【解决方案1】:

    您正在查看错误的张量;)

    通过调用x = x.double(),您创建了一个新张量,因此当您稍后调用x.grad 时,您将在xdouble() 版本上调用它,这不再是您原来的x

    【讨论】:

    • 是的,但我认为应该会出现新的 x.grad,这应该与第一个代码上的 x.grad 相同。当我向后使用时,dtype 是否有任何限制?
    • 一旦你在 GPU 上执行,dtype 确实很重要,除此之外,反向计算遵循任何其他计算的规则。执行 x_1 = x.double() 然后执行 x.grad ,它将按您的预期工作。
    【解决方案2】:
    The .grad attribute of a Tensor that is not a leaf Tensor is being accessed.
    

    表示您正在访问一个张量的 .grad 字段,PyTorch 永远不会为其填充 .grad 字段。请注意,叶张量将填充其.grad 字段。因此,如果出现此警告,则意味着您认为某事物是叶张量,但实际上并非如此。如果您在需要梯度的张量上执行操作,通常会发生这种情况。

    例如,在你的情况下,

    x = torch.ones(1, requires_grad=True) # x is a leaf tensor
    x = x.double() # x is not a leaf tensor
    

    使用第二个语句,x 不再是叶子,因为它是 .double() 操作的结果。

    【讨论】:

      猜你喜欢
      • 2017-09-08
      • 1970-01-01
      • 2019-06-06
      • 2021-01-06
      • 2013-03-19
      • 1970-01-01
      • 2019-03-12
      • 2015-09-21
      • 1970-01-01
      相关资源
      最近更新 更多