enable_grad#
- classtorch.enable_grad(orig_func=None)[source]#
Context-manager that enables gradient calculation.
Enables gradient calculation, if it has been disabled via
no_gradorset_grad_enabled.This context manager is thread local; it will not affect computationin other threads.
Also functions as a decorator.
Note
enable_grad is one of several mechanisms that can enable ordisable gradients locally seeLocally disabling gradient computation formore information on how they compare.
Note
This API does not apply toforward-mode AD.
- Example::
>>>x=torch.tensor([1.],requires_grad=True)>>>withtorch.no_grad():...withtorch.enable_grad():...y=x*2>>>y.requires_gradTrue>>>y.backward()>>>x.gradtensor([2.])>>>@torch.enable_grad()...defdoubler(x):...returnx*2>>>withtorch.no_grad():...z=doubler(x)>>>z.requires_gradTrue>>>@torch.enable_grad()...deftripler(x):...returnx*3>>>withtorch.no_grad():...z=tripler(x)>>>z.requires_gradTrue