Skip to content
class

inference_mode

inference_mode(mode: bool = True)

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= True
True 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:

(grad,inference)←(¬m,m)on entry,(grad,inference)prevon exit,(\text{grad}, \text{inference}) \leftarrow (\neg m, m) \quad\text{on entry}, \qquad (\text{grad}, \text{inference})_{\text{prev}} \quad\text{on exit},

where mm 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
False

Used by 2

Constructors

2
dunder

__init__

→None
__init__(mode: bool = True)

Record the requested mode.

dunder

__call__

→F
__call__(fn: F)

Wrap fn so every call runs inside a fresh scope of this mode.

Dunder methods

2
dunder

__enter__

→None
__enter__()

Enter the scope: grad tracking follows not mode, the inference flag follows mode.

dunder

__exit__

→None
__exit__(args: object = ())

Restore the grad mode and inference flag captured on entry.