Module contents
Lesson 8 of 20Core 100 min

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:

  1. What is the derivative of a composition? In one variable, (g∘f)′(x)=g′(f(x)) f′(x)(g\circ f)'(x) = g'(f(x))\,f'(x). 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.
  2. 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 f:U→Rmf: U \to \R^m, with U⊆RnU \subseteq \R^n open, is differentiable at x∈U\vb{x} \in U if there is a linear map Df(x):Rn→RmDf(\vb{x}): \R^n \to \R^m such that

f(x+h)=f(x)+Df(x)[h]+r(h),lim⁡h→0∥r(h)∥∥h∥=0,f(\vb{x} + \vb{h}) = f(\vb{x}) + Df(\vb{x})[\vb{h}] + r(\vb{h}), \qquad \lim_{\vb{h} \to \vb{0}} \frac{\norm{r(\vb{h})}}{\norm{\vb{h}}} = 0,

that is, r(h)=o(∥h∥)r(\vb{h}) = o(\norm{\vb{h}}). In the canonical basis, Df(x)Df(\vb{x}) is the Jacobian matrix Jf(x)∈Rm×n\mat{J}_f(\vb{x}) \in \R^{m\times n}, with entries ∂fi/∂xj\partial f_i / \partial x_j. The linearization h↦f(x)+Jf(x)h\vb{h} \mapsto f(\vb{x}) + \mat{J}_f(\vb{x})\vb{h} is the best affine approximation to ff near x\vb{x}. The chain rule says linearizing and composing commute.

This is the multivariable chain rule. Notice two details before proving it. The Jacobian of gg is evaluated at f(x)f(\vb{x}), the point through which the chain passes, not at x\vb{x}. And the product reads right to left, like composition: Jf\mat{J}_f acts first. Shapes fit automatically: (p×m)(m×n)=p×n(p\times m)(m\times n) = p\times n, because matrix multiplication was defined precisely so that the matrix of a composition of linear maps is their matrix product.

Proof

Call A=Jf(x)\mat{A} = \mat{J}_f(\vb{x}) and B=Jg(y)\mat{B} = \mat{J}_g(\vb{y}), and write both differentiability statements with their remainders:

f(x+h)=y+Ah+r(h),g(y+k)=g(y)+Bk+s(k),f(\vb{x} + \vb{h}) = \vb{y} + \mat{A}\vb{h} + r(\vb{h}), \qquad g(\vb{y} + \vb{k}) = g(\vb{y}) + \mat{B}\vb{k} + s(\vb{k}),

with r(h)=o(∥h∥)r(\vb{h}) = o(\norm{\vb{h}}) and s(k)=o(∥k∥)s(\vb{k}) = o(\norm{\vb{k}}). For small h\vb{h}, x+h∈U\vb{x} + \vb{h} \in U; let k(h)=f(x+h)−y=Ah+r(h)\vb{k}(\vb{h}) = f(\vb{x} + \vb{h}) - \vb{y} = \mat{A}\vb{h} + r(\vb{h}). Then y+k(h)∈V\vb{y} + \vb{k}(\vb{h}) \in V and

g(f(x+h))=g(y)+BAh+B r(h)⏟(i)+s(k(h))⏟(ii).g\big(f(\vb{x} + \vb{h})\big) = g(\vb{y}) + \mat{B}\mat{A}\vb{h} + \underbrace{\mat{B}\,r(\vb{h})}_{(\mathrm{i})} + \underbrace{s\big(\vb{k}(\vb{h})\big)}_{(\mathrm{ii})}.

It suffices to show (i) and (ii) are o(∥h∥)o(\norm{\vb{h}}), because then BA\mat{B}\mat{A} satisfies the definition of the differential of g∘fg\circ f at x\vb{x} (and the differential, if it exists, is unique). Term (i) is immediate: ∥B r(h)∥≤∥B∥ ∥r(h)∥\norm{\mat{B}\,r(\vb{h})} \le \norm{\mat{B}}\,\norm{r(\vb{h})}, with ∥B∥\norm{\mat{B}} the operator norm, and ∥r(h)∥/∥h∥→0\norm{r(\vb{h})}/\norm{\vb{h}} \to 0. Term (ii) is the only delicate one, because the remainder of gg is evaluated at k(h)\vb{k}(\vb{h}) rather than h\vb{h}. You prove this next.

∎
ProofThe remainder of g evaluated at k(h)
Prove: With the proof's notation, s(k(h))=o(∥h∥)s(\vb{k}(\vb{h})) = o(\norm{\vb{h}}).
0
You know k(h)=Ah+r(h)\vb{k}(\vb{h}) = \mat{A}\vb{h} + r(\vb{h}) with r(h)=o(∥h∥)r(\vb{h}) = o(\norm{\vb{h}}), that s(0)=0s(\vb{0}) = \vb{0} and that ∥s(k)∥/∥k∥→0\norm{s(\vb{k})}/\norm{\vb{k}} \to 0 as k→0\vb{k} \to \vb{0}.

Step 1 of 4. First, how large can k(h)\vb{k}(\vb{h}) be?

The assumption that ff and gg are differentiable (in Fréchet’s sense) cannot be weakened to existence of partial derivatives, or even all directional derivatives. With f(x,y)=x2y/(x2+y2)f(x, y) = x^2 y / (x^2 + y^2) and f(0,0)=0f(0, 0) = 0, both partials at the origin are 00 (because ff vanishes on the axes), so the “rule” would predict (f∘γ)′(0)=∇f(0)⊤γ′(0)=0(f\circ\gamma)'(0) = \grad f(\vb{0})\T\gamma'(0) = 0 for curve γ(t)=(t,t)\gamma(t) = (t, t). But f(γ(t))=t/2f(\gamma(t)) = t/2, whose derivative is 1/21/2. There is no contradiction: ff 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 v\vb{v} around x\vb{x} to displacement Jf(x)v\mat{J}_f(\vb{x})\vb{v} around f(x)f(\vb{x}), with error o(∥v∥)o(\norm{\vb{v}}). A circle of perturbations of radius ε\varepsilon therefore goes nearly to an ellipse. Applying gg afterward deforms that ellipse again by Jg(f(x))\mat{J}_g(f(\vb{x})), and the final ellipse is the circle’s image under the product.

