torch.autograd.functional.vhp — PyTorch 2.7 documentation (original) (raw)

torch.autograd.functional.vhp(func, inputs, v=None, create_graph=False, strict=False)[source][source]

Compute the dot product between vector v and Hessian of a given scalar function at a specified point.

Parameters

Returns

tuple with:

func_output (tuple of Tensors or Tensor): output of func(inputs)

vhp (tuple of Tensors or Tensor): result of the dot product with the same shape as the inputs.

Return type

output (tuple)

Example

def pow_reducer(x): ... return x.pow(3).sum() inputs = torch.rand(2, 2) v = torch.ones(2, 2) vhp(pow_reducer, inputs, v) (tensor(0.5591), tensor([[1.0689, 1.2431], [3.0989, 4.4456]])) vhp(pow_reducer, inputs, v, create_graph=True) (tensor(0.5591, grad_fn=), tensor([[1.0689, 1.2431], [3.0989, 4.4456]], grad_fn=)) 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)) vhp(pow_adder_reducer, inputs, v) (tensor(4.8053), (tensor([0., 0.]), tensor([6., 6.])))