快捷方式

torch.func.jacfwd

torch.func.jacfwd(func, argnums=0, has_aux=False, *, randomness='error')[源代码]

使用前向模式自动微分计算 func 相对于索引为 argnum 的参数的 Jacobian 矩阵

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

  • argnums (intTuple[int]) – 可选参数,整数或整数元组,指定要计算 Jacobian 矩阵的参数。默认值: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 矩阵,auxfunc 返回的辅助对象。

注意

您可能会看到此 API 报错,提示“运算符 X 未实现前向模式 AD”。如果遇到这种情况,请提交错误报告,我们将优先处理。另一种选择是使用 jacrev(),它具有更好的运算符覆盖范围。

对逐点一元运算的基本用法将得到一个对角数组作为 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 组合使用,以生成批处理的 Jacobian 矩阵

>>> from torch.func import jacfwd, vmap
>>> x = torch.randn(64, 5)
>>> jacobian = vmap(jacfwd(torch.sin))(x)
>>> assert jacobian.shape == (64, 5, 5)

如果您想计算函数的输出以及函数的 Jacobian 矩阵,请使用 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() 组合使用以生成 Hessian 矩阵

>>> 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() 计算相对于第一个输入的 Jacobian 矩阵。但是,它可以通过使用 argnums 计算相对于不同参数的 Jacobian 矩阵

>>> 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 将计算相对于多个参数的 Jacobian 矩阵

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

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取面向初学者和高级开发者的深入教程

查看教程

资源

查找开发资源并获得问题解答

查看资源