Skip to content
class

FunctionCtx

FunctionCtx()

Per-call context shared between Function.forward and Function.backward.

A fresh FunctionCtx is created on every Function.apply invocation. forward populates it with anything backward will need: saved tensors (via save_for_backward), non-differentiable output markers (via mark_non_differentiable), and arbitrary user-defined attributes (cached shapes, axis indices, scalar hyperparameters, ...) set with ordinary attribute assignment. The context is the only legal channel for passing state from forward to backward — capturing tensors through Python closures bypasses autograd's bookkeeping and leaks memory.

Parameters

None
FunctionCtx is instantiated by Function.apply with no arguments. User code never constructs one directly; it receives the instance as the first positional argument of forward / backward.

Attributes

needs_input_gradtuple of bool
One flag per positional Tensor input to forward, indicating whether autograd would propagate a gradient to that input. Use this to skip unneeded branches in backward.
saved_tensorstuple of Tensor
Read-only view of the tensors stored via save_for_backward, in registration order.

Notes

The context is what ties the forward and backward halves of a custom node together in the chain rule:

y=f(x;ctx),xˉ=g(ctx,yˉ),\mathbf{y} = f(\mathbf{x}; \text{ctx}), \qquad \bar{\mathbf{x}} = g(\mathbf{ctx}, \bar{\mathbf{y}}),

where yˉ=∂L/∂y\bar{\mathbf{y}} = \partial \mathcal{L} / \partial \mathbf{y} is the upstream gradient and the same ctx object is passed to both halves so gg can read back whatever ff saved.

Examples

>>> import lucid
>>> from lucid.autograd import Function
>>> class Square(Function):
...     @staticmethod
...     def forward(ctx, x):
...         ctx.save_for_backward(x)
...         ctx.shape = x.shape
...         return x * x
...     @staticmethod
...     def backward(ctx, grad_out):
...         (x,) = ctx.saved_tensors
...         return 2 * x * grad_out

Used by 24

… 12 more

Constructors

1
dunder

__init__

→None
__init__()

Initialise an empty context with no saved tensors or extras.

Properties

1
prop

saved_tensors

→tuple of Tensor
saved_tensors: tuple[Tensor, ...]

Read back the tensors saved during forward.

Returns

tuple of Tensor

The tensors stored by save_for_backward, wrapped back into Python Tensor instances if the engine stored raw TensorImpl handles.

Raises

VersionMismatch
A saved tensor was written in place after forward returned — its values are no longer the ones forward saw, so a gradient computed from them would be wrong. Suppressed inside lucid.autograd.graph.allow_mutation_on_saved_tensors.

Instance methods

4
fn

mark_dirty

→None
mark_dirty(tensors: Tensor = ())

Declare that forward modified the given inputs in place.

Parameters

*tensorsTensor= ()
Inputs of Function.forward that it wrote to in place. Every one must also be returned by forward.

Raises

TypeError
An argument is not a tensor.

Notes

Function.apply hands a dirty input back as the same tensor that was passed in, its history now the node of this call and its version counter as forward left it, so the write is an in-place op of the graph. backward is the derivative of the whole write, with respect to the value the input had before it.

Function.apply raises RuntimeError when a dirty tensor is not among the results, and — for a recorded call — when it is a leaf that requires a gradient, which no in-place op may overwrite.

Examples

>>> import lucid
>>> from lucid.autograd import Function
>>> class AddOne(Function):
...     @staticmethod
...     def forward(ctx, x):
...         x.add_(1)
...         ctx.mark_dirty(x)
...         return x
...     @staticmethod
...     def backward(ctx, grad):
...         return grad
>>> a = lucid.ones(3, requires_grad=True)
>>> b = a * 1
>>> AddOne.apply(b) is b
True
fn

mark_non_differentiable

→None
mark_non_differentiable(tensors: Tensor = ())

Declare that the given output tensors carry no gradient.

Parameters

*tensorsTensor= ()
Outputs of Function.forward for which autograd should not propagate gradients (e.g., integer indices, masks).

Notes

Function.apply hands a marked output back detached: requires_grad=False and no grad_fn, and a compiled step sends no gradient through it either. backward is still given a gradient for it — zeros — so its arguments keep one slot per output. What comes back is a new tensor over the same storage, and the tensor forward returned is left as it was: a marked input returned as-is keeps the caller's requires_grad, and a buffer forward read from a module keeps its place there.

Unlike the reference framework, that holds for every marked output. The reference hands back the very object forward returned when it needs no gradient, and detaches one that does in place: a leaf parameter forward closed over, returned and marked, loses its requires_grad there. Here the parameter keeps it, and the caller gets a new detached tensor instead.

An output of a dtype that carries no gradient — bool or an integer — is treated as marked without being named here, as the reference framework treats it.

Examples

>>> import lucid
>>> from lucid.autograd import Function
>>> class ScaleAndMask(Function):
...     @staticmethod
...     def forward(ctx, x, mask):
...         ctx.mark_non_differentiable(mask)
...         return x * 2, mask
...     @staticmethod
...     def backward(ctx, grad, grad_mask):
...         return grad * 2, None
>>> x = lucid.ones(2, requires_grad=True)
>>> mask = lucid.ones(2, requires_grad=True)
>>> y, out = ScaleAndMask.apply(x, mask)
>>> out.requires_grad, mask.requires_grad
(False, True)
fn

save_for_backward

→None
save_for_backward(tensors: Tensor = ())

Store tensors needed to compute the backward pass.

Parameters

*tensorsTensor= ()
Activations / inputs the backward implementation will require. They are retrieved later via the saved_tensors property as a tuple in the same order.

Notes

Each call replaces any tensors previously saved on this context.

A saved tensor must not be written in place between the end of forward and the backward that reads it: reading saved_tensors then raises VersionMismatch, as a built-in op's backward does, instead of handing backward the new values. Writes inside forward itself are fine — the version is taken once forward has returned.

forward's own outputs may be saved too: the engine context holds their data and a weak reference to the node (re-attaching the node on read), so a call that runs no backward is freed by refcounting the moment its last output is dropped. A tensor assigned to an attribute of the context (ctx.out = y) gets none of this — save tensors through this method.

fn

set_materialize_grads

→None
set_materialize_grads(value: bool)

Choose how backward is handed an output no gradient reached.

Parameters

valuebool
True (the default): such an output arrives as a zero tensor. False: it arrives as None, so backward can skip the work it would only multiply by zero.

Raises

TypeError
value is not a bool.

Notes

Call it from forward (or setup_context). An output marked non-differentiable never receives a gradient, so with False it arrives as None too. backward is still given one argument per output of forward.

Examples

>>> import lucid
>>> from lucid.autograd import Function
>>> class Split(Function):
...     @staticmethod
...     def forward(ctx, x):
...         ctx.set_materialize_grads(False)
...         return x * 2, x * 3
...     @staticmethod
...     def backward(ctx, grad_a, grad_b):
...         return grad_a * 2 if grad_b is None else grad_b * 3
>>> x = lucid.ones(2, requires_grad=True)
>>> a, b = Split.apply(x)
>>> a.sum().backward()
>>> x.grad.tolist()
[2.0, 2.0]