快捷方式

enable_grad

class torch.enable_grad(orig_func=None)[source][source]

啟用梯度計算的上下文管理器。

啟用梯度計算,如果之前透過 no_gradset_grad_enabled 停用了它。

此上下文管理器是執行緒區域性的;它不會影響其他執行緒中的計算。

也可以用作裝飾器。

注意

enable_grad 是幾種可以在本地啟用或停用梯度的機制之一,請參閱 本地停用梯度計算 以瞭解更多關於它們如何比較的資訊。

注意

此 API 不適用於 前向模式自動微分

示例:
>>> 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

文件

訪問 PyTorch 的全面開發者文件

檢視文件

教程

獲取針對初學者和高階開發者的深入教程

檢視教程

資源

查詢開發資源並獲得問題解答

檢視資源