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_ gradboolIf
true, gradients flowing into this tensor will be accumulated into grad (leaves) or propagated through grad_fn (non-leaves).is_ leafbooltrue for user-created tensors (no grad_fn); false for outputs of differentiable ops. Mirrors the reference framework's .is_leaf flag.versionstd::int64_tBumped 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_tIndex 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_ gradboolWhen
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.versionis monotonically non-decreasing for the lifetime of the owningTensorImpl.