torch.func.jacrev
- torch.func.jacrev(func, argnums=0, *, has_aux=False, chunk_size=None, _preallocate_and_copy=False)
-
使用反向模式自动微分,计算
func
相对于索引argnum
参数的雅可比矩阵。注意
使用
chunk_size=1
等同于用 for 循环逐行计算雅可比矩阵,此时vmap()
的约束条件不适用。- 参数
-
-
func(函数)– 一个接受一个或多个参数的Python函数,其中至少有一个参数是张量,并返回一个或多个张量。
-
has_aux (bool) – 标志,表示
func
返回一个包含两个元素的元组:(output, aux)
。其中第一个元素是需要求导的函数输出,第二个元素是辅助对象且不需要进行求导。默认值:False。 -
chunk_size (None或 int) – 如果为 None(默认值),则使用最大块大小,相当于对 vjp 进行一次 vmap 来计算雅可比矩阵。如果为 1,则通过 for 循环逐行计算雅可比矩阵。如果不为 None,则每次计算
chunk_size
行的雅可比矩阵,相当于多次对 vjp 进行 vmap。如果你在计算雅可比矩阵时遇到内存问题,请尝试指定一个非 None 的 chunk_size。
-
- 返回值
-
返回一个函数,该函数接受与
func
相同的输入,并返回func
相对于argnums
参数的雅可比矩阵。如果has_aux
为 True,则返回的函数将返回一个包含雅可比矩阵和辅助对象的元组(jacobian, aux)
,其中jacobian
是雅可比矩阵,而aux
是由func
返回的辅助对象。
使用逐点的一元操作的基本用法将得到一个对角矩阵作为雅可比矩阵
>>> from torch.func import jacrev >>> x = torch.randn(5) >>> jacobian = jacrev(torch.sin)(x) >>> expected = torch.diag(torch.cos(x)) >>> assert torch.allclose(jacobian, expected)
如果你想同时计算函数的输出和雅可比矩阵,可以使用
has_aux
标志将输出作为辅助对象返回。>>> from torch.func import jacrev >>> x = torch.randn(5) >>> >>> def f(x): >>> return x.sin() >>> >>> def g(x): >>> result = f(x) >>> return result, result >>> >>> jacobian_f, f_x = jacrev(g, has_aux=True)(x) >>> assert torch.allclose(f_x, f(x))
jacrev()
可以与 vmap 结合使用来生成批量雅可比矩阵。>>> from torch.func import jacrev, vmap >>> x = torch.randn(64, 5) >>> jacobian = vmap(jacrev(torch.sin))(x) >>> assert jacobian.shape == (64, 5, 5)
此外,
jacrev()
可以与其自身结合使用来生成 Hessian 矩阵。>>> from torch.func import jacrev >>> def f(x): >>> return x.sin().sum() >>> >>> x = torch.randn(5) >>> hessian = jacrev(jacrev(f))(x) >>> assert torch.allclose(hessian, torch.diag(-x.sin()))
默认情况下,
jacrev()
根据第一个输入计算雅可比矩阵。然而,可以通过设置argnums
参数来针对不同的输入计算雅可比矩阵:>>> from torch.func import jacrev >>> def f(x, y): >>> return x + y ** 2 >>> >>> x, y = torch.randn(5), torch.randn(5) >>> jacobian = jacrev(f, argnums=1)(x, y) >>> expected = torch.diag(2 * y) >>> assert torch.allclose(jacobian, expected)
此外,将元组传递给
argnums
可以计算多个参数的雅可比矩阵。>>> from torch.func import jacrev >>> def f(x, y): >>> return x + y ** 2 >>> >>> x, y = torch.randn(5), torch.randn(5) >>> jacobian = jacrev(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 的
torch.no_grad
和jacrev
。情况 1:在函数内部使用torch.no_grad
:>>> def f(x): >>> with torch.no_grad(): >>> c = x ** 2 >>> return x - c
在这种情况下,
jacrev(f)(x)
会遵守内部的torch.no_grad
。情况2:在
torch.no_grad
上下文中使用jacrev
:>>> with torch.no_grad(): >>> jacrev(f)(x)
在这种情况下,
jacrev
将会尊重内部的torch.no_grad
,但不会尊重外部的。这是因为jacrev
是一个“函数变换”,其结果不应依赖于f
之外的上下文管理器。