Context manager / decorator for inference-time autograd suppression.
inference_mode(True) (the default) disables gradient tracking
and marks the thread as being in inference mode; inference_mode(False)
clears the mark and re-enables gradient tracking, so it can carve a
differentiable region out of an enclosing inference or no_grad
scope. The previous gradient mode and inference flag are restored
on exit, so scopes nest freely.
Parameters
modebool= TrueTrue to enter inference mode, False to leave it (and
re-enable gradients) for the scope. Default True. When a
callable is passed instead (bare @inference_mode) it is
wrapped and returned.Notes
On exit the state captured at __enter__ is restored:
where is mode. Tensors created inside an
inference_mode(True) scope are marked as inference tensors
(Tensor.is_inference()): saving them for backward or
mutating them in place outside inference_mode raises a
RuntimeError.
Examples
>>> import lucid
>>> x = lucid.tensor([1.0, 2.0], requires_grad=True)
>>> with lucid.inference_mode():
... y = x * 3
>>> y.requires_grad
False
>>> @lucid.inference_mode()
... def predict(x):
... return x * 3
>>> predict(x).requires_grad
FalseUsed by 2
- lucid
- lucid.autograd