Skip to content
Mathematical foundations Core 25 min read

The multivariable chain rule and Jacobians

The derivative of a composition is the product of the derivatives. When the functions take and return vectors, each derivative is a matrix, the Jacobian, and the chain rule becomes matrix multiplication. Backpropagation is just this product, evaluated from the loss end so that it never needs more than a vector at a time. That choice of order is why a billion-parameter gradient costs about as much as a couple of forward passes.

10,000 ft

A neural network is a long composition of simple functions, and its loss is one more function on the end. To train it you need the gradient of that scalar loss with respect to every parameter. The multivariable chain rule says this gradient is a product of Jacobian matrices, one per layer. Reverse-mode automatic differentiation (backpropagation) evaluates the product from the output backwards as a chain of vector–Jacobian products, which makes the gradient cost a small constant multiple of the forward pass whatever the number of parameters. Every framework (PyTorch autograd, JAX, TensorFlow, MLX) is built on this (autodiff, backpropagation). The same products explain vanishing and exploding gradients, why residual connections work (residual networks), and the Jacobian determinants in normalising flows.

2,000 ft

For \(f:\mathbb{R}^n\to\mathbb{R}^m\), the Jacobian \(J_f\in\mathbb{R}^{m\times n}\) holds every partial derivative \(\partial f_i/\partial x_j\); it is the matrix of the best linear approximation, \(f(\mathbf{x}+\mathbf{h})\approx f(\mathbf{x}) + J_f\mathbf{h}\). The chain rule: \(J_{f\circ g} = J_f\,J_g\). For a loss \(L = \ell(f_k(\cdots f_1(\mathbf{x})))\), the gradient is a row vector times a product of Jacobians. Multiplying from the right (forward mode) carries \(n\)-column matrices; multiplying from the left (reverse mode) carries a single row vector, the gradient so far. Each step is a vector–Jacobian product (VJP), computed without ever forming the Jacobian. When a variable feeds several later computations, its gradient is the sum over those paths.

Backprop: forward values left to right, VJPs right to left
Backprop: forward values left to right, VJPs right to left. x, h₁ = f₁(x), h₂ = f₂(h₁), L = ℓ(h₂), ḡ₂ = ∂L/∂h₂, ḡ₁ = ḡ₂ J₂, ∂L/∂x = ḡ₁ J₁, start: 1, VJP through f₂, VJP through f₁Backprop: forward values left to right, VJPs right to left. x, h₁ = f₁(x), h₂ = f₂(h₁), L = ℓ(h₂), ḡ₂ = ∂L/∂h₂, ḡ₁ = ḡ₂ J₂, ∂L/∂x = ḡ₁ J₁, start: 1, VJP through f₂, VJP through f₁

Ground level

The one-variable chain rule: rates multiply

If \(y = g(x)\) and \(z = f(y)\), then

\[ \frac{dz}{dx} = \frac{dz}{dy}\cdot\frac{dy}{dx} = f'(g(x))\,g'(x). \]

Think of gears: if \(y\) turns 3 times as fast as \(x\), and \(z\) turns 8 times as fast as \(y\), then \(z\) turns 24 times as fast as \(x\). Worked example: \(z = (3x+1)^2\) at \(x=1\). Inner \(y = 3x+1 = 4\), \(dy/dx = 3\); outer \(z = y^2\), \(dz/dy = 2y = 8\). So \(dz/dx = 24\). Expanding \(z = 9x^2+6x+1\) and differentiating gives \(18x+6 = 24\) at \(x=1\). ✓

