評價此頁

torch.autograd.functional.hvp#

torch.autograd.functional.hvp(func, inputs, v=None, create_graph=False, strict=False)[原始碼]#

在指定點計算標量函式的海森矩陣與向量 v 的點積。

引數
  • func (function) – 一個接受 Tensor 輸入並返回具有單個元素的 Tensor 的 Python 函式。

  • inputs (tuple of TensorsTensor) – 函式 func 的輸入。

  • v (tuple of TensorsTensor) – 計算海森向量乘積的向量。其大小必須與 func 的輸入相同。當 func 的輸入只包含一個元素時,此引數是可選的,並且(如果未提供)將被設定為一個包含單個 1 的 Tensor。

  • create_graph (bool, 可選) – 如果為 True,則輸出和結果都將以可微分的方式計算。請注意,當 strictFalse 時,結果不能要求梯度或與輸入斷開連線。預設為 False

  • strict (bool, 可選) – 如果為 True,則在我們檢測到存在一個輸入,使得所有輸出都與其無關時,將引發錯誤。如果為 False,我們將為該輸入返回一個零 Tensor 作為 hvp,這在數學上是期望值。預設為 False

返回

包含以下內容的元組

func_output (tuple of Tensors or Tensor): func(inputs) 的輸出

hvp (tuple of Tensors 或 Tensor): 與輸入形狀相同的點積結果。

返回型別

output (tuple)

示例

>>> def pow_reducer(x):
...     return x.pow(3).sum()
>>> inputs = torch.rand(2, 2)
>>> v = torch.ones(2, 2)
>>> hvp(pow_reducer, inputs, v)
(tensor(0.1448),
 tensor([[2.0239, 1.6456],
         [2.4988, 1.4310]]))
>>> hvp(pow_reducer, inputs, v, create_graph=True)
(tensor(0.1448, grad_fn=<SumBackward0>),
 tensor([[2.0239, 1.6456],
         [2.4988, 1.4310]], grad_fn=<MulBackward0>))
>>> def pow_adder_reducer(x, y):
...     return (2 * x.pow(2) + 3 * y.pow(2)).sum()
>>> inputs = (torch.rand(2), torch.rand(2))
>>> v = (torch.zeros(2), torch.ones(2))
>>> hvp(pow_adder_reducer, inputs, v)
(tensor(2.3030),
 (tensor([0., 0.]),
  tensor([6., 6.])))

注意

由於後端 AD 的限制,此函式比 vhp 慢得多。如果您的函式是兩次連續可微的,則 hvp = vhp.t()。因此,如果您知道您的函式滿足此條件,則應使用 vhp,它在當前實現中速度要快得多。