torch.func.jacfwd#
- torch.func.jacfwd(func, argnums=0, has_aux=False, *, randomness='error')[source]#
使用前向模式自动微分计算
func
相对于argnum
索引处的参数(们)的雅可比矩阵。- 参数
func (function) – A Python function that takes one or more arguments, one of which must be a Tensor, and returns one or more Tensors
argnums (int or Tuple[int]) – 可选,整数或整数元组,用于指定要计算雅可比矩阵的参数。默认值:0。
has_aux (bool) – 指示
func
返回一个(output, aux)
元组的标志,其中第一个元素是要微分的函数的输出,第二个元素是不会被微分的辅助对象。默认值:False。randomness (str) – 指示要使用的随机性类型的标志。更多详细信息请参阅
vmap()
。允许的值:“different”、“same”、“error”。默认值:“error”。
- 返回
返回一个函数,该函数接受与
func
相同的输入,并返回func
相对于argnums
中指定参数的 Jacobian。如果has_aux 为 True
,则返回的函数将返回一个(jacobian, aux)
元组,其中jacobian
是 Jacobian,aux
是func
返回的辅助对象。
注意
您可能会看到此 API 因“前向模式 AD 未对操作符 X 实现”而报错。如果遇到这种情况,请提交一个 Bug 报告,我们会优先处理。另一种选择是使用
jacrev()
,它的操作符覆盖范围更广。A basic usage with a pointwise, unary operation will give a diagonal array as the Jacobian
>>> from torch.func import jacfwd >>> x = torch.randn(5) >>> jacobian = jacfwd(torch.sin)(x) >>> expected = torch.diag(torch.cos(x)) >>> assert torch.allclose(jacobian, expected)
jacfwd()
可以与 vmap 组合以生成批处理的雅可比矩阵。>>> from torch.func import jacfwd, vmap >>> x = torch.randn(64, 5) >>> jacobian = vmap(jacfwd(torch.sin))(x) >>> assert jacobian.shape == (64, 5, 5)
If you would like to compute the output of the function as well as the jacobian of the function, use the
has_aux
flag to return the output as an auxiliary object>>> from torch.func import jacfwd >>> x = torch.randn(5) >>> >>> def f(x): >>> return x.sin() >>> >>> def g(x): >>> result = f(x) >>> return result, result >>> >>> jacobian_f, f_x = jacfwd(g, has_aux=True)(x) >>> assert torch.allclose(f_x, f(x))
此外,
jacrev()
可以与其自身或jacrev()
组合以生成海森矩阵。>>> from torch.func import jacfwd, jacrev >>> def f(x): >>> return x.sin().sum() >>> >>> x = torch.randn(5) >>> hessian = jacfwd(jacrev(f))(x) >>> assert torch.allclose(hessian, torch.diag(-x.sin()))
默认情况下,
jacfwd()
会计算相对于第一个输入的雅可比矩阵。但是,您可以使用argnums
来计算相对于其他参数的雅可比矩阵。>>> from torch.func import jacfwd >>> def f(x, y): >>> return x + y ** 2 >>> >>> x, y = torch.randn(5), torch.randn(5) >>> jacobian = jacfwd(f, argnums=1)(x, y) >>> expected = torch.diag(2 * y) >>> assert torch.allclose(jacobian, expected)
Additionally, passing a tuple to
argnums
will compute the Jacobian with respect to multiple arguments>>> from torch.func import jacfwd >>> def f(x, y): >>> return x + y ** 2 >>> >>> x, y = torch.randn(5), torch.randn(5) >>> jacobian = jacfwd(f, argnums=(0, 1))(x, y) >>> expectedX = torch.diag(torch.ones_like(x)) >>> expectedY = torch.diag(2 * y) >>> assert torch.allclose(jacobian[0], expectedX) >>> assert torch.allclose(jacobian[1], expectedY)