In linear-approximation language: a small change \(h\) in \(x\) changes \(y\) by about \(g'(x)h\); that change in \(y\) changes \(z\) by about \(f'(y)\cdot g'(x)h\). Composing two linear approximations gives a linear approximation whose slope is the product. That sentence, with "slope" replaced by "matrix", is the multivariable chain rule.

Many paths: gradients add

Now let \(z\) depend on \(t\) through two intermediate variables, \(z = f(x(t), y(t))\). A small change in \(t\) moves both \(x\) and \(y\), and each movement changes \(z\). To first order the effects add:

\[ \frac{dz}{dt} = \frac{\partial f}{\partial x}\frac{dx}{dt} + \frac{\partial f}{\partial y}\frac{dy}{dt}. \]

The rule for any computation graph: the derivative along a path is the product of the local derivatives on its edges, and the total derivative is the sum over all paths. When one variable is used in several places (fan-out), its gradient is the sum of the gradients flowing back from each use. This is why the gradient of a broadcast is a sum (tensors) and why autodiff frameworks accumulate gradients with +=.

Worked example by hand. Let \(x=2\), \(y=3\) and compute

\[ q = x + y = 5,\qquad r = x\,y = 6,\qquad L = q\,r = 30 . \]

Backward, starting from \(\partial L/\partial L = 1\):

  • \(\partial L/\partial q = r = 6\) and \(\partial L/\partial r = q = 5\).
  • Through \(q = x+y\) (local derivatives 1 and 1): \(x\) gets \(6\), \(y\) gets \(6\).
  • Through \(r = xy\) (local derivatives \(y=3\) and \(x=2\)): \(x\) gets \(5\times3 = 15\), \(y\) gets \(5\times 2 = 10\).
  • Sum over paths: \(\partial L/\partial x = 6+15 = 21\), \(\partial L/\partial y = 6 + 10 = 16\).

Check: \(L = (x+y)xy = x^2y + xy^2\), so \(\partial L/\partial x = 2xy + y^2 = 12 + 9 = 21\) and \(\partial L/\partial y = x^2 + 2xy = 4+12 = 16\). ✓

The worked example as a graph: values forward, gradients backward
The worked example as a graph: values forward, gradients backward. x = 2 | ∂L/∂x = 6 + 15 = 21, y = 3 | ∂L/∂y = 6 + 10 = 16, q = x + y = 5 | ∂L/∂q = 6, r = x·y = 6 | ∂L/∂r = 5, L = q·r = 30 | ∂L/∂L = 1, local 1, local y = 3, local x = 2, local r = 6, local q = 5The worked example as a graph: values forward, gradients backward. x = 2 | ∂L/∂x = 6 + 15 = 21, y = 3 | ∂L/∂y = 6 + 10 = 16, q = x + y = 5 | ∂L/∂q = 6, r = x·y = 6 | ∂L/∂r = 5, L = q·r = 30 | ∂L/∂L = 1, local 1, local y = 3, local x = 2, local r = 6, local q = 5

Step through the same idea interactively. The widget runs the forward pass, then sends gradients back edge by edge:

The Jacobian

For a function with vector input and vector output, \(f:\mathbb{R}^n\to\mathbb{R}^m\), collect every partial derivative into an \(m\times n\) matrix:

\[ J_f(\mathbf{x}) = \begin{pmatrix} \dfrac{\partial f_1}{\partial x_1} & \cdots & \dfrac{\partial f_1}{\partial x_n}\\ \vdots & \ddots & \vdots\\ \dfrac{\partial f_m}{\partial x_1} & \cdots & \dfrac{\partial f_m}{\partial x_n} \end{pmatrix}, \qquad f(\mathbf{x}+\mathbf{h}) \approx f(\mathbf{x}) + J_f(\mathbf{x})\,\mathbf{h}. \]

Row \(i\) is the gradient of output \(i\); column \(j\) says how all outputs respond to input \(j\). The gradient of a scalar function is the special case \(m=1\) (a \(1\times n\) row, which we usually write as a column vector). The Jacobians you meet in every network:

Layer Function Jacobian w.r.t. its input Shape
Linear \(\mathbf{y} = W\mathbf{x}+\mathbf{b}\) \(W\) \(m\times n\)
Element-wise activation \(y_i = \phi(x_i)\) \(\operatorname{diag}(\phi'(\mathbf{x}))\) \(n\times n\), diagonal
Softmax \(\mathbf{p} = \operatorname{softmax}(\mathbf{z})\) \(\operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top\) \(n\times n\), symmetric
Residual block \(\mathbf{y} = \mathbf{x} + F(\mathbf{x})\) \(I + J_F\) \(n\times n\)
Sum / mean over \(n\) \(y = \sum_ix_i\) \(\mathbf{1}^\top\) \(1\times n\)

Softmax, worked. For \(\mathbf{z} = (2,1,0)\), \(\mathbf{p} \approx (0.665, 0.245, 0.090)\) and

\[ J = \operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top \approx \begin{pmatrix} 0.2227 & -0.1628 & -0.0599\\ -0.1628 & 0.1848 & -0.0220\\ -0.0599 & -0.0220 & 0.0819\end{pmatrix}. \]

Raising one logit raises its own probability and lowers all others, so off-diagonal entries are negative. Every row sums to zero, because the probabilities always sum to 1 so no logit change can alter the total. And \(J\mathbf{1} = \mathbf{0}\): adding the same constant to all logits changes nothing, which is why subtracting the maximum logit is a free stability trick (numerical computing).

The chain rule as matrix multiplication

If \(g:\mathbb{R}^n\to\mathbb{R}^k\) and \(f:\mathbb{R}^k\to\mathbb{R}^m\), then

\[ J_{f\circ g}(\mathbf{x}) = J_f(g(\mathbf{x}))\;J_g(\mathbf{x}) \qquad (m\times k)(k\times n) = (m\times n). \]

The local linear approximation of a composition is the composition of the local linear approximations, and composition of linear maps is matrix multiplication (matrices). The shapes check themselves. The earlier "sum over paths" rule is the same statement in index form: \((J_fJ_g)_{ij} = \sum_k \frac{\partial f_i}{\partial g_k}\frac{\partial g_k}{\partial x_j}\), a sum over every intermediate variable \(k\).

Forward mode versus reverse mode

Take a network \(L = \ell(f_k(\cdots f_2(f_1(\boldsymbol{\theta}))))\) with a scalar loss. By the chain rule its gradient (as a row) is

\[ \frac{\partial L}{\partial\boldsymbol{\theta}} = \underbrace{\nabla\ell^\top}_{1\times d}\;\underbrace{J_k}_{d\times d}\;J_{k-1}\cdots J_2\;\underbrace{J_1}_{d\times n}. \]

Matrix multiplication is associative, so we may bracket this however we like, and the bracketing decides the cost:

  • Forward mode brackets from the right: \(J_2J_1\), then \(J_3(J_2J_1)\), and so on. Every intermediate is a \(d\times n\) matrix. Equivalently, it pushes one input direction (a tangent vector) forward per pass: a Jacobian–vector product (JVP), \(J\mathbf{v}\). Getting the full gradient takes \(n\) such passes.
  • Reverse mode brackets from the left: \((\nabla\ell^\top J_k)\), then \((\cdot)J_{k-1}\), and so on. Every intermediate is a \(1\times d\) row vector: the gradient of the loss with respect to that layer's output. Each step is a vector–Jacobian product (VJP), \(\mathbf{u}^\top J\). One backward pass gives the gradient with respect to everything.

For \(k\) layers with \(d\times d\) Jacobians, reverse mode costs about \(2kd^2\) FLOPs; computing the full Jacobian product by forward mode costs about \(2kd^3\), a factor of \(d\) more (4,096× at \(d = 4096\)). The general rule: reverse mode wins when there are few outputs and many inputs (a scalar loss and a billion parameters: always the case in training), and forward mode wins when there are few inputs and many outputs (sensitivity of many quantities to one parameter). The price of reverse mode is memory: the backward pass needs the forward pass's intermediate values, so they are stored (activations), or recomputed (gradient checkpointing) when memory is tight (distributed training).

Never build the Jacobian

A VJP is almost always much cheaper than the Jacobian it multiplies. For an element-wise activation on a 4,096-vector, the Jacobian is a \(4096\times4096\) diagonal matrix (16.8 million entries, almost all zero), but the VJP is just g * phi_prime(x): 4,096 multiplications. For a linear layer the VJP is \(W^\top\mathbf{g}\). For softmax it is \(\mathbf{p}\odot(\mathbf{g} - (\mathbf{g}\cdot\mathbf{p})\mathbf{1})\), linear in \(n\), not quadratic. Autodiff frameworks store, for each primitive operation, a function that computes its VJP directly. They never materialise Jacobians.

Backprop through a two-layer network

Put it together for an MLP classifier with input \(\mathbf{x}\in\mathbb{R}^4\), a hidden ReLU layer of width 5 and 3 classes:

\[ \mathbf{z}_1 = W_1\mathbf{x}+\mathbf{b}_1,\quad \mathbf{h} = \operatorname{ReLU}(\mathbf{z}_1),\quad \mathbf{z}_2 = W_2\mathbf{h}+\mathbf{b}_2,\quad \mathbf{p} = \operatorname{softmax}(\mathbf{z}_2),\quad L = -\ln p_y . \]

The backward pass is one VJP per line, in reverse:

Step Gradient Rule used
1 \(\boldsymbol{\delta}_2 = \partial L/\partial\mathbf{z}_2 = \mathbf{p} - \mathbf{e}_y\) softmax + cross-entropy (derivatives)
2 \(\partial L/\partial W_2 = \boldsymbol{\delta}_2\mathbf{h}^\top\), \(\ \partial L/\partial\mathbf{b}_2 = \boldsymbol{\delta}_2\) linear layer, parameter side
3 \(\partial L/\partial\mathbf{h} = W_2^\top\boldsymbol{\delta}_2\) linear layer, input side (VJP with \(W_2\))
4 \(\boldsymbol{\delta}_1 = \partial L/\partial\mathbf{h}\odot[\mathbf{z}_1>0]\) ReLU: diagonal Jacobian (\([\cdot]\) is 1 where true, else 0)
5 \(\partial L/\partial W_1 = \boldsymbol{\delta}_1\mathbf{x}^\top\), \(\ \partial L/\partial\mathbf{b}_1 = \boldsymbol{\delta}_1\) linear layer, parameter side

Notice step 4: a hidden unit with \(z_1\le0\) passes back no gradient, so its incoming weights get no update from this example. In Build it, 3 of the 5 hidden units are inactive for the sampled input, and the corresponding rows of \(\partial L/\partial W_1\) are exactly zero. Units that are inactive for every input never recover: the "dying ReLU" problem.

Vanishing and exploding gradients

The gradient reaching layer 1 of a \(k\)-layer network is \(\nabla\ell^\top J_k\cdots J_2\). Norms of products behave roughly like products of norms, so if each Jacobian scales vectors by about \(s\), the gradient scales like \(s^k\). In the Build-it experiment, 50 random \(64\times64\) layer Jacobians with gain 0.8, 1.0 and 1.2 shrink or grow the gradient to:

gain per layer plain stack after 50 layers residual stack (\(I + 0.1J\))
0.8 \(9.0\times10^{-6}\) 1.19
1.0 0.75 1.20
1.2 \(8.7\times10^{3}\) 1.98

\(0.8^{50}\approx1.4\times10^{-5}\) and \(1.2^{50}\approx9{,}100\): the plain stack is exponential in depth. The fixes are all Jacobian engineering:

  • Initialisation chooses weight scales so that each layer's Jacobian preserves norms on average (initialisation and normalisation).
  • Normalisation layers (BatchNorm, LayerNorm, RMSNorm) keep activations, and hence the Jacobians of the layers that follow, in a healthy range.
  • Residual connections make each block's Jacobian \(I + J_F\). The product of such terms contains the identity path \(I\cdot I\cdots I\), so gradient can always reach early layers directly. He et al. (2016) write this out: the gradient at layer \(l\) is the gradient at the top plus terms through the residual branches, so it cannot vanish just because the branches are small. Transformers rely on the same structure (transformer block).
  • Gating in LSTMs creates an additive memory path with a Jacobian close to the identity (RNNs and LSTMs); gradient clipping caps explosions after the fact.

The Jacobian determinant: how volumes change

For a square Jacobian, \(\lvert\det J_f(\mathbf{x})\rvert\) is the factor by which \(f\) scales tiny volumes near \(\mathbf{x}\) (determinants). Polar coordinates are the classic example: \((x, y) = (r\cos\theta, r\sin\theta)\) has

\[ J = \begin{pmatrix}\cos\theta & -r\sin\theta\\ \sin\theta & r\cos\theta\end{pmatrix},\qquad\det J = r, \]

which is why \(dx\,dy = r\,dr\,d\theta\). In machine learning the same fact governs how probability densities transform: if \(\mathbf{x} = f(\mathbf{z})\) for an invertible \(f\), then

\[ \log p_X(\mathbf{x}) = \log p_Z(\mathbf{z}) - \log\left\lvert\det J_f(\mathbf{z})\right\rvert . \]

Normalising flows build \(f\) from layers whose Jacobians are triangular, so the determinant is the product of the diagonal and costs \(O(n)\) rather than \(O(n^3)\) (Dinh, Sohl-Dickstein and Bengio, 2016). Continuous-time versions replace the sum of log-determinants with an integral of a trace (Chen et al., 2018); flow-matching models inherit this view (score and flow matching).

Beyond first derivatives

  • Hessian–vector products. \(H\mathbf{v}\) is the JVP of the gradient function, so it costs only a small constant multiple of a gradient, without forming the \(n\times n\) Hessian (Pearlmutter, 1994). This is how researchers measure the top Hessian eigenvalue of a network (power iteration on \(H\mathbf{v}\); see edge of stability).
  • Jacobians with respect to inputs power saliency maps, adversarial attacks (derivatives and gradients) and Jacobian regularisation for robustness.
  • Composable transformations. JAX exposes grad, jvp, vjp, jacfwd, jacrev and hessian as functions you can nest; reading its autodiff cookbook is the best way to make forward vs reverse concrete.

History

From Leibniz to autograd

Leibniz wrote down the chain rule in the 1670s, and his notation \(\frac{dz}{dy}\frac{dy}{dx}\) makes it look like cancelling fractions. Carl Jacobi studied the determinants of these matrices of partial derivatives in the 1840s, hence "Jacobian". Reverse-mode differentiation of computer programs was described by Seppo Linnainmaa in his 1970 master's thesis; Paul Werbos proposed applying it to neural networks in 1974; Bert Speelpenning built an early automatic reverse-mode compiler around 1980; and Rumelhart, Hinton and Williams (1986) showed what it could learn, which made "backpropagation" famous. Andreas Griewank's work, collected in Evaluating Derivatives (Griewank and Walther), gave the theory its modern form. Deep-learning frameworks rediscovered and industrialised it: Theano (symbolic graphs), Autograd for NumPy (2015, the direct ancestor of JAX's interface), PyTorch's define-by-run autograd (2016–17) and JAX (2018). Baydin et al.'s survey tells the whole story.

First principles

Derive the chain rule from linear approximation. Suppose \(g(\mathbf{x}+\mathbf{h}) = g(\mathbf{x}) + A\mathbf{h} + o(\lVert\mathbf{h}\rVert)\) and \(f(\mathbf{y}+\mathbf{k}) = f(\mathbf{y}) + B\mathbf{k} + o(\lVert\mathbf{k}\rVert)\) with \(\mathbf{y} = g(\mathbf{x})\). Set \(\mathbf{k} = A\mathbf{h} + o(\lVert\mathbf{h}\rVert)\), which is \(O(\lVert\mathbf{h}\rVert)\). Then

\[ f(g(\mathbf{x}+\mathbf{h})) = f(\mathbf{y}) + B A\mathbf{h} + B\,o(\lVert\mathbf{h}\rVert) + o(\lVert\mathbf{k}\rVert) = f(g(\mathbf{x})) + BA\,\mathbf{h} + o(\lVert\mathbf{h}\rVert). \]

So the composition is differentiable with derivative \(BA\). Nothing more is needed: "derivative = best linear approximation" plus "linear maps compose by multiplication" is the chain rule.

Why reverse mode is cheap: the cheap gradient principle. Each primitive operation \(\mathbf{y} = \phi(\mathbf{x})\) in a program has a VJP whose cost is a small constant multiple of evaluating \(\phi\) itself (a matmul's VJP is two matmuls; an element-wise op's VJP is an element-wise op). The backward pass visits each primitive once. So the whole gradient costs a small constant multiple of the forward computation, independent of how many inputs there are: a result made precise by Baur and Strassen (1983) and Griewank. For matmul-dominated networks the backward pass is about twice the forward FLOPs, which is the origin of the "about 6 FLOPs per parameter per token" rule for training (matrices).

Why gradients add at a fork. If \(\mathbf{x}\) is copied to two places, the copy is the linear map \(\mathbf{x}\mapsto(\mathbf{x},\mathbf{x})\) with Jacobian \(\begin{pmatrix}I\\I\end{pmatrix}\). Its VJP takes \((\mathbf{g}_1,\mathbf{g}_2)\) to \(\begin{pmatrix}I & I\end{pmatrix}\begin{pmatrix}\mathbf{g}_1\\\mathbf{g}_2\end{pmatrix} = \mathbf{g}_1 + \mathbf{g}_2\). Summing is the transpose of copying, as reducing is the transpose of broadcasting.

What breaks if a function is not differentiable? The chain rule needs a linear approximation at every step. A step function (rounding, argmax, sampling a discrete token) has zero derivative almost everywhere and none at its jumps, so the gradient through it is useless. Practitioners route around it: replace argmax by softmax, use the straight-through estimator (pretend the derivative is 1), use the reparameterisation trick for continuous sampling (VAEs) or the score-function (REINFORCE) estimator for discrete choices (policy gradients).

The maths

Jacobian. For \(f:\mathbb{R}^n\to\mathbb{R}^m\) differentiable at \(\mathbf{x}\): \(J_f(\mathbf{x})\in\mathbb{R}^{m\times n}\), \([J_f]_{ij} = \partial f_i/\partial x_j\), and \(f(\mathbf{x}+\mathbf{h}) = f(\mathbf{x}) + J_f(\mathbf{x})\mathbf{h} + o(\lVert\mathbf{h}\rVert)\).

Chain rule. \(J_{f\circ g}(\mathbf{x}) = J_f(g(\mathbf{x}))\,J_g(\mathbf{x})\). In index form, \(\dfrac{\partial(f\circ g)_i}{\partial x_j} = \sum_k\dfrac{\partial f_i}{\partial y_k}\dfrac{\partial g_k}{\partial x_j}\).

JVP and VJP. \(\operatorname{jvp}(f, \mathbf{x}, \mathbf{v}) = J_f(\mathbf{x})\mathbf{v}\in\mathbb{R}^m\) (push a tangent forward); \(\operatorname{vjp}(f,\mathbf{x},\mathbf{u}) = \mathbf{u}^\top J_f(\mathbf{x})\in\mathbb{R}^{1\times n}\) (pull a cotangent back). For a scalar loss, \(\nabla_{\mathbf{x}}L = \operatorname{vjp}(\cdot)\) chained from \(\mathbf{u} = 1\).

Derivation: the softmax Jacobian

\(p_i = e^{z_i}/S\) with \(S = \sum_ke^{z_k}\). By the quotient rule,

\[ \frac{\partial p_i}{\partial z_j} = \frac{\delta_{ij}e^{z_i}S - e^{z_i}e^{z_j}}{S^2} = p_i\delta_{ij} - p_ip_j , \]

so \(J = \operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top\). Its VJP with an upstream gradient \(\mathbf{g}\) is \(\mathbf{g}^\top J = (\mathbf{g}\odot\mathbf{p})^\top - (\mathbf{g}\cdot\mathbf{p})\,\mathbf{p}^\top\), i.e. \(\mathbf{p}\odot(\mathbf{g} - (\mathbf{g}\cdot\mathbf{p})\mathbf{1})\): \(O(n)\) work. Chaining with cross-entropy, \(\mathbf{g} = \partial L/\partial\mathbf{p} = -\mathbf{e}_y/p_y\), gives \(\mathbf{g}\cdot\mathbf{p} = -1\) and so \(\partial L/\partial\mathbf{z} = \mathbf{p}\odot(-\mathbf{e}_y/p_y + \mathbf{1}) = \mathbf{p} - \mathbf{e}_y\): the same result as the direct derivation on the previous page.

Derivation: backprop for a layer, in matrix form for a batch

Forward for a batch of \(B\) rows: \(Z = XW^\top + \mathbf{1}\mathbf{b}^\top\) with \(X\in\mathbb{R}^{B\times n}\), \(W\in\mathbb{R}^{m\times n}\); \(H = \phi(Z)\). Given \(\bar H = \partial L/\partial H\in\mathbb{R}^{B\times m}\):

\[ \bar Z = \bar H\odot\phi'(Z),\qquad \bar W = \bar Z^\top X\ (m\times n),\qquad \bar{\mathbf{b}} = \bar Z^\top\mathbf{1}\ (m),\qquad \bar X = \bar ZW\ (B\times n). \]

Each is the per-example rule from the table above, summed over the batch for the parameters (they are shared by all rows: fan-out, so gradients add) and kept per-row for \(\bar X\). Checking shapes is a complete proof-reading strategy: \(\bar W\) must be \(m\times n\), and \(\bar Z^\top X\) is the only product of the available matrices with that shape.

Derivation: why residual connections protect the gradient

With \(\mathbf{x}_{l+1} = \mathbf{x}_l + F_l(\mathbf{x}_l)\), unrolling gives \(\mathbf{x}_L = \mathbf{x}_l + \sum_{i=l}^{L-1}F_i(\mathbf{x}_i)\). Differentiating,

\[ \frac{\partial L}{\partial\mathbf{x}_l} = \frac{\partial L}{\partial\mathbf{x}_L}\left(I + \frac{\partial}{\partial\mathbf{x}_l}\sum_{i=l}^{L-1}F_i(\mathbf{x}_i)\right). \]

The identity term delivers \(\partial L/\partial\mathbf{x}_L\) to every layer unchanged; the branch terms add to it. For the whole bracket to cancel, the branch Jacobians would have to sum to exactly \(-I\), which is unlikely. This is the argument of He et al. (2016), Section 2.

Build it

NumPy: the softmax Jacobian against finite differences, a hand-written backward pass for a two-layer MLP with a gradient check, and the vanishing/exploding experiment.

import numpy as np
rng = np.random.default_rng(0)

def softmax(z):
    e = np.exp(z - z.max())
    return e / e.sum()

# 1. The softmax Jacobian: analytic diag(p) - p p^T vs finite differences
z = np.array([2.0, 1.0, 0.0])
p = softmax(z)
J = np.diag(p) - np.outer(p, p)
J_num = np.column_stack([(softmax(z + e) - softmax(z - e)) / 2e-6 for e in 1e-6 * np.eye(3)])
print("p =", p.round(3))
print("J =\n", J.round(4), "\nmax |J - J_num| =", f"{np.abs(J - J_num).max():.1e}")
g = np.array([1.0, 0.0, 0.0])                     # upstream gradient dL/dp
print("VJP g^T J =", (g @ J).round(4), "  same as p*(g - g.p):", (p * (g - g @ p)).round(4))

# 2. Backprop through a 2-layer MLP by hand, checked numerically
x, y = rng.standard_normal(4), 2                  # one input, target class 2
W1, b1 = rng.standard_normal((5, 4)) * 0.5, np.zeros(5)
W2, b2 = rng.standard_normal((3, 5)) * 0.5, np.zeros(3)

def forward(W1):
    z1 = W1 @ x + b1; h = np.maximum(z1, 0)
    z2 = W2 @ h + b2; p = softmax(z2)
    return -np.log(p[y]), (z1, h, p)

L, (z1, h, p) = forward(W1)
d2 = p.copy(); d2[y] -= 1                          # dL/dz2 = p - onehot(y)
dW2 = np.outer(d2, h)                              # dL/dW2 = d2 h^T
dh = W2.T @ d2                                     # VJP through the linear layer
d1 = dh * (z1 > 0)                                 # VJP through ReLU: diagonal Jacobian
dW1 = np.outer(d1, x)
i = int(np.argmax(z1 > 0))                         # first active hidden unit
E = np.zeros_like(W1); E[i, 2] = 1e-6              # check one entry of dW1
print(f"loss {L:.4f}  active units {(z1 > 0).astype(int)}")
print(f"dW1[{i},2] analytic {dW1[i, 2]:.6f}  numeric {(forward(W1 + E)[0] - forward(W1 - E)[0]) / 2e-6:.6f}")

# 3. Products of Jacobians: vanish, explode, or stay healthy with residuals
d, depth = 64, 50
for scale in [0.8, 1.0, 1.2]:
    v_plain = v_res = np.ones(d) / np.sqrt(d)
    for _ in range(depth):
        Jl = rng.standard_normal((d, d)) * scale / np.sqrt(d)    # a layer's Jacobian
        v_plain = Jl.T @ v_plain                                  # plain stack
        v_res = (np.eye(d) + 0.1 * Jl).T @ v_res                  # residual: I + small branch
    print(f"scale {scale}: |grad| after {depth} layers  plain {np.linalg.norm(v_plain):.2e}  residual {np.linalg.norm(v_res):.2f}")

Output:

p = [0.665 0.245 0.09 ]
J =
 [[ 0.2227 -0.1628 -0.0599]
 [-0.1628  0.1848 -0.022 ]
 [-0.0599 -0.022   0.0819]] 
max |J - J_num| = 6.3e-11
VJP g^T J = [ 0.2227 -0.1628 -0.0599]   same as p*(g - g.p): [ 0.2227 -0.1628 -0.0599]
loss 1.1229  active units [1 0 0 1 0]
dW1[0,2] analytic 0.077729  numeric 0.077729
scale 0.8: |grad| after 50 layers  plain 8.99e-06  residual 1.19
scale 1.0: |grad| after 50 layers  plain 7.52e-01  residual 1.20
scale 1.2: |grad| after 50 layers  plain 8.73e+03  residual 1.98

Only hidden units 0 and 3 are active for this input, so rows 1, 2 and 4 of dW1 are exactly zero: ReLU's diagonal Jacobian has zeros there. The finite-difference check uses an entry of an active unit; checking an inactive one would compare two zeros and prove nothing, which is a real trap in gradient checking.

Things to try

  • Extend the MLP check to every entry of W1, b1, W2 and b2 and report the maximum relative error.
  • Implement a tiny reverse-mode autodiff: a Value class storing data, grad and a _backward closure, with +, * and relu, and a backward() that visits nodes in reverse topological order. Verify it on the \(q = x+y\), \(r = xy\), \(L = qr\) example (21 and 16). This is micrograd; the project page walks through it.
  • Compute the full Jacobian of a 3-layer tanh network two ways: by stacking JVPs with the unit vectors (forward mode, one per input) and by stacking VJPs (reverse mode, one per output). Time both for (inputs, outputs) = (1000, 1) and (1, 1000).
  • In the vanishing-gradient experiment, replace the random Jacobians with \(\operatorname{diag}(\sigma'(\mathbf{z}))W\) for sigmoid units. What is the best possible gain per layer, given \(\sigma'\le 1/4\)?
  • Estimate the top eigenvalue of the Hessian of the logistic-regression loss from the previous page with power iteration on finite-difference Hessian–vector products, \(H\mathbf{v}\approx(\nabla L(\mathbf{w}+\epsilon\mathbf{v}) - \nabla L(\mathbf{w}-\epsilon\mathbf{v}))/2\epsilon\).

Common misconceptions

  • "Backprop is a special neural-network algorithm." It is reverse-mode automatic differentiation, which applies to any program built from differentiable pieces, and it predates its use in neural networks.
  • "Autodiff is symbolic or numerical differentiation." Neither. Symbolic differentiation manipulates formulas (and can blow up in size); numerical differentiation uses finite differences (and is approximate and slow). Autodiff applies the chain rule to the actual operations executed, giving exact derivatives (up to floating point) at a small constant multiple of the cost.
  • "Backprop computes Jacobian matrices." It computes vector–Jacobian products and never forms the Jacobians.
  • "Gradients vanish because of sigmoids." Saturating activations make it worse, but the root cause is a long product of Jacobians whose gains are not close to 1, which can happen with any activation.

Check yourself

z = sin(x²). Use the chain rule to find dz/dx at x = √(π/3).

\(dz/dx = \cos(x^2)\cdot 2x\). At \(x^2 = \pi/3\): \(\cos(\pi/3) = 1/2\), so \(dz/dx = 2x/2 = x = \sqrt{\pi/3}\approx1.023\).

f(x, y) = (xy, x + y, x²). Write the Jacobian at (1, 2) and give its shape.

Rows are gradients of each output: \((y, x) = (2, 1)\); \((1, 1)\); \((2x, 0) = (2, 0)\). So \(J = \begin{pmatrix}2&1\\1&1\\2&0\end{pmatrix}\), shape \(3\times2\) (outputs × inputs).

A network maps 10⁹ parameters to a scalar loss. Why is reverse mode used rather than forward mode?

Reverse mode needs one backward pass (a constant multiple of the forward cost) for the gradient with respect to all \(10^9\) parameters. Forward mode needs one pass per input direction, i.e. \(10^9\) passes.

What is the VJP of y = tanh(x) (element-wise) with upstream gradient g, and how many FLOPs does it need for n = 4096?

\(\bar{\mathbf{x}} = \mathbf{g}\odot(1-\tanh^2\mathbf{x}) = \mathbf{g}\odot(1-\mathbf{y}^2)\): a few FLOPs per element, roughly \(3n\approx 12{,}000\), versus about \(2n^2\approx3.4\times10^7\) to multiply by the dense diagonal Jacobian.

In the worked example (q = x + y, r = xy, L = qr), what would ∂L/∂x be if you forgot to add the contributions from the two paths?

You would report only 6 (via \(q\)) or only 15 (via \(r\)) instead of 21. Missing an accumulation is the classic manual-backprop bug, and the reason frameworks accumulate .grad with += (and why you must zero gradients between steps).

Show that every row of the softmax Jacobian sums to zero, and explain what that means.

Row \(i\) sums to \(p_i - p_i\sum_jp_j = p_i - p_i = 0\). Adding the same amount to every logit (the direction \(\mathbf{1}\)) leaves the probabilities unchanged: softmax is invariant to shifts.

Hard: a normalising-flow layer is y = x ⊙ exp(s(x₁)) on the second half of x, leaving the first half x₁ unchanged. Why is its log-determinant cheap?

The Jacobian is block lower-triangular: \(\partial\mathbf{y}_1/\partial\mathbf{x}_1 = I\), \(\partial\mathbf{y}_1/\partial\mathbf{x}_2 = 0\), and \(\partial\mathbf{y}_2/\partial\mathbf{x}_2 = \operatorname{diag}(\exp s(\mathbf{x}_1))\). The determinant of a triangular matrix is the product of its diagonal, so \(\log\lvert\det J\rvert = \sum_i s_i(\mathbf{x}_1)\): \(O(n)\), and the complicated block \(\partial\mathbf{y}_2/\partial\mathbf{x}_1\) never matters. This is the Real NVP coupling layer.

Hard: why does gradient checkpointing trade compute for memory, and roughly how much?

Reverse mode needs every layer's forward activations to evaluate its VJP. Checkpointing stores only some of them (say every \(\sqrt{k}\)-th layer of \(k\)) and recomputes the rest from the nearest checkpoint during the backward pass. Memory falls from \(O(k)\) to about \(O(\sqrt{k})\) activations, at the cost of roughly one extra forward pass.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Code

  • micrograd — Andrej Karpathy. A complete scalar reverse-mode autodiff engine in about a hundred lines.

Where this leads