torch.func.jacrev¶
- torch.func.jacrev(func, argnums=0, *, has_aux=False, chunk_size=None, _preallocate_and_copy=False)[原始碼]¶
使用反向模式自動微分計算
func對索引為argnum的引數的 Jacobian 矩陣注意
使用
chunk_size=1等同於使用 for 迴圈逐行計算 Jacobian 矩陣,即vmap()的限制不適用。- 引數
func (function) – 一個 Python 函式,接受一個或多個引數(其中之一必須是 Tensor),並返回一個或多個 Tensor
argnums (int 或 Tuple[int]) – 可選,整數或整數元組,指定對哪些引數計算 Jacobian 矩陣。預設值:0。
has_aux (bool) – 標誌,指示
func返回一個(output, aux)元組,其中第一個元素是需要微分的函式輸出,第二個元素是不參與微分的輔助物件。預設值:False。chunk_size (None 或 int) – 如果為 None(預設),則使用最大分塊大小(等同於對 vjp 進行一次 vmap 以計算 Jacobian 矩陣)。如果為 1,則使用 for 迴圈逐行計算 Jacobian 矩陣。如果非 None,則每次計算
chunk_size行(等同於進行多次 vmap over vjp)。如果在計算 Jacobian 矩陣時遇到記憶體問題,請嘗試指定非 None 的chunk_size。
- 返回值
返回一個函式,該函式接受與
func相同的輸入,並返回func對argnums索引引數的 Jacobian 矩陣。如果has_aux 為 True,則返回的函式改為返回一個(jacobian, aux)元組,其中jacobian是 Jacobian 矩陣,aux是func返回的輔助物件。
點對點的單元操作的基本用法會得到對角陣列作為 Jacobian 矩陣
>>> 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)
如果您想同時計算函式的輸出和 Jacobian 矩陣,請使用
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 組合使用,生成批處理的 Jacobian 矩陣>>> 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()計算相對於第一個輸入的 Jacobian 矩陣。但是,可以透過使用argnums來計算相對於不同引數的 Jacobian 矩陣>>> 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將計算相對於多個引數的 Jacobian 矩陣>>> 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是一個“函式轉換”(function transform):其結果不應依賴於f外部的上下文管理器的結果。