class

enable_grad

enable_grad()
source

Context manager / decorator that (re-)enables gradient tracking.

Counterpart of no_grad: turns gradient recording back on inside the wrapped scope, even when an outer scope has disabled it. Useful when a small differentiable subroutine runs inside a larger no_grad block — for example, an inner training step embedded in an outer evaluation loop, or explicit gradient computation for diagnostic plots inside a decorated inference function.

The previous gradient mode is restored on exit (RAII), so the surrounding no_grad continues to apply once the inner scope finishes.

Parameters

None
No description.

Attributes

_prevbool
Internal — saved grad-mode flag captured at __enter__ time and restored at __exit__.

Notes

Setting the flag back to True re-arms autograd to record the chain rule

Lx=iLyiyix\frac{\partial \mathcal{L}}{\partial x} = \sum_i \frac{\partial \mathcal{L}}{\partial y_i} \cdot \frac{\partial y_i}{\partial x}

for every op executed inside the scope.

Examples

>>> import lucid
>>> from lucid.autograd import no_grad, enable_grad
>>> x = lucid.tensor([1.0, 2.0], requires_grad=True)
>>> with no_grad():
...     with enable_grad():
...         y = (x * x).sum()
>>> y.requires_grad
True

Methods (3)

dunder

__call__

_F
__call__(fn: _F)
source

Forward to the underlying callable (see class docstring).

dunder

__enter__

enable_grad
__enter__()
source

Enter the context. Returns self so the value can be bound via with ... as.

dunder

__exit__

None
__exit__(args: object = ())
source

Exit the context, restoring any state that was modified on entry.