InteractiveThe chain as a composition of linear maps
  • exact image of the circle
  • linear prediction (Jacobians)
  • v\vb{v} and its images
1. Input: x+ε u\vb{x} + \varepsilon\,\vb{u}
2. After ff: Jf(x)\mat{J}_f(\vb{x})
3. After gg: Jg(f(x)) Jf(x)\mat{J}_g(f(\vb{x}))\,\mat{J}_f(\vb{x})
0.35
34°
[0.76−0.470.320.54]⏟Jg(f(x)) [1.000.35−0.421.00]⏟Jf(x)=[0.96−0.200.100.65]⏟Jg∘f(x)\underbrace{\begin{bmatrix} 0.76 & -0.47 \\ 0.32 & 0.54 \end{bmatrix}}_{\mat{J}_g(f(\vb{x}))}\,\underbrace{\begin{bmatrix} 1.00 & 0.35 \\ -0.42 & 1.00 \end{bmatrix}}_{\mat{J}_f(\vb{x})} = \underbrace{\begin{bmatrix} 0.96 & -0.20 \\ 0.10 & 0.65 \end{bmatrix}}_{\mat{J}_{g\circ f}(\vb{x})}
Maximum deviation in panel 3, divided by ε\varepsilon0.149
Halve ε\varepsilon: the deviation divided by ε\varepsilon also roughly halves. The error is O(ε2)O(\varepsilon^2).
A circle of perturbations of radius ε\varepsilon around x\vb{x} (panel 1) is transformed by f(x)=(x1+0.35x22, x2−0.35x12)f(\vb{x}) = (x_1 + 0.35x_2^2,\ x_2 - 0.35x_1^2) (panel 2) and then by g(y)=tanh⁡(Ay)g(\vb{y}) = \tanh(\mat{A}\vb{y}) (panel 3). In blue, the exact image; in dashed magenta, the Jacobians' prediction. Gray curves are the image of the domain grid. Enable the magnifier and reduce ε\varepsilon: the two curves merge. Then enable the common error and evaluate Jg\mat{J}_g at x\vb{x} instead of f(x)f(\vb{x}).

What you should have seen:

  • With large ε\varepsilon, the exact image is not an ellipse: it bends and shifts. With the magnifier enabled, panel scale is proportional to ε\varepsilon; decreasing it brings the blue curve toward the magenta ellipse. The “maximum deviation divided by ε\varepsilon” readout roughly halves whenever ε\varepsilon halves: the error is O(ε2)O(\varepsilon^2) because these functions are class C2C^2 (with differentiability alone it would be o(ε)o(\varepsilon)).
  • The orange vector travels along the chain. v\vb{v} goes to Jf(x)v\mat{J}_f(\vb{x})\vb{v} then Jg(f(x))Jf(x)v\mat{J}_g(f(\vb{x}))\mat{J}_f(\vb{x})\vb{v}. 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. gg contains a tanh⁡\tanh, 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 Jg(x)\mat{J}_g(\vb{x}), the red ellipse points in another direction and deviation divided by ε\varepsilon does not tend to zero. gg acts on what reaches it, f(x)f(\vb{x}).

The same check, in numbers:

[ ]The chain rule, checkedBrowser
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 ε\varepsilon halves: the remainder is O(ε2)O(\varepsilon^2), and ratio ∥resto∥/ε\norm{\text{resto}}/\varepsilon tends to zero as required by the definition.

Special cases you will use daily

Derivative along a curve. If γ:I→Rn\gamma: I \to \R^n is a differentiable curve and f:Rn→Rf: \R^n \to \R is differentiable, f∘γf\circ\gamma is a function of one variable and its Jacobian 1×11\times 1 is the product of a row by a column:

ddtf(γ(t))=Jf(γ(t)) γ′(t)=∇f(γ(t))⊤γ′(t).\frac{d}{dt} f(\gamma(t)) = \mat{J}_f(\gamma(t))\,\gamma'(t) = \grad f(\gamma(t))\T\gamma'(t).

The rate of change of ff along a trajectory is the gradient times velocity. An example with consequences: if the trajectory follows gradient flow, γ′(t)=−∇f(γ(t))\gamma'(t) = -\grad f(\gamma(t)), then ddtf(γ(t))=−∥∇f(γ(t))∥2≤0\frac{d}{dt}f(\gamma(t)) = -\norm{\grad f(\gamma(t))}^2 \le 0. 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 xx and yy depend on tt, composition t↦f(x(t),y(t))t \mapsto f(x(t), y(t)) has derivative

ddtf(x(t),y(t))=∂f∂x x′(t)+∂f∂y y′(t),\frac{d}{dt} f\big(x(t), y(t)\big) = \pd{f}{x}\,x'(t) + \pd{f}{y}\,y'(t),

with partial derivatives evaluated at (x(t),y(t))(x(t), y(t)). Each intermediate variable contributes a term: sensitivity of ff 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 Φ(r,θ)=(rcos⁡θ,rsin⁡θ)\Phi(r, \theta) = (r\cos\theta, r\sin\theta) map polar to Cartesian coordinates and F=f∘ΦF = f\circ\Phi be the same function written in polar coordinates. Its Jacobian is

JΦ(r,θ)=[cos⁡θ−rsin⁡θsin⁡θrcos⁡θ],[∂F∂r∂F∂θ]=[∂f∂x∂f∂y]JΦ.\mat{J}_\Phi(r, \theta) = \begin{bmatrix} \cos\theta & -r\sin\theta \\ \sin\theta & r\cos\theta \end{bmatrix}, \qquad \begin{bmatrix} \pd{F}{r} & \pd{F}{\theta} \end{bmatrix} = \begin{bmatrix} \pd{f}{x} & \pd{f}{y} \end{bmatrix}\mat{J}_\Phi .

