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_tnext_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>saved_ versions_std::vector<std::int64_t>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>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
1Destructor
1Virtual methods
9Accumulate an arriving gradient into this barrier's internal buffer.
Parameters
input_ nrstd::uint32_tgradStorageRaises
:runtime_errorAdvance 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.
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
booltrue if the engine should drop an empty result instead of routing it on — routed, it became a leaf's .grad over no memory.
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.
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
booltrue if the engine should route incoming gradients through accumulate_barrier_grad / apply_barrier instead of apply.
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.
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
LucidErrorRefuse 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
VersionMismatchMethods
17Compute 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 , apply returns
where is the Jacobian of with respect to .
Parameters
grad_ outStorageReturns
std::vector<Storage>One Storage per forward input. An empty / default Storage at position i signals that no gradient flows to that input.
Flush an accumulated barrier and produce the consolidated gradients.
Returns
std::vector<Storage>One Storage per outgoing edge (same contract as apply).
Raises
:runtime_errorGraph-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&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_errornode_name.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
VersionMismatchallow_mutation_on_saved_tensors).The hook slots, made empty on first use.
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.
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.
Return a short human-readable identifier for this node.
Returns
std::stringDefaults 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.
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.
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.
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.
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.
Monotonically-increasing identifier assigned at construction.
Returns
std::uint64_tCreation order. The engine compares sequence numbers to break topological ties, executing later-created nodes first so that gradients flow from loss toward leaves.
Install the outgoing edges produced by the forward op builder.
Parameters
edgesstd::vector<Edge>Notes
Called exactly once at forward time; reading via next_edges
is the only legal access during backward.
Install the per-input version counters captured at forward time.
Parameters
vstd::vector<std::int64_t>Overwrite the sequence number. Used by serialisation / replay tools that need to reconstruct a graph deterministically.
Parameters
nstd::uint64_tThe 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.