评价此页

no_grad#

class torch.no_grad(orig_func=None)[source]#

禁用梯度计算的上下文管理器。

在您确定不会调用 Tensor.backward() 进行推理时,禁用梯度计算很有用。它将减少原本需要 requires_grad=True 的计算的内存消耗。

在此模式下,即使输入具有 requires_grad=True,每次计算的结果也将具有 requires_grad=False。有一个例外!所有工厂函数或创建新 Tensor 并接受 requires_grad kwarg 的函数将不受此模式影响。

此上下文管理器是线程局部(thread local)的;它不会影响其他线程中的计算。

也可作为装饰器使用。

注意

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

注意

此 API 不适用于 前向模式 AD。如果要禁用计算的前向 AD,可以解包您的双重张量。

示例:
>>> x = torch.tensor([1.], requires_grad=True)
>>> with torch.no_grad():
...     y = x * 2
>>> y.requires_grad
False
>>> @torch.no_grad()
... def doubler(x):
...     return x * 2
>>> z = doubler(x)
>>> z.requires_grad
False
>>> @torch.no_grad()
... def tripler(x):
...     return x * 3
>>> z = tripler(x)
>>> z.requires_grad
False
>>> # factory function exception
>>> with torch.no_grad():
...     a = torch.nn.Parameter(torch.rand(10))
>>> a.requires_grad
True