torch.func.grad#
- torch.func.grad(func, argnums=0, has_aux=False)[原始碼]#
grad運算元有助於計算func相對於由argnums指定的輸入(們)的梯度。此運算元可以巢狀以計算高階梯度。- 引數
- 返回
用於計算相對於其輸入的梯度的函式。預設情況下,函式的輸出是相對於第一個引數的梯度張量。如果指定了
has_aux等於True,則會返回梯度和輸出輔助物件的元組。如果argnums是一個整數元組,則會返回相對於每個argnums值的輸出梯度的元組。- 返回型別
使用
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 ... )
使用
grad結合has_aux和argnums的示例>>> 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_grad與grad一起使用。情況 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上下文管理器內部使用grad>>> with torch.no_grad(): >>> grad(f)(x)
在這種情況下,
grad將尊重內部的torch.no_grad,但不會尊重外部的。這是因為grad是一個“函式變換”:其結果不應取決於f外部的上下文管理器的結果。