Skip to content
class

enable_grad

extends_GradScope
enable_grad()

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

modebool
The grad mode the scope switches to.

Notes

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

∂L∂x=∑i∂L∂yi⋅∂yi∂x\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

Used by 9

Constructors

1
dunder

__init__

→None
__init__()

Build a scope that enables gradient tracking.