enable_grad#
- class torch.enable_grad(orig_func=None)[原始碼]#
啟用梯度計算的上下文管理器。
如果梯度計算已透過
no_grad或set_grad_enabled停用,則啟用梯度計算。此上下文管理器是執行緒區域性(thread local)的;它不會影響其他執行緒中的計算。
也可作為裝飾器使用。
注意
enable_grad 是可以本地啟用或停用梯度的幾種機制之一,有關它們之間比較的更多資訊,請參閱 本地停用梯度計算。
注意
此 API 不適用於前向模式 AD。
- 示例:
>>> x = torch.tensor([1.], requires_grad=True) >>> with torch.no_grad(): ... with torch.enable_grad(): ... y = x * 2 >>> y.requires_grad True >>> y.backward() >>> x.grad tensor([2.]) >>> @torch.enable_grad() ... def doubler(x): ... return x * 2 >>> with torch.no_grad(): ... z = doubler(x) >>> z.requires_grad True >>> @torch.enable_grad() ... def tripler(x): ... return x * 3 >>> with torch.no_grad(): ... z = tripler(x) >>> z.requires_grad True