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
modeboolTrue to enable gradient tracking, False to disable it.
Anything that is not a bool raises TypeError.Attributes
modeboolThe 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 * 2Used by 2
- lucid
- lucid.autograd