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
NoneFunction 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
forwardstaticmethodforward(ctx, *args, **kwargs) -> Tensor or tuple[Tensor, ...].
Computes the primal value; stores anything backward will
need on ctx.backwardstaticmethodbackward(ctx, *grad_outputs) -> tuple of Tensors (or None per non-tensor input). Returns the cotangents matching the
positional inputs of forward.applyclassmethodforward to the autograd graph, returning the forward
output and registering backward as the gradient closure._ traced_ backwardbool, default=Falselucid.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
and supplies the chain-rule contribution
for each input . 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
- lucid._ops.composite._bessel
- lucid._ops.composite._gamma
- lucid._ops.composite._inverse_hyperbolic
- lucid._ops.composite._lerp
- lucid._ops.composite._pow2
- lucid._ops.composite._rounding
- lucid._ops.composite.indexing
- lucid.autograd
- lucid.autograd._overwritten
- lucid.autograd.checkpoint
- lucid.compile._core.custom_backward
- lucid.compile._entry.segmented_step
… 11 more
Class methods
1Run 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
3Compute 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
ctxFunctionCtxforward.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
Raises
TypeErrorNone.RuntimeErrorNone,
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.
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
ctxFunctionCtxbackward.**kwargsAny= {}apply; they
receive no gradients.Returns
Tensor or tupleOne 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.
setup_context
→Nonesetup_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
ctxFunctionCtxbackward.inputstupleforward was called with, a defaulted one
included.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]