评价此页

torch.autograd.functional.hessian#

torch.autograd.functional.hessian(func, inputs, create_graph=False, strict=False, vectorize=False, outer_jacobian_strategy='reverse-mode')[源代码]#

计算给定标量函数的 Hessian。

参数
  • func (function) – 一个接受 Tensor 输入并返回具有单个元素的 Tensor 的 Python 函数。

  • inputs (tuple of TensorsTensor) – 函数 func 的输入。

  • create_graph (bool, optional) – 如果为 True,则 Hessian 将以可微分的方式计算。请注意,当 strictFalse 时,结果不能要求梯度或与输入断开连接。默认为 False

  • strict (bool, optional) – 如果为 True,当检测到存在某个输入,所有输出都与该输入无关时,将引发错误。如果为 False,我们将为该输入返回一个零张量作为 Hessian,这与数学预期值一致。默认为 False

  • vectorize (bool, optional) – 此功能仍处于实验阶段。如果您正在寻找更少实验性且性能更高的替代方案,请考虑使用 torch.func.hessian()。在计算 Hessian 时,通常我们会为 Hessian 的每一行调用一次 autograd.grad。如果此标志为 True,我们将使用 vmap 原型功能作为后端来矢量化对 autograd.grad 的调用,因此我们只调用一次,而不是每行调用一次。这在许多用例中应能提高性能,但由于此功能尚不完整,可能会出现性能下降。请使用 torch._C._debug_only_display_vmap_fallback_warnings(True) 显示任何性能警告,如果您的用例存在警告,请向我们提交 issue。默认为 False

  • outer_jacobian_strategy (str, optional) – Hessian 通过计算 Jacobian 的 Jacobian 来计算。内部 Jacobian 始终以反向模式 AD 计算。将策略设置为 "forward-mode""reverse-mode" 决定了外部 Jacobian 是使用前向模式还是反向模式 AD 计算。目前,使用 "forward-mode" 计算外部 Jacobian 需要 vectorized=True。默认为 "reverse-mode"

返回

如果有一个输入,这将是一个包含输入 Hessian 的单个张量。如果它是一个元组,那么 Hessian 将是一个元组的元组,其中 Hessian[i][j] 将包含第 i 个输入和第 j 个输入的 Hessian,大小为第 i 个输入的大小加上第 j 个输入的大小之和。Hessian[i][j] 将具有与相应的第 i 个输入相同的 dtype 和 device。

返回类型

Hessian (Tensor 或张量元组)

示例

>>> def pow_reducer(x):
...     return x.pow(3).sum()
>>> inputs = torch.rand(2, 2)
>>> hessian(pow_reducer, inputs)
tensor([[[[5.2265, 0.0000],
          [0.0000, 0.0000]],
         [[0.0000, 4.8221],
          [0.0000, 0.0000]]],
        [[[0.0000, 0.0000],
          [1.9456, 0.0000]],
         [[0.0000, 0.0000],
          [0.0000, 3.2550]]]])
>>> hessian(pow_reducer, inputs, create_graph=True)
tensor([[[[5.2265, 0.0000],
          [0.0000, 0.0000]],
         [[0.0000, 4.8221],
          [0.0000, 0.0000]]],
        [[[0.0000, 0.0000],
          [1.9456, 0.0000]],
         [[0.0000, 0.0000],
          [0.0000, 3.2550]]]], grad_fn=<ViewBackward>)
>>> def pow_adder_reducer(x, y):
...     return (2 * x.pow(2) + 3 * y.pow(2)).sum()
>>> inputs = (torch.rand(2), torch.rand(2))
>>> hessian(pow_adder_reducer, inputs)
((tensor([[4., 0.],
          [0., 4.]]),
  tensor([[0., 0.],
          [0., 0.]])),
 (tensor([[0., 0.],
          [0., 0.]]),
  tensor([[6., 0.],
          [0., 6.]])))