捷徑

torch.func.grad

torch.func.grad(func, argnums=0, has_aux=False)[來源]

grad 運算子有助於計算 func 相對於 argnums 指定的輸入的梯度。此運算子可以巢狀使用,以計算更高階的梯度。

參數
  • func (Callable) – 一個接受一個或多個參數的 Python 函數。必須傳回單一元素的 Tensor。如果指定的 has_aux 等於 True,則函數可以傳回單一元素的 Tensor 和其他輔助物件的元組:(output, aux)

  • argnums (intTuple[int]) – 指定要計算梯度所針對的參數。argnums 可以是單一整數或整數的 tuple。預設值:0。

  • has_aux (bool) – 旗標,表示 func 回傳一個 tensor 和其他輔助物件:(output, aux)。預設值:False。

回傳

用於計算相對於其輸入的梯度的函式。預設情況下,函式的輸出是相對於第一個參數的梯度 tensor。如果指定 has_aux 等於 True,則會回傳梯度和輸出輔助物件的 tuple。如果 argnums 是一個整數的 tuple,則會回傳相對於每個 argnums 值的輸出梯度的 tuple。

回傳類型

Callable

使用 grad 的範例

>>> from torch.func import grad
>>> x = torch.randn([])
>>> cos_x = grad(lambda x: torch.sin(x))(x)
>>> assert torch.allclose(cos_x, x.cos())
>>>
>>> # Second-order gradients
>>> neg_sin_x = grad(grad(lambda x: torch.sin(x)))(x)
>>> assert torch.allclose(neg_sin_x, -x.sin())

當與 vmap 結合使用時,grad 可用於計算每個樣本的梯度

>>> from torch.func import grad, vmap
>>> batch_size, feature_size = 3, 5
>>>
>>> def model(weights, feature_vec):
>>>     # Very simple linear model with activation
>>>     assert feature_vec.dim() == 1
>>>     return feature_vec.dot(weights).relu()
>>>
>>> def compute_loss(weights, example, target):
>>>     y = model(weights, example)
>>>     return ((y - target) ** 2).mean()  # MSELoss
>>>
>>> weights = torch.randn(feature_size, requires_grad=True)
>>> examples = torch.randn(batch_size, feature_size)
>>> targets = torch.randn(batch_size)
>>> inputs = (weights, examples, targets)
>>> grad_weight_per_example = vmap(grad(compute_loss), in_dims=(None, 0, 0))(*inputs)

使用 gradhas_auxargnums 的範例

>>> from torch.func import grad
>>> def my_loss_func(y, y_pred):
>>>    loss_per_sample = (0.5 * y_pred - y) ** 2
>>>    loss = loss_per_sample.mean()
>>>    return loss, (y_pred, loss_per_sample)
>>>
>>> fn = grad(my_loss_func, argnums=(0, 1), has_aux=True)
>>> y_true = torch.rand(4)
>>> y_preds = torch.rand(4, requires_grad=True)
>>> out = fn(y_true, y_preds)
>>> # > output is ((grads w.r.t y_true, grads w.r.t y_preds), (y_pred, loss_per_sample))

注意

將 PyTorch torch.no_gradgrad 一起使用。

案例 1:在函式內部使用 torch.no_grad

>>> def f(x):
>>>     with torch.no_grad():
>>>         c = x ** 2
>>>     return x - c

在這種情況下,grad(f)(x) 將會尊重內部的 torch.no_grad

案例 2:在 torch.no_grad context manager 內部使用 grad

>>> with torch.no_grad():
>>>     grad(f)(x)

在這種情況下,grad 將會尊重內部的 torch.no_grad,但不會尊重外部的 torch.no_grad。 這是因為 grad 是一個“函式轉換”:它的結果不應該取決於 f 外部的 context manager 的結果。

文件

存取 PyTorch 的完整開發人員文件

檢視文件

教學

取得適合初學者和進階開發人員的深入教學

檢視教學

資源

尋找開發資源並取得問題解答

檢視資源