Shortcuts

functorch.jacfwd

functorch.jacfwd(func, argnums=0, has_aux=False, *, randomness='error')[source]

计算func相对于索引argnum处的参数(s)的雅可比矩阵,使用前向模式自动微分

Parameters
  • func (function) – 一个Python函数,它接受一个或多个参数,其中一个必须是Tensor,并返回一个或多个Tensor

  • argnums (intTuple[int]) – 可选的,整数或整数元组, 指定要获取雅可比矩阵的参数。 默认值:0。

  • has_aux (bool) – 标志,表示 func 返回一个 (output, aux) 元组,其中第一个元素是要微分的函数的输出,第二个元素是 不会被微分的辅助对象。 默认值:False。

  • 随机性 (str) – 标志指示使用哪种类型的随机性。 有关更多详细信息,请参见 vmap()。允许的值:“different”(不同)、“same”(相同)、“error”(错误)。 默认值:“error”(错误)

Returns

返回一个函数,该函数接受与func相同的输入,并返回func相对于argnums处的参数的雅可比矩阵。如果has_aux is True,则返回的函数将返回一个(jacobian, aux)元组,其中jacobian是雅可比矩阵,aux是由func返回的辅助对象。

注意

你可能会看到这个API错误提示“forward-mode AD not implemented for operator X”。如果是这样,请提交一个错误报告,我们会优先处理。另一种选择是使用jacrev(),它的操作符覆盖范围更广。

使用逐点一元操作的基本用法将给出一个对角数组作为雅可比矩阵

>>> 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)

如果您想计算函数的输出以及函数的雅可比矩阵,请使用has_aux标志将输出作为辅助对象返回:

>>> 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() 组合以生成 Hessians

>>> 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)

此外,将元组传递给 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=(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)

警告

我们已经将functorch集成到PyTorch中。作为集成的最后一步,functorch.jacfwd在PyTorch 2.0中已被弃用,并将在未来版本PyTorch >= 2.3中删除。请改用torch.func.jacfwd;更多详情请参阅PyTorch 2.0发布说明和/或torch.func迁移指南https://pytorch.org/docs/master/func.migrating.html