Skip to content
fn

snapshot

int snapshot(const int & a, const int & other)

A stand-in for a to run the forward against.

A node keeps a handle on each tensor it was given, and graph-mode backward reads its values and its graph position through that handle, not through the Storage it saved by value. Handed a itself, the node read a as the write left it — the new values, and the new grad_fn, which is the node itself:

sin_ -> cos(sin(x)) instead of cos(x) buf.mul_(v) -> d/dv = buf * v instead of buf

in graph mode only, since eager backward() reads the Storage. So whenever the op records a node, the node is handed a tensor of its own: one that holds the values a holds now and sits where a sits now. a not requiring grad is no exception — the other operand of a binary op may, and its node saves this one. Being its own tensor, it also keeps its own version count, which is what lets the write move a's (adopt_graph_position) without the node refusing itself.

The snapshot shares the buffer rather than copying it, and the caller's assignment replaces a's slot rather than the buffer, so the original values stay alive and unmutated for as long as the node needs them. No data is copied, and when no node is recorded — no_grad, or no operand requiring grad — nothing is allocated either.

A write that lands in the buffer (TensorImpl::write_lands_in_buffer: a CPU tensor with live views, or one read from .grad) is the exception: a node holding the buffer would read the new values back, and the holder would stop the write besides — p.grad.add_(w) with w requiring grad was refused as a gradient something else reads. Its snapshot is a copy.