Skip to content
class

Engine

Engine

Reverse-mode autograd engine — drives the backward pass over a recorded computation graph rooted at a single output TensorImpl.

Engine is a stateless class that exposes a single static entry point (Engine::backward). It is never instantiated; all per-call state (worklist, accumulated gradients, visited set) lives on the stack of the invoking thread.

Algorithm

  1. Compute a reverse-topological ordering of the backward graph using an iterative post-order DFS (the recursive form would overflow on deep networks).
  2. Walk the ordering once, calling each node's apply(); gradients arriving at a node from multiple producers are summed into a pending map before the node is executed. A barrier (a node with several output slots) takes them slot by slot instead.
  3. When a node is popped, before it runs, the hooks of the tensors it produced (Tensor.register_hook) run on their slot's whole gradient and what they return is what the node receives; then retain_grad keeps that value in the tensor's .grad. The gradients of a hooked barrier slot are held by the engine until the barrier's turn so the hooks see their sum (TensorHooks.h). A node with no hooks pays one null test and Python is never called. The node's own checks (saved state already freed, saved inputs written in place) come after its hooks, which may themselves run a backward through it.
  4. Leaves (tensors with no grad_fn) are reached through their AccumulateGrad sentinel, which runs the leaf's own hooks and then writes the final gradient into leaf.grad.
  5. Without retain_graph, each node frees what it saved once it has run, and one more walk cuts the nodes whose release freed values an eager backward reads from the subgraph below them.

All four traversals — backward, backward(create_graph=True), grad and grad(create_graph=True) — run the hooks the same way; grad only on the nodes on a path to a requested input, and what it captures is the hooked value. Under create_graph a hook runs with grad mode on and sees the gradient's graph; otherwise grad mode is off.

Thread Safety

Two concurrent backward calls on the same graph are undefined behaviour — nodes are consumed and (when retain_graph=false) destroyed exactly once. Independent graphs may be driven from separate threads.

See Also

AccumulateGrad : terminal node that writes into leaf.grad. Node : abstract base for every backward graph node.

Static methods

2
static

backward

void backward(const int & root, int grad_seed, bool retain_graph, bool create_graph)

Run reverse-mode automatic differentiation starting from root.

Walks the computation graph attached to root->grad_fn() in reverse topological order, computes per-edge input gradients via each node's apply() method, accumulates contributions at branch points, and hands terminal gradients to AccumulateGrad for in-place accumulation into leaf.grad.

Parameters

rootstd::shared_ptr<TensorImpl>
Output tensor to differentiate. Must be non-null. If root has no grad_fn it is treated as a leaf and the seed is accumulated directly into root->grad.
grad_seedStorage= None
Initial gradient injected at root. An empty Storage (default) is replaced by a ones-tensor of root's shape / dtype / device — the common case of differentiating a scalar loss.
retain_graphbool= None
When false (default), each node's release_saved() is called immediately after its apply(), and a second pass that would read what was freed is refused; a graph that saved nothing its backward reads runs again (see the multi-root overload). Pass true to preserve the graph for multiple backward calls.
create_graphbool= None
When true, the backward pass itself is recorded in the autograd graph so that higher-order gradients can be taken on the resulting .grad tensors. Implies retain_graph=true because the forward nodes are re-used by the new graph. Concrete nodes must override apply_for_graph for this mode; nodes lacking graph support raise a clear error naming the op.

Raises

:runtime_error
If root is null, if a node returns an input_grads vector whose size disagrees with its outgoing edges (and both are non-empty), or if validate_versions() detects an in-place mutation of a saved input tensor.
:error_already_set
A tensor hook raised; the Python exception propagates unchanged.

Notes

The engine consumes nodes destructively when retain_graph=false: release_saved() frees the forward tensors each node had stashed for its backward formula — and, when the node can never run again, the tensor hooks it held — and each node whose release freed values an eager pass reads is cut from the subgraph below it, which a spent marker then stands for, so the chain of shared_ptrs below collapses.

Examples

>>> # Pseudo-C++: differentiate a scalar loss
>>> Engine::backward(loss);
>>> // Now every leaf with requires_grad=true has its .grad populated.
static

grad

→std::vector<TensorImplPtr>
int grad(const int & root, int grad_seed, const int)

Differentiate root with respect to inputs without writing any .grad.

The functional counterpart to backward. It walks the same graph, but instead of letting gradients terminate in the AccumulateGrad nodes that own each leaf's .grad slot, it intercepts them and returns them to the caller. No leaf's gradient state is read or modified — not the requested inputs', and not any other leaf's. A non-leaf that asked for retain_grad on a path to a requested input does keep what reaches it, as the reference does.

That last part is the reason this exists. Emulating it in Python by running a full backward and then restoring .grad can only restore the tensors the caller named; every other leaf in the graph keeps whatever the traversal deposited, which silently corrupts parameters the caller never mentioned.

See Also

Engine::backward — the accumulating counterpart.

Parameters

rootconst std::shared_ptr<TensorImpl>&
Output to differentiate. Must be non-null.
grad_seedStorage
Upstream gradient for root. An empty storage means "ones", matching backward.
inputsconst std::vector<std::shared_ptr<TensorImpl>>&
Tensors to differentiate with respect to. May be leaves or interior nodes; entries must be non-null.
retain_graphbool, default= false
Keep saved forward tensors so the graph can be traversed again.
create_graphbool, default= true for the returned gradients to be
differentiable in turn (higher-order). Implies retain_graph.

Returns

std::vector<TensorImplPtr>

One entry per requested input, in order. An entry is null when that input lies outside root's graph — the caller decides whether that is an error.

Raises

LucidError
If root or any entry of inputs is null.

Notes

A leaf is matched by the AccumulateGrad node bound to it; an interior tensor is matched by its own grad_fn. Interior captures do not stop the traversal, so asking for a tensor halfway down the graph still lets gradients reach everything below it.