Transposing, ∇(r,θ)F=JΦ⊤ ∇(x,y)f\grad_{(r,\theta)} F = \mat{J}_\Phi\T\,\grad_{(x,y)} f. With f(x,y)=x2+y2f(x, y) = x^2 + y^2 we get ∂F∂r=2xcos⁡θ+2ysin⁡θ=2r\pd{F}{r} = 2x\cos\theta + 2y\sin\theta = 2r and ∂F∂θ=−2xrsin⁡θ+2yrcos⁡θ=0\pd{F}{\theta} = -2xr\sin\theta + 2yr\cos\theta = 0, as expected for F=r2F = r^2.

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 x∈C\vb{x} \in C and consider curve t↦txt \mapsto t\vb{x}, with velocity x\vb{x}. By the chain rule, φ(t)=f(tx)\varphi(t) = f(t\vb{x}) is differentiable at (0,∞)(0, \infty) with φ′(t)=∇f(tx)⊤x\varphi'(t) = \grad f(t\vb{x})\T\vb{x}.

(⇒\Rightarrow) If ff is homogeneous, φ(t)=tkf(x)\varphi(t) = t^k f(\vb{x}), so φ′(1)=kf(x)\varphi'(1) = k f(\vb{x}). Equating with the preceding expression at t=1t = 1 gives the identity.

(⇐\Leftarrow) If the identity holds throughout CC, define ψ(t)=t−kφ(t)\psi(t) = t^{-k}\varphi(t) for t>0t > 0. Then

ψ′(t)=−k t−k−1f(tx)+t−k ∇f(tx)⊤x=t−k−1((tx)⊤∇f(tx)−kf(tx))=0,\psi'(t) = -k\,t^{-k-1} f(t\vb{x}) + t^{-k}\,\grad f(t\vb{x})\T\vb{x} = t^{-k-1}\big((t\vb{x})\T\grad f(t\vb{x}) - k f(t\vb{x})\big) = 0,

applying the identity at point tx∈Ct\vb{x} \in C. Since (0,∞)(0, \infty) is an interval, ψ\psi is constant and equal to ψ(1)=f(x)\psi(1) = f(\vb{x}), that is, f(tx)=tkf(x)f(t\vb{x}) = t^k f(\vb{x}).

∎

This is Euler’s homogeneous function theorem. Differentiating f(tx)=tkf(x)f(t\vb{x}) = t^k f(\vb{x}) with respect to x\vb{x} (again the chain rule) also gives t ∇f(tx)=tk∇f(x)t\,\grad f(t\vb{x}) = t^k \grad f(\vb{x}): the gradient of a degree-kk homogeneous function is homogeneous of degree k−1k - 1. Three places it appears:

  • Bias-free ReLU networks. Since ReLU⁡(tz)=t ReLU⁡(z)\relu(t z) = t\,\relu(z) for t>0t > 0, network f(x)=WLReLU⁡(WL−1⋯ReLU⁡(W1x))f(\vb{x}) = \mat{W}_L\relu(\mat{W}_{L-1}\cdots\relu(\mat{W}_1\vb{x})) is positively homogeneous of degree 1 in x\vb{x}. At every point where differentiable (all except a null set), Euler gives f(x)=Jf(x) xf(\vb{x}) = \mat{J}_f(\vb{x})\,\vb{x}: the network equals exactly its Jacobian applied to the input. Thus in these networks, “gradient times input” attribution, xi ∂f/∂xix_i\,\partial f/\partial x_i, distributes the output with no remainder.
  • The same network, in its weights. Scaling one matrix Wℓ\mat{W}_\ell by t>0t > 0 scales output by tt, so for each layer ⟨Wℓ,∇Wℓf⟩F=f\inner{\mat{W}_\ell}{\grad_{\mat{W}_\ell} f}_F = f. With scalar loss L(f)\Loss(f), the chain rule gives ⟨Wℓ,∇WℓL⟩=L′(f) f\inner{\mat{W}_\ell}{\grad_{\mat{W}_\ell}\Loss} = \Loss'(f)\,f, the same value for every layer. Under gradient flow, ddt∥Wℓ∥F2=−2⟨Wℓ,∇WℓL⟩\frac{d}{dt}\norm{\mat{W}_\ell}_F^2 = -2\inner{\mat{W}_\ell}{\grad_{\mat{W}_\ell}\Loss} is then equal in all layers, and differences ∥Wℓ∥F2−∥Wℓ+1∥F2\norm{\mat{W}_\ell}_F^2 - \norm{\mat{W}_{\ell+1}}_F^2 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 σ(w)=w⊤Σw\sigma(\vb{w}) = \sqrt{\vb{w}\T\mat{\Sigma}\vb{w}} of a portfolio with weights w\vb{w} and covariance matrix Σ\mat{\Sigma} is homogeneous of degree 1. Euler gives σ(w)=∑iwi ∂σ/∂wi\sigma(\vb{w}) = \sum_i w_i\,\partial\sigma/\partial w_i with ∂σ/∂wi=(Σw)i/σ\partial\sigma/\partial w_i = (\mat{\Sigma}\vb{w})_i/\sigma: 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.
[ ]Euler in a ReLU network and a portfolioBrowser
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 v1,…,vNv_1, \dots, v_N in which v1=xv_1 = x is input and each other variable is obtained from some preceding variables, its parents: vj=ϕj(vi:i∈pa(j))v_j = \phi_j(v_i : i \in \mathrm{pa}(j)). The graph with an edge i→ji \to j for each i∈pa(j)i \in \mathrm{pa}(j) is acyclic. Each edge carries a local number, partial derivative ∂ϕj/∂vi\partial\phi_j/\partial v_i, calculated with the other arguments of ϕj\phi_j fixed.

Proof

By induction in computation order, prove dvj/dxdv_j/dx is the sum over paths from xx to vjv_j (with dv1/dx=1dv_1/dx = 1, the empty path). Function x↦vj(x)x \mapsto v_j(x) is the composition of x↦(vi(x))i∈pa(j)x \mapsto (v_i(x))_{i\in\mathrm{pa}(j)} with ϕj\phi_j, so the chain rule, with a row Jacobian times a column, gives

