Context manager / decorator that disables gradient tracking.
Inside a no_grad scope every op skips the graph-building
bookkeeping that autograd normally performs: no autograd node
is registered, no activations are saved, and the produced
tensors carry requires_grad=False regardless of their
inputs. The flag is process-global, so this affects all code
running inside the scope.
Use no_grad for inference, for validation loops, and for
parameter updates that should not themselves be differentiable
(e.g. EMA accumulation, optimizer steps if performed outside
an Optimizer object). The savings — fewer Python objects
allocated, no saved activations holding memory, no overhead
on each op — are typically large.
The previous gradient mode is restored on exit (RAII), so
no_grad may be safely nested inside enable_grad
and vice-versa.
Parameters
Noneno_grad takes no arguments; configure with
set_grad_enabled if a dynamic flag is needed.Attributes
_prevbool__enter__
time and restored at __exit__.Notes
Gradient mode controls whether autograd records the chain rule
With no_grad the graph that this sum is computed over is
never built, so calling backward afterwards is a
no-op on tensors produced inside the scope.
Examples
As a context manager:
>>> import lucid
>>> from lucid.autograd import no_grad
>>> x = lucid.tensor([1.0, 2.0], requires_grad=True)
>>> with no_grad():
... y = x * 2
>>> y.requires_grad
False
As a decorator:
>>> @no_grad()
... def eval_step(x):
... return (x * x).sum()Used by 12
- lucid
- lucid.autograd
- lucid.autograd.checkpoint
- lucid.compile._debug.diagnose
- lucid.compile._entry.decode_step
- lucid.compile._entry.function
- lucid.compile._entry.fused_step
- lucid.compile._entry.module
- lucid.compile._entry.segmented_step
- lucid.compile._entry.step
- lucid.compile._optim.compiler
- lucid.utils.checkpoint