Skip to content
class

Function

Function()

Base class for custom differentiable operations.

Subclass to define an operation whose forward and backward passes Lucid's autograd cannot deduce automatically — for example, an operation that wraps an external library, an op with a custom backward formula for numerical stability, or a piecewise-defined function whose gradient differs from naïve autograd.

Define forward and backward as @staticmethod on the subclass, then invoke the op via apply (NOT by calling forward directly — that would skip autograd registration).

Parameters

None
Function itself is never instantiated. Subclasses are stateless — their behaviour is defined entirely by the forward / backward static methods, and ops are invoked through the apply classmethod rather than __init__.

Attributes

forwardstaticmethod
forward(ctx, *args, **kwargs) -> Tensor or tuple[Tensor, ...]. Computes the primal value; stores anything backward will need on ctx.
backwardstaticmethod
backward(ctx, *grad_outputs) -> tuple of Tensors (or None per non-tensor input). Returns the cotangents matching the positional inputs of forward.
applyclassmethod
Bind forward to the autograd graph, returning the forward output and registering backward as the gradient closure.
_traced_backwardbool, default=False
Class attribute opting the subclass into traced custom-VJP lowering under lucid.compile. When True and both forward and backward consist of traceable tensor operations on GPU, make_step, fused_step, and compiled_step trace backward into a VjpRegion inside the compiled executable instead of falling back to eager execution.

Notes

The FunctionCtx passed to forward carries the bookkeeping autograd needs to call backward later — saved tensors plus per-input non-differentiable flags.

forward runs with gradient recording off, as in the reference framework: the node apply registers is the whole graph of the call, and a tensor forward computes needs no gradient of its own.

An output that is non-differentiable — marked so, or of a bool or integer dtype — comes back as a new, detached tensor over the same storage, and the tensor forward returned is left as it was: an input passed through keeps the caller's requires_grad. Unlike the reference framework, which hands back the very object forward returned when it needs no gradient and detaches a closed-over leaf in place, every such output here is a new tensor. An unmarked input returned as-is comes back as the same tensor, now the node's output: where the reference framework hands back a view of it, the caller's tensor here is no longer a leaf after the call.

forward may also be written without a ctx: override setup_context and forward(*args) becomes a plain function of its inputs, with everything backward needs put on ctx there. A backward that cannot be differentiated again is decorated with once_differentiable.

Each Function defines a node in the computation graph

y=f(x1,…,xn;θ)\mathbf{y} = f(\mathbf{x}_1, \ldots, \mathbf{x}_n; \theta)

and supplies the chain-rule contribution

∂L∂xi=∑j∂L∂yj⋅∂yj∂xi\frac{\partial \mathcal{L}}{\partial \mathbf{x}_i} = \sum_j \frac{\partial \mathcal{L}}{\partial y_j} \cdot \frac{\partial y_j}{\partial x_{i}}

for each input xi\mathbf{x}_i. The backward method implements precisely this Jacobian-vector product.

Examples

Custom ReLU with an explicit backward:
>>> import lucid
>>> from lucid.autograd import Function
>>> class MyReLU(Function):
...     @staticmethod
...     def forward(ctx, x):
...         ctx.save_for_backward(x)
...         return x.clamp(min=0.0)
...     @staticmethod
...     def backward(ctx, grad_out):
...         (x,) = ctx.saved_tensors
...         return grad_out * (x > 0).float()
>>> y = MyReLU.apply(lucid.tensor([-1.0, 2.0], requires_grad=True))
>>> y.sum().backward()

Used by 23

… 11 more

Class methods

1
cls

apply

→object
apply(args: object = (), kwargs: object = {})

Run the function — autograd-tracked when forward requests grad.

FunctionMeta rewrites this on every concrete subclass to dispatch through forward/backward; the base implementation here exists only so Function.apply is a real attribute (matters for tooling and hasattr checks). Calling it on the base class is meaningless and raises.

Static methods

3
static

backward

→Tensor or tuple of Tensor
backward(ctx: FunctionCtx, grad_outputs: Any = ())

Compute gradients of the loss w.r.t. each input of forward.

Subclasses override this static method. The returned tuple must contain one gradient per positional argument of forward, in the same order; non-Tensor arguments receive None.

Parameters

The same context that was populated during forward.
*grad_outputsTensor or None= ()
Upstream gradients ∂L/∂yi\partial L / \partial y_i, one per output that forward returned — None at the slot of an output that is not a tensor, and, after FunctionCtx.set_materialize_grads (False), at that of one no gradient reached (a zero tensor otherwise).

Returns

Tensor or tuple of Tensor

Downstream gradients matching the positional inputs of forward. Use None for inputs that have no gradient. One gradient per tensor input — leaving out the non-tensor arguments — is accepted as well, and trailing None entries past the last argument are ignored.

Raises

TypeError
When a gradient is neither a tensor nor None.
RuntimeError
When the number of gradients fits neither form, when a non-tensor argument is given a gradient other than None, or when a gradient does not fit its input: a shape the input does not broadcast to, or a device other than the input's.

Notes

Each gradient is checked against the input it is for, once backward returns. A shape the input broadcasts to is summed back down to the input's shape, another dtype is cast to the input's (a complex gradient for a real input keeps its real part), and a 0-d gradient on another device is moved to the input's.

static

forward

→Tensor or tuple
forward(ctx: FunctionCtx, args: Any = (), kwargs: Any = {})

Compute the forward result of the custom op.

Subclasses override this static method. Save anything needed during backward on ctx (via ctx.save_for_backward(...) or by setting attributes like ctx.shape = x.shape); do not capture tensors via closure.

It runs under no_grad: lucid.is_grad_enabled() is False inside it and the tensors it computes record no graph. A forward that differentiates something itself does so inside lucid.enable_grad().

Parameters

Per-call context; will be passed unchanged to backward.
*argsTensor= ()
Positional inputs to the custom op. Non-Tensor positional arguments are allowed but receive no gradients.
**kwargsAny= {}
Keyword inputs forwarded unchanged from apply; they receive no gradients.

Returns

Tensor or tuple

One or more output tensors. A tuple may carry values that are not tensors (a count, a flag): they pass through unchanged, receive no gradient, and take a slot in backward's arguments, which is None.

static

setup_context

→None
setup_context(ctx: FunctionCtx, inputs: tuple[object, ...], output: object)

Fill ctx for backward, in the form where forward takes no ctx.

Overriding it selects that form: forward(*args) is then a plain function of its inputs, run first, and setup_context(ctx, inputs, output) is called with what it returned. Everything forward would have put on ctx — FunctionCtx.save_for_backward, FunctionCtx.mark_dirty, FunctionCtx.mark_non_differentiable, attributes — goes here instead.

Parameters

Per-call context; will be passed unchanged to backward.
inputstuple
The arguments forward was called with, a defaulted one included.
outputTensor or tuple of Tensor
What forward returned.

Notes

setup_context runs with gradient recording off, as forward does.

Examples

>>> import lucid
>>> from lucid.autograd import Function
>>> class Exp(Function):
...     @staticmethod
...     def forward(x):
...         return x.exp()
...     @staticmethod
...     def setup_context(ctx, inputs, output):
...         ctx.save_for_backward(output)
...     @staticmethod
...     def backward(ctx, grad):
...         (out,) = ctx.saved_tensors
...         return grad * out
>>> x = lucid.tensor([0.0], requires_grad=True)
>>> Exp.apply(x).sum().backward()
>>> x.grad.tolist()
[1.0]