Skip to content
class

AutogradMeta

AutogradMeta

Autograd bookkeeping for a single tensor.

Stored as std::optional<AutogradMeta> inside TensorImpl and only heap-emplaced when a tensor actually participates in the autograd graph (requires_grad == true or a grad_fn is attached). Tensors that never need gradients therefore pay zero overhead beyond the empty-optional inline storage.

Attributes

requires_gradbool
If true, gradients flowing into this tensor will be accumulated into grad (leaves) or propagated through grad_fn (non-leaves).
is_leafbool
true for user-created tensors (no grad_fn); false for outputs of differentiable ops. Mirrors the reference framework's .is_leaf flag.
versionstd::int64_t
Bumped on every in-place write via TensorImpl::bump_version. Autograd saves the pre-forward version for each input and raises VersionMismatch if the tensor is mutated between forward and backward.
grad_fnstd::shared_ptr<Node>
Edge into the autograd graph — the Node that produced this tensor. nullptr for leaves.
grad_output_nrstd::uint32_t
Index of this tensor among grad_fn's outputs, used to pick the right cotangent slot during backward.
gradstd::optional<Storage>
Accumulated gradient storage. Populated on leaves (and on retain_grad non-leaves) after a normal backward call. Cleared by zero_grad.
grad_implstd::shared_ptr<TensorImpl>
Full TensorImpl view of the gradient — populated instead of (or in addition to) grad when backward(create_graph=True) is used. Allows the gradient itself to participate in further autograd (second-order derivatives, MAML, Hessian-vector products, …).
retain_gradbool
When true, the engine accumulates incoming gradients into grad even for non-leaf tensors — mirroring the reference framework's Tensor.retain_grad() opt-in. The engine finds the tensor through its producer's hook slot (autograd/TensorHooks.h); this flag is what says it still asks.
leaf_hooksstd::shared_ptr<TensorHookSlot>
A leaf's gradient hooks, run before each accumulation into grad. Here rather than on the leaf's AccumulateGrad, which is made lazily and dropped by release_root / detach_. Null for a leaf without hooks — and for every non-leaf, whose hooks live on its producer node.

Notes

Invariants enforced by the autograd layer:

  • is_leaf == true ⇒ grad_fn == nullptr.
    • is_leaf == false ⇒ grad_fn != nullptr.
    • version is monotonically non-decreasing for the lifetime of the owning TensorImpl.