autograd: PyTorch's dynamic graph
How PyTorch records operations in a dynamic graph and backward traverses it to accumulate leaf gradients. Control graph recording and accumulation, compute higher derivatives, use torch.func, and verify custom autograd functions.
After this lesson you can
- Trace autograd's graph for an expression and predict which tensors receive .grad.
- Explain and control gradient accumulation, retain_graph and graph release after backward.
- Deliberately cut the graph with no_grad, inference_mode and detach, and understand saved-tensor version counters.
- Calculate Jacobians, Hessian-vector products and higher gradients with torch.autograd.grad and torch.func.
- Implement a torch.autograd.Function with analytical backward and verify it with gradcheck and gradgradcheck.
Before you start
Motivation: a gradient that is None, zero or NaN
Sooner or later, a training run that should learn does not, and printing the gradient shows one of these three things:
print(modelo.encoder.weight.grad) # None
print(modelo.cabeza.weight.grad) # tensor([[0., 0., ..., 0.]])
print(perdida.item()) # nan
Each has a different cause and is diagnosed with a different piece of autograd. None means no graph path connects that parameter to the loss: someone cut it with detach, computed it inside torch.no_grad(), the parameter lacks requires_grad, or you are looking at a non-leaf tensor. Zero means the path exists but the gradient along it vanishes: a dead ReLU, a saturated clamp, a mask. NaN means some local derivative was evaluated outside its domain and autograd silently propagated it to the leaves. Other symptoms include .grad growing each iteration even though the model does not change, memory climbing while you merely log loss, or a RuntimeError about “versions” of a tensor you do not remember touching.
Solving these problems requires knowing exactly what the tool does: what it records during forward, saves, the order in which it traverses the record, where it writes results and what it deletes afterward. You will study automatic differentiation theory in depth in reverse mode, and derive backpropagation for a dense network by hand. Here you get a mental model precise enough to predict before execution which tensors have .grad, its value and which error arises. Then use it to cut gradients intentionally (target networks, frozen encoders), calculate gradients of gradients (penalties, Hessian-vector products), transform functions with torch.func, and write differentiable functions with a verified analytical backward.
The graph autograd records
Recall from the previous lesson that a PyTorch tensor is memory plus metadata. Autograd adds three metadata fields: requires_grad (a Boolean), grad_fn (a reference to the node that produced it), and grad (where its gradient accumulates). While the program runs, these build a record of everything needed for later differentiation.
Two rules determine what enters the graph. First, propagation: an operation’s result requires gradients if and only if any input does (and recording is enabled; we will see how to disable it). Second, origin: only tensors you create can be leaves with requires_grad=True; nn.Module parameters are leaves by construction, while data are not by default. Thus in y = (w * x + b).relu().sum() with parameters w and b and data x, the graph has four operation nodes and two AccumulateGrad nodes, and the MulBackward0 edge to x is None.
Notice the direction: the autograd graph is not the forward graph but the one traversed backward. Its nodes are backward functions (MulBackward0 knows how to multiply the incoming gradient by the other factor) and its edges point from each result to its inputs.
AccumulateGrad do with both contributions? Remove requires_grad from b and see what disappears. At the end, press ‘backward again’ with and without retain_graph, and ‘another iteration’ several times before zero_grad(). Write your own expressions: (w * x).sqrt() without .sum(), b.detach() * w or torch.sigmoid(u).log().sum().Three observations from the figure. First, each node’s name is the operation followed by Backward and a variant number (RsubBackward1 is 1 - w, subtraction with the number first); what it saves depends on who requires gradients: MulBackward0 in w * x saves only x (_saved_other), because differentiation with respect to w needs the other factor and nobody requests the derivative with respect to x. Second, ReluBackward0, ExpBackward0 and TanhBackward0 save their output, not input, because the derivative is expressed through it (, ); this matters for in-place operations. Third, with a nonscalar output, backward() without arguments fails, as it does when no leaf requires gradients; both errors are PyTorch’s verbatim.
The graph from code
Everything in the figure is accessible from Python. This cell traverses the ReLU neuron’s graph via next_functions and prints what each node saves:
import torch
x = torch.tensor([1.0, -2.0, 3.0])
w = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(-1.0, requires_grad=True)
y = (w * x + b).relu().sum()
def recorrer(fn, nivel=0):
"""Imprime el grafo de backward desde fn siguiendo next_functions."""
if fn is None:
print(" " * nivel + "None")
return
# dir() lista los atributos posibles; solo algunos están rellenos
guardados = [a for a in dir(fn) if a.startswith("_saved_") and getattr(fn, a) is not None]
extra = f" hoja de forma {tuple(fn.variable.shape)}" if type(fn).__name__ == "AccumulateGrad" else ""
print(" " * nivel + type(fn).__name__, guardados or "", extra)
for siguiente, _ in fn.next_functions:
recorrer(siguiente, nivel + 1)
recorrer(y.grad_fn)
relu = y.grad_fn.next_functions[0][0]
acc_w = relu.next_functions[0][0].next_functions[0][0].next_functions[0][0]
print("\nis_leaf:", w.is_leaf, x.is_leaf, y.is_leaf, "| requires_grad:", w.requires_grad, x.requires_grad, y.requires_grad)
print("el AccumulateGrad apunta a w:", acc_w.variable is w)
print("ReluBackward0 guarda su salida:", relu._saved_result)
y.backward()
print("w.grad =", w.grad, " b.grad =", b.grad, " x.grad =", x.grad)
try:
relu._saved_result
except RuntimeError as e:
print("tras backward:", str(e)[:68], "...")npm run lab and open the connection link.The final attempt to read _saved_result fails with the same message as a second backward: saved tensors no longer exist. We will return to this.
A new graph on every forward
“Dynamic” is literal. PyTorch does not compile your function: it executes Python line by line and each operation adds its node at that moment. The graph records the path execution took, not the program. If an if or loop depends on data, each call produces a different graph and backward differentiates exactly the branch taken.
import torch
def crecer(x, w, umbral=100.0):
"""Multiplica por w hasta superar el umbral: el número de operaciones depende de los datos."""
y, pasos = x, 0
while y.abs() < umbral:
y = y * w
pasos += 1
return y, pasos
def longitud(fn):
n = 0
while fn is not None and type(fn).__name__ != "AccumulateGrad":
n += 1
fn = next((f for f, _ in fn.next_functions if f is not None), None)
return n
w = torch.tensor(2.0, requires_grad=True)
for x0 in [1.5, 30.0, 0.01]:
y, k = crecer(torch.tensor(x0), w)
(g,) = torch.autograd.grad(y, w)
print(f"x = {x0:5}: {k:2d} productos, {longitud(y.grad_fn):2d} nodos en el grafo, "
f"dy/dw = {g.item():8.1f} (k x w^(k-1) = {k * x0 * 2.0 ** (k - 1):8.1f})")npm run lab and open the connection link.Each input generates a chain of different length, and in each case the gradient is the derivative of for the resulting . Note what that means: autograd differentiates the piecewise function defined by the code without seeing that depends on . Where jumps, the actual function is discontinuous and autograd returns the derivative of the active piece.
This design makes PyTorch convenient to debug (a print or breakpoint in forward works as in any program) but also has a cost: the Python interpreter is in every operation’s path. Capturing the graph once for optimization is the job of TorchDynamo, in the torch.compile lesson.
backward: traversing the graph in reverse
Calling L.backward() on a scalar loss starts the autograd engine. It applies the multivariable chain rule node by node, from output to leaves. Each node can calculate a vector-Jacobian product: if it produced and receives , it returns
without ever forming Jacobians. For MulBackward0 this is ; for SumBackward0, copy the incoming scalar to every position; for an operation with broadcasting, sum over expanded axes (in the figure, b’s gradient is the sum of three contributions).
Proof
Number graph tensors in reverse topological order: first, each tensor after all its consumers. We claim that when the engine executes tensor ‘s node, its input buffer equals . This holds for because the engine starts with gradient 1. Assume it holds for every tensor before . Each consumer is earlier, has run with in its buffer, and sent the product . The engine executes only when its dependency counter reaches zero, meaning all contributions have arrived, and sums them. By the multivariable chain rule, since depends on only through its consumers, this sum is . At a leaf, the node is its AccumulateGrad, which adds its buffer to .grad. If is disconnected, no path carries a gradient to it and its AccumulateGrad does not execute.
The theorem gives three everyday facts. The result is the derivative at the point where forward ran (so a forward NaN contaminates backward). A leaf used several times receives the sum of all contributions, exactly the chain rule: in the figure, (w * x).sum() + w ** 2 gives w.grad . And the result is added to .grad, not substituted. The first explains the opening NaN. In the figure’s ‘A propagating NaN’ example, (w * x).sqrt() evaluates , which is nan, and SqrtBackward0 divides the incoming gradient by : the poisoned component reaches w.grad summed with healthy ones, making the whole result nan even though only one of three elements is outside the domain. To locate the culprit in a large model, torch.autograd.set_detect_anomaly(True) records each node’s call stack during forward and stops backward at the first NaN, identifying its originating forward line; it is slow, so enable it only for debugging (you will use it in NaN and Inf tracing).
The real engine also chooses an order that does not change values but affects what you see in a hook or profile: among ready nodes it executes the highest sequence number first (most recent in forward), and AccumulateGrad as soon as they are ready.
Accumulate, release, retain
The rules determining what happens to gradients and the graph form backward semantics:
- Accumulation.
backwardperformsℓ.grad += ∂L/∂ℓat each leaf. If.gradisNone, it creates it. Nothing clears it except you:optimizer.zero_grad()(which since PyTorch 2.0 defaults to resetting it toNone) orp.grad = None. - Leaves only. Intermediate tensors do not retain
.grad; reading it returnsNoneand a warning. To retain it, callt.retain_grad()before backward; to inspect without storing, use a hook. - Release. On finishing, the engine frees saved tensors of each executed node (by default,
retain_graph=False). A secondbackwardthrough the same graph fails withTrying to backward through the graph a second timeas soon as a node needs a saved tensor, normally the case (a graph of only additions and negations, saving nothing, can be traversed again without complaint; the figure demonstrates(w + b).sum()). Withretain_graph=True, saved tensors survive and you can repeat, at a memory cost.
Release exists because saved tensors make up most training memory: the activations of every layer, which forward must retain until backward uses them. Freeing them immediately after use makes peak memory occur at the forward-to-backward transition rather than grow each iteration (quantified in reverse-mode memory cost and the GPU memory budget).
import torch
w = torch.tensor(1.5, requires_grad=True)
L = 2 * w ** 2 # dL/dw = 4w = 6
for i in range(3):
L.backward(retain_graph=True)
print(f"backward {i + 1}: w.grad = {w.grad.item()}")
L.backward() # el último puede liberar el grafo
try:
L.backward()
except RuntimeError as e:
print("quinto backward:", str(e)[:58], "...")
# acumulación deliberada: 4 micro-lotes con la pérdida dividida por 4 dan el gradiente del lote
torch.manual_seed(0)
X, y = torch.randn(64, 3), torch.randn(64)
p = torch.zeros(3, requires_grad=True)
def perdida(xb, yb):
return ((xb @ p - yb) ** 2).mean()
perdida(X, y).backward()
g_lote = p.grad.clone()
p.grad = None # lo mismo que optimizer.zero_grad()
for xb, yb in zip(X.split(16), y.split(16)):
(perdida(xb, yb) / 4).backward() # cada micro-lote crea y libera su propio grafo
print("micro-lotes = lote completo:", torch.allclose(p.grad, g_lote), " error máximo:", (p.grad - g_lote).abs().max().item())
# el error del logging: sumar pérdidas como tensores encadena todos los grafos
def nodos(t):
vistos, pila = set(), [t.grad_fn]
while pila:
fn = pila.pop()
if fn is None or fn in vistos:
continue
vistos.add(fn)
pila.extend(f for f, _ in fn.next_functions)
return len(vistos)
total_mal, total_bien = 0.0, 0.0
for paso in range(100):
loss = perdida(X, y)
total_mal = total_mal + loss # tensor: mantiene vivo el grafo de cada paso
total_bien += loss.item() # número de Python: el grafo se libera
print("nodos que mantiene vivos total_mal:", nodos(total_mal), " | total_bien es", type(total_bien).__name__)npm run lab and open the connection link.The cell shows both sides of accumulation. The useful side: since the gradient of a sum is the sum of gradients, accumulating microbatches with loss divided by gives exactly the full-batch gradient (up to rounding), allowing training with effective batches that do not fit in memory. The dangerous side: total_mal is a tensor whose graph hangs from all 100 losses, 501 nodes with saved tensors never released. In real training that line leaks memory at every step.
The accumulation trap
What exactly happens to training if you forget zero_grad? The answer is more interesting than “it goes wrong.”
w.grad used by optimizer.step() (bars) with the true gradient there (circles). Start without zero_grad: the parameter oscillates around without approaching it, and bars do not match circles. Enable zero_grad. Switch to ‘2 on same loss’ and disable retain_graph. Then ‘4 microbatches’: dividing loss by 4 matches the gray trajectory; without division, the same diverges. Above what does this happen?The figure’s oscillation is not an accident of the chosen numbers.
Proof
Without zero_grad, at iteration the accumulated gradient is and the step is . At this gives . Subtracting step from step : , which rearranges to the recurrence. For the invariant, use : , and also . They are equal. Evaluating at , . The quadratic form has eigenvalues , so . If , the lower bound is positive and, since for all , gives : the sequence is bounded. The upper bound gives the stated inequality, and since , the maximum cannot tend to zero. If , and the characteristic equation has two negative real roots with product 1, and , and . Coefficient vanishes only if , but ; hence and . At , the double root gives , growing linearly. In both cases is unbounded.
With (the figure’s initial state), and the oscillation period is iterations. Accumulated .grad is momentum with : Polyak momentum damps oscillation by multiplying history by ; without that factor there is no dissipation. Two practical lessons follow. Training without zero_grad can appear to learn for a few iterations before oscillating, making it hard to detect. And calling backward times before each step, on the same loss or undivided microbatches, multiplies the effective step by : a stable can diverge without changing the optimizer.
A pocket autograd from scratch
The next cell implements the same design as PyTorch in NumPy and about a hundred lines: tensors with requires_grad, grad_fn and a version counter; nodes with next_functions and saved tensors; one AccumulateGrad shared by all uses of a leaf; and an engine counting dependencies, executing the ready node with the highest sequence number first, summing inputs at each node and releasing saved data afterward. It runs in the browser.
import numpy as np
class Tensor:
def __init__(self, data, requires_grad=False):
self.data = np.asarray(data, dtype=float)
self.requires_grad = requires_grad
self.grad_fn = None # el Node que lo creó; None en las hojas
self.grad = None
self._version = 0 # contador de versiones: sube con cada in-place
self._acc = None # AccumulateGrad de la hoja, compartido por todos sus usos
@property
def is_leaf(self):
return self.grad_fn is None
def add_(self, c): # operación in-place
self.data += c
self._version += 1
return self
def __mul__(self, o): return op(MulBackward, self, lift(o))
__rmul__ = __mul__
def __add__(self, o): return op(AddBackward, self, lift(o))
__radd__ = __add__
def relu(self): return op(ReluBackward, self)
def sum(self): return op(SumBackward, self)
def __repr__(self):
fn = f", grad_fn=<{type(self.grad_fn).__name__}>" if self.grad_fn else ""
return f"tensor({np.round(self.data, 4).tolist()}{fn})"
def lift(o):
return o if isinstance(o, Tensor) else Tensor(o)
def unbroadcast(g, shape):
"""Suma g sobre los ejes que el broadcasting expandió (el sum_to_size de PyTorch)."""
while g.ndim > len(shape):
g = g.sum(axis=0)
for ax, n in enumerate(shape):
if n == 1 and g.shape[ax] != 1:
g = g.sum(axis=ax, keepdims=True)
return g
class Node:
contador = 0
def __init__(self, inputs, saved=()):
self.next_functions = [arista(t) for t in inputs]
self.shapes = [t.data.shape for t in inputs]
self._saved = [(t, t._version) for t in saved] # guarda el tensor y su versión
self.seq = Node.contador
Node.contador += 1
def saved_tensors(self):
if self._saved is None:
raise RuntimeError("Trying to backward through the graph a second time")
for t, v in self._saved:
if t._version != v:
raise RuntimeError(f"one of the variables needed for gradient computation has been "
f"modified by an inplace operation: is at version {t._version}; expected version {v}")
return [t.data for t, _ in self._saved]
class AccumulateGrad:
seq = float("inf") # en cuanto está listo, se ejecuta
next_functions = []
def __init__(self, variable):
self.variable = variable
def apply(self, g):
v = self.variable
v.grad = g.copy() if v.grad is None else v.grad + g # acumula, no sobrescribe
return []
def arista(t):
if not t.requires_grad:
return None
if t.is_leaf:
if t._acc is None:
t._acc = AccumulateGrad(t)
return t._acc
return t.grad_fn
class MulBackward(Node):
def apply(self, g):
a, b = self.saved_tensors()
return [unbroadcast(g * b, self.shapes[0]), unbroadcast(g * a, self.shapes[1])]
class AddBackward(Node):
def apply(self, g):
return [unbroadcast(g, s) for s in self.shapes]
class ReluBackward(Node):
def apply(self, g):
(r,) = self.saved_tensors()
return [g * (r > 0)]
class SumBackward(Node):
def apply(self, g):
return [np.broadcast_to(g, self.shapes[0]).copy()]
def op(cls, *inputs):
a = [t.data for t in inputs]
out_data = {MulBackward: lambda: a[0] * a[1], AddBackward: lambda: a[0] + a[1],
ReluBackward: lambda: np.maximum(a[0], 0), SumBackward: lambda: a[0].sum()}[cls]()
out = Tensor(out_data, requires_grad=any(t.requires_grad for t in inputs))
if out.requires_grad: # solo se registra si alguna entrada requiere gradiente
saved = {MulBackward: inputs, ReluBackward: (out,)}.get(cls, ())
out.grad_fn = cls(inputs, saved)
return out
def backward(y, retain_graph=False):
if y.grad_fn is None:
raise RuntimeError("element 0 of tensors does not require grad and does not have a grad_fn")
if y.data.size != 1:
raise RuntimeError("grad can be implicitly created only for scalar outputs")
# 1) cuántas aristas llegan a cada nodo alcanzable desde la raíz
deps, pila, vistos = {}, [y.grad_fn], set()
while pila:
n = pila.pop()
if n in vistos:
continue
vistos.add(n)
for m in n.next_functions:
if m is not None:
deps[m] = deps.get(m, 0) + 1
pila.append(m)
# 2) ejecutar los nodos listos, el de mayor número de secuencia primero
buffers, listos, orden = {y.grad_fn: np.ones_like(y.data)}, [y.grad_fn], []
while listos:
listos.sort(key=lambda n: n.seq)
n = listos.pop()
g = buffers.pop(n) # suma de todo lo que ha llegado a este nodo
orden.append(type(n).__name__)
for m, gm in zip(n.next_functions, n.apply(g)):
if m is None:
continue
buffers[m] = gm if m not in buffers else buffers[m] + gm
deps[m] -= 1
if deps[m] == 0:
listos.append(m)
if not retain_graph and isinstance(n, Node):
n._saved = None # libera los tensores guardados
return orden
# 1) el ejemplo de la figura
x = Tensor([1.0, -2.0, 3.0])
w = Tensor(2.0, requires_grad=True)
b = Tensor(-1.0, requires_grad=True)
y = (w * x + b).relu().sum()
print("y =", y)
print("orden del backward:", backward(y))
print("w.grad =", w.grad, " b.grad =", b.grad, " x.grad =", x.grad)
# 2) una hoja usada dos veces: el buffer suma antes de AccumulateGrad
w.grad = None
y2 = (w * x).sum() + w * w
print("\norden:", backward(y2), " w.grad =", w.grad, " (sum(x) + 2w = 6)")
# 3) comprobación contra diferencias centrales
def f(wv, bv):
return np.maximum(wv * x.data + bv, 0).sum()
h = 1e-6
print("\ndiferencias finitas:", (f(2 + h, -1) - f(2 - h, -1)) / (2 * h), (f(2, -1 + h) - f(2, -1 - h)) / (2 * h))
# 4) los tres errores clásicos
for nombre, prueba in [
("segundo backward", lambda: backward(y)),
("salida no escalar", lambda: backward(w * x)),
("nada requiere grad", lambda: backward((x * x).sum())),
]:
try:
prueba()
except RuntimeError as e:
print(f"{nombre:20s} RuntimeError: {e}")
# 5) retain_graph acumula, y un in-place sobre un tensor guardado rompe el backward
w.grad = None
y3 = (w * x + b).relu().sum()
backward(y3, retain_graph=True)
backward(y3)
print("\ndos backward con retain_graph: w.grad =", w.grad)
z = (w * x + b).relu()
z.add_(1.0) # z es el resultado guardado de ReluBackward
try:
backward(z.sum())
except RuntimeError as e:
print("in-place:", e)Compare the first example’s printed order with the figure: SumBackward, ReluBackward, AddBackward, then b’s AccumulateGrad, already ready with maximum priority, before MulBackward. In the second, w’s AccumulateGrad receives three contributions (two from w * w and one from the first product) and executes once with their sum. Unlike this engine, PyTorch has hundreds of derivatives written in C++, multithreaded and GPU execution, handling of saved tensors that are the node’s own outputs, higher-order gradients and everything we see below.
Nonscalar outputs: backward is a VJP
If with , there is no single “gradient”: there is a Jacobian . The engine propagates a vector from the output, so y.backward(gradient=v) (or torch.autograd.grad(y, x, grad_outputs=v)) calculates
the vector-Jacobian product. This is equivalent to differentiating scalar , which is why a scalar output has implicit gradient 1. The cost consequence is immediate: one backward gives one combined row of the Jacobian for roughly the cost of a forward. The full Jacobian needs backward passes, one for each basis vector of . For a loss () this is unbeatable; for a function from to , it takes a thousand passes. Forward mode does the reverse, one column per pass; see torch.func.jacfwd and Jacobian computation strategies.
import torch
def f(x):
return torch.stack([x[0] * x[1], torch.sin(x[2]), (x ** 2).sum()])
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = f(x)
# el jacobiano fila a fila: un VJP con cada vector de la base
filas = []
for i in range(3):
e_i = torch.zeros(3)
e_i[i] = 1.0
(fila,) = torch.autograd.grad(y, x, grad_outputs=e_i, retain_graph=True)
filas.append(fila)
J = torch.stack(filas)
print("J por filas:\n", J)
print("igual a autograd.functional.jacobian:", torch.allclose(J, torch.autograd.functional.jacobian(f, x)))
# las tres filas en una sola llamada, vectorizada
(J_lote,) = torch.autograd.grad(y, x, grad_outputs=torch.eye(3), retain_graph=True, is_grads_batched=True)
print("con is_grads_batched:", torch.allclose(J_lote, J))
# backward con gradient: x.grad = v^T J
v = torch.tensor([1.0, 0.5, -1.0])
y.backward(gradient=v)
print("x.grad =", x.grad, " v @ J =", v @ J)npm run lab and open the connection link.retain_graph=True in the loop is essential: every VJP traverses the same graph. is_grads_batched=True performs all three passes together using vmap underneath, which torch.func generalizes.
Cutting the graph
So far the problem was obtaining gradients. Often the opposite is true: some tensors should not receive them, or computations should not be recorded. The tools for cutting the graph each cut in a different place:
| Tool | What it does | Forward cost | Typical use |
|---|---|---|---|
with torch.no_grad(): | records nothing computed inside; results do not require grad | no graph or saved tensors | evaluation, targets, manual parameter updates |
with torch.inference_mode(): | like no_grad, also marks tensors as inference tensors: no version counter or view metadata | cheapest | pure inference whose results never return to autograd |
t.detach() | returns a tensor sharing memory and version counter with t, without history: a new leaf without requires_grad | graph up to t was already built | cut one particular use of a tensor |
p.requires_grad_(False) | leaf stops requiring gradients; only valid for leaves | anything depending only on p is not recorded | freeze parameters |
t.data | memory access bypassing autograd and version counter | do not use: silently breaks the graph |
torch.set_grad_enabled(flag) is the conditional version of no_grad, and torch.enable_grad() reenables gradients inside a no_grad block. The differences matter as soon as a graph has two branches, the usual case.
.detach(), a block's tab to wrap it in torch.no_grad(), or a parameter to remove requires_grad. Edges carrying gradients light up with their values, and the code below reflects your cuts. In ‘Fine-tuning’, cut only the edge from to : why does gradient still reach ? In ‘TD target’, compare the uncut gradient with the semi-gradient. In ‘Actor-critic’, try all three tools and discover which lets the actor learn without touching the critic.The three scenarios recur throughout the curriculum:
- Fine-tuning. With a pretrained encoder and new head, freezing the encoder (
requires_grad_(False)on its parameters or forward insideno_grad) avoids computing and saving its graph, nearly all the memory. Adetachat the encoder output gives the same gradients but after building the graph unnecessarily; and if features are used twice, as in the figure,detachon one use is insufficient. See fine-tuning strategies. - TD targets. Target depends on the same parameters as prediction. Differentiating through it gives the residual gradient; TD methods and DQN use the semi-gradient, treating as constant: calculate it with
no_grad(ordetach) and, in DQN, copied parameters in a target network. - Actor-critic. To update the actor with , the gradient must pass through the critic to the action and reach . Freezing the critic with
no_grador cutting the action prevents this; instead its parameters should not require gradients (or, in practice, do not apply its optimizer and clear its.grad).
The general rule: no_grad and requires_grad_(False) decide what is recorded; detach decides where gradients flow for a particular use. What is not recorded consumes no graph memory.
In-place operations and the version counter
An in-place operation (add_, mul_, relu_, assignments such as t[0] = 1, and view writes from view and in-place semantics) modifies memory of a tensor the graph may have saved. If ExpBackward0 saved its output and someone then calls e.add_(1), backward would multiply by instead of and give a false gradient. To prevent this, each tensor has a version counter (t._version) incremented by in-place operations; when saving it, the node also records the version and compares it during backward. If it differs, backward fails instead of returning garbage.
Three surprising consequences. First, the error occurs only if the modified tensor was saved. y = w * 2; y.add_(1) works because MulBackward0 with a number saves the number, not y. Second, detach() shares the counter with the original, so modifying the detached version in place also breaks backward; .data does not share it, so the same error passes silently. Third, manually updating parameters inside no_grad (w -= lr * w.grad) increments their version, so a previously built graph with saved w can no longer be used.
import torch
w = torch.tensor([0.5, -1.0, 2.0], requires_grad=True)
with torch.no_grad():
a = w * 2
print("no_grad: requires_grad =", a.requires_grad, " grad_fn =", a.grad_fn)
d = (w * 2).detach()
print("detach: requires_grad =", d.requires_grad, " is_leaf =", d.is_leaf)
with torch.inference_mode():
t = w * 2
print("inference_mode: requires_grad =", t.requires_grad, " is_inference =", t.is_inference())
# detach comparte memoria y contador de versiones con el original
e = w.exp()
e_det = e.detach()
print("\nmisma memoria:", e_det.data_ptr() == e.data_ptr(), "| versiones:", e._version, e_det._version)
e_det.mul_(2)
print("tras e_det.mul_(2):", e._version, e_det._version)
try:
e.sum().backward()
except RuntimeError as err:
print("backward:", str(err)[:96], "...")
# .data no tiene contador de versiones: el mismo error pasa en silencio
e = w.exp()
e.data.mul_(2)
e.sum().backward()
print("\ncon .data, w.grad =", w.grad, " (correcto: exp(w) =", w.exp().detach(), ")")
# un tensor de inference_mode no puede guardarse para el backward
q = torch.tensor(0.7, requires_grad=True)
with torch.inference_mode():
y = torch.tensor(1.8)
((q - y) ** 2).backward() # la resta no guarda y: funciona
try:
(q * y).backward() # el producto necesita guardar y
except RuntimeError as err:
print("inference_mode:", str(err)[:52], "...")
# requires_grad_(False) solo vale para hojas
try:
(w * 2).requires_grad_(False)
except RuntimeError as err:
print("no hoja:", str(err)[:64], "...")npm run lab and open the connection link.The inference_mode case deserves a note: a target calculated in inference mode works while only subtracted from the prediction, but stops working when someone multiplies it by importance weights. For results reentering a loss, no_grad is the robust choice.
Gradients of gradients
backward writes to .grad and discards the graph of gradient computation itself. Sometimes the gradient is an intermediate step: you want to differentiate it again or put it in a loss. That is what higher-order gradients and torch.func are for.
The basic tool is torch.autograd.grad(outputs, inputs, grad_outputs=None, retain_graph=None, create_graph=False, allow_unused=None). It differs from backward in three ways: it returns gradients as a tuple rather than accumulating them in .grad (changing no state); accepts any graph tensor as inputs, including non-leaves; and with create_graph=True records backward computation itself, so the returned gradient has grad_fn and is differentiable. If an input does not participate in the graph, it fails unless allow_unused=True, which returns None instead.
import torch
# derivada segunda: create_graph=True hace que el gradiente tenga su propio grafo
x = torch.tensor(2.0, requires_grad=True)
y = x ** 3
(g,) = torch.autograd.grad(y, x, create_graph=True)
(g2,) = torch.autograd.grad(g, x)
print(f"dy/dx = {g.item()} (grad_fn={type(g.grad_fn).__name__}), d2y/dx2 = {g2.item()}, x.grad = {x.grad}")
# producto hessiano-vector sin formar el hessiano: H v = grad(grad f · v)
def f(x):
return (x ** 4).sum() / 4 + x[0] * x[1] * x[2]
x = torch.tensor([1.0, -2.0, 0.5], requires_grad=True)
v = torch.tensor([1.0, 0.0, -1.0])
(gx,) = torch.autograd.grad(f(x), x, create_graph=True)
(Hv,) = torch.autograd.grad(gx @ v, x)
H = torch.autograd.functional.hessian(f, x)
print("Hv =", Hv, " H @ v =", H @ v)
# penalización del gradiente: media de ||grad_x D(x)||^2, derivable respecto a los parámetros de D
torch.manual_seed(0)
D = torch.nn.Sequential(torch.nn.Linear(2, 16), torch.nn.Tanh(), torch.nn.Linear(16, 1))
xb = torch.randn(8, 2, requires_grad=True)
(gx,) = torch.autograd.grad(D(xb).sum(), xb, create_graph=True)
penal = (gx.norm(dim=1) ** 2).mean()
penal.backward()
print(f"penalización = {penal.item():.4f} | norma de dP/dW1 = {D[0].weight.grad.norm().item():.4f}")npm run lab and open the connection link.The second part of the cell uses an identity worth proving because it underlies all large-scale second-order methods.
Proof
Let . Since is constant, , using existence of second derivatives (and continuity makes symmetric by Schwarz’s theorem, so differentiation order does not matter). For cost: the first grad with create_graph=True builds a graph for proportional in size to forward (each backward node is another recorded operation), the dot product with adds , and the second grad traverses that graph once. Each pass costs a constant multiple of forward, the reverse-mode bound proved in reverse-mode automatic differentiation.
This trick, published by Pearlmutter in 1994, allows computing curvature of a network with millions of parameters without the Hessian, via Lanczos or power iterations on Hessian-vector products (used to study real networks’ Hessian spectrum). The cell’s third part is a gradient penalty, in the family of WGAN-GP (penalizing at interpolated points) and R1 (penalizing on real data, as here): the loss contains an input gradient and its backward must differentiate that with respect to parameters. Without create_graph=True, gx would have no graph and the penalty would change nothing.
torch.func: autograd as function transformation
torch.autograd.grad works on tensors that already have history. torch.func (formerly functorch) offers the alternative JAX view: transformations taking a function and returning another.
| Transformation | Returns | Cost per call |
|---|---|---|
grad(f) | , for scalar | one forward and one backward |
jacrev(f) | Jacobian by rows (VJP) | vectorized VJPs |
jacfwd(f) | Jacobian by columns (JVP, forward mode) | vectorized JVPs |
hessian(f) | jacfwd(jacrev(f)) | |
jvp(f, (x,), (v,)), vjp(f, x) | individual products | one |
vmap(f) | applied to each batch element without a loop | one vectorized call |
functional_call(modulo, params, args) | module as a pure function of its parameters |
They compose: vmap(grad(perdida)) gives per-example gradients (impossible with one backward on the mean and needed in differential privacy or gradient-noise estimation), and jvp(grad(f), (x,), (v,)) gives with forward over reverse, often more efficient than reverse over reverse. Choose between jacrev and jacfwd by fewer passes: jacrev for few outputs (), jacfwd for few inputs.
import time
import torch
from torch.func import functional_call, grad, jacrev, jacfwd, vmap, jvp
torch.manual_seed(0)
net = torch.nn.Sequential(torch.nn.Linear(4, 32), torch.nn.Tanh(), torch.nn.Linear(32, 3))
params = {k: v.detach() for k, v in net.named_parameters()}
# el modelo como función pura de (parámetros, entrada)
def modelo(p, x):
return functional_call(net, p, (x,))
# jacobiano de la salida (3) respecto a la entrada (4), para cada ejemplo de un lote
X = torch.randn(256, 4)
J = vmap(jacrev(modelo, argnums=1), in_dims=(None, 0))(params, X)
print("jacobianos por ejemplo:", tuple(J.shape))
J0 = torch.autograd.functional.jacobian(lambda x: net(x), X[0])
print("coincide con el de autograd en el ejemplo 0:", torch.allclose(J[0], J0, atol=1e-6))
print("jacfwd da lo mismo:", torch.allclose(vmap(jacfwd(modelo, argnums=1), in_dims=(None, 0))(params, X), J, atol=1e-6))
# gradientes por ejemplo, imposibles con un solo backward sobre la media
y = torch.randn(256, 3)
def perdida(p, x, t):
return ((modelo(p, x) - t) ** 2).sum()
g_ej = vmap(grad(perdida), in_dims=(None, 0, 0))(params, X, y)
print("gradiente por ejemplo de la primera capa:", tuple(g_ej["0.weight"].shape))
# producto hessiano-vector frente al hessiano explícito, en una función de n variables
def f(x):
return torch.log(torch.cosh(x)).sum() + 0.5 * (x[1:] * x[:-1]).sum()
def hvp(f, x, v):
return jvp(grad(f), (x,), (v,))[1] # forward sobre reverse: H v
def medir(fn, rep=5):
fn() # calentamiento
ts = []
for _ in range(rep):
t0 = time.perf_counter(); r = fn(); ts.append(time.perf_counter() - t0)
return r, 1e3 * sorted(ts)[rep // 2] # mediana en ms
for n in [500, 2000, 4000]:
x, v = torch.randn(n), torch.randn(n)
Hv, t_hvp = medir(lambda: hvp(f, x, v))
H, t_h = medir(lambda: torch.func.hessian(f)(x), rep=3)
print(f"n = {n:4d}: hvp {t_hvp:6.2f} ms | hessiano {t_h:7.1f} ms y {4 * n * n / 2**20:5.1f} MiB "
f"| iguales: {torch.allclose(Hv, H @ v, atol=1e-4)}")npm run lab and open the connection link.On the lab laptop, Hessian-vector product time barely changes from to (dominated by launch overhead for a few small operations), while the explicit Hessian grows approximately quadratically in time and exactly quadratically in memory: 61 MiB at , and 3.6 TiB for a million-parameter network. Functional style also opens the door to JAX, where it is the only style, revisited in JAX function transformations.
Custom autograd functions
Three reasons to write your own backward: the derivative autograd obtains by chaining operations is numerically poor or expensive (log-sum-exp, a norm near zero); the operation is nondifferentiable and you want a surrogate gradient (rounding); or you want to modify the passing gradient (clip, reverse, scale). All three use a custom autograd function, a torch.autograd.Function subclass with two static methods:
forward(ctx, *args)computes the output with ordinary operations (nothing inside is recorded) and saves what backward needs: tensors withctx.save_for_backward(...), respecting version counters and release; numbers and other objects asctxattributes.backward(ctx, *grad_outputs)receives one gradient per output and returns one perforwardinput, withNonefor non-tensors or those not needing gradients (ctx.needs_input_gradidentifies those that do).
Call it with MiFuncion.apply(...), never by instantiating it; it creates a MiFuncionBackward graph node. If backward uses torch operations, it is itself differentiable and supports higher-order gradients. To also work with torch.func, documentation asks to separate forward(*args) from setup_context(ctx, inputs, output); the style with ctx in forward remains valid for ordinary autograd.
gradcheck: checking backward against finite differences
A hand-written backward can be silently wrong in many ways. torch.autograd.gradcheck(f, inputs) compares it with the numerical Jacobian by central finite differences: perturb each input component by (default ), requiring each entry of the analytic Jacobian, built with VJPs, to satisfy with and . gradgradcheck does the same for backward’s backward.
These tolerances make sense only in float64. Central difference error has two terms: truncation, of order , and rounding, of order , where is unit roundoff. In float32, and rounding gives : thousands of times the tolerance. In float64, and it falls to . This is the same reasoning as tolerance-based assertions: tolerance must exceed reference-method error, and in float32 that reference is worse than what you want to check.
import warnings
import torch
from torch.autograd import Function, gradcheck, gradgradcheck
class LogSumExp(Function):
"""log Σ exp(x_i) sobre el último eje, estable, con backward analítico."""
@staticmethod
def forward(ctx, x):
m = x.max(dim=-1, keepdim=True).values
out = m.squeeze(-1) + torch.log(torch.exp(x - m).sum(dim=-1))
ctx.save_for_backward(x, out)
return out
@staticmethod
def backward(ctx, g):
x, out = ctx.saved_tensors
# d lse / dx = softmax(x); escrito con operaciones de torch, el backward es a su vez derivable
return g.unsqueeze(-1) * torch.exp(x - out.unsqueeze(-1))
class RedondeoST(Function):
"""Redondea en el forward y deja pasar el gradiente intacto (straight-through)."""
@staticmethod
def forward(ctx, x):
return torch.round(x)
@staticmethod
def backward(ctx, g):
return g
class RecorteGrad(Function):
"""Identidad en el forward; recorta el gradiente a [-c, c] en el backward."""
@staticmethod
def forward(ctx, x, c):
ctx.c = c # un número de Python va en ctx, no en save_for_backward
return x.view_as(x)
@staticmethod
def backward(ctx, g):
return g.clamp(-ctx.c, ctx.c), None # un gradiente por cada entrada de forward
lse = LogSumExp.apply
x = torch.tensor([[1000.0, 1000.5, 999.0], [-3.0, 0.0, 2.0]], dtype=torch.float64, requires_grad=True)
print("lse:", lse(x).detach(), " ingenua:", torch.log(torch.exp(x).sum(-1)).detach())
print("igual que torch.logsumexp:", torch.allclose(lse(x), torch.logsumexp(x, -1)))
x64 = torch.randn(4, 5, dtype=torch.float64, requires_grad=True)
print("gradcheck float64:", gradcheck(lse, (x64,)), "| gradgradcheck:", gradgradcheck(lse, (x64,)))
x32 = x64.detach().float().requires_grad_()
with warnings.catch_warnings():
warnings.simplefilter("ignore")
print("gradcheck float32:", gradcheck(lse, (x32,), raise_exception=False))
# el straight-through y el recorte NO son el gradiente de su forward: gradcheck tiene que fallar
z = torch.tensor([-1.4, -0.6, 0.3, 0.7, 1.6], dtype=torch.float64, requires_grad=True)
print("\nround ST:", RedondeoST.apply(z).detach().tolist())
RedondeoST.apply(z).sum().backward()
print("gradiente ST:", z.grad.tolist())
print("gradcheck del ST (falla, como debe):", gradcheck(RedondeoST.apply, (z,), raise_exception=False))
u = torch.tensor([0.5, -2.0, 3.0], dtype=torch.float64, requires_grad=True)
(RecorteGrad.apply(u, 1.0) * torch.tensor([0.3, 4.0, -7.0], dtype=torch.float64)).sum().backward()
print("gradiente recortado:", u.grad.tolist())npm run lab and open the connection link.The log-sum-exp function applies the log-sum-exp trick in forward and uses the fact that its derivative is softmax, obtainable from output without recomputation: it saves only x and out. The naive version overflows to inf with inputs of 1000. The same code passes gradcheck in float64 and fails in float32, exactly the trap in the error table. The other two functions must fail gradcheck, because their backward is deliberately not the derivative of forward: the straight-through estimator (Bengio, Léonard and Courville, 2013) treats rounding as identity in backward, while clipping limits what passes, in the spirit of gradient clipping. For these, the right test checks the gradient you define.
Hooks: inspecting and changing passing gradients
t.register_hook(fn) registers a function the engine calls with the gradient reaching t when calculated; if it returns a tensor, that replaces the gradient. Use it to inspect intermediate gradients without retain_grad (which stores them all), log per-layer norms, or modify a gradient without writing a Function (a lambda g: g.clamp(-1, 1) on an activation). Module hooks build on these in the next lesson; training instrumentation is covered in debugging.
The final lab in this part traverses a small network’s graph like a visualization tool, registers a hook and deliberately triggers the three classic errors:
import warnings
import torch
torch.manual_seed(0)
net = torch.nn.Sequential(torch.nn.Linear(3, 4), torch.nn.ReLU(), torch.nn.Linear(4, 1))
nombres = {p: n for n, p in net.named_parameters()}
X, y = torch.randn(8, 3), torch.randn(8, 1)
loss = ((net(X) - y) ** 2).mean()
def grafo(raiz):
"""Lista de aristas (nodo -> entrada) del grafo de backward, recorrido en anchura."""
ids, aristas, cola = {}, [], [raiz]
def nombre(fn):
if fn not in ids:
base = type(fn).__name__
if base == "AccumulateGrad":
base += f"[{nombres.get(fn.variable, '?')}]"
ids[fn] = f"{base}#{len(ids)}"
return ids[fn]
nombre(raiz)
while cola:
fn = cola.pop(0)
for sig, _ in fn.next_functions:
if sig is None:
continue
nuevo = sig not in ids
aristas.append((nombre(fn), nombre(sig)))
if nuevo:
cola.append(sig)
return aristas
for a, b in grafo(loss.grad_fn):
print(f"{a:28s} -> {b}")
# hooks: ver (y modificar) el gradiente que llega a un tensor intermedio
h = net[1](net[0](X))
h.register_hook(lambda g: print(f"\nhook: gradiente en la salida de la ReLU, norma {g.norm():.4f}"))
h.retain_grad()
((net[2](h) - y) ** 2).mean().backward()
print("h.grad guardado con retain_grad:", tuple(h.grad.shape))
# tres errores clásicos, provocados a propósito
def prueba(nombre, fn):
try:
with warnings.catch_warnings(record=True) as avisos:
warnings.simplefilter("always")
r = fn()
aviso = f" aviso: {str(avisos[0].message)[:60]}..." if avisos else ""
print(f"{nombre:22s} sin error, devuelve {r}{aviso}")
except RuntimeError as e:
print(f"{nombre:22s} RuntimeError: {str(e)[:70]}...")
def inplace():
z = torch.sigmoid(net(X)) # SigmoidBackward0 guarda su salida
z.mul_(2) # la modifica: versión 1
z.sum().backward()
def dos_veces():
l = net(X).sum()
l.backward()
l.backward()
def grad_no_hoja():
z = net(X)
z.sum().backward()
return z.grad
prueba("in-place en guardado", inplace)
prueba("backward dos veces", dos_veces)
prueba(".grad de un no hoja", grad_no_hoja)npm run lab and open the connection link.The network graph shows a linear layer’s decomposition: AddmmBackward0 (bias plus in one operation) with three edges, to bias, input and TBackward0, the weight transpose. In the first layer, input is X, which does not require gradients, so its edge does not appear. When a model’s .grad is None, this traversal is the fastest way to see where the path is cut.
Common mistakes
Exercises
w = torch.randn(3, requires_grad=True), x = torch.randn(3), h = w * x, h.retain_grad(), z = h.sum(), s = torch.tensor(0.5, requires_grad=True), v = (w * 2).detach().requires_grad_(), L = z * s + (v * x).sum() and L.backward(), which tensors have .grad other than None? More than one may apply.More than one answer may be correct.
w = torch.tensor(1.5, requires_grad=True) and L = 2 * w ** 2, call L.backward(retain_graph=True) three times without clearing gradients. What is w.grad?zero_grad), with and , the sequence is periodic. What is its period, the smallest with for all ?zero_grad enabled, 4 microbatches per iteration without dividing loss by 4, and , by what factor is multiplied each iteration?w = torch.randn(3, requires_grad=True), which snippets raise the version-counter error when calling backward? More than one may apply.More than one answer may be correct.
g = grad(f(x), x, create_graph=True) at and Hv = grad(g @ v, x) with , what is ?zero_grad, error does not tend to zero if .Step 1 of 4. What recurrence does the error satisfy?
Huber, a torch.autograd.Function calculating Huber loss elementwise: if and otherwise, with analytical backward . delta is a Python number. Backward must use torch operations (to pass gradgradcheck) and return one gradient per forward input. The function huber(r, delta) is already written.import torch
from torch.autograd import Function
class Huber(Function):
@staticmethod
def forward(ctx, r, delta):
# tu código: el valor elemento a elemento y lo que necesite el backward
raise NotImplementedError
@staticmethod
def backward(ctx, g):
# tu código: un gradiente por cada entrada de forward
raise NotImplementedError
def huber(r, delta=1.0):
return Huber.apply(r, delta)Huber loss, encountered as the Huber estimator in robust statistics and as DQN’s TD loss, is quadratic near zero and linear far away: its derivative is clipping, exactly what goes into backward.
penalizacion_gradiente(f, x), where f applies a network to batch x of shape (B, d) and returns one scalar per example, shape (B,), without mixing examples. Return scalar , differentiable with respect to f's parameters (so P.backward() updates them), without modifying x or making it require gradients and without loops over examples. Tests compare it with finite differences.import torch
def penalizacion_gradiente(f, x):
"""Media sobre el lote de ||grad_x f(x)_i||^2, derivable respecto a los parámetros de f."""
# tu código: no modifiques x; usa torch.autograd.grad con create_graph=True
return torch.zeros(())Summary
backward traverses it in reverse, sums vector-Jacobian products, accumulates the result in leaves’ .grad and releases it. Every None, zero and autograd error can be understood through those four actions: record, traverse, accumulate, release.- The graph originates at leaves with
requires_grad=True: each operation with a gradient-requiring input creates agrad_fnwith edges (next_functions) and saved tensors (_saved_*). It is rebuilt each forward and records the execution path. backwardexecutes each node when all contributions arrive and passes their sum: the multivariable chain rule. It writesℓ.grad += ∂L/∂ℓonly at leaves and releases saved data unlessretain_graph=True.- Accumulation is a tool (microbatches with loss divided by ) and a trap: without
zero_grad, gradient descent is an undamped oscillator conserving . - With nonscalar output,
backward(v)computes ; the full Jacobian costs one pass per row. no_gradandinference_modedecide what is recorded;detachcuts a particular use;requires_grad_(False)freezes leaves; do not use.data. The version counter protects saved tensors from in-place operations, anddetachshares it.torch.autograd.gradwithcreate_graph=Truegives differentiable gradients: second derivatives, without the Hessian, and gradient penalties.torch.funcoffers composable transforms:grad,jacrev,jacfwd,vmap,functional_call.- A
torch.autograd.Functionspecifies backward by hand (stability, straight-through, clipping); verify withgradcheckandgradgradcheckinfloat64, except when the surrogate gradient is intentional.