dvjdx=∑i∈pa(j)∂ϕj∂vi dvidx.\frac{dv_j}{dx} = \sum_{i \in \mathrm{pa}(j)} \pd{\phi_j}{v_i}\,\frac{dv_i}{dx}.

By the induction hypothesis, each dvi/dxdv_i/dx is the sum over paths from xx to viv_i; multiplication by ∂ϕj/∂vi\partial\phi_j/\partial v_i extends them with edge i→ji \to j, and every path from xx to vjv_j ends in exactly one edge i→ji \to j with i∈pa(j)i \in \mathrm{pa}(j). The sum is therefore the sum over all paths from xx to vjv_j.

∎

The minimal example is z=F(x,y)z = F(x, y) with y=h(x)y = h(x): two paths, direct and via yy, and

dzdx=∂F∂x+∂F∂y h′(x).\frac{dz}{dx} = \pd{F}{x} + \pd{F}{y}\,h'(x).

Notation is treacherous. Physics and economics often write ∂z/∂x\partial z/\partial x for both, and the distinction exists only in the writer’s head. If F(x,y)=xyF(x, y) = xy and y=x2y = x^2, the partial is ∂F/∂x=y=x2\partial F/\partial x = y = x^2, while the total is dz/dx=y+x⋅2x=3x2dz/dx = y + x\cdot 2x = 3x^2, the derivative of z=x3z = x^3.

InteractiveEvery path counts
∂y/∂x = cos x = 0.27∂u/∂x = y = 0.96∂u/∂y = x = 1.30∂z/∂x = 2x = 2.60∂z/∂y = 1 = 1.00∂z/∂u = 2u = 2.51x1.300y0.964u1.253z4.223
y=sin⁡xy = \sin x, u=x y\quad u = x\,y, z=x2+y+u2\quad z = x^2 + y + u^2
x → z
∂z∂x=2.60\displaystyle \pd{z}{x} = 2.60
2.600
x → y → z
∂z∂y∂y∂x=1.00⋅0.27\displaystyle \pd{z}{y}\pd{y}{x} = 1.00 \cdot 0.27
0.267
x → u → z
∂z∂u∂u∂x=2.51⋅0.96\displaystyle \pd{z}{u}\pd{u}{x} = 2.51 \cdot 0.96
2.414
x → y → u → z
∂z∂u∂u∂y∂y∂x=2.51⋅1.30⋅0.27\displaystyle \pd{z}{u}\pd{u}{y}\pd{y}{x} = 2.51 \cdot 1.30 \cdot 0.27
0.871
1.30
Sum of complete paths6.15265
Centered finite differences, h=10−5h = 10^{-5}6.15265
Partial ∂z/∂x\partial z / \partial x with y,uy, u fixed2.60000
Matches: the total derivative is the sum of the four paths.
Variable zz depends on xx along four paths. Each edge carries its local derivative, evaluated at the current point. Remove edges by clicking them or using switches: paths losing an edge stop contributing, and comparison with finite differences of z(x)z(x) fails and names the missing path. The third readout is partial ∂z/∂x\partial z / \partial x, the direct edge alone, which almost never equals the total.

Two observations before continuing. First, at some points removing a path has no effect because its contribution is zero there (with x=0x = 0, path x→u→zx \to u \to z contributes y⋅2u=0y \cdot 2u = 0). 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 LL diamonds, each with two branches, has 2L2^L), but the proof’s recursion does not enumerate them: it computes dvj/dxdv_j/dx 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 vˉi=dvN/dvi\bar{v}_i = dv_N/dv_i satisfying vˉi=∑j:i∈pa(j)vˉj ∂ϕj/∂vi\bar{v}_i = \sum_{j : i \in \mathrm{pa}(j)} \bar{v}_j\,\partial\phi_j/\partial v_i, is reverse mode. The next section explains why the latter wins when output is scalar.

JVP and VJP: push forward, pull backward

A Jacobian Jf(x)∈Rm×n\mat{J}_f(\vb{x}) \in \R^{m\times n} can be used in two ways without ever writing its mnmn 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 v\vb{v}. The VJP has an equally concrete reading. A covector u\vb{u} defines a scalar measure of output, y↦⟨u,y⟩\vb{y} \mapsto \inner{\vb{u}}{\vb{y}}, and the VJP is its gradient with respect to input:

∇x ⟨u,f(x)⟩=Jf(x)⊤u.\grad_{\vb{x}}\,\inner{\vb{u}}{f(\vb{x})} = \mat{J}_f(\vb{x})\T\vb{u}.

Shapes tell the story. JVP receives something shaped like the input and returns something shaped like the output: it goes forward, like ff. VJP receives something shaped like the output and returns something shaped like the input: it goes backward.

Proof

(1) Jei\mat{J}\vb{e}_i is column ii of J\mat{J} and ej⊤J\vb{e}_j\T\mat{J} is row jj. (2) With m=1m = 1, Jf(x)=∇f(x)⊤\mat{J}_f(\vb{x}) = \grad f(\vb{x})\T is a row and Jf⊤⋅1=∇f(x)\mat{J}_f\T\cdot 1 = \grad f(\vb{x}). (3) By the chain rule, Jg∘fv=Jg(Jfv)\mat{J}_{g\circ f}\vb{v} = \mat{J}_g(\mat{J}_f\vb{v}), and transposing, Jg∘f⊤u=Jf⊤(Jg⊤u)\mat{J}_{g\circ f}\T\vb{u} = \mat{J}_f\T(\mat{J}_g\T\vb{u}). Coordinate-free: ⟨u,BAv⟩=⟨B∗u,Av⟩=⟨A∗B∗u,v⟩\inner{\vb{u}}{BA\vb{v}} = \inner{B^{*}\vb{u}}{A\vb{v}} = \inner{A^{*}B^{*}\vb{u}}{\vb{v}}, so (B∘A)∗=A∗∘B∗(B\circ A)^{*} = A^{*}\circ B^{*}. The adjoint of a composition is the composition of adjoints in reverse order.

∎

