Skip to content
class

set_grad_enabled

extends_GradScope
set_grad_enabled(mode: bool)

Set the autograd gradient-tracking flag, as a function or a scope.

Constructing it switches the flag at once, so a bare set_grad_enabled(False) call works as an imperative setter. Used in a with block the previous mode is restored on exit, also when the body raises; used as a decorator every call of the wrapped function runs in a scope of mode and the decoration itself changes nothing. The flag is per thread, like no_grad and enable_grad.

Parameters

modebool
True to enable gradient tracking, False to disable it. Anything that is not a bool raises TypeError.

Attributes

modebool
The grad mode the scope switches to.

Notes

Called as a function the switch is permanent until another call changes it; nothing restores it. Pair it with is_grad_enabled to save and restore by hand, or use the with form.

Examples

As a function:
>>> import lucid
>>> from lucid.autograd import set_grad_enabled, is_grad_enabled
>>> _ = set_grad_enabled(False)
>>> is_grad_enabled()
False
>>> _ = set_grad_enabled(True)
As a context manager:
>>> is_train = False
>>> with set_grad_enabled(is_train):
...     is_grad_enabled()
False
>>> is_grad_enabled()
True
As a decorator:
>>> @set_grad_enabled(False)
... def predict(x):
...     return x * 2

Used by 2

Constructors

2
dunder

__init__

→None
__init__(mode: bool)

Switch the flag to mode now, keeping the mode it replaces.

dunder

__call__

→F
__call__(fn: F)

Wrap fn; the constructor's switch is undone so decorating changes nothing.

Dunder methods

1
dunder

__enter__

→Self
__enter__()

Enter the scope; the first entry reuses the mode the constructor saved.