【问题标题】:Computing gradients of intermediate nodes in PyTorch在 PyTorch 中计算中间节点的梯度
【发布时间】:2018-01-02 13:38:42
【问题描述】:

我正在尝试了解 autograd 在 PyTorch 中的工作原理。在下面的简单程序中,我不明白为什么loss w.r.t W1W2 的渐变是None 据我从文档中了解到,W1W2 是不稳定的,因此无法计算梯度。 是这样吗?我的意思是,我怎么不能对中间节点的损失求导?谁能解释一下我在这里缺少什么?

import torch
import torch.autograd as tau

W = tau.Variable(torch.FloatTensor([[0, 1]]), requires_grad=True)
a = tau.Variable(torch.FloatTensor([[2, 2]]), requires_grad=False)
b = tau.Variable(torch.FloatTensor([[3, 3]]), requires_grad=False)

W1 = W  + a * a
W2 = W1 - b * b * b
Z = W2 * W2

print 'W:', W
print 'W1:', W1
print 'W2:', W2
print 'Z:', Z

loss = torch.sum((Z - 3) * (Z - 3))
print 'loss:', loss

# free W gradient buffer in case you are running this cell more than 2 times
if W.grad is not None: W.grad.data.zero_()

loss.backward()
print 'W.grad:', W.grad

# all of them are None
print 'W1.grad:', W1.grad
print 'W2.grad:', W2.grad
print 'a.grad:', a.grad
print 'b.grad:', b.grad
print 'Z.grad:', Z.grad

【问题讨论】:

    标签: pytorch


    【解决方案1】:

    当需要时,中间梯度会累积in a C++ buffer,但为了节省内存,默认情况下不会保留它们(暴露在 python 对象中)。 只有使用requires_grad=True 设置的叶变量的梯度将被保留(因此在您的示例中为W

    保留中间渐变的一种方法是注册一个钩子。这项工作的一个钩子是retain_grad() (see PR) 在你的例子中,如果你写W2.retain_grad()W2的中间渐变将暴露在W2.grad

    W1W2 不是 volatile 的(您可以通过访问它们的 volatile 属性(即:W1.volatile)来检查)并且不能因为它们不是叶变量(例如 W、@987654334 @ 和 b)。相反,需要计算它们的梯度,参见它们的requires_grad 属性。 如果只有一个叶变量是volatile,则整个后向图都没有构造(可以通过做一个volatile来检查,看看loss梯度函数)

    a = tau.Variable(torch.FloatTensor([[2, 2]]), volatile=True)
    # ...
    assert loss.grad_fn is None
    

    总结一下

    • 波动性意味着没有梯度计算:在推理模式下很有用
      • 只有一个叶变量设置为 volatile 禁用梯度计算
    • 需要梯度意味着梯度计算。中间的暴露与否
      • 只有一个叶变量需要梯度启用梯度计算

    【讨论】:

    • 感谢您的回答。现在更清楚了。
    • 嗨,那是哪个 pytorch 版本?在 0.3 和 0.4 中,即使我设置了 W2.retain_grad=True,我也不会得到 W2.grad
    • 嗨,我想它是 v0.3。为了在 W2 上保留中间渐变,您是否尝试过使用 requires_grad=True 初始化 W 变量(如 OP' 问题中所示)并在 W2调用 retain_grad() ? (另外,将W2.retain_grad 设置为True 将覆盖旨在通过挂钩有效保留渐变的方法)
    猜你喜欢
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    相关资源
    最近更新 更多