Point 3 is the heart of everything. In a chain x0→f1x1→f2⋯→fkxk\vb{x}_0 \xrightarrow{f_1} \vb{x}_1 \xrightarrow{f_2} \cdots \xrightarrow{f_k} \vb{x}_k, JVPs chain in computation order: tangent vector x˙0\dot{\vb{x}}_0 enters from the left and each function pushes it, x˙i=Jix˙i−1\dot{\vb{x}}_i = \mat{J}_i\dot{\vb{x}}_{i-1}, with Ji=Jfi(xi−1)\mat{J}_i = \mat{J}_{f_i}(\vb{x}_{i-1}). VJPs chain in reverse: covector xˉk\bar{\vb{x}}_k enters from the right and each function pulls it backward, xˉi−1=Ji⊤xˉi\bar{\vb{x}}_{i-1} = \mat{J}_i\T\bar{\vb{x}}_i. And since a node’s JVP needs only its evaluation point xi−1\vb{x}_{i-1}, it can be computed alongside the forward pass and forgotten afterward; the VJP, however, needs points xi−1\vb{x}_{i-1} 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 L=ℓ(fk(⋯f1(x0)))\Loss = \ell(f_k(\cdots f_1(\vb{x}_0))) with scalar ℓ\ell, point 2 applied to the entire composition and point 3 give

∇x0L=J1⊤ J2⊤⋯Jk⊤ ∇ℓ(xk),\grad_{\vb{x}_0}\Loss = \mat{J}_1\T\,\mat{J}_2\T \cdots \mat{J}_k\T\,\grad\ell(\vb{x}_k),

and this is evaluated right to left: xˉk=∇ℓ(xk)\bar{\vb{x}}_k = \grad\ell(\vb{x}_k), which is vjpℓ(xk,1)\mathrm{vjp}_\ell(\vb{x}_k, 1), then xˉi−1=vjpfi(xi−1,xˉi)\bar{\vb{x}}_{i-1} = \mathrm{vjp}_{f_i}(\vb{x}_{i-1}, \bar{\vb{x}}_i). Each xˉi=∇xiL\bar{\vb{x}}_i = \grad_{\vb{x}_i}\Loss has the shape of xi\vb{x}_i 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 11 of a scalar output. If output is not scalar, y.backward(u) requests seed u\vb{u} and computes a VJP (seen in the autograd dynamic graph). Systematically applying this scheme to every network operation is backpropagation.

Key idea
For a scalar function, the gradient is J⊤⋅1\mat{J}\T\cdot 1, not J\mat{J}. It is obtained with a single VJP traversing the chain backward, applying each stage’s transposed Jacobian to the gradient arriving from the next.

The formula also says how much the gradient can grow or shrink crossing kk stages. Since ∥J⊤u∥≤∥J∥ ∥u∥\norm{\mat{J}\T\vb{u}} \le \norm{\mat{J}}\,\norm{\vb{u}} in operator norm, and ∥J⊤u∥≥σmin⁡(J) ∥u∥\norm{\mat{J}\T\vb{u}} \ge \sigma_{\min}(\mat{J})\,\norm{\vb{u}} if J\mat{J} is square,

∏i=1kσmin⁡(Ji)  ∥xˉk∥  ≤  ∥xˉ0∥  ≤  ∏i=1k∥Ji∥  ∥xˉk∥.\prod_{i=1}^{k}\sigma_{\min}(\mat{J}_i)\;\norm{\bar{\vb{x}}_k} \;\le\; \norm{\bar{\vb{x}}_0} \;\le\; \prod_{i=1}^{k}\norm{\mat{J}_i}\;\norm{\bar{\vb{x}}_k}.

If all Jacobians have norm below ρ<1\rho < 1, the gradient reaching the input is less than ρk\rho^k times the output gradient; if all singular values exceed ρ>1\rho > 1, it is greater than ρk\rho^k times. In a recurrent network, ht=tanh⁡(Wht−1+Uxt)\vb{h}_t = \tanh(\mat{W}\vb{h}_{t-1} + \mat{U}\vb{x}_t), the kk factors are diag⁡(1−ht2) W\diag(1 - \vb{h}_t^2)\,\mat{W} with the same W\mat{W} 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, Ji∈Rni×ni−1\mat{J}_i \in \R^{n_i\times n_{i-1}}, and you want the full Jacobian J=JkJk−1⋯J1∈Rnk×n0\mat{J} = \mat{J}_k\mat{J}_{k-1}\cdots\mat{J}_1 \in \R^{n_k\times n_0}. Multiplying a matrix p×qp\times q by another q×rq\times r costs pqrpqr scalar multiplications. The two extreme strategies are:

  • Forward, right to left: Jk(⋯(J3(J2J1)))\mat{J}_k(\cdots(\mat{J}_3(\mat{J}_2\mat{J}_1))). The accumulated product always has n0n_0 columns, and costs ∑i=2kni ni−1 n0\sum_{i=2}^{k} n_i\,n_{i-1}\,n_0. This is forward mode: equivalent to pushing the n0n_0 vectors e1,…,en0\vb{e}_1, \dots, \vb{e}_{n_0} with JVPs.
  • Backward, left to right: (((JkJk−1)Jk−2)⋯ )J1(((\mat{J}_k\mat{J}_{k-1})\mat{J}_{k-2})\cdots)\mat{J}_1. The accumulated product always has nkn_k rows, and costs ∑i=1k−1nk ni ni−1\sum_{i=1}^{k-1} n_k\,n_i\,n_{i-1}. This is reverse mode: equivalent to pulling back the nkn_k covectors e1,…,enk\vb{e}_1, \dots, \vb{e}_{n_k} with VJPs.

With a loss, nk=1n_k = 1, and backward cost is ∑i=1k−1nini−1\sum_{i=1}^{k-1} n_i n_{i-1}: exactly the cost of applying each Jacobian once to a vector except the last, row Jk\mat{J}_k, which acts as the seed, the same order as a dense network’s forward pass. Forward cost is multiplied by n0n_0, the number of inputs (parameters, if differentiating with respect to them). With a billion parameters, the difference is nine orders of magnitude.

