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

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

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

Parameters

Returns

tuple with:

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

hvp (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) 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=), tensor([[2.0239, 1.6456], [2.4988, 1.4310]], 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)) hvp(pow_adder_reducer, inputs, v) (tensor(2.3030), (tensor([0., 0.]), tensor([6., 6.])))

Note

This function is significantly slower than vhp due to backward mode AD constraints. If your functions is twice continuously differentiable, then hvp = vhp.t(). So if you know that your function satisfies this condition, you should use vhp instead that is much faster with the current implementation.