torch.func.hessian¶
- torch.func.hessian(func, argnums=0)[source]¶
通过前向-反向策略计算
func
对索引argnum
处参数的 Hessian。前向-反向策略(组合
jacfwd(jacrev(func))
)是实现良好性能的默认选择。也可以通过jacfwd()
和jacrev()
的其他组合来计算 Hessian,例如jacfwd(jacfwd(func))
或jacrev(jacrev(func))
。- 参数
- 返回
返回一个函数,该函数接受与
func
相同的输入,并返回func
相对于argnums
处参数的 Hessian。
注意
您可能会遇到此 API 报告“前向模式 AD 未为运算符 X 实现”的错误。如果发生这种情况,请提交 bug 报告,我们将优先处理。另一种选择是使用
jacrev(jacrev(func))
,它具有更好的运算符覆盖范围。对于 R^N -> R^1 函数,基本用法会得到一个 N x N 的 Hessian 矩阵
>>> from torch.func import hessian >>> def f(x): >>> return x.sin().sum() >>> >>> x = torch.randn(5) >>> hess = hessian(f)(x) # equivalent to jacfwd(jacrev(f))(x) >>> assert torch.allclose(hess, torch.diag(-x.sin()))