InteractiveIn what order should Jacobians be multiplied?
Dimensions n0→⋯→n4n_0 \to \cdots \to n_4: 10⁶ → 10³ → 10³ → 10² → 1
J₄1×10²·J₃10²×10³·J₂10³×10³·J₁10³×10⁶
start
Press play or advance step by step. Each product of a p×qp \times q matrix by a q×rq \times r matrix costs pqrpqr multiplications.
Forward (JVP)
1.10 × 10¹²
Backward (VJP)
1.00 × 10⁹
Optimal order
1.00 × 10⁹
Each bar length is proportional to the logarithm of the number of multiplications.
Strategy
Scalar multiplications1.00×1091.00 \times 10^{9}
Entries in the largest product formed1.00×1061.00 \times 10^{6}
Its memory in float323.81 MiB
Forward / backward1099 ×
Scalar output: going backward, each step is a row vector times a matrix (a VJP), and nothing larger than 1×n1 \times n is formed.
Each Jacobian Ji∈Rni×ni−1\mat{J}_i \in \R^{n_i\times n_{i-1}} is drawn as a rectangle with sides proportional to the logarithm of its dimensions, in product order. Choose a chain and strategy and step through products: the highlighted block is the last product formed. Bars compare total multiplications of the three strategies. Try the scalar-loss network, the scalar-input chain and the bottleneck, where neither extreme wins.

What the interactive shows:

  • Scalar-loss network (106→103→103→102→110^6 \to 10^3 \to 10^3 \to 10^2 \to 1): backward costs 1.00×1091.00\times 10^9 multiplications and never forms anything larger than a row vector of 10610^6 numbers; forward costs 1.10×10121.10\times 10^{12} and needs an intermediate product of 10910^9 numbers, about 4 GB (3.7 GiB) in float32. Over a thousand times more expensive, and too large for many GPUs. (J1\mat{J}_1 itself already has 10910^9 entries: the dense matrix model exaggerates the memory problem, which is why, as seen next, in practice nobody forms the Ji\mat{J}_i.)
  • Scalar input (1→102→103→1041 \to 10^2 \to 10^3 \to 10^4): the situation reverses. Forward, each step is a matrix times a column vector; backward forms J3J2∈R104×102\mat{J}_3\mat{J}_2 \in \R^{10^4\times 10^2}, one hundred times more expensive. This is sensitivity of an entire trajectory to a single parameter.
  • Bottleneck (102→103→1→103→10210^2 \to 10^3 \to 1 \to 10^3 \to 10^2): both extremes cost the same, 1.02×1071.02\times 10^7, and optimal order, 2.1×1052.1\times 10^5, about fifty times less: reduce each half of the chain to the bottleneck, J4J3∈R102×1\mat{J}_4\mat{J}_3 \in \R^{10^2\times 1} and J2J1∈R1×102\mat{J}_2\mat{J}_1 \in \R^{1\times 10^2}, and only form their product at the end. Generally, optimal matrix-chain order is a problem of dynamic programming over intervals, costing O(k3)\bigO(k^3) for kk factors.

In practice nobody forms the Ji\mat{J}_i. The Jacobian of a linear layer R103→R103\R^{10^3} \to \R^{10^3} with respect to its weight matrix has 103×10610^3 \times 10^6 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.

[ ]Association order, measuredBrowser
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 v⊤AB\vb{v}\T\mat{A}\mat{B} is (n3+n2)/(2n2)=(n+1)/2(n^3 + n^2)/(2n^2) = (n + 1)/2, 150.5150.5 with n=300n = 300, and measured times differ by over two orders of magnitude. You will calculate it for n=100n = 100 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 y=Wx+b\vb{y} = \mat{W}\vb{x} + \vb{b}, with W∈Rm×n\mat{W} \in \R^{m\times n}, viewed as a function of the three variables (x,W,b)(\vb{x}, \mat{W}, \vb{b}). Its differential is dy=W dx+dW x+dbd\vb{y} = \mat{W}\,d\vb{x} + d\mat{W}\,\vb{x} + d\vb{b}, already the JVP. For the VJP with covector yˉ\bar{\vb{y}}, measure the perturbation with it and rearrange each term to isolate each variable’s perturbation:

⟨yˉ,dy⟩=⟨W⊤yˉ,dx⟩+⟨yˉx⊤,dW⟩F+⟨yˉ,db⟩,\inner{\bar{\vb{y}}}{d\vb{y}} = \inner{\mat{W}\T\bar{\vb{y}}}{d\vb{x}} + \inner{\bar{\vb{y}}\vb{x}\T}{d\mat{W}}_F + \inner{\bar{\vb{y}}}{d\vb{b}},

because yˉ⊤dW x=∑ijyˉi dWij xj\bar{\vb{y}}\T d\mat{W}\,\vb{x} = \sum_{ij}\bar{y}_i\,dW_{ij}\,x_j. Therefore xˉ=W⊤yˉ\bar{\vb{x}} = \mat{W}\T\bar{\vb{y}}, Wˉ=yˉx⊤\bar{\mat{W}} = \bar{\vb{y}}\vb{x}\T and bˉ=yˉ\bar{\vb{b}} = \bar{\vb{y}}. The weight VJP is an outer product, costing mnmn, the same as the forward pass.

