Automatic differentiation II: reverse mode and general backpropagation
Reverse mode computes the full gradient of a scalar function at a cost comparable to evaluating it, making it possible to train models with billions of parameters or calibrate simulations with thousands. Build a tape-based reverse engine for arbitrary scientific programs, verify it with the dot-product test against forward mode, and apply it to a simulation gradient before comparing it with torch.autograd. The tensor engine for neural networks is built in m15.
After this lesson you can
- Run a trace's backward pass by hand, propagating adjoints and accumulating them at nodes with multiple consumers.
- Implement a tape-based reverse engine that differentiates programs with loops and branches.
- Verify adjoints with the dot-product test and a gradient checker.
- Explain the cheap gradient principle and reverse mode's memory cost.
- Compute a simulation's gradient with respect to hundreds of parameters in one pass and compare its cost with forward mode and finite differences.
Before you start
Motivation: the gradient of something enormous
Training a model means following the gradient of a scalar loss with respect to all its parameters. If has components, the three tools you know fail for the same reason: finite differences need one or two evaluations of per component, and forward mode from the previous lesson, although exact, gives one directional derivative per pass. Both require on the order of evaluations for a single gradient. The same happens outside machine learning: calibrating a heat simulation with a different conductivity in each of 500 cells, or calculating a portfolio’s sensitivity to each point on an interest-rate curve, involves gradients of a scalar function with respect to hundreds or thousands of inputs.
Reverse mode solves the problem with a simple idea: instead of pushing a tangent from inputs to output, it pulls backward from the output its sensitivity to each intermediate variable. A single backward pass produces all partial derivatives at once, at a cost that is a small multiple of evaluating the function, regardless of the number of inputs. This is the algorithm behind loss.backward() and backpropagation in neural networks, but it is much more general: it differentiates any program, with loops, branches and integrators, and therefore works for a simulation as well as a network.
The price is memory: to traverse the computation backward you must remember what happened forward. This lesson builds the method by hand, proves why it works and what it costs, builds a tape-based engine that differentiates arbitrary scientific programs, verifies it with the dot-product test and uses it to calibrate that simulation with 500 conductivities. Finally you will compare your engine with torch.autograd, which does exactly the same thing at industrial scale. The tensor engine for networks, with matmul, broadcasting and reduction rules, is built in the tensor autograd engine.
By hand: the backward pass over a trace
Return to the function from the previous lesson, the example from Baydin et al., at :
Its evaluation trace has two inputs, and , and five elementary instructions. The forward pass executes them in order and stores each value:
| Instruction | Value at |
|---|---|
Now define, for each variable, its adjoint : how much the output changes if you perturb and let the rest of the program run unchanged. At the output, . Going backward, each instruction distributes its adjoint among its arguments by multiplying it by the local partial derivative, :
- sends to and to .
- sends to and to .
- sends to .
- sends to and to .
- sends to .
Notice the inputs: is used by two instructions ( and ), and by two others ( and ). Each receives two contributions, and its adjoint is their sum: and . These are exactly and . One forward and one backward pass have produced the entire gradient; forward mode would have needed two passes, one per input.
Two details of the procedure are key to everything that follows. Order matters: a variable can send its adjoint only when it has received it in full, that is, when all instructions that consume it have been processed. Traversing the trace backward guarantees this, because a variable’s consumers always follow it in the trace. And the forward-pass values are needed: the contribution from uses , that from uses and , and that from uses . This is the source of reverse mode’s memory cost.
Why it works: the chain rule backward
The informal definition “ letting the rest of the program execute” needs precision, because is not an input of : it is an intermediate value that depends on others. The clean approach is to look at the program from each point in the trace to the end.
A straight-line program (loops and branches are unfolded in the particular execution) with inputs executes instructions , , where are its arguments and implies . The output is . For each , call the result of executing instructions starting from arbitrary values of , treated as independent variables. Thus and , and executing instruction relates two consecutive functions:
Proof
Call the accumulators . We prove the invariant by descending induction: after processing instruction (or at the start, with ), for every .
At the start, and for , which are the derivatives of . Suppose the invariant holds after processing , that is, for . Differentiate the relation with respect to , , using the chain rule: appears directly as an argument of and, if , also inside , so
where the second term is zero if . Multiplied by , the first term is the current value of and the second is exactly what instruction adds, because . After processing the invariant holds for . Moreover, the instructions still to process have index smaller than , and their arguments have index smaller than theirs, so none touches again: its value when processing was final, . At the end (), for the inputs.
∎The proof explains the algorithm’s two pieces. += is not an implementation detail: it is the already accumulated term plus the new path opened by instruction . A variable with multiple consumers receives a contribution from each, and its derivative is the sum over all paths, as in the chain rule for multivariable functions. And reverse order ensures that is complete when used.
The VJP as a unit and duality with the JVP
Group instructions into larger blocks, such as network layers or integrator steps: with . By the chain rule, the Jacobian is a product of block Jacobians, with . The two modes are the two ways to multiply that chain by a vector without ever forming a matrix:
Forward mode propagates a tangent in the same order as the computation, so it needs to remember nothing. Reverse mode starts at the end, so it needs the at which to evaluate each : that is why the forward pass comes first. Each reverse-mode factor is a vector–Jacobian product (VJP), , the unit from which every reverse engine is built: each operation knows how to compute its output and, given the output adjoint, its input adjoints. Some rules you will use:
| Operation | VJP: contribution to each input |
|---|---|
| , | |
| (elementwise) | , |
| , | |
| (save the output, not the input) | |
| , | |
| (read positions) | (write to those positions) |
The table shows a symmetry that is no coincidence: what reads forward writes backward, and what copies or broadcasts forward sums backward. This is transposition: if a linear operation is , its VJP is , and reading a subset of positions is a matrix of zeros and ones whose transpose writes them. The relationship between the two products is the identity defining the transpose,
which will be the basis of verification later.
Cost of the full Jacobian
One forward pass gives a Jacobian column () and one reverse pass gives a row (). If each pass costs times an evaluation of , the Jacobian of costs evaluations in forward mode and in reverse. Baydin et al. give exactly these two expressions, with a constant “guaranteed and typically ”. For a scalar loss, : the full gradient costs evaluations, regardless of . The actual constants for each mode depend on implementation, but move the crossover point by a small factor, while varies over many orders of magnitude.
The figure summarizes the rule of thumb: reverse for few outputs and many inputs (losses, calibration, portfolio Greeks), forward for few inputs and many outputs (the sensitivity of an entire trajectory to three parameters, the JVP of a Newton–Krylov method), and for intermediate cases, memory or Jacobian structure decides. The next lesson, on strategies for computing Jacobians, combines the two modes and exploits sparsity.
The tape and topological order
A reverse engine needs to know which operations were executed, with which arguments and in what order. The most direct way is to record them as they happen.
Why is it topological? Because an operation can execute only when its inputs already exist: each edge of the graph goes from an operation recorded earlier to one recorded later. Reverse traversal then processes each variable after all its consumers, exactly the condition required by the proof. This has three practical consequences.
- Loops and branches for free. The tape does not see
fororif: it sees the operations that executed. A Newton loop that stops when the residual is small is recorded with however many iterations it performed, and a branch is recorded on the side taken. The derivative is that of the executed program, not the mathematical function the program approximates (you will see this again with iterative solvers in the next lesson). - Freeing on the fly. Once an operation is processed backward, its saved values and output adjoint are no longer needed and can be freed. PyTorch does this by default: that is why a second
backward()on the same graph fails unless you passretain_graph=True. - No recursion. An engine that does not store the tape and knows only each node’s parents must reconstruct the order with a depth-first search. Written recursively, it overflows the stack when the computation is long; you will check this in the lab with a chain of 5000 operations.
The cheap gradient principle
Exactly how much does the backward pass cost? The answer is one of the most important results in scientific computing, and it is proved by counting.
This is the cheap gradient principle. The proof counts the algorithm’s operations and you will reconstruct it step by step in a guided exercise: the forward pass costs ; the backward pass visits each tape instruction only once and executes its VJP rule, costing at most ; and additions to accumulators are already included in that cost. appears nowhere: the input adjoints are accumulators filled along the way.
What is ? With the four arithmetic operations and cost 1 per operation:
- : the VJP makes two accumulator additions, and . Cost 2.
- : two products ( and ) and two additions. Cost 4.
- : with , and . One division, one product and two additions: cost 4.
Thus and the gradient costs at most . This is the Baur–Strassen bound (1983): if an arithmetic circuit of size computes , one of size at most exists that computes and all its partial derivatives. They used it for a very different purpose, proving lower bounds on algebraic complexity: since the gradient costs the same as the function up to a constant, a lower bound for computing all partials is also one for . Elementary functions do not change the picture: the VJP of needs , which costs the same as sine, plus a product and an addition.
Memory: what must be saved
Reverse mode has traded time for memory. The backward pass processes the last operation first, by which time the forward pass has finished: every value needed by a VJP rule must have been saved. In a computation of steps with a state of size (simulation steps, network layers), the tape stores on the order of numbers, while forward mode needs only the current state’s tangent, on the order of .
An example gives the scale. A simulation of steps with a state of float64 numbers that saves the state at each step needs bytes: 800 GB, when the simulation itself fits in 8 MB. In a network, the activations of each layer for each batch example are saved, and they often dominate training memory.
The classic solution is to save only some states (checkpoints) and recompute the others from the nearest checkpoint when the backward pass needs them. The figure shows this tradeoff.
In the model, with checkpoints every layers about activations are saved during the forward pass and, when processing a segment, at most another . The peak is on the order of , minimal at , with value on the order of , and the price is recomputing layers: less than an additional forward pass, at most 33% more over the cost per layer. This is the result of Chen et al. (2016), Training Deep Nets with Sublinear Memory Cost: memory for an -layer network in exchange for an extra forward pass per batch; in their experiment, a 1000-layer residual network went from 48 GB to 7 GB with 30% more time. Optimal multilevel strategies, Griewank’s binomial checkpointing, are the subject of the next lesson, and their use at scale, with activation checkpointing and ZeRO sharding, belongs to distributed training systems.
Verifying adjoints: the dot-product test
A reverse engine is only as reliable as its VJP rules, and a handwritten VJP rule is easy to get wrong: a transposed factor, a sign, an index. The gradient checker from lesson 13 compares against finite differences, but only distinguishes errors larger than its own truncation error, on the order of in the best case and as a reasonable threshold. There is a much finer test that does not use finite differences and reaches rounding level.
Why do random vectors suffice? Because is a bilinear form in . If , the matrix is nonzero and the polynomial is not identically zero; its zero set is a proper algebraic subset of , which has Lebesgue measure zero. With Gaussian and , an error in the VJP produces with probability 1. The discrepancy’s size is informative: a factor-of-2 error gives in every trial; a sign, ; a transpose, a cloud unrelated to the diagonal.
The RK4 step deserves a closer look. A step of a Runge–Kutta method is a small trace: , , and so on. Its VJP traverses the stages backward: it starts with and , and each stage applies to its adjoint and distributes it between and the previous stage’s adjoint, with the same weight with which the previous stage entered . Using in all four stages instead of is an error that hides well: the difference between Jacobians is of order , so the resulting discrepancy decreases when reducing the step (check it on the bench by moving ), but stays many orders of magnitude above rounding. A gradient with that error “looks like” the correct one and an optimization may even converge with it; the dot-product test distinguishes it unambiguously.
Lab 1: a tape-based reverse engine
The engine has four pieces: a class Var that wraps a value (a float or NumPy array, elementwise) and its adjoint; an active Cinta on which each operation records itself when executed; each operation’s VJP rules, which receive the output adjoint and saved values and return a contribution per input; and retropropaga, which traverses the tape backward accumulating. Each operation explicitly declares what it saves (guardado), so you can measure tape memory and free it when processing each record.
import numpy as np
class Cinta:
"""Lista de Wengert: cada operación sobre Var se apunta aquí en orden de ejecución."""
activa = None
def __init__(self):
self.registros = []
def __enter__(self):
Cinta.activa = self
return self
def __exit__(self, *exc):
Cinta.activa = None
def bytes_guardados(self):
return sum(np.asarray(g).nbytes for r in self.registros if r.guardado for g in r.guardado)
class Registro:
__slots__ = ("salida", "entradas", "vjp", "guardado")
def __init__(self, salida, entradas, vjp, guardado):
self.salida, self.entradas, self.vjp, self.guardado = salida, entradas, vjp, guardado
def _ajusta(g, forma):
"""Deshace el broadcasting: suma g sobre los ejes que la operación estiró."""
g = np.asarray(g)
while g.ndim > len(forma):
g = g.sum(axis=0)
for i, n in enumerate(forma):
if n == 1 and g.shape[i] != 1:
g = g.sum(axis=i, keepdims=True)
return g
class Var:
"""Valor (escalar o array) que apunta en la cinta activa las operaciones que lo usan."""
__array_priority__ = 1000 # para que ndarray * Var llame a Var.__rmul__
def __init__(self, valor):
self.valor = valor if isinstance(valor, np.ndarray) else float(valor)
self.adj = None # adjunto: ∂(salida)/∂(esta variable), se rellena hacia atrás
@property
def forma(self):
return np.shape(self.valor)
def __repr__(self):
return f"Var({self.valor})"
def _v(x):
return x if isinstance(x, Var) else Var(x)
def _op(valor, entradas, vjp, guardado=()):
"""Crea la salida de una operación y la apunta en la cinta (si hay una activa)."""
out = Var(valor)
if Cinta.activa is not None:
Cinta.activa.registros.append(Registro(out, entradas, vjp, guardado))
return out
# --- reglas VJP: reciben el adjunto de la salida g y lo guardado; devuelven una contribución por entrada ---
def suma(a, b):
a, b = _v(a), _v(b)
fa, fb = a.forma, b.forma
return _op(a.valor + b.valor, (a, b), lambda g: (_ajusta(g, fa), _ajusta(g, fb)))
def resta(a, b):
a, b = _v(a), _v(b)
fa, fb = a.forma, b.forma
return _op(a.valor - b.valor, (a, b), lambda g: (_ajusta(g, fa), _ajusta(-g, fb)))
def producto(a, b):
a, b = _v(a), _v(b)
fa, fb = a.forma, b.forma
return _op(a.valor * b.valor, (a, b),
lambda g, av, bv: (_ajusta(g * bv, fa), _ajusta(g * av, fb)), (a.valor, b.valor))
def cociente(a, b):
a, b = _v(a), _v(b)
fa, fb = a.forma, b.forma
y = a.valor / b.valor
return _op(y, (a, b), lambda g, bv, yv: (_ajusta(g / bv, fa), _ajusta(-g * yv / bv, fb)), (b.valor, y))
def potencia(a, p): # exponente constante
return _op(a.valor ** p, (a,), lambda g, av: (g * p * av ** (p - 1),), (a.valor,))
def _unaria(f, df_de):
"""df_de(x, y) da f'(x) a partir de la entrada x y la salida y = f(x)."""
def op(a):
if not isinstance(a, Var):
return f(a)
y = f(a.valor)
return _op(y, (a,), lambda g, av, yv: (g * df_de(av, yv),), (a.valor, y))
return op
exp = _unaria(np.exp, lambda x, y: y)
log = _unaria(np.log, lambda x, y: 1 / x)
sin = _unaria(np.sin, lambda x, y: np.cos(x))
cos = _unaria(np.cos, lambda x, y: -np.sin(x))
tanh = _unaria(np.tanh, lambda x, y: 1 - y * y)
sqrt = _unaria(np.sqrt, lambda x, y: 0.5 / y)
def recorta(a, idx): # a[idx]: lineal, su VJP reparte g en las posiciones leídas
forma = a.forma
def vjp(g):
z = np.zeros(forma)
np.add.at(z, idx, g)
return (z,)
return _op(a.valor[idx], (a,), vjp)
def concatena(partes):
partes = [_v(p) for p in partes]
cortes = np.cumsum([np.size(p.valor) for p in partes])[:-1]
return _op(np.concatenate([np.atleast_1d(p.valor) for p in partes]), tuple(partes),
lambda g: tuple(s.reshape(p.forma) for s, p in zip(np.split(g, cortes), partes)))
def total(a): # suma de todas las componentes
forma = a.forma
return _op(np.sum(a.valor), (a,), lambda g: (np.broadcast_to(g, forma).copy(),))
Var.__add__ = lambda a, b: suma(a, b)
Var.__radd__ = lambda a, b: suma(b, a)
Var.__sub__ = lambda a, b: resta(a, b)
Var.__rsub__ = lambda a, b: resta(b, a)
Var.__mul__ = lambda a, b: producto(a, b)
Var.__rmul__ = lambda a, b: producto(b, a)
Var.__truediv__ = lambda a, b: cociente(a, b)
Var.__rtruediv__ = lambda a, b: cociente(b, a)
Var.__neg__ = lambda a: producto(a, -1.0)
Var.__pow__ = lambda a, p: potencia(a, p)
Var.__getitem__ = lambda a, idx: recorta(a, idx)
def retropropaga(cinta, salidas, semillas=None, liberar=True):
"""Pasada hacia atrás: recorre la cinta al revés (orden topológico inverso) acumulando adjuntos."""
salidas = salidas if isinstance(salidas, (list, tuple)) else [salidas]
semillas = semillas if semillas is not None else [np.ones_like(s.valor) for s in salidas]
for s, sb in zip(salidas, semillas):
s.adj = sb if s.adj is None else s.adj + sb
for r in reversed(cinta.registros):
if r.salida.adj is None: # esta operación no influye en las salidas
continue
contribuciones = r.vjp(r.salida.adj, *r.guardado)
for x, c in zip(r.entradas, contribuciones):
x.adj = c if x.adj is None else x.adj + c # acumulación: x puede tener varios consumidores
if liberar:
r.vjp, r.guardado = None, () # lo que guardaba este nodo ya no hace falta
if r.salida not in salidas:
r.salida.adj = None
def grad(f):
"""grad(f)(*args): gradiente de una f escalar respecto a cada argumento, con una pasada reverse."""
def g(*args):
xs = [Var(np.array(a, dtype=float) if np.ndim(a) else float(a)) for a in args]
with Cinta() as cinta:
y = f(*xs)
retropropaga(cinta, y)
return [x.adj if x.adj is not None else np.zeros_like(x.valor) for x in xs]
return g
# --- la traza de la lección 14, a mano y con el motor ---
x1, x2 = Var(2.0), Var(5.0)
with Cinta() as cinta:
y = log(x1) + x1 * x2 - sin(x2)
retropropaga(cinta, y)
print(f"f(2, 5) = {y.valor:.6f} registros en la cinta: {len(cinta.registros)}")
print(f"∂f/∂x1 = {x1.adj:.6f} (exacta: 1/x1 + x2 = 5.5)")
print(f"∂f/∂x2 = {x2.adj:.6f} (exacta: x1 - cos x2 = {2 - np.cos(5):.6f})")The tape has five records, one per trace instruction, and both adjoints match the exact derivatives. Notice three code decisions. Accumulation x.adj = c if x.adj is None else x.adj + c creates a new array instead of adding in place: adding in place could modify an array saved by another operation. _ajusta undoes broadcasting by summing over stretched axes, the table’s “what broadcasts forward sums backward” rule. And the rules for exp, tanh and sqrt use the saved output instead of recomputing the function.
The dot-product test needs an independent JVP. The next cell rebuilds lesson 14’s forward mode in compact form (a class Dual with scalar or vector tangents) and makes functions exp, sin, concatena, total, etc., accept floats, Var and Dual interchangeably, so that the same code of a program can be evaluated, differentiated forward and differentiated backward.
import numpy as np
class Dual:
"""Modo forward de la lección 14, compacto: valor y tangente (escalares o arrays)."""
__array_priority__ = 1000
def __init__(self, valor, tan):
self.valor, self.tan = valor, tan
def __add__(a, b):
b = b if isinstance(b, Dual) else Dual(b, 0.0)
return Dual(a.valor + b.valor, a.tan + b.tan)
__radd__ = __add__
def __sub__(a, b):
b = b if isinstance(b, Dual) else Dual(b, 0.0)
return Dual(a.valor - b.valor, a.tan - b.tan)
def __rsub__(a, b):
return Dual(b - a.valor, -a.tan)
def __mul__(a, b):
b = b if isinstance(b, Dual) else Dual(b, 0.0)
return Dual(a.valor * b.valor, a.tan * b.valor + a.valor * b.tan)
__rmul__ = __mul__
def __truediv__(a, b):
b = b if isinstance(b, Dual) else Dual(b, 0.0)
y = a.valor / b.valor
return Dual(y, (a.tan - y * b.tan) / b.valor)
def __rtruediv__(a, b):
y = b / a.valor
return Dual(y, -y * a.tan / a.valor)
def __neg__(a):
return Dual(-a.valor, -a.tan)
def __pow__(a, p):
return Dual(a.valor ** p, p * a.valor ** (p - 1) * a.tan)
def __getitem__(a, idx):
return Dual(a.valor[idx], a.tan[idx])
def _despacha(fv, dfv, nombre):
"""Una misma función para floats, Var (reverse) y Dual (forward)."""
rev = globals()[nombre] # la versión reverse definida en la celda anterior
def f(x):
if isinstance(x, Dual):
return Dual(fv(x.valor), dfv(x.valor) * x.tan)
return rev(x)
return f
exp = _despacha(np.exp, np.exp, "exp")
log = _despacha(np.log, lambda x: 1 / x, "log")
sin = _despacha(np.sin, np.cos, "sin")
cos = _despacha(np.cos, lambda x: -np.sin(x), "cos")
tanh = _despacha(np.tanh, lambda x: 1 - np.tanh(x) ** 2, "tanh")
sqrt = _despacha(np.sqrt, lambda x: 0.5 / np.sqrt(x), "sqrt")
_concatena_rev, _total_rev = concatena, total
def concatena(partes):
if any(isinstance(p, Dual) for p in partes):
ps = [p if isinstance(p, Dual) else Dual(p, np.zeros(np.shape(p))) for p in partes]
return Dual(np.concatenate([np.atleast_1d(p.valor) for p in ps]),
np.concatenate([np.atleast_1d(p.tan) for p in ps]))
if any(isinstance(p, Var) for p in partes):
return _concatena_rev(partes)
return np.concatenate(partes)
def total(a):
if isinstance(a, Dual):
return Dual(np.sum(a.valor), np.sum(a.tan))
return _total_rev(a) if isinstance(a, Var) else np.sum(a)
def valor(x):
return x.valor if isinstance(x, (Var, Dual)) else xNow, programs with control flow. The first computes by Newton’s method, with a loop whose length depends on the input and a stopping condition evaluated with values, not Var. The second integrates the Lotka–Volterra predator–prey model with 200 RK4 steps and measures the trajectory’s mismatch with observations, as a function of the four parameters and initial state.
# --- programa 1: una raíz cuadrada por Newton, con un bucle cuya longitud depende del dato ---
def raiz_newton(a, tol=1e-15):
x = a # punto inicial que depende de a
iteraciones = 0
while abs(valor(x) * valor(x) - valor(a)) > tol * valor(a): # rama: decide con valores, no con Var
x = 0.5 * (x + a / x)
iteraciones += 1
return x, iteraciones
for a in [2.0, 1e4]:
da, = grad(lambda a: raiz_newton(a)[0])(a)
_, it = raiz_newton(a)
print(f"a = {a:g}: {it} iteraciones de Newton; d sqrt(a)/da por reverse = {da:.16f} exacta = {0.5 / np.sqrt(a):.16f}")
# --- programa 2: RK4 sobre Lotka-Volterra; pérdida respecto a parámetros y estado inicial ---
def lotka_volterra(z, th):
x, y = z
a, b, c, d = th
return [a * x - b * x * y, d * x * y - c * y]
def rk4(f, z, th, h, pasos):
tray = [z]
for _ in range(pasos):
k1 = f(z, th)
k2 = f([zi + 0.5 * h * ki for zi, ki in zip(z, k1)], th)
k3 = f([zi + 0.5 * h * ki for zi, ki in zip(z, k2)], th)
k4 = f([zi + h * ki for zi, ki in zip(z, k3)], th)
z = [zi + h / 6 * (a + 2 * b + 2 * c + d) for zi, a, b, c, d in zip(z, k1, k2, k3, k4)]
tray.append(z)
return tray
th_ref = [1.0, 0.4, 1.0, 0.1] # alfa, beta, gamma, delta
z_obs = rk4(lotka_volterra, [10.0, 5.0], th_ref, 0.05, 200)
obs = np.array([[valor(v) for v in z] for z in z_obs])
def perdida_lv(p): # p = (alfa, beta, gamma, delta, x0, y0)
tray = rk4(lotka_volterra, [p[4], p[5]], p[:4], 0.05, 200)
L = 0.0
for z, o in zip(tray, obs):
L = L + (z[0] - o[0]) ** 2 + (z[1] - o[1]) ** 2
return 0.5 * L
p0 = np.array([1.1, 0.38, 0.95, 0.11, 9.5, 5.3])
P = [Var(v) for v in p0]
with Cinta() as cinta:
L = perdida_lv(P)
n_reg = len(cinta.registros)
retropropaga(cinta, L)
g_lv = np.array([v.adj for v in P])
print(f"\nRK4, 200 pasos: {n_reg} operaciones en la cinta; L = {L.valor:.6f}")
print("gradiente reverse:", np.array2string(g_lv, precision=6))
def grad_check(f, g, x):
"""Verificador de la lección 13: máximo error relativo frente a diferencias centradas."""
eps = (3 * 2.0**-53) ** (1 / 3)
peor = 0.0
for j in range(x.size):
hj = eps * max(1.0, abs(x[j]))
xp, xm = x.copy(), x.copy()
xp[j] += hj
xm[j] -= hj
num = (f(xp) - f(xm)) / (xp[j] - xm[j])
den = max(abs(g[j]), abs(num))
peor = max(peor, 0.0 if den == 0 else abs(g[j] - num) / den)
return peor
print(f"verificador de gradientes (diferencias centradas): error relativo máximo {grad_check(lambda p: perdida_lv(list(p)), g_lv, p0):.1e}")The output deserves attention. Newton performs a different number of iterations for each , and the tape records exactly those executed; even so, the algorithm’s derivative agrees with to every printed digit. This is no coincidence: the derivative of the iterate, , converges to the solution’s derivative because the factor tends to zero as fast as Newton itself. Differentiating an iterative solver through its trace works, but costs memory proportional to the number of iterations; the next lesson studies when it is worthwhile and when it is better to differentiate the equation it solves. For RK4, the tape has on the order of scalar operations and the gradient checker confirms all six derivatives with relative error on the order of , typical of centered differences.
Now the dot-product test on the map taking the parameters and initial state to the Lotka–Volterra state after 20 RK4 steps, using the forward engine’s JVP and the reverse engine’s VJP. Then a deliberately broken rule: the product rule with factors swapped ( instead of ), a transpose error in miniature.
def jvp(F, x, u):
"""J u con el modo forward: una pasada con tangentes u."""
return np.array([s.tan for s in F([Dual(xi, ui) for xi, ui in zip(x, u)])])
def vjp(F, x, ybar):
"""Jᵀ ȳ con el modo reverse: una pasada hacia atrás sembrada con ȳ."""
X = [Var(xi) for xi in x]
with Cinta() as cinta:
S = F(X)
retropropaga(cinta, S, list(ybar))
return np.array([xi.adj if xi.adj is not None else 0.0 for xi in X])
def prueba_producto_escalar(F, x, m, ensayos=20, semilla=0):
"""Máxima discrepancia relativa entre ⟨ȳ, J u⟩ y ⟨Jᵀ ȳ, u⟩ con u, ȳ gaussianos."""
rng = np.random.default_rng(semilla)
peor = 0.0
for _ in range(ensayos):
u, ybar = rng.normal(size=len(x)), rng.normal(size=m)
a = ybar @ jvp(F, x, u)
b = vjp(F, x, ybar) @ u
r = abs(a - b) / max(abs(a), abs(b), 1e-300)
if not np.isfinite(r):
return np.inf # un NaN es un fallo; max() lo ignoraría
peor = max(peor, r)
return peor
def estado_final(p, pasos=20): # R^6 -> R^2: estado de Lotka-Volterra tras 20 pasos de RK4
return rk4(lotka_volterra, [p[4], p[5]], p[:4], 0.05, pasos)[-1]
print(f"RK4 (R^6 -> R^2): discrepancia máxima en 20 ensayos = {prueba_producto_escalar(estado_final, p0, 2):.1e}")
print(f"unidad de redondeo u = 2^-53 = {2.0**-53:.1e}")
# rompemos a propósito la regla del producto: intercambiar los factores (el error de «transposición» más común)
producto_bueno = producto
def producto_roto(a, b):
a, b = _v(a), _v(b)
fa, fb = a.forma, b.forma
return _op(a.valor * b.valor, (a, b),
lambda g, av, bv: (_ajusta(g * av, fa), _ajusta(g * bv, fb)), (a.valor, b.valor))
Var.__mul__ = lambda a, b: producto_roto(a, b)
Var.__rmul__ = lambda a, b: producto_roto(b, a)
print(f"con la regla del producto rota: discrepancia máxima = {prueba_producto_escalar(estado_final, p0, 2):.1e}")
with np.errstate(over="ignore", invalid="ignore"): # con 200 pasos, la regla rota desborda
b200 = vjp(lambda p: estado_final(p, 200), p0, np.ones(2))
print(f"200 pasos con la regla rota: VJP = {b200}; max(0.0, nan) = {max(0.0, float('nan'))}")
Var.__mul__ = lambda a, b: producto_bueno(a, b)
Var.__rmul__ = lambda a, b: producto_bueno(b, a)
print(f"restaurada: discrepancia máxima = {prueba_producto_escalar(estado_final, p0, 2):.1e}")With correct rules, the maximum discrepancy in 20 trials is , about fifty units of rounding accumulated over 20 steps. With the broken rule, the discrepancy is order 1. A detail in prueba_producto_escalar is not cosmetic: if the broken VJP overflows and produces NaN, max(peor, nan) returns peor in Python, because every comparison with NaN is false, and the test would silently pass. The penultimate line shows it: with 200 steps instead of 20, the broken rule grows adjoints until overflow, the VJP comes out as nan and max(0.0, nan) returns 0.0. Without the np.isfinite check, the test would accept the broken engine.
Finally, why the engine uses a tape rather than a graph search. An engine that stores only references to each node’s parents (like the simplest version of the m15 scalar engine) must order the graph before traversing it, and the most natural way to do so is recursive.
import sys
class Nodo:
"""Un grafo sin cinta, como el de un motor escalar mínimo: cada nodo solo conoce a sus padres."""
def __init__(self, valor, padres=()):
self.valor, self.padres = valor, padres
def cadena(n): # un bucle largo: n operaciones encadenadas
x = Nodo(1.0)
for _ in range(n):
x = Nodo(x.valor * 1.0001, (x,))
return x
def topo_recursivo(raiz):
orden, vistos = [], set()
def visita(v):
if id(v) in vistos:
return
vistos.add(id(v))
for p in v.padres:
visita(p)
orden.append(v) # postorden: después de todos sus padres
visita(raiz)
return orden
def topo_iterativo(raiz):
orden, vistos, pila = [], set(), [(raiz, False)]
while pila:
v, expandido = pila.pop()
if expandido:
orden.append(v)
continue
if id(v) in vistos:
continue
vistos.add(id(v))
pila.append((v, True)) # se emitirá cuando terminen sus padres
pila.extend((p, False) for p in v.padres if id(p) not in vistos)
return orden
y = cadena(5000)
print("límite de recursión de Python:", sys.getrecursionlimit())
try:
topo_recursivo(y)
except RecursionError as e:
print("recursivo -> RecursionError:", e)
orden = topo_iterativo(y)
pos = {id(v): i for i, v in enumerate(orden)}
print(f"iterativo -> {len(orden)} nodos; ¿todo padre antes que su hijo? {all(pos[id(p)] < pos[id(v)] for v in orden for p in v.padres)}")A chain of 5000 operations, produced by a short simulation loop, exceeds Python’s recursion limit. The version with an explicit stack produces a correct topological order of any length. The tape avoids the problem at its root: the order is already written.
Lab 2: the gradient of a simulation with 500 parameters
The problem: a rod of length 1 with temperature obeying the heat equation with variable conductivity, , with at the ends. The conductivity is unknown; you know the initial temperature and observe the temperature throughout the rod at eight times, with a little noise. You want to recover in each of 500 cells.
The discretization is the simplest finite-volume one. With cells of width , the flux through the face between cells and is , with , and at the boundaries the face is from the wall, giving . Explicit Euler advances . Each new is a convex combination of (and the scheme amplifies nothing) if in every cell; with and boundary face , suffices, and calibration is restricted to . The mismatch is
a scalar function of 500 inputs defined by a program with 400 steps. This is the case for which reverse mode exists.
import time
N, PASOS = 500, 400 # celdas y pasos de tiempo
hx = 1.0 / N
xc = (np.arange(N) + 0.5) * hx # centros de las celdas
k_real = 1.0 + 0.4 * np.sin(2 * np.pi * xc) + 0.5 * np.exp(-((xc - 0.7) / 0.06) ** 2)
u0 = np.sin(np.pi * xc) + 0.5 * np.sin(9 * np.pi * xc) + 0.3 * np.sin(31 * np.pi * xc)
dt = 0.2 * hx**2 # estable si (dt/hx^2)(k_cara_izq + k_cara_der) <= 1: basta k <= 2
OBS_CADA = 50
def caras(k):
"""Conductividad en las N + 1 caras: media aritmética dentro y k de la celda en los bordes (u = 0 fuera)."""
dentro = 0.5 * (k[:-1] + k[1:])
return concatena([2.0 * k[:1], dentro, 2.0 * k[-1:]]) if isinstance(k, (Var, Dual)) else \
np.concatenate([2.0 * k[:1], dentro, 2.0 * k[-1:]])
def simula(k):
"""Esquema explícito de volúmenes finitos para u_t = (k u_x)_x; devuelve los estados observados."""
c = (dt / hx**2) * caras(k)
u, obs = u0, []
cero = np.zeros(1)
for n in range(1, PASOS + 1):
ue = concatena([cero, u, cero])
flujo = c * (ue[1:] - ue[:-1]) # flujo por cada cara (sin el signo)
u = u + (flujo[1:] - flujo[:-1])
if n % OBS_CADA == 0:
obs.append(u)
return obs
rng = np.random.default_rng(1)
datos = [o + 0.002 * rng.normal(size=N) for o in simula(k_real)] # observaciones con un poco de ruido
def desajuste(k):
J = 0.0
for u, d in zip(simula(k), datos):
r = u - d
J = J + 0.5 * total(r * r)
return J
k_ini = np.full(N, 1.2)
t0 = time.perf_counter(); J0 = desajuste(k_ini); t_f = time.perf_counter() - t0
K = Var(k_ini.copy())
t0 = time.perf_counter()
with Cinta() as cinta:
J = desajuste(K)
t_grab = time.perf_counter() - t0
n_reg, mem = len(cinta.registros), cinta.bytes_guardados()
t0 = time.perf_counter(); retropropaga(cinta, J); t_back = time.perf_counter() - t0
g_calor = K.adj
print(f"una evaluación de J sin cinta: {1e3 * t_f:.0f} ms")
print(f"reverse: grabar {1e3 * t_grab:.0f} ms + hacia atrás {1e3 * t_back:.0f} ms = {(t_grab + t_back) / t_f:.1f} evaluaciones de J")
print(f"cinta: {n_reg} operaciones, {mem / 2**20:.1f} MiB guardados (el estado ocupa {u0.nbytes / 2**10:.1f} KiB)")
print(f"tras la pasada hacia atrás (liberar=True) la cinta guarda {cinta.bytes_guardados()} bytes")The tape has about 3650 array operations and stores on the order of 3 MiB: about 800 times the state size. This is reverse-mode memory in action, with steps, and it is all freed at the end of the backward pass. The cost of the gradient relative to one evaluation of depends on the comparison, and the next cell separates it: pure NumPy evaluation creates no objects and records nothing, while the engine, written in Python, pays per-operation overhead unrelated to the cheap gradient principle.
# el mismo programa con objetos Var pero sin cinta: mide la sobrecarga del motor sin la pasada hacia atrás
t0 = time.perf_counter(); desajuste(Var(k_ini.copy())); t_var = time.perf_counter() - t0
print(f"misma evaluación con objetos Var y sin cinta: {1e3 * t_var:.0f} ms -> gradiente = {(t_grab + t_back) / t_var:.1f} evaluaciones de ese programa")
# modo forward: una pasada por conductividad; medimos 10 de las 500
cols = rng.choice(N, size=10, replace=False)
t0 = time.perf_counter()
g_fwd = np.array([desajuste(Dual(k_ini.copy(), np.eye(N)[j])).tan for j in cols])
t_fwd = (time.perf_counter() - t0) / len(cols)
print(f"\nforward: {1e3 * t_fwd:.0f} ms por pasada -> las 500 pasadas, unos {N * t_fwd:.1f} s ({N * t_fwd / (t_grab + t_back):.0f} veces el reverse)")
print(f"forward frente a reverse en esas 10 componentes: diferencia relativa máxima {np.max(np.abs(g_fwd - g_calor[cols]) / np.abs(g_calor[cols])):.1e}")
# diferencias centradas: 2 evaluaciones por componente, con el paso de la lección 13
h_fd = (3 * 2.0**-53) ** (1 / 3) * 1.2
t0 = time.perf_counter()
g_fd = []
for j in cols:
e = np.zeros(N); e[j] = h_fd
g_fd.append((desajuste(k_ini + e) - desajuste(k_ini - e)) / (2 * h_fd))
t_fd = (time.perf_counter() - t0) / len(cols)
g_fd = np.array(g_fd)
print(f"centradas: {1e3 * t_fd:.0f} ms por componente -> las 500, unos {N * t_fd:.1f} s")
print(f"centradas frente a reverse: diferencia relativa máxima {np.max(np.abs(g_fd - g_calor[cols]) / np.abs(g_calor[cols])):.1e}")
print(f"memoria extra: forward, la tangente del estado ({u0.nbytes / 2**10:.1f} KiB por array vivo); reverse, {mem / 2**20:.1f} MiB de cinta")Read the ratios, not the milliseconds, which depend on the machine (in the browser everything runs several times slower than native Python). Reverse: the full gradient costs about 4 evaluations of the same program with Var objects, in line with Baydin’s plus recording overhead; against pure NumPy evaluation the ratio rises to about 19, and that difference is interpreter overhead, not arithmetic. Forward: each pass costs roughly one evaluation with objects, but 500 are needed; extrapolating the 10 measurements, forward mode needs about 70 times more time than reverse, and agrees with it to a relative difference of , accumulated rounding, because both are exact. Centered differences: 1000 evaluations of , each cheaper because it does not use the engine, and a relative difference of : five or six correct digits, as the V curve of lesson 13 predicts. Memory goes in the other direction: reverse stores 3.1 MiB of tape and forward only one tangent per live array, 3.9 KiB.
With the 500-component gradient in hand, calibration is optimization. The problem is ill-conditioned: the mismatch is very sensitive to where temperature varies rapidly and almost insensitive where it is flat, so a smoothness penalty with is added and, like every part of the program, its gradient comes from the same tape.
def objetivo(k, lam=1e-2):
"""Desajuste más una penalización de suavidad (lam/2) Σ (k_{i+1} - k_i)^2, y su gradiente por reverse."""
K = Var(np.array(k, dtype=float))
with Cinta() as cinta:
dk = K[1:] - K[:-1]
J = desajuste(K) + (0.5 * lam) * total(dk * dk)
retropropaga(cinta, J)
return J.valor, K.adj
error_k = lambda k: np.sqrt(np.mean((k - k_real) ** 2))
J_ruido = 0.5 * sum(np.sum((d - o) ** 2) for d, o in zip(datos, simula(k_real)))
print(f"desajuste inicial {objetivo(k_ini)[0]:.3e}; con la k verdadera (solo ruido) {J_ruido:.3e}")
k, eta = k_ini.copy(), 2.0
for it in range(1, 11):
Jk, gk = objetivo(k)
k = np.clip(k - eta * gk, 0.2, 2.0)
if it in (1, 5, 10):
print(f"descenso de gradiente, iteración {it:2d}: J = {Jk:.3e} error RMS en k = {error_k(k):.3f}")Fixed-step gradient descent advances slowly: at the tenth iteration the mismatch is , a factor of 8 smaller than at the start, but the mean squared error in has only fallen from to . The gradient is large in cells where is large and almost zero elsewhere, so descent corrects those cells first, like descent in a very elongated valley (conditioning again). A quasi-Newton method like L-BFGS builds an approximation of curvature from previous gradients and needs nothing beyond what the engine already computes: value and gradient.
from scipy.optimize import minimize
import matplotlib.pyplot as plt
hist, vistos = [], {}
def objetivo_anotado(k): # guarda J de cada punto para no recalcularlo en el callback
J, g = objetivo(k)
vistos[k.tobytes()] = J
return J, g
res = minimize(objetivo_anotado, k_ini, jac=True, method="L-BFGS-B", bounds=[(0.2, 2.0)] * N,
options=dict(maxiter=15), callback=lambda kk: hist.append(vistos.get(kk.tobytes(), np.nan)))
print(f"L-BFGS: {res.nit} iteraciones, {res.nfev} gradientes; J = {res.fun:.3e} error RMS en k = {error_k(res.x):.3f} (al principio {error_k(k_ini):.3f})")
fig, ax = plt.subplots(1, 2, figsize=(10, 3.4))
ax[0].plot(xc, k_real, color="gray", lw=2, label="k verdadera")
ax[0].plot(xc, k, label="descenso de gradiente (10 it.)")
ax[0].plot(xc, res.x, label="L-BFGS (15 it.)")
ax[0].set_xlabel("x"); ax[0].set_ylabel("conductividad k(x)"); ax[0].legend()
ax[1].semilogy(range(1, len(hist) + 1), hist, marker="o", ms=3)
ax[1].axhline(J_ruido, color="gray", ls="--", label="nivel del ruido")
ax[1].set_xlabel("iteración de L-BFGS"); ax[1].set_ylabel("J"); ax[1].legend()
plt.show()With 15 L-BFGS iterations the mismatch falls from to , near the noise level (, what the true conductivity would give), and mean squared error in goes from to . The figure on the left shows where the error remains: in the region from to , where conductivity has its finest structure. Each iteration cost one 500-component gradient in one pass; with finite differences, each would have cost 1000 simulations.
Beyond networks: simulations and finance
The lab is a small example of a general situation: a physical model with many unknown parameters and a scalar mismatch measure. In inverse problems with partial differential equations (seismic tomography, weather data assimilation, aerodynamic design), the gradient is obtained with the adjoint method, reverse mode applied to the solver; you will study it as the adjoint gradient for PDE problems. The next lesson distinguishes differentiating the discretized program, as you have done here, from discretizing the continuous adjoint equation: the discrete versus continuous adjoint.
In quantitative finance the same idea is called adjoint algorithmic differentiation (AAD). A bank needs sensitivities (the “Greeks”) of its portfolio value to hundreds or thousands of market inputs: each point on the rate curve, each volatility. A portfolio’s value is one scalar output, or a few, of a program with many inputs, usually a Monte Carlo simulation. Giles and Glasserman, in “Smoking adjoints: fast Monte Carlo Greeks” (Risk, 2006), applied reverse mode along each simulated path to compute pathwise Greeks in the LIBOR market model. According to their abstract, the adjoint method outperforms the forward implementation when seeking sensitivities of few outputs to many inputs, and its computational advantage grows in proportion to the number of initial forward rates, that is, the number of inputs, as this lesson’s cost analysis predicts.
In libraries: torch.autograd
PyTorch implements exactly the lab engine, with tensors and rules written in C++. Every tensor created by an operation on tensors with requires_grad=True carries an attribute grad_fn: the record of the operation that produced it, with the VJP rule and references to its inputs’ records in next_functions. loss.backward() seeds and traverses that graph in reverse topological order, and leaf adjoints are added into their .grad attribute. torch.autograd.grad(y, x) returns adjoints instead of accumulating them, and torch.func.vjp(f, x) returns the output and a function applying to any , the piece needed by the dot-product test.
The local lab rewrites the previous programs with tensors and compares them with your engine. Because local cells run in another process, a hidden cell defines the engine and programs above there again, with the same code.
import time
import numpy as np
import torch
from torch.func import jvp as t_jvp, vjp as t_vjp
torch.set_default_dtype(torch.float64)
# 1. Newton: el mismo bucle con parada dependiente del dato; PyTorch graba lo que se ejecuta
a = torch.tensor(2.0, requires_grad=True)
x = a
while abs(x.item() ** 2 - a.item()) > 1e-15 * a.item():
x = 0.5 * (x + a / x)
x.backward()
print(f"Newton: d sqrt(a)/da = {a.grad.item():.16f} exacta {0.5 / np.sqrt(2):.16f}")
# la cadena de grad_fn: el grafo que PyTorch construyó, recorrido desde la salida
nodo, cadena = x.grad_fn, []
while nodo is not None and len(cadena) < 6:
cadena.append(type(nodo).__name__)
hijos = [f for f, _ in nodo.next_functions if f is not None]
nodo = hijos[0] if hijos else None
print("grad_fn desde la salida:", " <- ".join(cadena), "...")
# 2. Lotka-Volterra con RK4: mismo programa, tensores en lugar de Var
def rk4_t(p, pasos=200, h=0.05):
a_, b_, c_, d_, x0, y0 = p
f = lambda x, y: (a_ * x - b_ * x * y, d_ * x * y - c_ * y)
x, y, tray = x0, y0, [(x0, y0)]
for _ in range(pasos):
k1 = f(x, y)
k2 = f(x + 0.5 * h * k1[0], y + 0.5 * h * k1[1])
k3 = f(x + 0.5 * h * k2[0], y + 0.5 * h * k2[1])
k4 = f(x + h * k3[0], y + h * k3[1])
x = x + h / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0])
y = y + h / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1])
tray.append((x, y))
return tray
obs_t = torch.tensor(obs)
p = torch.tensor(p0, requires_grad=True)
tray = rk4_t(p)
L = 0.5 * sum((z[0] - o[0]) ** 2 + (z[1] - o[1]) ** 2 for z, o in zip(tray, obs_t))
L.backward()
print(f"\nRK4: L = {L.item():.6f}; diferencia relativa máxima con el motor propio: {np.max(np.abs(p.grad.numpy() - g_lv) / np.abs(g_lv)):.1e}")
# 3. Calor: el gradiente respecto a las 500 conductividades
def simula_t(k, u0, pasos, dt, hx):
c = (dt / hx**2) * torch.cat([2 * k[:1], 0.5 * (k[:-1] + k[1:]), 2 * k[-1:]])
u, cero, salidas = u0, torch.zeros(1, device=k.device), []
for n in range(1, pasos + 1):
ue = torch.cat([cero, u, cero])
flujo = c * (ue[1:] - ue[:-1])
u = u + (flujo[1:] - flujo[:-1])
if n % OBS_CADA == 0:
salidas.append(u)
return salidas
u0_t, datos_t = torch.tensor(u0), [torch.tensor(d) for d in datos]
k = torch.tensor(k_ini, requires_grad=True)
J = sum(0.5 * ((u - d) ** 2).sum() for u, d in zip(simula_t(k, u0_t, PASOS, dt, hx), datos_t))
J.backward()
print(f"calor: diferencia relativa máxima con el motor propio en las 500 componentes: {np.max(np.abs(k.grad.numpy() - g_calor) / np.abs(g_calor)):.1e}")
# 4. Prueba del producto escalar con torch.func: F(k) = estado final, de R^500 en R^500
F = lambda k: simula_t(k, u0_t, PASOS, dt, hx)[-1]
gen = torch.Generator().manual_seed(0)
kk = torch.tensor(k_ini)
peor = 0.0
for _ in range(5):
v = torch.randn(N, generator=gen)
ybar = torch.randn(N, generator=gen)
_, Jv = t_jvp(F, (kk,), (v,))
_, f_vjp = t_vjp(F, kk)
(JTy,) = f_vjp(ybar)
a_, b_ = (ybar @ Jv).item(), (JTy @ v).item()
peor = max(peor, abs(a_ - b_) / max(abs(a_), abs(b_)))
print(f"prueba del producto escalar con torch.func (5 ensayos): {peor:.1e}")
# 5. Los gradientes se acumulan y el grafo se libera
k = torch.tensor(k_ini, requires_grad=True)
J = sum(0.5 * ((u - d) ** 2).sum() for u, d in zip(simula_t(k, u0_t, PASOS, dt, hx), datos_t))
J.backward(retain_graph=True)
g1 = k.grad.clone()
J.backward() # segunda pasada sobre el mismo grafo: suma, no sustituye
print(f"\ntras dos backward: k.grad / gradiente = {(k.grad / g1).mean().item():.3f}")
try:
J.backward()
except RuntimeError as e:
print("tercera llamada sin retain_graph:", str(e).split(".")[0])
k.grad = None # lo que hace optimizer.zero_grad() por defecto
# 6. Modificar in situ algo que la pasada hacia atrás necesita
z = torch.tensor([1.0, 2.0], requires_grad=True)
e = z.exp() # exp guarda su salida para el VJP
e.add_(1.0) # ... y la cambiamos en el sitio
try:
e.sum().backward()
except RuntimeError as err:
print("in situ:", str(err).split(";")[0][:120])
# 7. Tiempos: CPU frente a GPU, con el problema pequeño y con uno grande
def mide(n, pasos, dispositivo, rep=3):
hx_ = 1.0 / n
dt_ = 0.4 * hx_**2 / 2.0
xc_ = (torch.arange(n, device=dispositivo) + 0.5) * hx_
u0_ = torch.sin(torch.pi * xc_)
mejores = []
for _ in range(rep):
k = torch.full((n,), 1.2, device=dispositivo, requires_grad=True)
if dispositivo == "cuda":
torch.cuda.synchronize()
t0 = time.perf_counter()
J = (simula_t(k, u0_, pasos, dt_, hx_)[-1] ** 2).sum()
J.backward()
if dispositivo == "cuda":
torch.cuda.synchronize()
mejores.append(time.perf_counter() - t0)
return min(mejores)
hay_gpu = torch.cuda.is_available()
for n in (500, 2**16):
t_cpu = mide(n, 200, "cpu")
linea = f"N = {n:6d}, 200 pasos, valor + gradiente: CPU {1e3 * t_cpu:7.1f} ms"
if hay_gpu:
mide(n, 50, "cuda", rep=1) # calentamiento
t_gpu = mide(n, 200, "cuda")
linea += f" GPU {1e3 * t_gpu:7.1f} ms CPU/GPU = {t_cpu / t_gpu:.2f}"
print(linea)
if hay_gpu:
torch.cuda.empty_cache()npm run lab and open the connection link.What the output shows:
- Newton and
grad_fn. PyTorch records the loop just like your tape, and the chain ofgrad_fnfrom the output is the operations list in reverse. Always following the first argument givesMulBackward0 <- AddBackward0 <- MulBackward0 <- ...: each Newton iteration is a product by of a sum, and the quotient hangs off the other argument of each sum. - Same gradients. In Lotka–Volterra RK4 and all 500 components of the heat gradient, the relative difference from your engine is exactly 0: both implementations perform the same float64 operations in the same order.
- The dot-product test with
torch.func, withjvpandvjpon the map at that takes to the final state, gives discrepancies on the order of . - Accumulation. Two
backward()calls on the same graph (the first withretain_graph=True) leave exactly twice the gradient ink.grad; a third fails because the graph has already been freed. - Modifying in place a tensor needed by a VJP rule (here, the output of
exp) is detected by PyTorch’s version counter, which raises an error during backpropagation instead of giving a false gradient. - CPU versus GPU. With 500 cells, the GPU is slower than the CPU: each step launches a few tiny operations and time is dominated by kernel launch latency, not computation. With cells and the same number of steps, GPU time barely changes and it is now faster than the CPU. Exact times vary with machine load; the direction of the comparison does not.
Common mistakes
Exercises
+=. Why, and what happens in PyTorch if you do not zero gradients between iterations?More than one answer may be correct.
Step 1 of 4. How many times is each instruction's VJP rule executed during the backward pass?
dot_test(jvp, vjp, x, trials=10, seed=0), where jvp(x, u) returns and vjp(x, ybar) returns what should be , for at point x. Generate trials Gaussian pairs with np.random.default_rng(seed) (obtain from the size of jvp(x, u)) and return the maximum relative discrepancy with and . If any trial gives a nonfinite discrepancy, return np.inf. Do not modify x.import numpy as np
def dot_test(jvp, vjp, x, trials=10, seed=0):
"""Máxima discrepancia relativa entre <ybar, J u> y <vjp(ybar), u> en 'trials' ensayos gaussianos."""
x = np.asarray(x, dtype=float)
rng = np.random.default_rng(seed)
peor = 0.0
# tu código
return peorsoftplus(a) to compute elementwise without overflow for large and record its also stable VJP rule, , on the tape. The tests evaluate values and gradients at and , compare with centered differences and apply the dot-product test against an independent JVP. Conceptual hint: the naive form np.log(1 + np.exp(x)) gives inf at , and its derivative exp(x) / (1 + exp(x)) gives nan.import numpy as np
# motor mínimo (el del laboratorio, recortado): no hace falta tocarlo
class Var:
def __init__(self, valor):
self.valor, self.adj = np.asarray(valor, dtype=float), None
class Cinta:
activa = None
def __init__(self):
self.registros = []
def __enter__(self):
Cinta.activa = self
return self
def __exit__(self, *exc):
Cinta.activa = None
def _op(valor, entradas, vjp, guardado=()):
out = Var(valor)
if Cinta.activa is not None:
Cinta.activa.registros.append((out, entradas, vjp, guardado))
return out
def retropropaga(cinta, y, semilla=None):
y.adj = np.ones_like(y.valor) if semilla is None else np.asarray(semilla, dtype=float)
for out, entradas, vjp, guardado in reversed(cinta.registros):
if out.adj is None:
continue
for x, c in zip(entradas, vjp(out.adj, *guardado)):
x.adj = c if x.adj is None else x.adj + c
def softplus(a):
"""log(1 + e^x) elemento a elemento, sin desbordar, con su regla VJP registrada en la cinta."""
# tu código: calcula el valor de forma estable y llama a _op(valor, (a,), vjp, guardado)
raise NotImplementedErrorConnections and reading
For further reading: chapters 3 and 4 of Griewank and Walther are the complete reverse-mode reference, with its cost and memory analysis; section 3 of Baydin et al. (2018) is the clearest introduction and the source of this lesson’s example; Baur and Strassen (1983) is the original complexity result; Paszke et al. (2019) describe PyTorch’s autograd design; and Giles and Glasserman (2006) are the starting point for AAD in finance.
Summary
- Adjoint is the derivative of the output with respect to as the rest of the program executes. The chain rule gives the backward recursion, and
+=sums the paths of a variable with multiple consumers. - Each operation contributes a VJP, : what reads forward writes backward, and what broadcasts forward sums backward. The full Jacobian costs on the order of forward passes or reverse passes.
- The tape records operations in execution order, a topological order; traversing it backward differentiates loops and branches along the executed path, allows memory to be freed on the fly and avoids recursion.
- Cheap gradient principle: if each VJP costs at most times its operation, the gradient costs at most ; with arithmetic, , the Baur–Strassen bound.
- Memory grows with computation length, ; checkpoints reduce it in exchange for recomputation, with a peak of order for an extra pass.
- The dot-product test, with random vectors, verifies a VJP at rounding level against an independent JVP; treat
NaNas failure and complement it with the gradient checker. - In the lab, one reverse pass gave all 500 components of a heat simulation gradient and enabled conductivity calibration, while forward mode would have needed tens of times more time and finite differences gave only five or six digits.