Shortcuts

启用梯度计算

class torch.enable_grad(orig_func=None)[源代码]

上下文管理器,用于启用梯度计算。

启用梯度计算,如果它已通过no_gradset_grad_enabled被禁用。

此上下文管理器是线程本地的;它不会影响其他线程中的计算。

也可以作为装饰器使用。

注意

enable_grad 是几种可以在本地启用或禁用梯度的机制之一,有关它们如何比较的更多信息,请参见 本地禁用梯度计算

注意

此API不适用于前向模式自动微分

Example::
>>> 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