Elementwise activation. If h=σ(a)\vb{h} = \sigma(\vb{a}) componentwise, ∂hi/∂aj=0\partial h_i/\partial a_j = 0 for i≠ji \ne j and the Jacobian is diagonal, diag⁡(σ′(a))\diag(\sigma'(\vb{a})). Its JVP and VJP coincide: σ′(a)⊙v\sigma'(\vb{a}) \odot \vb{v}, costing O(n)\bigO(n) instead of O(n2)\bigO(n^2). For tanh⁡\tanh, σ′(a)=1−h2\sigma'(\vb{a}) = 1 - \vb{h}^2 is obtained from output without recomputation, so h\vb{h} is saved rather than a\vb{a}.

Softmax. With p=softmax⁡(z)\vb{p} = \softmax(\vb{z}), pi=ezi/∑kezkp_i = e^{z_i}/\sum_k e^{z_k}, the Jacobian is not diagonal, because every probability depends on all logits through the denominator. Try to predict each step:

log⁡pi=zi−log⁡∑kezk\log p_i = z_i - \log\textstyle\sum_k e^{z_k}
Differentiating the logarithm is cleaner than applying the quotient rule.
1/4

Matrix diag⁡(p)−pp⊤\diag(\vb{p}) - \vb{p}\vb{p}\T has a probabilistic interpretation: it is the covariance matrix of one-hot vector eY\vb{e}_Y when YY follows distribution p\vb{p}. It is therefore positive semidefinite, and J1=p−p(p⊤1)=0\mat{J}\vb{1} = \vb{p} - \vb{p}(\vb{p}\T\vb{1}) = \vb{0}: adding a constant to all logits does not change probabilities. If all pip_i are positive, the kernel is exactly the line generated by 1\vb{1} and the rank is n−1n - 1.

With temperature, p=softmax⁡(z/τ)\vb{p} = \softmax(\vb{z}/\tau), the chain rule adds factor 1/τ1/\tau: J=(diag⁡(p)−pp⊤)/τ\mat{J} = (\diag(\vb{p}) - \vb{p}\vb{p}\T)/\tau. If the largest logit exceeds the second by Δ>0\Delta > 0, each nonmaximum probability is at most e−Δ/τe^{-\Delta/\tau}, and every entry of J\mat{J} is bounded by (n−1) e−Δ/τ/τ(n-1)\,e^{-\Delta/\tau}/\tau, which tends to zero as τ→0\tau \to 0 (the exponential beats factor 1/τ1/\tau). Saturated softmax blocks the gradient.

InteractiveThe softmax Jacobian
Logits z\vb{z} (drag the bars)
2.01.00.4−0.5−1.2
p=softmax⁡(z/τ)\vb{p} = \softmax(\vb{z}/\tau), with τ=1.00\tau = 1.00
0.590.220.120.050.02
J=(diag⁡(p)−pp⊤)/τ\mat{J} = (\diag(\vb{p}) - \vb{p}\vb{p}\T)/\tau
0.24−0.13−0.07−0.03−0.01−0.130.17−0.03−0.01−0.01−0.07−0.030.11−0.010.00−0.03−0.01−0.010.050.00−0.01−0.010.000.000.021234512345
Red positive, blue negative; full color from ∣Jij∣=0.25\abs{J_{ij}} = 0.25.
JVP: Jv\mat{J}\vb{v} with v=\vb{v} = e1\vb{e}_1
0.242−0.128−0.070−0.029−0.014
VJP: u⊤J=p⊙(u−⟨u,p⟩1)/τ\vb{u}\T\mat{J} = \vb{p} \odot (\vb{u} - \inner{\vb{u}}{\vb{p}}\vb{1})/\tau, u=\vb{u} = mixed
0.276−0.224−0.0280.013−0.037
∑i(Jv)i=0.000,⟨u⊤J,1⟩=0.000\textstyle\sum_i (\mat{J}\vb{v})_i = 0.000, \qquad \inner{\vb{u}\T\mat{J}}{\vb{1}} = 0.000
1.00
JVP vector v\vb{v}
VJP covector u\vb{u}
max⁡ipi\max_i p_i0.591
∥J∥F\norm{\mat{J}}_F0.384
max⁡ij∣Jij∣\max_{ij} \abs{J_{ij}}0.242
Drag the logit bars and temperature. The heatmap is J=(diag⁡(p)−pp⊤)/τ\mat{J} = (\diag(\vb{p}) - \vb{p}\vb{p}\T)/\tau: positive diagonal (red), negative elsewhere (blue). Below, its action on vector v\vb{v} (JVP) and covector u\vb{u} (VJP), the latter computed without forming the matrix. Choose 1\vb{1} in either, then lower temperature to the minimum.

With the initial logits, ∥J∥F\norm{\mat{J}}_F is 0.3840.384 at temperature 11 and 0.2300.230 at temperature 0.30.3; at temperature 0.10.1 it falls to 0.00090.0009 and at 0.050.05 is of order 10−710^{-7}, while max⁡ipi\max_i p_i approaches 11. At high temperature the Jacobian also shrinks, but for another reason: p\vb{p} tends to uniform and J\mat{J} behaves like (I/n−11⊤/n2)/τ(\mat{I}/n - \vb{1}\vb{1}\T/n^2)/\tau. Both sums on the last line always vanish: that of Jv\mat{J}\vb{v} because probabilities sum to one and cannot all change in the same direction, and that of u⊤J\vb{u}\T\mat{J} because it is ⟨u,J1⟩=0\inner{\vb{u}}{\mat{J}\vb{1}} = 0.

Implementation from scratch: a hand-differentiated network

Now construct the gradient of L=12B∑b=1B∥f(xb)−yb∥2\Loss = \frac{1}{2B}\sum_{b=1}^{B}\norm{f(\vb{x}_b) - \vb{y}_b}^2 with f(x)=W2tanh⁡(W1x+b1)+b2f(\vb{x}) = \mat{W}_2\tanh(\mat{W}_1\vb{x} + \vb{b}_1) + \vb{b}_2 by chaining the three primitives’ VJPs. The code works on a batch of BB examples in rows, like PyTorch: a row x⊤\vb{x}\T maps to x⊤W⊤+b⊤\vb{x}\T\mat{W}\T + \vb{b}\T, and the preceding section’s formulas are transposed accordingly (Xˉ=YˉW\bar{\mat{X}} = \bar{\mat{Y}}\mat{W}, Wˉ=Yˉ⊤X\bar{\mat{W}} = \bar{\mat{Y}}\T\mat{X}, bˉ=Yˉ⊤1\bar{\vb{b}} = \bar{\mat{Y}}\T\vb{1}, the sum over the batch).

[ ]Primitives with forward and VJP, chained by handBrowser
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 10−1010^{-10}, 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:

[ ]Backward costs a small multiple of forwardBrowser
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:

[ ]Columns by JVP, rows by VJPBrowser
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 11. All operate on tensors and can be nested, enabling higher-order derivatives.

[ ]JVP and VJP in PyTorch versus our implementationLocal GPU
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")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

All six checks give True, and timings reproduce the cost interactive: for function R2000→R\R^{2000} \to \R, jacrev performs one VJP and jacfwd needs 20002000 JVPs; for R→R2000\R \to \R^{2000}, the reverse. jacfwd and jacrev vectorize those passes with vmap, so the expensive mode does not take 20002000 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

NumericDerivative along a circle
Let f(x,y)=x2yf(x, y) = x^2 y and curve γ(t)=(cos⁡t,sin⁡t)\gamma(t) = (\cos t, \sin t). Calculate ddtf(γ(t))\frac{d}{dt} f(\gamma(t)) at t=π/4t = \pi/4.
NumericPartial versus total
Let z=F(x,y)=x y2z = F(x, y) = x\,y^2 with y=exy = e^x. Calculate total derivative dz/dxdz/dx at x=1x = 1.
NumericTwo ways to calculate a covector
Let A,B∈R100×100\mat{A}, \mat{B} \in \R^{100\times 100} and v∈R100\vb{v} \in \R^{100}. Counting scalar multiplications for each matrix product (pqrpqr for p×qp\times q times q×rq\times r), what is the cost ratio of calculating v⊤(AB)\vb{v}\T(\mat{A}\mat{B}) to calculating (v⊤A)B(\vb{v}\T\mat{A})\mat{B}?
NumericWhose risk is it?
A portfolio invests w=(0.5,0.5)w = (0.5, 0.5) in two assets with volatilities 20% and 10% and correlation 0.30.3, that is, Σ=[0.040.0060.0060.01]\mat{\Sigma} = \begin{bmatrix} 0.04 & 0.006 \\ 0.006 & 0.01 \end{bmatrix}. What fraction of volatility σ(w)=w⊤Σw\sigma(\vb{w}) = \sqrt{\vb{w}\T\mat{\Sigma}\vb{w}} belongs to the first asset under Euler allocation, w1 ∂σ/∂w1w_1\,\partial\sigma/\partial w_1? Answer as a fraction between 0 and 1.
QuizShapes and mode
Let f:Rn→Rmf: \R^n \to \R^m be differentiable. Which statement is correct, and what is a reasonable way to obtain the gradient when m=1m = 1 and n=109n = 10^9?
QuizA gradient missing a path
In a language model with tied embeddings, the same matrix E\mat{E} encodes input tokens and projects the final state onto the vocabulary. When differentiating by hand, you sum only the output projection contribution. What will a central-difference gradient check show?
QuizA cold softmax
An attention mechanism uses softmax⁡(s/τ)\softmax(\vb{s}/\tau) and during training logits s\vb{s} become widely separated: the largest exceeds the second by Δ=20\Delta = 20, with τ=1\tau = 1. What happens to the gradient passing through that softmax?
CodeThe softmax VJP in O(n)
Implement softmax_vjp(z, v), returning v⊤Jsoftmax⁡(z)\vb{v}\T\mat{J}_{\softmax}(\vb{z}) as a NumPy array of the same shape as z, without forming the Jacobian: use v⊤J=p⊙(v−⟨v,p⟩1)\vb{v}\T\mat{J} = \vb{p}\odot(\vb{v} - \inner{\vb{v}}{\vb{p}}\vb{1}). Compute p\vb{p} stably (subtract the maximum before exponentiating). Tests compare against the full Jacobian in small dimension, test huge logits and measure time with n=2⋅105n = 2\cdot 10^5, where the Jacobian would have 4⋅10104\cdot 10^{10} entries.
import numpy as np

def softmax_vjp(z, v):
  """Devuelve vᵀ J_softmax(z) sin formar J."""
  pass
Shift+Enter to run

Summary

Key idea
The differential of a composition is the composition of differentials, and in coordinates the product of Jacobians, each evaluated at the point through which the chain passes. The product is associative, but its cost is not: a JVP pushes a perturbation forward and gives a Jacobian column; a VJP pulls a covector backward and gives a row. A scalar loss has one row, the gradient, obtained by one VJP with seed 1 for the price of a few model evaluations.
  • Chain rule: Jg∘f(x)=Jg(f(x)) Jf(x)\mat{J}_{g\circ f}(\vb{x}) = \mat{J}_g(f(\vb{x}))\,\mat{J}_f(\vb{x}) if ff is differentiable at x\vb{x} and gg at f(x)f(\vb{x}). The proof controls the remainder of gg evaluated at k(h)\vb{k}(\vb{h}), which may vanish; existence of partial derivatives is insufficient.
  • Special cases: ddtf(γ(t))=∇f⊤γ′\frac{d}{dt}f(\gamma(t)) = \grad f\T\gamma'; under a change of coordinates, gradients transform with J⊤\mat{J}\T. For ff homogeneous of degree kk, x⊤∇f=kf\vb{x}\T\grad f = k f (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: jvpf(x,v)=Jv\mathrm{jvp}_f(\vb{x}, \vb{v}) = \mat{J}\vb{v}, from input to output shape; vjpf(x,u)=J⊤u\mathrm{vjp}_f(\vb{x}, \vb{u}) = \mat{J}\T\vb{u}, 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, ∑inini−1n0\sum_i n_i n_{i-1} n_0; backward, ∑inknini−1\sum_i n_k n_i n_{i-1}. Scalar output, backward; scalar input, forward; with a bottleneck, dynamic programming.
  • Primitives: linear (xˉ=W⊤yˉ\bar{\vb{x}} = \mat{W}\T\bar{\vb{y}}, Wˉ=yˉx⊤\bar{\mat{W}} = \bar{\vb{y}}\vb{x}\T), elementwise (diagonal, σ′⊙yˉ\sigma'\odot\bar{\vb{y}}) and softmax (p⊙(pˉ−⟨pˉ,p⟩1)\vb{p}\odot(\bar{\vb{p}} - \inner{\bar{\vb{p}}}{\vb{p}}\vb{1}), vanishing under saturation). None forms its Jacobian.