Skip to content
class

Node

Node

Abstract base class for every node in the backward computation graph.

A Node is the unit of work that Engine executes during backward. Each concrete subclass saves whatever tensors and scalars it needs at forward time (typically into its own member fields) and implements apply to compute input gradients from the incoming output gradient via the chain rule.

The reference framework's Function corresponds to a Python-side lucid.autograd.Function; on the C++ side that role is split into a forward op (free function or struct method) plus this Node subclass. Subclassing Node directly is unusual — most engine-resident ops inherit through AutogradNode / FuncOp, which add fixed-size storage for saved inputs and version checking.

See Also

Edge — the directed link between nodes. AutogradNode — CRTP base with saved-input slots and version checking that most ops actually inherit from.

Attributes

sequence_nr_std::uint64_t
Globally-unique creation order assigned via next_sequence_nr. The engine uses this to break topological ties so that nodes closer to the loss are executed first.
next_edges_std::vector<Edge>
Outgoing edges — one per input tensor of the forward op. Populated by the op builder at forward time and read-only thereafter.
saved_versions_std::vector<std::int64_t>
Version counters captured at forward. AutogradNode keeps one per input slot; a node that subclasses Node directly keeps one per tensor it holds for backward, in an order of its own. validate_versions compares exactly the ones whose values the backward reads against the live counters, to catch in-place writes that would silently corrupt gradients.
tensor_hooks_std::unique_ptr<NodeHooks>
Hooks and retain_grad targets of the tensors this node produced, by output slot; null for the common node that has none.

Notes

Lifetime. Nodes are jointly owned by the TensorImpl that produced them (via grad_fn) and by the Edge objects of consumer nodes. Once backward completes and grad_fn is cleared on the root, the chain of shared_ptr references collapses and all temporary nodes are destroyed.

Thread safety. Node is not thread-safe. The engine runs the backward graph on a single thread; concurrent backward invocations on the same graph are undefined behaviour.

Constructors

1
ctor

Node

void Node()

Construct a node and assign the next monotonically increasing sequence number via next_sequence_nr.

Destructor

1
dtor

~Node

void ~Node()

Polymorphic destructor; subclasses are deleted through Node*. Out of line: the tensor hooks it owns are a complete type only in Node.cpp, which keeps pybind11 out of this header.

Virtual methods

9
virt

accumulate_barrier_grad

void accumulate_barrier_grad(int, int)

Accumulate an arriving gradient into this barrier's internal buffer.

Parameters

input_nrstd::uint32_t
The slot the gradient is destined for.
gradStorage
The gradient produced by an upstream node.

Raises

:runtime_error
Always, unless overridden — calling barrier accumulation on a non-barrier node is a programmer error.
virt

advance_saved_output_version

void advance_saved_output_version(int)

Advance any saved-output version baseline recorded on this node to v when an out-of-place op's result is rebound in-place onto a destination tensor whose version counter moves to v.

virtconst

empty_grad_is_none

→bool
bool empty_grad_is_none()

Whether an empty storage among this node's results means "no gradient for that input" rather than a gradient of zero elements. The nodes that call into Python say None that way; a native node's empty result is a real gradient of a zero-size tensor, which a CPU allocation of zero bytes also leaves empty.

Returns

bool

true if the engine should drop an empty result instead of routing it on — routed, it became a leaf's .grad over no memory.

virtconst

for_each_owned_tensor

void for_each_owned_tensor(const int & fn)

Call fn on every tensor this node holds a strong reference to — what it keeps for backward — so that the cyclic garbage collector, which reaches the graph only through the engine, can see past the node. The default holds none.

virtconst

is_barrier

→bool
bool is_barrier()

Whether this node is a barrier that batches gradients from many edges before executing. Regular ops return false; barrier nodes (e.g. AccumulateGrad) override to true.

Returns

bool

true if the engine should route incoming gradients through accumulate_barrier_grad / apply_barrier instead of apply.

virt

release_saved

void release_saved()

Release every Storage saved for backward, allowing the memory to be reclaimed once the engine no longer needs this node.

Notes

Default is a no-op. Subclasses override to reset their saved slots to empty CpuStorage. Called automatically by the engine after apply returns, unless retain_graph=True. What it frees is said by saved_kind.

virt

restore_saved_for_graph

void restore_saved_for_graph()

Make the tensors apply_for_graph reads the ones this node was handed at forward time again.

Graph-mode backward reads its inputs through the tensors it was handed, where eager backward reads the Storage it saved by value — and not every write between the two passes validate_versions. A saved output is not version-checked: after y = x.sigmoid(), a y.mul_(2) (metal; the CPU refuses that write) or a y.exp_() under no_grad gave grad(y.sum(), x, create_graph=True) the derivative at the written y, while eager backward used the saved one. Nor is anything under allow_mutation_on_saved_tensors, whose promise is the values from before the write. Rebuilt, those reads answer what eager backward answers.

Called by the engine after validate_versions and before apply_for_graph. Eager backward does not call it. The default has nothing to restore. Declared after the other virtuals so their slots keep their places.

Raises

LucidError
(Through overrides) when such a tensor's values were not kept in a form the forward-time tensor can be rebuilt from.
virtconst

saved_kind

SavedKind saved_kind()
virt

validate_versions

void validate_versions()

Refuse backward when a tensor whose values this node reads has been written in place since forward.

A node validates exactly the tensors whose values its backward reads — no more, or a write into an input the formula never reads (add, sum, a view) is refused where the reference allows it; no fewer, or the write reaches the gradient in silence. The default has nothing to check: it is right only for a node that holds no tensor for backward. AutogradNode guards the inputs it saved by value; a node that holds a tensor any other way overrides this (tools/check_saved_versions.py refuses a node class that holds one without saying how it is guarded).

