The multivariable chain rule, JVPs and VJPs
The multivariable chain rule says the differential of a composition is the composition of differentials, a product of Jacobians. From it come two objects enabling deep learning: the Jacobian–vector product (JVP), pushing perturbations forward, and the vector–Jacobian product (VJP), pulling sensitivities backward. This lesson establishes the mathematics and cost of associating the chain; automatic differentiation algorithms are built in m09.
After this lesson you can
- Prove the chain rule for Fréchet derivatives and write it as a product of Jacobians.
- Calculate total derivatives in dependency graphs by summing contributions from every path.
- Define JVP and VJP, relate VJP to the differential's adjoint, and obtain a scalar function's gradient as a VJP.
- Calculate the cost of evaluating a Jacobian chain under different associations and justify differentiating a scalar loss backward.
- Differentiate a composition of layers by hand with VJPs and verify the result by gradient check and torch.func.
Before you start
Motivation: hundreds of functions and one number
A small transformer is a composition of a few hundred functions: embeddings, normalizations, linear projections, softmax, activations, residual sums. At the end of the chain is a loss, one number. Training means moving one hundred million parameters in the direction that most reduces that number, requiring its gradient, a vector of one hundred million components, at every step.
Two questions separate someone who uses loss.backward() from someone who understands what it does:
- What is the derivative of a composition? In one variable, . With many variables, each piece’s derivative is a Jacobian matrix, and the answer is their product. The lesson begins by proving this properly, with the Fréchet derivative and little-o notation.
- In what order is that product multiplied? Matrix multiplication is associative, so the result does not depend on order. Cost does, enormously: for scalar loss, one order costs as much as a few network evaluations and the other as many as there are parameters. This asymmetry is why deep learning is possible.
The second question gives the two objects naming the lesson: the Jacobian–vector product (JVP), pushing an input perturbation toward the output, and the vector–Jacobian product (VJP), bringing output sensitivity back toward the input. Here we establish their mathematics and cost; general automatic differentiation algorithms chaining them over any program are built in the numerical methods module.
The chain rule for differentials
Recall the definition. A function , with open, is differentiable at if there is a linear map such that
that is, . In the canonical basis, is the Jacobian matrix , with entries . The linearization is the best affine approximation to near . The chain rule says linearizing and composing commute.
This is the multivariable chain rule. Notice two details before proving it. The Jacobian of is evaluated at , the point through which the chain passes, not at . And the product reads right to left, like composition: acts first. Shapes fit automatically: , because matrix multiplication was defined precisely so that the matrix of a composition of linear maps is their matrix product.
Proof
Call and , and write both differentiability statements with their remainders:
with and . For small , ; let . Then and
It suffices to show (i) and (ii) are , because then satisfies the definition of the differential of at (and the differential, if it exists, is unique). Term (i) is immediate: , with the operator norm, and . Term (ii) is the only delicate one, because the remainder of is evaluated at rather than . You prove this next.
∎Step 1 of 4. First, how large can be?
The assumption that and are differentiable (in Fréchet’s sense) cannot be weakened to existence of partial derivatives, or even all directional derivatives. With and , both partials at the origin are (because vanishes on the axes), so the “rule” would predict for curve . But , whose derivative is . There is no contradiction: is not differentiable at the origin, although it has derivatives in every direction.
What the rule says geometrically
A Jacobian is a linear map between perturbation spaces: it takes a small displacement around to displacement around , with error . A circle of perturbations of radius therefore goes nearly to an ellipse. Applying afterward deforms that ellipse again by , and the final ellipse is the circle’s image under the product.
What you should have seen:
- With large , the exact image is not an ellipse: it bends and shifts. With the magnifier enabled, panel scale is proportional to ; decreasing it brings the blue curve toward the magenta ellipse. The “maximum deviation divided by ” readout roughly halves whenever halves: the error is because these functions are class (with differentiability alone it would be ).
- The orange vector travels along the chain. goes to then . Press ‘Rotate v’: the vector traces the circle and its images trace both ellipses. It is literally a JVP at each stage.
- Near the edge of panel 3, the ellipse flattens. contains a , and in regions where it saturates its Jacobian has nearly zero rows. This is the geometric form of vanishing gradients.
- The evaluation point matters. With , the red ellipse points in another direction and deviation divided by does not tend to zero. acts on what reaches it, .
The same check, in numbers:
import numpy as np
A_G = np.array([[0.9, -0.55], [0.45, 0.75]])
f = lambda x: np.array([x[0] + 0.35 * x[1]**2, x[1] - 0.35 * x[0]**2])
Jf = lambda x: np.array([[1.0, 0.7 * x[1]], [-0.7 * x[0], 1.0]])
g = lambda y: np.tanh(A_G @ y)
Jg = lambda y: (1 - np.tanh(A_G @ y)**2)[:, None] * A_G # diag(tanh'(Ay)) A
def jac_fd(F, x, h=1e-6):
"""Jacobiano por diferencias centradas, columna a columna."""
return np.column_stack([(F(x + h * e) - F(x - h * e)) / (2 * h) for e in np.eye(len(x))])
x = np.array([0.6, 0.5])
gf = lambda x: g(f(x))
J_bien = Jg(f(x)) @ Jf(x)
J_mal = Jg(x) @ Jf(x) # J_g evaluado en el punto equivocado
print("J_{g∘f} por diferencias finitas:\n", jac_fd(gf, x).round(6))
print("J_g(f(x)) J_f(x):\n", J_bien.round(6))
print("error con J_g(f(x)):", np.abs(jac_fd(gf, x) - J_bien).max().round(10),
" con J_g(x):", np.abs(jac_fd(gf, x) - J_mal).max().round(4))
u = np.array([np.cos(0.6), np.sin(0.6)]) # dirección unitaria
print("\n ε ‖resto‖/ε")
for eps in [0.4, 0.2, 0.1, 0.05, 0.025]:
resto = gf(x + eps * u) - gf(x) - eps * J_bien @ u
print(f"{eps:6.3f} {np.linalg.norm(resto) / eps:.6f}")The last column halves each time halves: the remainder is , and ratio tends to zero as required by the definition.
Special cases you will use daily
Derivative along a curve. If is a differentiable curve and is differentiable, is a function of one variable and its Jacobian is the product of a row by a column:
The rate of change of along a trajectory is the gradient times velocity. An example with consequences: if the trajectory follows gradient flow, , then . The function value never increases, and decreases strictly while the gradient does not vanish. This is the idea behind gradient flow and Lyapunov functions.
Total derivative with two intermediate variables. If and depend on , composition has derivative
with partial derivatives evaluated at . Each intermediate variable contributes a term: sensitivity of to that variable times the variable’s velocity. This is the minimal version of the path sum in the next section.
Change of coordinates. Let map polar to Cartesian coordinates and be the same function written in polar coordinates. Its Jacobian is
Transposing, . With we get and , as expected for .
Homogeneous functions and Euler’s theorem
A short, surprisingly useful application of the chain rule arises by differentiating with respect to a scale factor.
Proof
Fix and consider curve , with velocity . By the chain rule, is differentiable at with .
() If is homogeneous, , so . Equating with the preceding expression at gives the identity.
() If the identity holds throughout , define for . Then
applying the identity at point . Since is an interval, is constant and equal to , that is, .
∎This is Euler’s homogeneous function theorem. Differentiating with respect to (again the chain rule) also gives : the gradient of a degree- homogeneous function is homogeneous of degree . Three places it appears:
- Bias-free ReLU networks. Since for , network is positively homogeneous of degree 1 in . At every point where differentiable (all except a null set), Euler gives : the network equals exactly its Jacobian applied to the input. Thus in these networks, “gradient times input” attribution, , distributes the output with no remainder.
- The same network, in its weights. Scaling one matrix by scales output by , so for each layer . With scalar loss , the chain rule gives , the same value for every layer. Under gradient flow, is then equal in all layers, and differences are conserved during training. This is the automatic balancing result of Du, Hu and Lee (2018), who carefully handle points where ReLU is not differentiable.
- Portfolio risk contributions. Volatility of a portfolio with weights and covariance matrix is homogeneous of degree 1. Euler gives with : total risk is exactly allocated to asset contributions. The same holds for any coherent differentiable risk measure, because coherence includes positive homogeneity; this is Euler allocation used by risk departments.
rng = np.random.default_rng(0)
# red ReLU sin sesgos, R^5 -> R; su gradiente se obtiene encadenando VJPs (lo justificamos más abajo)
W1, W2, W3 = rng.standard_normal((16, 5)), rng.standard_normal((16, 16)), rng.standard_normal((1, 16))
def red(x):
a1 = W1 @ x; h1 = np.maximum(a1, 0)
a2 = W2 @ h1; h2 = np.maximum(a2, 0)
return (W3 @ h2)[0], (a1, a2)
def grad_red(x):
_, (a1, a2) = red(x)
g2 = W3[0] * (a2 > 0) # VJP de la última capa y de la segunda ReLU
g1 = (W2.T @ g2) * (a1 > 0) # VJP de W2 y de la primera ReLU
return W1.T @ g1 # VJP de W1
x = rng.standard_normal(5)
print("f(x) =", red(x)[0].round(10))
print("x · ∇f(x) =", (x @ grad_red(x)).round(10))
print("f(3x) / f(x) =", (red(3 * x)[0] / red(x)[0]).round(10))
# contribuciones de Euler a la volatilidad de una cartera de tres activos
vol = np.array([0.20, 0.10, 0.15])
corr = np.array([[1.0, 0.3, 0.5], [0.3, 1.0, 0.2], [0.5, 0.2, 1.0]])
Sigma = np.outer(vol, vol) * corr
w = np.array([0.4, 0.4, 0.2])
sigma = np.sqrt(w @ Sigma @ w)
contrib = w * (Sigma @ w) / sigma
print("\nvolatilidad de la cartera:", sigma.round(6))
print("contribuciones w_i ∂σ/∂w_i:", contrib.round(6), " suma:", contrib.sum().round(6))
print("en porcentaje:", (100 * contrib / sigma).round(1), "| pesos:", 100 * w)The portfolio is allocated 40, 40 and 20%, but risk is not: the first asset, the most volatile, contributes 62.5% of total volatility, and the second, with the same weight, only 20.4%. Euler’s identity makes the decomposition exact, not a first-order approximation.
Total versus partial derivative: sum every path
In a network, one variable affects the loss along multiple paths: a weight shared by two layers, a residual connection adding a block’s input to its output, a tied embedding matrix used at the beginning and end of the model. The chain rule handles all these cases at once when written on a graph.
Consider a calculation as a sequence of scalar variables in which is input and each other variable is obtained from some preceding variables, its parents: . The graph with an edge for each is acyclic. Each edge carries a local number, partial derivative , calculated with the other arguments of fixed.
Proof
By induction in computation order, prove is the sum over paths from to (with , the empty path). Function is the composition of with , so the chain rule, with a row Jacobian times a column, gives
By the induction hypothesis, each is the sum over paths from to ; multiplication by extends them with edge , and every path from to ends in exactly one edge with . The sum is therefore the sum over all paths from to .
∎The minimal example is with : two paths, direct and via , and
Notation is treacherous. Physics and economics often write for both, and the distinction exists only in the writer’s head. If and , the partial is , while the total is , the derivative of .
Two observations before continuing. First, at some points removing a path has no effect because its contribution is zero there (with , path contributes ). A gradient check at a single point may therefore pass with a forgotten path; that is why random points are checked. Second, the number of paths grows exponentially with depth (a chain of diamonds, each with two branches, has ), but the proof’s recursion does not enumerate them: it computes for each node in order and costs one operation per edge. This recursion, accumulated from the input, is forward mode automatic differentiation. The same sum, organized from the output, with adjoints satisfying , is reverse mode. The next section explains why the latter wins when output is scalar.
JVP and VJP: push forward, pull backward
A Jacobian can be used in two ways without ever writing its entries: multiplying by a vector on the right or a row vector on the left.
The JVP is the directional derivative of all outputs at once: how much output moves when input moves in direction . The VJP has an equally concrete reading. A covector defines a scalar measure of output, , and the VJP is its gradient with respect to input:
Shapes tell the story. JVP receives something shaped like the input and returns something shaped like the output: it goes forward, like . VJP receives something shaped like the output and returns something shaped like the input: it goes backward.
Proof
(1) is column of and is row . (2) With , is a row and . (3) By the chain rule, , and transposing, . Coordinate-free: , so . The adjoint of a composition is the composition of adjoints in reverse order.
∎Point 3 is the heart of everything. In a chain , JVPs chain in computation order: tangent vector enters from the left and each function pushes it, , with . VJPs chain in reverse: covector enters from the right and each function pulls it backward, . And since a node’s JVP needs only its evaluation point , it can be computed alongside the forward pass and forgotten afterward; the VJP, however, needs points in reverse order, so they must be saved during the forward pass. This is reverse mode’s memory bill, forcing gradient checkpointing in large models.
A loss gradient is a VJP with seed 1
For a loss with scalar , point 2 applied to the entire composition and point 3 give
and this is evaluated right to left: , which is , then . Each has the shape of and measures how much loss would change if that intermediate state were perturbed. For graph leaves (parameters and inputs with requires_grad), this is exactly what PyTorch stores in .grad, which is why loss.backward() needs no argument: the seed is the implicit of a scalar output. If output is not scalar, y.backward(u) requests seed and computes a VJP (seen in the autograd dynamic graph). Systematically applying this scheme to every network operation is backpropagation.
The formula also says how much the gradient can grow or shrink crossing stages. Since in operator norm, and if is square,
If all Jacobians have norm below , the gradient reaching the input is less than times the output gradient; if all singular values exceed , it is greater than times. In a recurrent network, , the factors are with the same repeated along the sequence, and this geometric product is the origin of vanishing or exploding gradients in backpropagation through time.
In what order should a Jacobian chain be multiplied?
Suppose each chain Jacobian is an already formed dense matrix, , and you want the full Jacobian . Multiplying a matrix by another costs scalar multiplications. The two extreme strategies are:
- Forward, right to left: . The accumulated product always has columns, and costs . This is forward mode: equivalent to pushing the vectors with JVPs.
- Backward, left to right: . The accumulated product always has rows, and costs . This is reverse mode: equivalent to pulling back the covectors with VJPs.
With a loss, , and backward cost is : exactly the cost of applying each Jacobian once to a vector except the last, row , which acts as the seed, the same order as a dense network’s forward pass. Forward cost is multiplied by , the number of inputs (parameters, if differentiating with respect to them). With a billion parameters, the difference is nine orders of magnitude.
What the interactive shows:
- Scalar-loss network (): backward costs multiplications and never forms anything larger than a row vector of numbers; forward costs and needs an intermediate product of numbers, about 4 GB (3.7 GiB) in float32. Over a thousand times more expensive, and too large for many GPUs. ( itself already has entries: the dense matrix model exaggerates the memory problem, which is why, as seen next, in practice nobody forms the .)
- Scalar input (): the situation reverses. Forward, each step is a matrix times a column vector; backward forms , one hundred times more expensive. This is sensitivity of an entire trajectory to a single parameter.
- Bottleneck (): both extremes cost the same, , and optimal order, , about fifty times less: reduce each half of the chain to the bottleneck, and , and only form their product at the end. Generally, optimal matrix-chain order is a problem of dynamic programming over intervals, costing for factors.
In practice nobody forms the . The Jacobian of a linear layer with respect to its weight matrix has entries, almost all zero. What is implemented for each primitive are its JVP and VJP functions, which exploit structure and cost the same order as its forward pass. With these, reverse mode obtains a scalar-loss gradient at a small multiple of evaluation cost, regardless of parameter count: the cheap gradient principle. The price, as seen, is memory for intermediate states, which forward mode does not need.
import time
def mults_cadena(dims, orden):
"""Multiplicaciones de J_k ⋯ J_1 con J_i de forma dims[i] × dims[i-1], hacia delante o hacia atrás."""
k = len(dims) - 1
if orden == "delante":
return sum(dims[i] * dims[i - 1] * dims[0] for i in range(2, k + 1))
return sum(dims[k] * dims[i] * dims[i - 1] for i in range(1, k))
for nombre, dims in [("pérdida escalar", [10**6, 10**3, 10**3, 10**2, 1]), ("entrada escalar", [1, 10**2, 10**3, 10**4])]:
d, a = mults_cadena(dims, "delante"), mults_cadena(dims, "atras")
print(f"{nombre:16s} delante {d:.3e} atrás {a:.3e} delante / atrás = {d / a:.3g}")
# lo mismo con matrices reales: v^T (A B) frente a (v^T A) B
n = 300
rng = np.random.default_rng(1)
A, B, v = rng.standard_normal((n, n)), rng.standard_normal((n, n)), rng.standard_normal(n)
t0 = time.perf_counter(); r1 = v @ (A @ B); t1 = time.perf_counter()
r2 = (v @ A) @ B; t2 = time.perf_counter()
print(f"\nn = {n}: mismo resultado: {np.allclose(r1, r2)}")
print(f"v^T (A B): {n**3 + n**2:.2e} multiplicaciones, {1e3 * (t1 - t0):7.2f} ms")
print(f"(v^T A) B: {2 * n**2:.2e} multiplicaciones, {1e3 * (t2 - t1):7.2f} ms")The multiplication ratio between the two ways to compute is , with , and measured times differ by over two orders of magnitude. You will calculate it for in the exercises.
VJPs of primitives
An automatic differentiation framework only needs, for each elementary operation, its forward pass and VJP (and JVP, for forward mode). The next three build a multilayer perceptron; the matrix-and-batch version, and many more primitives, are in the VJP of matrix calculus.
Linear layer. Let , with , viewed as a function of the three variables . Its differential is , already the JVP. For the VJP with covector , measure the perturbation with it and rearrange each term to isolate each variable’s perturbation:
because . Therefore , and . The weight VJP is an outer product, costing , the same as the forward pass.
Elementwise activation. If componentwise, for and the Jacobian is diagonal, . Its JVP and VJP coincide: , costing instead of . For , is obtained from output without recomputation, so is saved rather than .
Softmax. With , , the Jacobian is not diagonal, because every probability depends on all logits through the denominator. Try to predict each step:
Matrix has a probabilistic interpretation: it is the covariance matrix of one-hot vector when follows distribution . It is therefore positive semidefinite, and : adding a constant to all logits does not change probabilities. If all are positive, the kernel is exactly the line generated by and the rank is .
With temperature, , the chain rule adds factor : . If the largest logit exceeds the second by , each nonmaximum probability is at most , and every entry of is bounded by , which tends to zero as (the exponential beats factor ). Saturated softmax blocks the gradient.
With the initial logits, is at temperature and at temperature ; at temperature it falls to and at is of order , while approaches . At high temperature the Jacobian also shrinks, but for another reason: tends to uniform and behaves like . Both sums on the last line always vanish: that of because probabilities sum to one and cannot all change in the same direction, and that of because it is .
Implementation from scratch: a hand-differentiated network
Now construct the gradient of with by chaining the three primitives’ VJPs. The code works on a batch of examples in rows, like PyTorch: a row maps to , and the preceding section’s formulas are transposed accordingly (, , , the sum over the batch).
def lineal_fwd(X, W, b): return X @ W.T + b
def lineal_vjp(X, W, Ybar): return Ybar @ W, Ybar.T @ X, Ybar.sum(0) # X̄, W̄, b̄
def tanh_fwd(A): return np.tanh(A)
def tanh_vjp(H, Hbar): return Hbar * (1 - H**2) # jacobiano diagonal: usa la salida
def mse_fwd(F, Y): return 0.5 * np.sum((F - Y)**2) / len(F)
def mse_vjp(F, Y, sem=1.0): return sem * (F - Y) / len(F) # semilla 1: la pérdida es escalar
def perdida_y_gradiente(params, X, Y):
W1, b1, W2, b2 = params
# forward: se guardan los estados que necesitarán los VJP
A1 = lineal_fwd(X, W1, b1)
H = tanh_fwd(A1)
F = lineal_fwd(H, W2, b2)
L = mse_fwd(F, Y)
# backward: los VJP en orden inverso, cada uno con el covector que le llega
Fbar = mse_vjp(F, Y)
Hbar, W2bar, b2bar = lineal_vjp(H, W2, Fbar)
A1bar = tanh_vjp(H, Hbar)
Xbar, W1bar, b1bar = lineal_vjp(X, W1, A1bar)
return L, [W1bar, b1bar, W2bar, b2bar], Xbar
rng = np.random.default_rng(0)
d, h, o, B = 4, 8, 3, 16
params = [rng.standard_normal((h, d)) / 2, rng.standard_normal(h) / 2, rng.standard_normal((o, h)) / 2, rng.standard_normal(o) / 2]
X, Y = rng.standard_normal((B, d)), rng.standard_normal((B, o))
L, grads, Xbar = perdida_y_gradiente(params, X, Y)
# gradient check: diferencias centradas sobre cada uno de los parámetros
def grad_numerico(params, X, Y, eps=1e-6):
out = []
for P in params:
G = np.zeros_like(P)
for idx in np.ndindex(P.shape):
orig = P[idx]
P[idx] = orig + eps; Lp = perdida_y_gradiente(params, X, Y)[0]
P[idx] = orig - eps; Lm = perdida_y_gradiente(params, X, Y)[0]
P[idx] = orig
G[idx] = (Lp - Lm) / (2 * eps)
out.append(G)
return out
num = grad_numerico(params, X, Y)
for nombre, g_vjp, g_num in zip(["W1", "b1", "W2", "b2"], grads, num):
err = np.linalg.norm(g_vjp - g_num) / (np.linalg.norm(g_vjp) + np.linalg.norm(g_num))
print(f"{nombre}: forma {str(g_vjp.shape):8s} error relativo {err:.1e}")
print("parámetros:", sum(P.size for P in params), "| evaluaciones de la pérdida en el gradient check:", 2 * sum(P.size for P in params))The four relative errors are around , the level permitted by central differences in double precision. This is the same gradient checker from the partial derivatives lesson. Notice the last line: gradient checking needs two loss evaluations per parameter, whereas the VJP chain obtains everything in one backward pass. Measure it with a larger network:
d, h, o, B = 128, 256, 64, 256
params = [rng.standard_normal((h, d)) / np.sqrt(d), np.zeros(h), rng.standard_normal((o, h)) / np.sqrt(h), np.zeros(o)]
X, Y = rng.standard_normal((B, d)), rng.standard_normal((B, o))
def solo_forward(params, X, Y):
W1, b1, W2, b2 = params
return mse_fwd(lineal_fwd(tanh_fwd(lineal_fwd(X, W1, b1)), W2, b2), Y)
def cronometra(fn, rep=5):
fn()
t0 = time.perf_counter()
for _ in range(rep):
fn()
return (time.perf_counter() - t0) / rep
t_fwd = cronometra(lambda: solo_forward(params, X, Y))
t_all = cronometra(lambda: perdida_y_gradiente(params, X, Y))
mult_fwd = B * (d * h + h * o) # productos de matrices del forward
mult_bwd = 2 * mult_fwd # cada capa: un producto para el covector de la entrada y otro para los pesos
print(f"multiplicaciones: forward {mult_fwd:.2e}, backward {mult_bwd:.2e} (cociente {mult_bwd / mult_fwd:.1f})")
print(f"tiempo: forward {1e3 * t_fwd:.1f} ms, forward + backward {1e3 * t_all:.1f} ms (cociente {t_all / t_fwd:.1f})")
print(f"parámetros: {sum(P.size for P in params)}; un gradient check costaría {2 * sum(P.size for P in params)} forwards")Each linear layer’s backward pass performs two matrix products of the same size as the forward product, one for the input covector and one for the weight gradient; the rest (tanh, loss, biases) is linear in size. Thus forward plus backward costs three times the forward multiplications, and somewhat more in time (backward adds elementwise operations, products with transposed matrices and memory allocation), but that ratio does not depend on parameter count. Gradient checking, by contrast, grows with it: with 49 472 parameters it would cost almost one hundred thousand forward passes.
The same skeleton also gives the network Jacobian with respect to input, by columns (JVP) or rows (VJP), and lets us verify the adjoint-defining identity:
d, h, o = 5, 7, 3
W1, b1, W2, b2 = rng.standard_normal((h, d)), rng.standard_normal(h), rng.standard_normal((o, h)), rng.standard_normal(o)
x = rng.standard_normal(d)
def red_jvp(x, v):
"""Empuja v hacia delante: la tangente viaja junto al forward y no hay que guardar nada."""
a, da = W1 @ x + b1, W1 @ v
hh, dh = np.tanh(a), (1 - np.tanh(a)**2) * da
return W2 @ hh + b2, W2 @ dh
def red_vjp(x, u):
"""Trae u hacia atrás: hace falta el estado del forward (hh) para el VJP de tanh."""
hh = np.tanh(W1 @ x + b1)
return W1.T @ ((1 - hh**2) * (W2.T @ u))
J_cols = np.column_stack([red_jvp(x, e)[1] for e in np.eye(d)]) # d JVP
J_rows = np.vstack([red_vjp(x, e) for e in np.eye(o)]) # o VJP
J_fd = np.column_stack([(red_jvp(x + 1e-6 * e, e)[0] - red_jvp(x - 1e-6 * e, e)[0]) / 2e-6 for e in np.eye(d)])
print("forma del jacobiano:", J_cols.shape)
print("columnas (JVP) = filas (VJP):", np.allclose(J_cols, J_rows), "| = diferencias finitas:", np.allclose(J_cols, J_fd, atol=1e-8))
u, v = rng.standard_normal(o), rng.standard_normal(d)
print("<u, J v> =", (u @ red_jvp(x, v)[1]).round(12))
print("<Jᵀu, v> =", (red_vjp(x, u) @ v).round(12))The professional version: torch.func
PyTorch exposes both operations directly in torch.func, with a functional interface patterned after JAX (seen in the JAX lesson): jvp(f, primales, tangentes) returns output and JVP, while vjp(f, primales) returns output and a function applying the adjoint to any covector, closing over saved states. Above them are jacfwd (Jacobian by columns, using vectorized JVPs) and jacrev (by rows, using vectorized VJPs), and grad, a VJP with seed . All operate on tensors and can be nested, enabling higher-order derivatives.
import time
import torch
from torch.func import jvp, vjp, jacrev, jacfwd, grad
torch.manual_seed(0)
dt = torch.float64
d, h, o = 5, 7, 3
W1, b1 = torch.randn(h, d, dtype=dt), torch.randn(h, dtype=dt)
W2, b2 = torch.randn(o, h, dtype=dt), torch.randn(o, dtype=dt)
f = lambda x: W2 @ torch.tanh(W1 @ x + b1) + b2
def mi_jvp(x, v):
a = W1 @ x + b1
return W2 @ ((1 - torch.tanh(a)**2) * (W1 @ v))
def mi_vjp(x, u):
hh = torch.tanh(W1 @ x + b1)
return W1.T @ ((1 - hh**2) * (W2.T @ u))
x, v, u = torch.randn(d, dtype=dt), torch.randn(d, dtype=dt), torch.randn(o, dtype=dt)
y, Jv = jvp(f, (x,), (v,))
y2, pullback = vjp(f, x) # pullback: covector de la salida -> covector de la entrada
(uJ,) = pullback(u)
print("JVP coincide con el propio:", torch.allclose(Jv, mi_jvp(x, v)), "| VJP coincide:", torch.allclose(uJ, mi_vjp(x, u)))
J = jacrev(f)(x)
cols = torch.stack([jvp(f, (x,), (e,))[1] for e in torch.eye(d, dtype=dt)], dim=1)
rows = torch.stack([pullback(e)[0] for e in torch.eye(o, dtype=dt)])
print("JVP con e_i = columna i:", torch.allclose(cols, J), "| VJP con e_j = fila j:", torch.allclose(rows, J),
"| jacfwd = jacrev:", torch.allclose(jacfwd(f)(x), J))
y_obj = torch.randn(o, dtype=dt)
L = lambda x: 0.5 * ((f(x) - y_obj)**2).sum()
_, pull_L = vjp(L, x)
print("grad = VJP con semilla 1:", torch.allclose(grad(L)(x), pull_L(torch.tensor(1.0, dtype=dt))[0]))
# el coste de cada modo depende de la forma de la función
n = 2000
A = torch.randn(n, n) / n**0.5
ancha = lambda z: torch.tanh(A @ torch.tanh(A @ z)).sum() # R^n -> R
alta = lambda t: torch.tanh(A @ torch.tanh(A[:, 0] * t)) # R -> R^n
z0, t0 = torch.randn(n), torch.tensor(0.7)
def mide(fn, rep=3):
fn()
t = time.perf_counter()
for _ in range(rep):
fn()
return (time.perf_counter() - t) / rep
print(f"\nR^{n} -> R : jacrev {1e3 * mide(lambda: jacrev(ancha)(z0)):8.2f} ms jacfwd {1e3 * mide(lambda: jacfwd(ancha)(z0)):8.2f} ms")
print(f"R -> R^{n} : jacrev {1e3 * mide(lambda: jacrev(alta)(t0)):8.2f} ms jacfwd {1e3 * mide(lambda: jacfwd(alta)(t0)):8.2f} ms")npm run lab and open the connection link.All six checks give True, and timings reproduce the cost interactive: for function , jacrev performs one VJP and jacfwd needs JVPs; for , the reverse. jacfwd and jacrev vectorize those passes with vmap, so the expensive mode does not take times longer, but still one or two orders of magnitude longer. A practical rule: jacrev when there are more inputs than outputs, jacfwd otherwise, and for a Hessian, jacfwd(jacrev(f)), combining both modes and leading to the Hessian–vector product in the next lesson.
Common mistakes
Exercises
softmax_vjp(z, v), returning as a NumPy array of the same shape as z, without forming the Jacobian: use . Compute stably (subtract the maximum before exponentiating). Tests compare against the full Jacobian in small dimension, test huge logits and measure time with , where the Jacobian would have entries.import numpy as np
def softmax_vjp(z, v):
"""Devuelve vᵀ J_softmax(z) sin formar J."""
passSummary
- Chain rule: if is differentiable at and at . The proof controls the remainder of evaluated at , which may vanish; existence of partial derivatives is insufficient.
- Special cases: ; under a change of coordinates, gradients transform with . For homogeneous of degree , (Euler): bias-free ReLU networks, self-balancing layers, risk contributions.
- Total derivative: the sum, over all dependency graph paths, of products of local derivatives. The partial is only the direct path. It is computed without enumerating paths, with a recursion costing one operation per edge, forward or backward.
- JVP and VJP: , from input to output shape; , the reverse, the adjoint of the differential. The adjoint of a composition is the composition of adjoints in reverse order, and VJP needs saved forward states.
- Association cost: forward, ; backward, . Scalar output, backward; scalar input, forward; with a bottleneck, dynamic programming.
- Primitives: linear (, ), elementwise (diagonal, ) and softmax (, vanishing under saturation). None forms its Jacobian.