Skip to content
class

PythonBackwardNode

extendsNodeGraphBarrier
PythonBackwardNode

Autograd graph node that defers backward computation to a Python callable.

When a user subclasses lucid.autograd.Function and invokes MySubclass.apply(...), the Python layer constructs a PythonBackwardNode, populates py_ctx and py_backward_fn, and registers the node as the output tensor's grad_fn via _register_python_backward_node. The Engine then treats this node like any other backward node — when apply is called during graph traversal, control crosses back into Python with the GIL held.

See Also

lucid.autograd.Function — Python base class users subclass. FunctionCtx — context object carrying saved state.

Attributes

py_ctxpy::object
The FunctionCtx wrapper carrying saved tensors and extras. Forwarded unchanged as the first argument to py_backward_fn.
py_backward_fnpy::object
The user's backward(ctx, grad_output) static method. Expected signature: (ctx, grad_output: Tensor) -> Tensor | tuple[Tensor | None, ...].
out_shapeShape
Shape of the forward output; used to reconstruct a proper TensorImpl wrapper around the raw grad_out storage.
out_dtypeDtype
Dtype of the forward output (default F32).
out_deviceDevice
Device of the forward output (default CPU).

Notes

The public py_ctx / py_backward_fn data members are exposed directly via def_readwrite so the pybind11 binding can set them without accessor boilerplate.

Thread safety: none. The Engine guarantees single-threaded execution of the backward pass, so apply does not lock; calling it concurrently from multiple threads is undefined.

Constructors

1

Destructor

1

Virtual methods

3
virtconst

empty_grad_is_none

bool empty_grad_is_none()

A Python None comes back as an empty storage.

virtconst

is_barrier

→bool
bool is_barrier()

Whether this node stands behind several forward outputs.

Returns

bool

true once out_shapes describes more than one output, which routes the engine through the barrier protocol. A single-output custom op stays on the direct path, exactly as before multi-output support existed.

Methods

11
fn

accumulate_barrier_grad

void accumulate_barrier_grad(int input_nr, int grad)

Park one output's gradient until the rest arrive.

Parameters

input_nrstd::uint32_t
Which forward output this gradient belongs to. Out-of-range values are ignored rather than throwing, matching the other barrier nodes and keeping the engine robust against pruned graphs.
gradStorage
The arriving gradient. A slot reached by more than one path accumulates rather than overwrites.
fn

accumulate_barrier_grad_for_graph

void accumulate_barrier_grad_for_graph(int input_nr, int grad)

The create_graph half of the barrier: an output's gradient is parked as the tensor it arrived as, and backward runs once on them all, as apply_barrier runs it on the eager ones.

fn

apply

→std::vector<Storage>
int apply(int grad_out)

Invoke the Python backward callable and collect the resulting gradients.

Acquires the GIL, wraps grad_out in a temporary TensorImpl matching out_shape / out_dtype / out_device, calls py_backward_fn(py_ctx, grad_tensor), then unpacks the returned tuple/list/tensor back into a vector of Storage values — one per forward input.

Parameters

grad_outStorage
Upstream gradient delivered by the Engine; assumed to match the output dtype/device of the original forward call.

Returns

std::vector<Storage>

One Storage per input edge. Python None entries become empty CpuStorage{} values representing "no gradient for this input".

Raises

LucidError
The Python backward_fn is unset.
:error_already_set
backward_fn raised. It is not rewrapped: the binding that started the backward pass restores the original Python exception, so the caller sees its own type, message and traceback.
fn

apply_barrier

→std::vector<Storage>
int apply_barrier()

Run the user's backward once with every output's gradient.

Outputs that never received a gradient — because the loss did not depend on them — are materialised as zeros of the right shape, dtype and device, so backward always sees one real tensor per output and never has to guard against None.

Returns

std::vector<Storage>

One Storage per forward input, as for apply.

fn

apply_barrier_for_graph

int apply_barrier_for_graph()
fn

apply_for_graph

int apply_for_graph(const int & grad_out)

create_graph=True: the user's backward, run on the live gradient.

The same Python backward is called, but handed the upstream gradient as the tensor the engine holds — grad_fn and all — and its results are returned as tensors rather than storages. Written in Lucid ops, as a backward is, it records its own graph the way any other code does when grad mode is on, so a custom Function differentiates twice without saying anything about it. The engine calls it for a single-output Function; one with several outputs is a barrier and collects its gradients per output (apply_barrier_for_graph).

fn

enter_pass

void enter_pass()

Make the slots the running pass's (GraphBarrier.h).

fnconst

for_each_owned_tensor

void for_each_owned_tensor(const int & fn)

The create_graph gradients parked for the running pass. What backward saved belongs to py_ctx, whose own traversal reaches it.

fnconst

graph_results

int graph_results(const int & result)

The user's backward result under create_graph, as tensors.

fn

invoke_backward

int invoke_backward(const int & grads)

Shared tail of apply and apply_barrier: call into Python with the prepared gradient tensors and unpack the returned per-input gradients.

fnconst

name

→std::string_view
int name()

Human-readable node name for debugger / profiler output.

Returns

std::string_view

The literal "PythonBackward".