Raises

VersionMismatch
(Through overrides) when such a tensor's live version counter differs from the value snapshotted during forward.

Methods

17
fn

apply

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

Compute input gradients from the upstream output gradient.

This is the core chain-rule contribution implemented by each concrete backward node. The returned vector has one entry per outgoing edge — i.e. per input to the corresponding forward op — and the engine dispatches entry i along next_edges_[i].

Math

For a forward op y=f(x1,…,xn)y = f(x_1, \ldots, x_n), apply returns

xˉi=∂L∂xi=Jf(i) T yˉ,\bar{x}_i = \frac{\partial \mathcal{L}}{\partial x_i} = J_f^{(i)\,T}\, \bar{y},

where Jf(i)J_f^{(i)} is the Jacobian of ff with respect to xix_i.

Parameters

grad_outStorage
Upstream gradient ∂L/∂y\partial \mathcal{L} / \partial y matching the forward output's shape, dtype, and device. Implementations may assume it is non-null.

Returns

std::vector<Storage>

One Storage per forward input. An empty / default Storage at position i signals that no gradient flows to that input.

fn

apply_barrier

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

Flush an accumulated barrier and produce the consolidated gradients.

Returns

std::vector<Storage>

One Storage per outgoing edge (same contract as apply).

Raises

:runtime_error
Always, unless overridden — calling barrier flush on a non-barrier node is a programmer error.
fn

apply_for_graph

→std::vector<TensorImplPtr>
int apply_for_graph(const int & grad_out)

Graph-recording variant of apply for higher-order autograd.

Invoked by the engine when create_graph=True: the backward computation itself is performed through TensorImpl-based ops so that the resulting gradient tensors carry their own grad_fn, enabling differentiation of gradients (Hessians, double-backward).

Parameters

grad_outconst TensorImplPtr&
Upstream gradient as a live TensorImpl, possibly with a grad_fn of its own.

Returns

std::vector<TensorImplPtr>

One TensorImpl per forward input, each possibly carrying autograd metadata.

Raises

:runtime_error
If the concrete node has not overridden this method — create-graph is opt-in per op. The message names the offending op via node_name.
fnconst

check_saved_version

void check_saved_version(const int & live, int k, int op_name, int input_idx)

Refuse when live has moved past the version recorded at k in saved_versions_. input_idx names the tensor in the error as the op's argument position. Nothing is checked when no version was recorded at k or the tensor is gone — nothing can then reach the gradient through it.

Raises

VersionMismatch
The tensor was written in place since forward and the check is not waived (allow_mutation_on_saved_tensors).
fn

ensure_tensor_hooks

NodeHooks & ensure_tensor_hooks()

The hook slots, made empty on first use.

fn

mark_released

void mark_released(SavedKind freed)

Record that a pass released this node, freeing what freed says — saved_kind, read before release_saved ran. The version counters go too: nothing they guard is left to check.

fnconst

next_edges

→const std::vector<Edge>&
const int & next_edges()

Read-only view of this node's outgoing edges.

Returns

const std::vector<Edge>&

Edge list whose i-th entry is the destination of the gradient apply returns at position i.

fnconst

node_name

→std::string
int node_name()

Return a short human-readable identifier for this node.

Returns

std::string

Defaults to "unknown"; concrete nodes override to expose their schema_v1.name (e.g. "matmul", "linear").

Notes

Used in error messages emitted by apply_for_graph and in debugger / profiler output.

fn

release_tensor_hooks

void release_tensor_hooks()

Drop every hook slot. Called by the engine once release_saved has made this node impossible to run again: a hook's closure that refers to the tensor it is on closes a cycle — tensor, node, hook, tensor — that Python's collector cannot see through the engine.

fnconst

released

bool released()

Whether a pass released what this node held for backward. A create_graph pass refuses such a node: graph-mode backward reads the tensors the node was handed, and a release frees them all.

fnconst

saved_released

bool saved_released()

Whether a release freed values this node's eager backward reads, so that every pass refuses it. A node that saved none of them — add, sum, a view — runs eagerly again, as the reference allows.

fnconst

saved_versions

→const std::vector<std::int64_t>&
const int & saved_versions()

Read-only view of the input version counters captured at forward.

Returns

const std::vector<std::int64_t>&

One counter per forward input, in input order.

fnconst

sequence_nr

→std::uint64_t
int sequence_nr()

Monotonically-increasing identifier assigned at construction.

Returns

std::uint64_t

Creation order. The engine compares sequence numbers to break topological ties, executing later-created nodes first so that gradients flow from loss toward leaves.

fn

set_next_edges

void set_next_edges(int edges)

Install the outgoing edges produced by the forward op builder.

Parameters

edgesstd::vector<Edge>
One edge per forward input. Moved into the node.

Notes

Called exactly once at forward time; reading via next_edges is the only legal access during backward.

fn

set_saved_versions

void set_saved_versions(int v)

Install the per-input version counters captured at forward time.

Parameters

vstd::vector<std::int64_t>
One counter per forward input. Moved into the node.
fn

set_sequence_nr

void set_sequence_nr(int n)

Overwrite the sequence number. Used by serialisation / replay tools that need to reconstruct a graph deterministically.

Parameters

nstd::uint64_t
New sequence number to install.
fnconst

tensor_hooks

NodeHooks * tensor_hooks()

The hooks and retain_grad targets of the tensors this node produced, by output slot (TensorHooks.h), or null when there are none — the only cost a node without hooks pays.