Matrix calculus and backprop: Jacobians, layouts, vector-Jacobian products, autodiff

Reading: 32 min, plus 22 in closed details. The shape of every derivative, the chain rule as Jacobian products, why reverse mode wins for one loss, backprop through a two-layer network by hand, the layer gradients ML needs, what the backward pass costs and keeps, and how to check a gradient. A child page of Topic: math; data as of October 2026.

The idea in one screen

Training needs the slope of one scalar loss with respect to every parameter. Backpropagation is the chain rule multiplied from the loss end: each layer turns the gradient at its output into the gradient at its input with one vector-Jacobian product (VJP), never building the Jacobian, so every slope comes out of one backward pass that costs about twice the forward pass in FLOPs and is paid for by keeping the forward pass's activations.

  1. Forward: values flow left to right (green). x=(2,1)x = (2, 1) passes through the glass plate W1W_1 to give aa, the ReLU gives hh, W2W_2 gives the scores zz, and softmax with cross-entropy gives the loss LL. Orange plinths mark what the pass must keep: xx, the sign of aa, hh and pp.
  2. The backward pass starts at the loss. L‾=1\bar L = 1, and softmax with cross-entropy hands back z‾=p−y\bar z = p - y in one step (section 6d).
  3. One VJP per layer, back through the same plates. z‾\bar z goes back through W2⊤W_2^\top to h‾\bar h, through the ReLU's mask to a‾\bar a, through W1⊤W_1^\top to x‾\bar x: each blue stream is one VJP, a matrix-vector product with a stored value, not a Jacobian.
  4. Each weight gradient is an outer product, shaped like its weight. W‾2=z‾h⊤\bar W_2 = \bar z\,h^\top (3 × 3) and W‾1=a‾x⊤\bar W_1 = \bar a\,x^\top (3 × 2): the gradient arriving at the layer (blue) times the input the layer kept (green).
  5. The price. The backward pass did 30 matrix-product multiply-adds to the forward pass's 15 (section 8's factor of two), and every orange plinth stayed in memory from its forward step until the backward pass used it (section 9).

The two-layer network of section 5, where every number is worked out; bar heights are its real values and gradients.

You need: derivatives, the one-variable chain rule and the tiny model's loss (the root, Topic: math, Reading sections 2 and 3); matrix products and transposes (Linear algebra for ML). The losses themselves are on Loss functions, what happens to the gradient next on Optimisers and learning-rate schedulers, PyTorch's autograd engine on Tensors, the dispatcher and autograd and JAX's transforms on JAX core.

Jacobian JJ
every output's slope with respect to every input: outputs by inputs, m×nm \times n.
Layout
which way round a derivative table is written; numerator (Jacobian, m×nm \times n) or denominator (gradient, n×mn \times m).
v‾\bar v, the adjoint
the gradient of the loss with respect to vv, shaped like vv.
VJP, JVP
vector-Jacobian product J⊤y‾J^\top \bar y (reverse mode, one output, every input) and Jacobian-vector product JuJ u (forward mode, one input direction, every output).
Activation (saved)
a forward value a backward rule needs, kept until the backward pass reaches it.
Checkpointing
keeping only some activations and recomputing the rest during the backward pass.
The running example
The same tiny next-token model as the root page: the context "the cat" is the input x=(2,1)x = (2, 1), the weight matrix WW has one row per word, cat (1,0)(1, 0), dog (0,1)(0, 1), sat (1,−2)(1, -2), the scores are z=Wx=(2,1,0)z = Wx = (2, 1, 0), softmax turns them into probabilities p=(0.665,0.245,0.090)p = (0.665, 0.245, 0.090), and the right next word is sat, so the loss is L=−ln⁡0.090=2.408L = -\ln 0.090 = 2.408. Every formula below is tried on these numbers first.

1. The shape of every derivative: gradients and Jacobians

For a scalar LL of a vector or a matrix, the gradient holds one partial derivative per entry, laid out like the variable. Rule: the gradient of a scalar has the shape of the thing you differentiate with respect to. It is the most useful sanity check in this whole subject, and it is exactly what PyTorch stores in W.grad: for the tiny model's 3×23 \times 2 weight, ∇WL\nabla_W L is 3×23 \times 2. With respect to the scores, the root page derives ∇zL=p−y=(0.665,0.245,−0.910)\nabla_z L = p - y = (0.665, 0.245, -0.910): raising the cat score by a small ε\varepsilon raises the loss by about 0.665ε0.665\varepsilon; raising the sat score lowers it by about 0.910ε0.910\varepsilon.

A function f:ℝn→ℝmf: \mathbb{R}^n \to \mathbb{R}^m has one slope per (output, input) pair. Arranged with one row per output, they form the Jacobian:

J=∂f∂x,Jij=∂fi∂xj,J is m×n,f(x+δ)≈f(x)+JδJ = \frac{\partial f}{\partial x}, \qquad J_{ij} = \frac{\partial f_i}{\partial x_j}, \quad J \text{ is } m \times n, \qquad f(x + \delta) \approx f(x) + J\delta

Row ii is the gradient of output ii, laid flat; column jj says how every output responds when only input jj moves. Three Jacobians cover most of a network:

  • A linear map z=Wxz = Wx: ∂zi/∂xj=Wij\partial z_i/\partial x_j = W_{ij}, so J=WJ = W, here 3×23 \times 2.
  • An elementwise function h=ϕ(a)h = \phi(a) (ReLU, tanh): output ii depends only on input ii, so J=diag⁡(ϕ′(a))J = \operatorname{diag}(\phi'(a)).
  • Softmax pi=ezi/∑kezkp_i = e^{z_i}/\sum_k e^{z_k}: ∂pi/∂zj=pi(δij−pj)\partial p_i/\partial z_j = p_i(\delta_{ij} - p_j), so J=diag⁡(p)−pp⊤J = \operatorname{diag}(p) - p\,p^\top, with the Kronecker delta δij\delta_{ij} (1 if i=ji = j, else 0) and the outer product pp⊤p\,p^\top.
The softmax Jacobian on the tiny model, p=(0.665,0.245,0.090)p = (0.665, 0.245, 0.090)
∂/∂zcat\partial / \partial z_{\text{cat}}∂/∂zdog\partial / \partial z_{\text{dog}}∂/∂zsat\partial / \partial z_{\text{sat}}
pcatp_{\text{cat}}0.2227−0.1628−0.0599
pdogp_{\text{dog}}−0.16280.1848−0.0220
psatp_{\text{sat}}−0.0599−0.02200.0819
Each row adds up to 0: the probabilities always add up to 1, so no change of scores can change their total. The table is symmetric, and the sat diagonal entry, 0.0819, is the p(1−p)p(1 - p) the root page used in its chain-rule example.
Softmax's Jacobian, derived without skipping a step (2 min)

Write pi=ezi/Sp_i = e^{z_i}/S with S=∑kezkS = \sum_k e^{z_k}. For the same index, the quotient rule (top' times bottom minus top times bottom', over bottom squared), with ∂ezi/∂zi=ezi\partial e^{z_i}/\partial z_i = e^{z_i} and ∂S/∂zi=ezi\partial S/\partial z_i = e^{z_i}:

∂pi∂zi=eziS−ezieziS2=pi−pi2=pi(1−pi)\frac{\partial p_i}{\partial z_i} = \frac{e^{z_i} S - e^{z_i} e^{z_i}}{S^2} = p_i - p_i^2 = p_i(1 - p_i)

For a different index j≠ij \ne i, the top does not move, the bottom does:

∂pi∂zj=0⋅S−eziezjS2=−pipj\frac{\partial p_i}{\partial z_j} = \frac{0 \cdot S - e^{z_i} e^{z_j}}{S^2} = -p_i p_j

Both cases at once: ∂pi/∂zj=pi(δij−pj)\partial p_i/\partial z_j = p_i(\delta_{ij} - p_j), that is Jsoftmax=diag⁡(p)−pp⊤J_{\text{softmax}} = \operatorname{diag}(p) - p\,p^\top, where the outer product is a column times a row, a square table whose entry (i,j)(i, j) is pipjp_i p_j.

The shape of every derivative. The derivative of something with aa entries with respect to something with bb entries holds a×ba \times b numbers (WW here is p×qp \times q):

derivative of ... with respect to ...scalar ttvector xx (nn)matrix WW (p×qp \times q)
scalar LLscalarvector, nn (the gradient)matrix, p×qp \times q
vector zz (mm)vector, mmmatrix, m×nm \times n (the Jacobian)3-index array, m×p×qm \times p \times q
matrix YY (r×sr \times s)matrix, r×sr \times s3-index array4-index array, r×s×p×qr \times s \times p \times q

The bottom-right corner is where matrix calculus gets its reputation, and ML never needs it: the loss is a scalar, so the only derivatives that must be stored are in the top row, each shaped like its parameter. The big arrays appear only in the middle of the chain rule, and section 3 shows they can always be skipped.

  1. ∂z/∂x\partial z/\partial x is WW itself. x=(2,1)x = (2, 1) passes through the plate WW to give z=(2,1,0)z = (2, 1, 0). Laid flat in front, the Jacobian's six entries: one row per score, one column per input, J=WJ = W, 3 × 2.
  2. Softmax's Jacobian is 3 × 3, symmetric, and each row adds up to 0. diag⁡(p)−pp⊤\operatorname{diag}(p) - p\,p^\top at p=(0.665,0.245,0.090)p = (0.665, 0.245, 0.090): positive on the diagonal, negative (paler bars) off it; the numbers are in the table above.
  3. With respect to a matrix, a 3-index array that is mostly zeros. ∂z/∂W\partial z/\partial W has 3×3×2=183 \times 3 \times 2 = 18 entries, ∂zi/∂Wkl=δikxl\partial z_i / \partial W_{kl} = \delta_{ik}\, x_l: one 3 × 2 slice per score, zero except its own row, which is x=(2,1)x = (2, 1). Score ii depends only on row ii of WW, so twelve of the 18 are zero. For one real layer with a 4096×40964096 \times 4096 weight the same array would have 40963≈6.9×10104096^3 \approx 6.9 \times 10^{10} entries, almost all zero.
  4. Training keeps only the top row. The backward pass weights each slice by its score's gradient z‾=(0.665,0.245,−0.910)\bar z = (0.665, 0.245, -0.910) and adds them up: W‾=z‾x⊤\bar W = \bar z\,x^\top, 3 × 2 like WW, −1.820-1.820 at (sat, 1). The 18-number array is never built (section 3 shows why it never has to be).
Refresher: partial derivatives and the gradient on a function of two numbers (2 min)

Think of f(x1,x2)f(x_1, x_2) as the height of a landscape. The slope walking due east (only x1x_1 changes) and due north (only x2x_2) are the partial derivatives; every other direction's slope is a mix of them. Stacking them gives ∇xf\nabla_x f, and the best linear prediction of a small step δ\delta is f(x+δ)≈f(x)+∇xf⋅δf(x + \delta) \approx f(x) + \nabla_x f \cdot \delta. The slope along a unit direction uu, the directional derivative, is ∇xf⋅u\nabla_x f \cdot u; it is largest along the gradient, which is why training steps the other way.

Worked example: f(x1,x2)=x12+3x1x2f(x_1, x_2) = x_1^2 + 3x_1x_2 at x=(2,1)x = (2, 1), where f=4+6=10f = 4 + 6 = 10. ∂f/∂x1=2x1+3x2=7\partial f/\partial x_1 = 2x_1 + 3x_2 = 7 and ∂f/∂x2=3x1=6\partial f/\partial x_2 = 3x_1 = 6, so ∇f=(7,6)\nabla f = (7, 6). Prediction for δ=(0.01,0)\delta = (0.01, 0): 10+7×0.01=10.0710 + 7 \times 0.01 = 10.07; the exact value is 2.012+3×2.01=10.07012.01^2 + 3 \times 2.01 = 10.0701. Along u=(0.6,0.8)u = (0.6, 0.8) the slope is 7×0.6+6×0.8=9.07 \times 0.6 + 6 \times 0.8 = 9.0, a little under the steepest possible slope ‖∇f‖=85=9.22\lVert \nabla f \rVert = \sqrt{85} = 9.22.

What gradients are used for in ML: every optimiser step (W←W−η∇WLW \leftarrow W - \eta \nabla_W L, learning rate η\eta); gradient norms for clipping and for spotting exploding or vanishing training; saliency maps (the gradient of a class score with respect to the input pixels or tokens).

2. Numerator and denominator layout: why papers disagree

A paper writes ∂L/∂W\partial L/\partial W and its shape is the transpose of W.grad. Neither is wrong: the slopes are the same numbers, written the other way round.

Numerator layout (the Jacobian convention)

Rows follow the thing on top: ∂y/∂x\partial y/\partial x is m×nm \times n, the Jacobian of section 1. A scalar's derivative with respect to a vector is a row (1×n1 \times n). The chain rule reads left to right in the order of the composition, with no transposes.

Denominator layout (the gradient convention)

Rows follow the thing underneath: ∂y/∂x\partial y/\partial x is n×mn \times m, the transpose. A scalar's derivative with respect to a vector is a column shaped like xx, which is what an update x←x−η∇xLx \leftarrow x - \eta \nabla_x L needs.

What frameworks do. A parameter's gradient (W.grad, jax.grad's output) always has the parameter's own shape, which for a scalar loss is the denominator layout. A full Jacobian comes back outputs first: torch.func.jacrev(f)(x) and jax.jacrev return an array of shape (output shape, then input shape), the numerator layout. This page makes the same choice: gradients in the parameter's shape, Jacobians as outputs by inputs.

The working rule
Derive in whichever layout you like, but never mix them in one derivation. Then check the shape: a scalar's gradient has the shape of the parameter. If yours is the transpose, transpose it and test one entry with a finite difference (section 11). The shapes alone nearly force many answers: for the squared error L=‖Wx−y‖2L = \lVert Wx - y \rVert^2 with WW of shape 3×23 \times 2, the only way to make 3×23 \times 2 from a 3-vector and a 2-vector is the outer product, ∇WL=2(Wx−y)x⊤\nabla_W L = 2(Wx - y)\,x^\top.
Correction to the old Linear algebra page
The old page said numerator layout is "used by MML book, most papers". The MML book half is right (quoted below); "most papers" is not supported by any source found: the conventions are mixed within fields and often within one paper.
Who uses which, in their own words; the squared error checked (2 min)

There is no field-wide standard. Wikipedia's survey: "even within a given field different authors can be found using competing conventions. Authors of both groups often write as though their specific conventions were standard", and "some choose denominator layout for gradients (laying them out as column vectors), but numerator layout for the vector-by-vector derivative" (Wikipedia, Matrix calculus, Layout conventions). Two of the best-known ML texts use numerator layout and say so: Deisenroth, Faisal and Ong, "In this book, we use the numerator layout of the derivative" (Mathematics for Machine Learning, section 5.3, p. 150; they also write the gradient as a row vector, Eq. 5.40), and Parr and Howard, "We are using the so-called numerator layout but many papers and software will use the denominator layout" (The Matrix Calculus You Need For Deep Learning, section 4). Their reason is the chain rule: in numerator layout it reads left to right with no transposes.

Carried from the old Linear algebra page (checked): with the tiny model's WW and xx and a target y=(1,0,0)y = (1, 0, 0), Wx−y=(1,1,0)Wx - y = (1, 1, 0), so ∇WL=2(Wx−y)x⊤\nabla_W L = 2(Wx - y)\,x^\top has rows (4,2)(4, 2), (2,2)(2, 2), (0,0)(0, 0), the same as PyTorch's autograd (checked in src/recompute.py). The root's Notation decoder has a second worked example, L=u⊤WxL = u^\top W x, on its layout card (Topic: math, Notation decoder).

The same six slopes, written both ways

Entry by entry they agree: ∂L/∂Wij=(pi−yi)xj\partial L/\partial W_{ij} = (p_i - y_i)\,x_j, for example ∂L/∂Wsat,1=−0.910×2=−1.820\partial L/\partial W_{\text{sat},1} = -0.910 \times 2 = -1.820 (highlighted). In symbols: ∂z/∂x\partial z/\partial x for z=Wxz = Wx is WW (3×23 \times 2) in numerator layout and W⊤W^\top (2×32 \times 3) in denominator layout; ∂L/∂z\partial L/\partial z is the row (0.665,0.245,−0.910)(0.665, 0.245, -0.910) or the same numbers as a column; ∂L/∂W\partial L/\partial W is x(p−y)⊤x\,(p - y)^\top, 2×32 \times 3, or (p−y)x⊤(p - y)\,x^\top, 3×23 \times 2, what W.grad holds.

3. The chain rule as a product of Jacobians

Let y=g(x)y = g(x) and z=f(y)z = f(y). A small step δx\delta x moves yy by about JgδxJ_g\,\delta x, and that moves zz by about JfJ_f times it:

δz≈JfJgδx⟹Jf∘g(x)=Jf(g(x))Jg(x)\delta z \approx J_f\,J_g\,\delta x \qquad\Longrightarrow\qquad J_{f \circ g}(x) = J_f\big(g(x)\big)\; J_g(x)

The Jacobian of a chain is the product of the Jacobians, in the order of the chain; entry by entry, ∂zi∂xk=∑j∂zi∂yj∂yj∂xk\frac{\partial z_i}{\partial x_k} = \sum_j \frac{\partial z_i}{\partial y_j}\frac{\partial y_j}{\partial x_k}, the effect of xkx_k on ziz_i through every intermediate yjy_j. The shapes line up by themselves, (m×p)(m \times p) times (p×n)(p \times n), and JfJ_f is evaluated at the value yy that gg actually produced, which is why the backward pass needs the forward pass's values.

For a scalar loss the last Jacobian is a single row, ∂L/∂y\partial L/\partial y. Written as gradients shaped like the variables, the chain rule becomes the vector-Jacobian product:

x‾=J⊤y‾(row form: ∂L∂x=∂L∂yJ),v‾:=∇vL, shaped like v\bar x = J^\top \bar y \qquad\text{(row form: } \tfrac{\partial L}{\partial x} = \tfrac{\partial L}{\partial y}\,J \text{)}, \qquad \bar v := \nabla_v L \text{, shaped like } v
The tiny model: from the scores back to the input
z‾=p−y=(0.665,0.245,−0.910)\bar z = p - y = (0.665, 0.245, -0.910) and J=WJ = W, so x‾=W⊤z‾\bar x = W^\top \bar z: 1×0.665+0×0.245+1×(−0.910)=−0.2451 \times 0.665 + 0 \times 0.245 + 1 \times (-0.910) = -0.245 and 0×0.665+1×0.245+(−2)×(−0.910)=2.0650 \times 0.665 + 1 \times 0.245 + (-2) \times (-0.910) = 2.065, so x‾=(−0.245,2.065)\bar x = (-0.245, 2.065). One step further back, from the loss to the probabilities to the scores: p‾=(0,0,−1/psat)=(0,0,−11.107)\bar p = (0, 0, -1/p_{\text{sat}}) = (0, 0, -11.107), and z‾=Jsoftmax⊤p‾\bar z = J_{\text{softmax}}^\top \bar p is −11.107-11.107 times the sat column of section 1's table: −11.107×(−0.0599,−0.0220,0.0819)-11.107 \times (-0.0599, -0.0220, 0.0819) =(0.665,0.245,−0.910)= (0.665, 0.245, -0.910). The famous "prediction minus target" is just two VJPs multiplied out.

Order matters: multiply from the loss end. For kk layers, ∂L∂x=∂L∂hkJkJk−1⋯J1\frac{\partial L}{\partial x} = \frac{\partial L}{\partial h_k} J_k J_{k-1} \cdots J_1. Any bracketing gives the same answer, not the same cost. From the loss end every product is a row times a matrix: d2d^2 multiply-adds for width dd, kd2k d^2 in all. From the input end every product is a matrix times a matrix, d3d^3 each: at d=4096d = 4096 a factor of 4096 more. Section 4 turns the two orders into the two modes of automatic differentiation.

Several paths: gradients add. When one value feeds two places, the sum over intermediates becomes a sum over paths:

  • A residual connection y=x+F(x)y = x + F(x) has Jacobian I+JFI + J_F, so x‾=y‾+JF⊤y‾\bar x = \bar y + J_F^\top \bar y: the gradient arrives once through the identity path, untouched, and once through the block. That untouched copy is why very deep residual networks still train (section 10).
  • A weight used twice, such as an embedding tied to the output layer, gets the sum of the gradients from both uses. In PyTorch's graph of a transformer block (section 12), the embedding's accumulator is the very last node the engine runs, because it waits for both contributions.

4. Forward mode against reverse mode: why reverse wins for one loss

Automatic differentiation (AD) sees a program as a computational graph of primitive operations (a matrix product, an exponential, a sum), runs it, and applies the chain rule to each primitive operation as it runs, using that operation's known local derivative: exact up to rounding, works through loops and branches, and costs a small multiple of one evaluation. (Symbolic differentiation blows up in size and has no formula for code with branches; finite differences are approximate and need two evaluations per input, section 11.) The two modes are the two orders of section 3:

Forward mode: Jacobian-vector products

Pick one input direction uu and carry a tangent v˙\dot v (how fast each value changes along uu) alongside every value, in the order of the computation: z˙=J1u\dot z = J_1 u, p˙=J2z˙\dot p = J_2 \dot z, ... One pass gives JuJu: how every output changes along one input direction. A full gradient over nn inputs needs nn passes.

Reverse mode: vector-Jacobian products

Run forward once, keeping what each local derivative will need. Then carry an adjoint v‾\bar v backwards from one output: p‾\bar p, then z‾=J2⊤p‾\bar z = J_2^\top \bar p, then W‾\bar W and x‾\bar x. One backward pass gives the slope of one output with respect to every input. Backpropagation is reverse mode applied to a loss.
Predict: the tiny model has six weights. How many sweeps does each mode need for all six slopes, and how many multiply-adds? Then watch both: the stage plays reverse mode; the button switches to forward mode.
  1. The forward pass, shared by both modes. z=Wx=(2,1,0)z = Wx = (2, 1, 0), p=(0.665,0.245,0.090)p = (0.665, 0.245, 0.090), L=2.408L = 2.408. Reverse mode keeps xx and pp (orange), the values its local derivatives will need.
  2. Start at the loss: p‾\bar p. L‾=1\bar L = 1 and L=−ln⁡psatL = -\ln p_{\text{sat}}, so p‾=(0,0,−1/psat)=(0,0,−11.107)\bar p = (0, 0, -1/p_{\text{sat}}) = (0, 0, -11.107). One multiply-add.
  3. Back through softmax: z‾=J⊤p‾\bar z = J^\top \bar p. A vector-Jacobian product, nine multiply-adds: z‾=(0.665,0.245,−0.910)\bar z = (0.665, 0.245, -0.910), the prediction minus the target.
  4. All six slopes at once: W‾=z‾x⊤\bar W = \bar z\,x^\top. An outer product of the arriving gradient (blue) and the stored input (green): every entry of ∂L/∂W\partial L/\partial W in one step, six multiply-adds.
  5. And the input's gradient for free. x‾=W⊤z‾=(−0.245,2.065)\bar x = W^\top \bar z = (-0.245, 2.065): what an earlier layer (here the embedding) would receive; six more multiply-adds.
  6. One sweep for every slope. All six slopes plus the input's, in one backward sweep. Its cost does not grow with the number of weights, only with the size of the computation, which is why every training framework uses it.

Multiply-adds counted the same way in both modes: applying a matrix with rr rows and cc columns costs r×cr \times c; the shared forward pass is not counted. Forward mode: 16 per sweep, 96 for six; reverse mode: 16 for W‾\bar W, 6 more for x‾\bar x. Values from parts/22b_js_core.js, checked against src/recompute.py.

The rule. For f:ℝn→ℝmf: \mathbb{R}^n \to \mathbb{R}^m the whole Jacobian costs nn forward-mode passes or mm reverse-mode passes. The standard survey's bound: "ncops(f)n\,c\,\text{ops}(f)" in forward mode and "mcops(f)m\,c\,\text{ops}(f)" in reverse mode, "where c is a constant guaranteed to be c < 6 and typically c ∼ [2, 3]" (Baydin et al. 2018, section 3.2, p. 13, citing Griewank and Walther 2008). Training has m=1m = 1 and nn in the billions, so reverse mode, by a factor of nn. Forward mode wins when inputs are few and outputs many, such as the sensitivity of every output of a simulation to one hyperparameter. Measured with torch.func.jacfwd and jacrev on f(x)=Btanh⁡(Ax)f(x) = B\tanh(Ax) (hidden width 256, float64, two CPU threads):

The price of reverse mode is memory. The backward sweep runs in the opposite order to the computation, so every value a local derivative needs must still exist when the sweep reaches it: stored during the forward pass, or recomputed. Forward mode carries its tangent along and can forget each value at once. Sections 8 and 9 measure both costs.

A third option: estimate the error, keep the outer product. Step 4 above, W‾=z‾x⊤\bar W = \bar z\,x^\top, needs only the error z‾\bar z arriving at the layer's output. Node perturbation estimates that error with forward passes alone: add noise to the layer's outputs, see how the loss moves, credit each token's noise with that token's own loss change, and form the same outer product. There is no backward sweep, but the estimate is noisy and its cost grows with the number of forward passes instead of staying a small constant multiple. For linear networks Werfel, Xie and Seung showed it learns slower than gradient descent by a factor of the number of outputs, and that perturbing the weights directly is slower again by the number of inputs (Werfel et al. 2005). Q Labs' Dust trains small transformers this way with up to tens of thousands of forward passes per update, by our count 19 to 4,900 backprop updates' worth of compute per update; it matches constant-rate SGD backprop on short runs and falls behind once backprop gets Adam (Dust).

The cheaper mode flips with the shape of the Jacobian

Dual numbers, JAX's cost notes, and a little history (2 min)

The cheap gradient principle. Griewank calls a gradient at a small constant multiple of the function's cost, whatever nn, the "Cheap Gradient Principle", and adds that "there is no corresponding Cheap Jacobian Principle" (Griewank 2012, p. 391).

Dual numbers. Forward mode has a neat algebraic form: numbers a+bεa + b\varepsilon with ε2=0\varepsilon^2 = 0. Then f(a+bε)=f(a)+f′(a)bεf(a + b\varepsilon) = f(a) + f'(a)\,b\,\varepsilon for any smooth ff (the Taylor series stops after the linear term), so evaluating with dual numbers carries the derivative along for free. PyTorch exposes it as torch.func.jvp and dual tensors in torch.autograd.forward_ad; JAX as jax.jvp.

JAX's documentation gives the same picture: for a VJP "the FLOP cost ... is only about three times the cost of evaluating f", and "though the FLOPs are friendly, memory scales with the depth of the computation"; for a JVP "the memory cost is independent of the depth of the computation"; and "jacfwd ... is more efficient for "tall" Jacobian matrices (more outputs than inputs), while jacrev ... is more efficient for "wide" Jacobian matrices" (JAX, The Autodiff Cookbook).

History. "Forward mode AD as a general method for evaluating partial derivatives was essentially discovered by Wengert (1964)"; the work of "Linnainmaa (1970, 1976) is often cited as the first published description of the reverse mode"; in machine learning it "has been reinvented several times ... until it was eventually brought to fame by Rumelhart et al. (1986)" (Baydin et al. 2018, section 3.3). Griewank's history adds that Ostrowski used the reverse idea some five years before Linnainmaa, in chemical engineering (Griewank 2012, p. 389). As Baydin et al. put it, "the backpropagation algorithm is only a special case of AD" (section 4.2).

5. Backprop through a two-layer network, by hand

Put a ReLU layer in front of the scores: a=W1xa = W_1 x, h=ReLU⁡(a)h = \operatorname{ReLU}(a), z=W2hz = W_2 h, cross-entropy on sat. This is the root page's Gradient lab network, W1W_1 (3×23 \times 2) with rows (0.5,0)(0.5, 0), (0,1)(0, 1), (1,−3)(1, -3) and W2W_2 (3×33 \times 3) with rows (2,0,1)(2, 0, 1), (0,1,0)(0, 1, 0), (−1,1,0)(-1, 1, 0) illustrative, chosen so the scores come out (2,1,0)(2, 1, 0) again and one hidden unit is off. Every step below is one of the rules in section 6, and the hero figure at the top is this network. The stage walks it one value at a time, moving in close on each layer.

  1. The network, before anything runs. x=(2,1)x = (2, 1), the plates W1W_1 and W2W_2 as above, and the right next word is sat. Predict before it plays: hidden unit 3 will come out negative. What will its row of W‾1\bar W_1 be?
  2. Layer 1: a=W1xa = W_1 x. a1=0.5×2+0×1=1a_1 = 0.5 \times 2 + 0 \times 1 = 1, a2=0×2+1×1=1a_2 = 0 \times 2 + 1 \times 1 = 1, a3=1×2−3×1=−1a_3 = 1 \times 2 - 3 \times 1 = -1, so a=(1,1,−1)a = (1, 1, -1). Six multiply-adds.
  3. ReLU: h=max⁡(0,a)=(1,1,0)h = \max(0, a) = (1, 1, 0). Unit 3 is off. The forward pass keeps xx, the sign of aa, and hh (orange), because the backward rules need them.
  4. Layer 2: z=W2h=(2,1,0)z = W_2 h = (2, 1, 0). The running example's scores, cat 2, dog 1, sat 0. Nine multiply-adds, 15 forward in all.
  5. Loss. p=softmax⁡(z)=(0.665,0.245,0.090)p = \operatorname{softmax}(z) = (0.665, 0.245, 0.090), so L=−ln⁡0.090=2.408L = -\ln 0.090 = 2.408. The forward pass is done; pp is kept.
  6. Start at the loss: z‾=p−y\bar z = p - y. L‾=1\bar L = 1; softmax and cross-entropy together give z‾=(0.665,0.245,−0.910)\bar z = (0.665, 0.245, -0.910) (section 6d).
  7. W2W_2's gradient, an outer product: W‾2=z‾h⊤\bar W_2 = \bar z\,h^\top. 3 × 3 like W2W_2, nine multiply-adds. Its third column is 0 because h3=0h_3 = 0: a weight that reads a silent unit gets no gradient.
  8. Back through W2W_2: h‾=W2⊤z‾\bar h = W_2^\top \bar z. Each hidden unit collects the score gradients through its column of W2W_2: h‾1=2×0.665−1×(−0.910)\bar h_1 = 2 \times 0.665 - 1 \times (-0.910), h‾2=0.245+(−0.910)\bar h_2 = 0.245 + (-0.910), h‾3=0.665\bar h_3 = 0.665, so h‾=(2.240,−0.665,0.665)\bar h = (2.240, -0.665, 0.665). Nine multiply-adds.
  9. Back through the ReLU: a‾=h‾⊙[a>0]=(2.240,−0.665,0)\bar a = \bar h \odot [a > 0] = (2.240, -0.665, 0). The ReLU's slope is 0 where it was off, so unit 3's 0.665 is blocked.
  10. W1W_1's gradient: W‾1=a‾x⊤\bar W_1 = \bar a\,x^\top. Rows (4.481,2.240)(4.481, 2.240), (−1.330,−0.665)(-1.330, -0.665), (0,0)(0, 0), six multiply-adds. Unit 3's row is all zero, the answer to the prediction.
  11. And the input's gradient: x‾=W1⊤a‾=(1.120,−0.665)\bar x = W_1^\top \bar a = (1.120, -0.665). What the embedding below would receive. Six multiply-adds: 30 backward in all, twice the forward 15.
  12. One gradient step. W←W−0.1W‾W \leftarrow W - 0.1\,\bar W on both layers, the input held fixed: psatp_{\text{sat}} rises from 0.090 to 0.483 and the loss falls from 2.408 to 0.728.

Every number above checked against PyTorch 2.14.1 autograd: largest difference 4.4e-16 (src/two_layer.py).

Three moves did all of it: a matrix product sends y‾\bar y back through W⊤W^\top and gives its weight y‾x⊤\bar y\,x^\top; an elementwise function multiplies by its slope (a ReLU's is 0 or 1); and the loss starts the pass at p−yp - y. Unit 3 was off, so its row of W‾1\bar W_1 and its column of W‾2\bar W_2 are zero: a unit that is off for every example never learns (a dead ReLU). The matrix-product work was 15 multiply-adds forward and 30 backward, twice, which is section 8's rule on the smallest possible case.

Carried from the old Calculus and optimisation page (checked): one logistic unit and one step (1 min)

x=(1,2)x = (1, 2), w=(0.5,−0.25)w = (0.5, -0.25), b=0.1b = 0.1, label 1. Forward: z=w⋅x+b=0.1z = w \cdot x + b = 0.1, p=σ(0.1)=0.525p = \sigma(0.1) = 0.525, loss −ln⁡0.525=0.644-\ln 0.525 = 0.644. Backward: z‾=p−1=−0.475\bar z = p - 1 = -0.475; the linear rule gives w‾=z‾x=(−0.475,−0.950)\bar w = \bar z\,x = (-0.475, -0.950), b‾=−0.475\bar b = -0.475 and x‾=z‾w=(−0.2375,0.1188)\bar x = \bar z\,w = (-0.2375, 0.1188). One step with learning rate 0.1: w=(0.5475,−0.155)w = (0.5475, -0.155), b=0.1475b = 0.1475, new z=0.385z = 0.385, p=0.595p = 0.595: the right answer became more likely.

6. The layer gradients ML needs, each derived

Every block of a transformer is made of six backward rules. Each comes from the same three moves: write one output entry with indices, differentiate, and recognise the result as a matrix product. Each rule takes y‾\bar y, the gradient arriving at the output, and returns the gradient for each input. The workbench runs any of them on numbers you can change and checks it against finite differences, live; its defaults are the numbers in the text, and its layer buttons cover 6b to 6f as well.

6a. Linear layer: y=Wx+by = Wx + b

WW is m×nm \times n. One entry is yk=∑jWkjxj+bky_k = \sum_j W_{kj}\,x_j + b_k; WijW_{ij} appears only in output ii, times xjx_j; xjx_j appears in every output, times WkjW_{kj}; bkb_k once, with slope 1. So

W‾=y‾x⊤(m×n),x‾=W⊤y‾(n),b‾=y‾(m)\bar W = \bar y\,x^\top \;(m \times n), \qquad \bar x = W^\top \bar y \;(n), \qquad \bar b = \bar y \;(m)

A batch. PyTorch's nn.Linear stores WW as (out, in) and computes Y=XW⊤+bY = XW^\top + b for XX of shape B×nB \times n, one example per row:

W‾=Y‾⊤X(m×n),X‾=Y‾W(B×n),b‾=∑rowsY‾(m)\bar W = \bar Y^\top X \;(m \times n), \qquad \bar X = \bar Y\,W \;(B \times n), \qquad \bar b = \textstyle\sum_{\text{rows}} \bar Y \;(m)

A weight's gradient is (gradient coming in) times (input that went in), summed over the batch; an input's gradient is the gradient sent back through the transposed weights; a bias added to every row collects every row's gradient. Y‾⊤X\bar Y^\top X is a sum of one outer product per example, so one example's weight gradient has rank 1 and a batch's has rank at most BB.

The tiny model (b=0b = 0, y‾=p−y\bar y = p - y)
W‾=(0.665,0.245,−0.910)⊤(2,1)\bar W = (0.665, 0.245, -0.910)^\top (2, 1) has rows (1.330,0.665)(1.330, 0.665), (0.489,0.245)(0.489, 0.245), (−1.820,−0.910)(-1.820, -0.910); x‾=(−0.245,2.065)\bar x = (-0.245, 2.065); b‾=(0.665,0.245,−0.910)\bar b = (0.665, 0.245, -0.910). PyTorch autograd and jax.grad give the same to 15 digits (src/recompute.py).

6b. Elementwise nonlinearities: h=ϕ(a)h = \phi(a)

The Jacobian is diagonal (section 1), so the VJP is an entry-by-entry product, a‾=h‾⊙ϕ′(a)\bar a = \bar h \odot \phi'(a):

ϕ\phiϕ′(a)\phi'(a)what PyTorch saves for it (derivatives.yaml, v2.14.1, lines 2132, 1788, 1550, 2160)
ReLU, max⁡(0,a)\max(0, a)1 where a>0a > 0, else 0its output: threshold_backward(grad, result, 0)
tanh1−tanh2⁡a=1−h21 - \tanh^2 a = 1 - h^2its output: tanh_backward(grad, result)
sigmoid σ(a)=1/(1+e−a)\sigma(a) = 1/(1 + e^{-a})σ(a)(1−σ(a))=h(1−h)\sigma(a)(1 - \sigma(a)) = h(1 - h)its output: sigmoid_backward(grad, result)
GELU, aΦ(a)a\,\Phi(a)Φ(a)+aφ(a)\Phi(a) + a\,\varphi(a)its input: gelu_backward(grad, self, approximate)

Φ\Phi is the standard normal cumulative distribution and φ\varphi its density. Functions whose derivative can be written from the output save the output; GELU's cannot, so it saves the input. Either way one tensor the size of the layer stays in memory until the backward pass (section 9). At a=(−1.5,−0.2,0.4,2.0)a = (-1.5, -0.2, 0.4, 2.0) with h‾=(0.5,−1,0.25,1)\bar h = (0.5, -1, 0.25, 1): ReLU passes (0,0,0.25,1)(0, 0, 0.25, 1); GELU's slopes are (−0.1275,0.3425,0.8027,1.0852)(-0.1275, 0.3425, 0.8027, 1.0852), so a‾=(−0.0637,−0.3425,0.2007,1.0852)\bar a = (-0.0637, -0.3425, 0.2007, 1.0852). GELU's slope is negative below about −0.75-0.75 and above 1 near a=2a = 2: it is not a monotone function.

Derivative workbench: the hand-derived rule against a finite difference, and the Jacobian it never builds

Shapes

Forward and backward, with the numerical check

The Jacobian the backward rule never builds

The check nudges every input entry by ±h\pm h and differences the probe loss L~=y‾⋅f(inputs)\tilde L = \bar y \cdot f(\text{inputs}), whose gradient is exactly the VJP (section 11). The Jacobian with respect to the first input is built one VJP per output entry. All arithmetic is float64 JavaScript (parts/22b_js_core.js); at the defaults every number is checked against PyTorch autograd (and, for attention, scaled_dot_product_attention) by src/recompute.py and src/check_js.mjs.

6c. Softmax: the VJP without the Jacobian

Multiply section 1's Jacobian (symmetric, so J⊤=JJ^\top = J) by an incoming p‾\bar p and simplify:

z‾=(diag⁡(p)−pp⊤)p‾=p⊙(p‾−(p⋅p‾)𝟏)\bar z = \big(\operatorname{diag}(p) - p\,p^\top\big)\,\bar p = p \odot \big(\bar p - (p \cdot \bar p)\,\mathbf{1}\big)

Subtract from each incoming gradient the probability-weighted average of all of them, then scale by the probability. Cost: one dot product and one pass, O(K)O(K), against O(K2)O(K^2) to build the Jacobian; for a 128,000-word vocabulary, a vector against a table of 16 billion numbers per token. PyTorch's softmax node saves only its output pp (_softmax_backward_data(grad, result, dim, ...), derivatives.yaml line 2237). On z=(2,1,0)z = (2, 1, 0) with p‾=(0.5,−1,0.25)\bar p = (0.5, -1, 0.25): p⋅p‾=0.1104p \cdot \bar p = 0.1104, so z‾=(0.2592,−0.2717,0.0126)\bar z = (0.2592, -0.2717, 0.0126), which adds up to 0, as it must.

6d. Softmax cross-entropy: two VJPs that collapse

L=−ln⁡pyL = -\ln p_y gives p‾=−𝟏y/py\bar p = -\mathbf{1}_y / p_y (the one-hot vector of the right word, divided by its probability, which can be tiny), so p⋅p‾=−1p \cdot \bar p = -1, and softmax's VJP gives

z‾=p⊙(p‾+𝟏)=p−𝟏y\bar z = p \odot (\bar p + \mathbf{1}) = p - \mathbf{1}_y

The division by pyp_y cancels exactly. Computed separately, a probability that underflows to 0 would give p‾=−∞\bar p = -\infty and a NaN; fused, the gradient is just the probabilities minus the target. That is why F.cross_entropy takes logits, and why PyTorch's graph shows LogSoftmaxBackward0 feeding NllLossBackward0: log-softmax is computed stably once and saved. For a batch averaged over BB examples (reduction="mean") each row's gradient is (p−𝟏y)/B(p - \mathbf{1}_y)/B; with label smoothing or distillation targets qq, it is p−qp - q. The losses themselves, and the same result from L=−zy+ln⁡∑jezjL = -z_y + \ln \sum_j e^{z_j}, are on Loss functions and Calculus and optimisation for ML, section 2.

6e. Layer norm

Layer norm (Ba, Kiros and Hinton 2016) rescales each token's vector xx (NN entries) to mean 0 and variance 1, then applies a learned scale γ\gamma and shift β\beta: xˆ=(x−μ)r\hat x = (x - \mu)\,r with r=1/σ2+ϵr = 1/\sqrt{\sigma^2 + \epsilon} (PyTorch's rstd; ϵ\epsilon defaults to 10−510^{-5}), and y=γ⊙xˆ+βy = \gamma \odot \hat x + \beta. The backward rule, with gˆ=y‾⊙γ\hat g = \bar y \odot \gamma:

x‾=r(gˆ−mean⁡(gˆ)−xˆ⊙mean⁡(gˆ⊙xˆ)),γ‾=y‾⊙xˆ,β‾=y‾\bar x = r\Big(\hat g - \operatorname{mean}(\hat g) - \hat x \odot \operatorname{mean}(\hat g \odot \hat x)\Big), \qquad \bar\gamma = \bar y \odot \hat x, \qquad \bar\beta = \bar y

Take the incoming gradient, remove its average (the output cannot respond to adding a constant to every entry of xx), remove its component along xˆ\hat x (nor to scaling xx up), and scale by 1/σ1/\sigma. The result always adds up to 0 and is orthogonal to xˆ\hat x. On x=(2,1,0,−1)x = (2, 1, 0, -1), γ=(1,0.5,−1,2)\gamma = (1, 0.5, -1, 2), y‾=(0.3,−0.6,0.9,0.1)\bar y = (0.3, -0.6, 0.9, 0.1): μ=0.5\mu = 0.5, σ2=1.25\sigma^2 = 1.25, r=0.8944r = 0.8944, and x‾=(0.3041,−0.1521,−0.6082,0.4562)\bar x = (0.3041, -0.1521, -0.6082, 0.4562), the same as PyTorch's F.layer_norm.

Layer norm's backward, derived completely; PyTorch's kernel form; RMSNorm (4 min)
μ=1N∑ixi,σ2=1N∑i(xi−μ)2,r=1σ2+ϵ,xˆi=(xi−μ)r,yi=γixˆi+βi\mu = \frac{1}{N}\sum_i x_i, \quad \sigma^2 = \frac{1}{N}\sum_i (x_i - \mu)^2, \quad r = \frac{1}{\sqrt{\sigma^2 + \epsilon}}, \quad \hat x_i = (x_i - \mu)\,r, \quad y_i = \gamma_i \hat x_i + \beta_i
  1. The easy ones: yi=γixˆi+βiy_i = \gamma_i \hat x_i + \beta_i gives γ‾=y‾⊙xˆ\bar\gamma = \bar y \odot \hat x and β‾=y‾\bar\beta = \bar y (summed over the tokens of a batch), and passes gˆ:=xˆ‾=y‾⊙γ\hat g := \bar{\hat x} = \bar y \odot \gamma to the normalisation.
  2. xˆi\hat x_i depends on xjx_j through three routes: directly, through μ\mu and through rr. The first two give r(δij−1N)r\,(\delta_{ij} - \tfrac{1}{N}), because ∂μ/∂xj=1/N\partial \mu/\partial x_j = 1/N.
  3. The variance: ∂σ2/∂xj=2N(xj−μ)\partial \sigma^2/\partial x_j = \tfrac{2}{N}(x_j - \mu). (Its route through μ\mu contributes −2N2∑i(xi−μ)=0-\tfrac{2}{N^2}\sum_i (x_i - \mu) = 0, because deviations from the mean add up to 0.)
  4. So ∂r/∂xj=−12(σ2+ϵ)−3/2⋅2N(xj−μ)\partial r/\partial x_j = -\tfrac{1}{2}(\sigma^2 + \epsilon)^{-3/2} \cdot \tfrac{2}{N}(x_j - \mu) =−r3N(xj−μ)=−r2Nxˆj= -\tfrac{r^3}{N}(x_j - \mu) = -\tfrac{r^2}{N}\hat x_j.
  5. All three routes together:
    ∂xˆi∂xj=r(δij−1N)+(xi−μ)(−r2Nxˆj)=r(δij−1N−xˆixˆjN)\frac{\partial \hat x_i}{\partial x_j} = r\Big(\delta_{ij} - \frac{1}{N}\Big) + (x_i - \mu)\Big(-\frac{r^2}{N}\hat x_j\Big) = r\Big(\delta_{ij} - \frac{1}{N} - \frac{\hat x_i \hat x_j}{N}\Big)
  6. The VJP sums over ii, x‾j=∑igˆi∂xˆi/∂xj\bar x_j = \sum_i \hat g_i\,\partial \hat x_i/\partial x_j, which gives the rule above.

On the numbers: xˆ=(1.3416,0.4472,−0.4472,−1.3416)\hat x = (1.3416, 0.4472, -0.4472, -1.3416), gˆ=(0.3,−0.3,−0.9,0.2)\hat g = (0.3, -0.3, -0.9, 0.2), mean⁡(gˆ)=−0.175\operatorname{mean}(\hat g) = -0.175, mean⁡(gˆ⊙xˆ)=0.1006\operatorname{mean}(\hat g \odot \hat x) = 0.1006, so x‾=0.8944×(0.340,−0.170,−0.680,0.510)\bar x = 0.8944 \times (0.340, -0.170, -0.680, 0.510); it adds up to 0 and its dot product with xˆ\hat x is 0.

The real kernel writes the same thing with two sums per row. From PyTorch v2.14.1's CPU kernel (scale is 1/N1/N, a is rr, ds =∑jy‾jxjγj= \sum_j \bar y_j x_j \gamma_j, db =∑jy‾jγj= \sum_j \bar y_j \gamma_j):

const opmath_t a = rstd_data[i];
const opmath_t b = (db * opmath_t(mean_data[i]) - ds) * a * a * a * scale;
const opmath_t c = -b * opmath_t(mean_data[i]) - db * a * scale;
// Scalar math:
// for (const auto j : c10::irange(N)) {
//   const T gamma_v = gamma_null ? T(1) : gamma_data[j];
//   dX_ptr[j] = a * dY_ptr[j] * gamma_v + b * X_ptr[j] + c;
// }

aten/src/ATen/native/cpu/layer_norm_kernel.cpp at v2.14.1, lines 287-294. On the defaults: a=0.8944a = 0.8944, b=−0.0805b = -0.0805, c=0.1968c = 0.1968, and ay‾⊙γ+bx+ca\,\bar y \odot \gamma + b\,x + c reproduces x‾\bar x (checked in src/recompute.py).

RMSNorm (used by Llama and most 2026 open models) drops the mean: y=γ⊙x/rmsy = \gamma \odot x / \text{rms}, rms=mean⁡(x2)+ϵ\text{rms} = \sqrt{\operatorname{mean}(x^2) + \epsilon}, and the same steps give x‾=(gˆ−x~⊙mean⁡(gˆ⊙x~))/rms\bar x = (\hat g - \tilde x \odot \operatorname{mean}(\hat g \odot \tilde x))/\text{rms} with x~=x/rms\tilde x = x/\text{rms}: only the scaling direction is removed. On the same numbers, x‾=(0.2177,−0.2586,−0.7348,0.1769)\bar x = (0.2177, -0.2586, -0.7348, 0.1769). Why these norms are there is Normalisation and initialisation's subject.

6f. Attention, at the level of shapes

One head: QQ is Tq×dT_q \times d, KK and VV are Tk×dT_k \times d; S=QK⊤/dS = QK^\top/\sqrt d, A=softmaxrows⁡(S)A = \operatorname{softmax}_{\text{rows}}(S), O=AVO = AV. Backward, each line one of the rules above, given O‾\bar O:

  1. O=AVO = AV is a matrix product (6a): V‾=A⊤O‾\bar V = A^\top \bar O and A‾=O‾V⊤\bar A = \bar O V^\top.
  2. Each row of AA is a softmax (6c): S‾ij=Aij(A‾ij−Di)\bar S_{ij} = A_{ij}\big(\bar A_{ij} - D_i\big) with Di=∑jAijA‾ijD_i = \sum_j A_{ij}\bar A_{ij}.
  3. S=QK⊤/dS = QK^\top/\sqrt d is a matrix product again: Q‾=S‾K/d\bar Q = \bar S K/\sqrt d and K‾=S‾⊤Q/d\bar K = \bar S^\top Q/\sqrt d.

One identity makes attention's backward pass cheap in memory. Substituting A‾=O‾V⊤\bar A = \bar O V^\top:

Di=∑jAij∑cO‾icVjc=∑cO‾ic∑jAijVjc=∑cO‾icOicD_i = \sum_j A_{ij} \sum_c \bar O_{ic} V_{jc} = \sum_c \bar O_{ic} \sum_j A_{ij} V_{jc} = \sum_c \bar O_{ic}\,O_{ic}

DD comes from the output and its gradient alone, one number per query, without the T×TT \times T matrix AA. FlashAttention's backward pass uses exactly this DiD_i and recomputes AA block by block instead of storing it (Dao et al. 2022 define Di=doi⊤oiD_i = do_i^\top o_i in Eq. 4 of appendix B.2 and compute "Di=rowsum⁡(dOi∘Oi)D_i = \operatorname{rowsum}(dO_i \circ O_i)" in Algorithm 4, line 19; they describe recomputing the attention matrix as "a form of selective gradient checkpointing", section 3.1: arXiv 2205.14135; FlashAttention paper page). In the 8-layer stack of section 9, the stored attention probabilities are 128 of the 422 MiB the backward pass keeps.

Attention's numbers; PyTorch's own backward rules in derivatives.yaml (2 min)

Numbers (workbench defaults). QQ has rows (2,1)(2, 1) and (0,1)(0, 1); K=V=WK = V = W of the tiny model; d=2d = 2. The first query is the root page's: scores (1.414,0.707,0)(1.414, 0.707, 0), weights (0.576,0.284,0.140)(0.576, 0.284, 0.140), output (0.716,0.004)(0.716, 0.004). With O‾\bar O rows (1,0)(1, 0) and (0,−1)(0, -1): D=(0.716,−0.471)D = (0.716, -0.471), Q‾\bar Q rows (0.1438,−0.2000)(0.1438, -0.2000) and (0.2318,−0.4915)(0.2318, -0.4915), V‾\bar V rows (0.576,−0.306)(0.576, -0.306), (0.284,−0.620)(0.284, -0.620), (0.140,−0.074)(0.140, -0.074). PyTorch's fused scaled_dot_product_attention gives the same.

The real code. PyTorch writes the backward rules of its built-in operators in one file, tools/autograd/derivatives.yaml. At v2.14.1, lines 1235 to 1238 hold the matrix product:

- name: mm(Tensor self, Tensor mat2) -> Tensor
  self: mm_mat1_backward(grad, mat2, self.sym_sizes(), self.sym_strides(), self.layout(), 1)
  mat2: mm_mat2_backward(grad, self, mat2.sym_sizes(), mat2.sym_strides(), mat2.layout(), 1)
  result: at::mm(self_t, mat2_p) + at::mm(self_p, mat2_t)

derivatives.yaml at v2.14.1, lines 1235-1238; the two helpers in torch/csrc/autograd/FunctionsManual.cpp, lines 1722-1758.

For C=ABC = AB the helpers' general case is grad.mm(mat2.t()) for AA and mat1.t().mm(grad) for BB: A‾=C‾B⊤\bar A = \bar C B^\top and B‾=A⊤C‾\bar B = A^\top \bar C, rule 6a. The result: line is the forward-mode rule (section 4): the tangent of ABAB is A˙B+AB˙\dot A B + A \dot B, the product rule.

Only the blue T × T blocks grow with the square of the sequence

Drawn to scale for T=8T = 8 positions and head width d=4d = 4 illustrative sizes. Forward: QQ and K⊤K^\top make SS, softmax makes AA, AA times VV makes OO. Backward: O‾\bar O gives V‾=A⊤O‾\bar V = A^\top \bar O and A‾=O‾V⊤\bar A = \bar O V^\top; with DD, one number per query (gold), A‾\bar A becomes S‾\bar S; S‾\bar S gives Q‾\bar Q and K‾\bar K. Every gradient has its variable's shape.

7. Differentials and the trace trick: matrix gradients without indices

Index-by-index derivations get long for expressions like tr⁡(X⊤AXB)\operatorname{tr}(X^\top A X B) or log⁡det⁡Σ\log\det\Sigma. Instead, take the differential dLdL, the first-order change in LL when the input changes by a small dXdX, with the familiar rules applied to whole matrices (keeping the order of factors). Since tr⁡(G⊤dX)=∑ijGijdXij\operatorname{tr}(G^\top dX) = \sum_{ij} G_{ij}\,dX_{ij} is exactly the linear prediction with slopes GijG_{ij}, the identification rule reads the gradient off:

dL=tr⁡(G⊤dX) for every dX⟹∇XL=GdL = \operatorname{tr}\!\big(G^\top dX\big) \text{ for every } dX \quad\Longrightarrow\quad \nabla_X L = G

The recipe: take the differential, use tr⁡(ABC)=tr⁡(CAB)\operatorname{tr}(ABC) = \operatorname{tr}(CAB) to move dXdX to the far right inside a trace, and read off what stands in front of it, transposed. For a linear layer, dL=y‾⊤(dW)x=tr⁡(xy‾⊤dW)dL = \bar y^\top (dW)\,x = \operatorname{tr}(x\,\bar y^\top\, dW), so ∇WL=y‾x⊤\nabla_W L = \bar y\,x^\top: section 6a in one line.

The rules, four derivations and the identities table (4 min)
ruledifferential
sum, constantd(A+B)=dA+dBd(A + B) = dA + dB,  d(cA)=cdA\ d(cA) = c\,dA,  dC=0\ dC = 0 for a constant
productd(AB)=(dA)B+A(dB)d(AB) = (dA)\,B + A\,(dB)
transpose, traced(A⊤)=(dA)⊤d(A^\top) = (dA)^\top,  dtr⁡(A)=tr⁡(dA)\ d\operatorname{tr}(A) = \operatorname{tr}(dA)
inversed(X−1)=−X−1(dX)X−1d(X^{-1}) = -X^{-1}\,(dX)\,X^{-1} (differentiate XX−1=IXX^{-1} = I)
log-determinantdln⁡det⁡X=tr⁡(X−1dX)d\ln\det X = \operatorname{tr}(X^{-1}\,dX)
elementwise functiondϕ(X)=ϕ′(X)⊙dXd\,\phi(X) = \phi'(X) \odot dX

Three facts about the trace (the sum of the diagonal) do the rest: a scalar is its own trace; the trace is unchanged by cycling a product, tr⁡(ABC)=tr⁡(CAB)=tr⁡(BCA)\operatorname{tr}(ABC) = \operatorname{tr}(CAB) = \operatorname{tr}(BCA); and tr⁡(G⊤dX)=∑ijGijdXij\operatorname{tr}(G^\top dX) = \sum_{ij} G_{ij}\,dX_{ij}. Minka's classic note states the recipe as "1. compute the differential 2. massage the result into canonical form after which the derivative is immediately read off as the coefficient of dx, dx, or dX" (Minka 2000, Old and New Matrix Algebra Useful for Statistics, p. 2, based on Magnus and Neudecker). His canonical form is dy=tr⁡(AdX)dy = \operatorname{tr}(A\,dX) with the derivative laid out by X⊤X^\top, so his AA is the transpose of the gradient GG here: the same rule in the other layout.

A quadratic form f=x⊤Axf = x^\top A x: df=dx⊤Ax+x⊤Adx=x⊤A⊤dx+x⊤Adxdf = dx^\top A x + x^\top A\,dx = x^\top A^\top dx + x^\top A\,dx (a scalar equals its transpose), so ∇xf=(A+A⊤)x\nabla_x f = (A + A^\top)\,x, which is 2Ax2Ax when AA is symmetric. With AA rows (2,1)(2, 1), (0,3)(0, 3) and x=(1,2)x = (1, 2): f=2x12+x1x2+3x22f = 2x_1^2 + x_1x_2 + 3x_2^2, and both routes give (6,13)(6, 13).

A log-determinant (in every Gaussian log-likelihood and in normalising flows): dln⁡det⁡X=tr⁡(X−1dX)d\ln\det X = \operatorname{tr}(X^{-1}dX), so ∇Xln⁡det⁡X=X−⊤\nabla_X \ln\det X = X^{-\top}. With XX rows (2,1)(2, 1), (1,3)(1, 3): det⁡X=5\det X = 5 and X−⊤X^{-\top} has rows (0.6,−0.2)(0.6, -0.2), (−0.2,0.4)(-0.2, 0.4). Check one entry: raising X11X_{11} by hh makes the determinant 5+3h5 + 3h, so ln⁡det⁡\ln\det rises by about 3h/5=0.6h3h/5 = 0.6h.

Least squares L=‖Xw−y‖2L = \lVert Xw - y \rVert^2, with XX the data matrix: dL=2(Xw−y)⊤XdwdL = 2(Xw - y)^\top X\,dw, so ∇wL=2X⊤(Xw−y)\nabla_w L = 2X^\top(Xw - y), and setting it to zero gives the normal equations X⊤Xw=X⊤yX^\top X w = X^\top y. Carried from the old Linear algebra page (checked): fit yˆ=w0+w1t\hat y = w_0 + w_1 t to (t,y)=(0,1),(1,2),(2,2)(t, y) = (0, 1), (1, 2), (2, 2); X⊤XX^\top X has rows (3,3)(3, 3), (3,5)(3, 5) and X⊤y=(5,6)X^\top y = (5, 6), so w=16(7,3)=(1.167,0.5)w = \tfrac{1}{6}(7, 3) = (1.167, 0.5). The residuals (−0.167,0.333,−0.167)(-0.167, 0.333, -0.167) add up to 0 and are orthogonal to tt, which is what ∇wL=0\nabla_w L = 0 says. Why solvers prefer QR to forming X⊤XX^\top X (it squares the condition number, here 2.92 to 8.55) is on Linear algebra for ML.

The identities, each checked against PyTorch autograd in src/recompute.py (gradient layout):

LLdLdLgradient
a⊤xa^\top xa⊤dxa^\top dx∇x=a\nabla_x = a
x⊤Axx^\top A xx⊤(A+A⊤)dxx^\top(A + A^\top)dx∇x=(A+A⊤)x\nabla_x = (A + A^\top)x
tr⁡(AX)\operatorname{tr}(AX)tr⁡(AdX)\operatorname{tr}(A\,dX)∇X=A⊤\nabla_X = A^\top
‖X‖F2=tr⁡(X⊤X)\lVert X \rVert_F^2 = \operatorname{tr}(X^\top X)2tr⁡(X⊤dX)2\operatorname{tr}(X^\top dX)∇X=2X\nabla_X = 2X
ln⁡det⁡X\ln\det Xtr⁡(X−1dX)\operatorname{tr}(X^{-1}dX)∇X=X−⊤\nabla_X = X^{-\top}
‖Xw−y‖2\lVert Xw - y \rVert^22(Xw−y)⊤Xdw2(Xw - y)^\top X\,dw∇w=2X⊤(Xw−y)\nabla_w = 2X^\top(Xw - y)

‖X‖F\lVert X \rVert_F is the Frobenius norm. In numerator layout each gradient would be written transposed. For anything not here: the Matrix Cookbook (look up, do not memorise) or matrixcalculus.org, which derives symbolic matrix derivatives (Further reading).

8. Why the backward pass costs about twice the forward pass

Count one linear layer. Forward computes Y=XW⊤Y = XW^\top: one matrix product, B×n×mB \times n \times m multiply-adds. Backward (6a) computes two of the same size: X‾=Y‾W\bar X = \bar Y W and W‾=Y‾⊤X\bar W = \bar Y^\top X. Almost all of a transformer's arithmetic is matrix products, and a multiply-add is 2 FLOPs, so a model with NN weights spends about 2N2N FLOPs per token forward and 4N4N backward. Kaplan et al.: "Accounting for the backwards pass (approximately twice the compute as the forwards pass), we then define the estimated non-embedding compute as C≈6NC \approx 6N floating point operators per training token" (Scaling Laws for Neural Language Models, section 2.1; paper page). Their forward count is 2N+2nlayernctxdmodel2N + 2\,n_{\text{layer}}\,n_{\text{ctx}}\,d_{\text{model}} (Eq. 2.2); the second term, attention over the context, is left out of the 6N.

Measured on a small GPT-style stack: eight pre-norm blocks (width 512, 8 heads, MLP width 2048, vocabulary 8,192, tied embeddings, 29.4 million parameters, 25.2 million outside the embedding), a batch of 2 sequences of 512 tokens, float32, PyTorch 2.14.1; FLOPs from torch.utils.flop_counter.FlopCounterMode (matrix products only), times medians of 15 rounds on 2 CPU threads (src/inputs/measure/). FLOPs: exactly 2.00, forward 68.7 GFLOP and backward 137.4 GFLOP. Time: 1.44, 0.182 s backward against 0.126 s forward: the matrix products alone take 2.1 times as long backward (0.122 s against 0.057 s), but the forward pass also spends 0.026 s on softmax exponentials whose backward costs 0.006 s, and elementwise and memory-bound operations do not double.

So: "about twice" is a FLOP statement
It is exact for the matrix products, which is why FLOP budgets use 6N (and add the attention term at long context). Wall-clock time also depends on memory traffic and on the non-matmul operations, so measure it rather than assume it.
Where 6N and the measured 206.2 GFLOP differ; the runs under load (1 min)

By kind of product: mm 60.1 against 120.3 GFLOP, the attention bmm 8.6 against 17.2. Kaplan's 6N with NN = 25.2 million gives 154.9 GFLOP for the step; the counter's total is 206.2. The gap is the two things 6N leaves out on purpose: the tied output layer (25.8 GFLOP, because it reuses the embedding) and attention over the context (another 25.8 at 512 tokens); 0.2 GFLOP goes the other way, because 6N counts the biases and norm weights as if they were matrix weights. Two earlier timing runs on the same machine under load gave backward-to-forward ratios of 1.95 and 1.57: wall-clock ratios depend on the hardware and on how much of the work is matrix products.

Backward is exactly twice forward in FLOPs, less than twice in time

9. Memory: what the backward pass must keep, and checkpointing

Every rule in section 6 needs something from the forward pass: a linear layer's weight gradient needs its input xx; GELU needs its input; softmax and tanh need their outputs; layer norm needs its input and its statistics. These activations must be kept from the moment the forward pass computes them until the backward pass uses them, so at the turn from forward to backward almost all of them are alive at once. Inference keeps nothing: each value can be freed as soon as the next layer has read it.

Activation checkpointing (also gradient checkpointing or rematerialisation) keeps only some activations and recomputes the missing ones from the nearest checkpoint during the backward pass. Chen et al.: "we design an algorithm that costs O(n)O(\sqrt{n}) memory to train a n layer network, with only the computational cost of an extra forward pass per mini-batch" (Chen et al. 2016, abstract). The argument (their section 4.3, Eq. 1): split nn layers into kk segments, keep the segment boundaries, and hold one segment's n/kn/k activations at a time; memory is about n/k+kn/k + k, smallest at k=nk = \sqrt n, where it is 2n2\sqrt n instead of nn, and each segment is recomputed once, so the extra work is at most one forward pass.

Predict: with 9 layers, how many activations does store-everything hold at its peak, and how many does checkpointing every 3 layers hold? Then step through both: the widget opens at the turn from forward to backward, where memory peaks; its schedule buttons and sliders change the run, and its arrows and scrubber walk it event by event.

One chain, four ways to run it: memory held against layers recomputed

held in memoryrecomputed nowbackward step nowfreed or not yet computed

A chain hk=tanh⁡(wkhk−1)h_k = \tanh(w_k\,h_{k-1}) with a squared-error loss illustrative weights; the backward step through layer kk needs hk−1h_{k-1} (for the weight's gradient) and hkh_k (tanh's derivative is 1−hk21 - h_k^2), exactly what PyTorch saves for mul and tanh. Memory is counted in activations (the input h0h_0 included), compute in layer evaluations. Store-everything peaks at n+1n + 1; checkpointing with k=nk = \sqrt n peaks near 2n2\sqrt n and recomputes fewer than nn layers; storing nothing needs only 4 but recomputes n(n−1)/2n(n-1)/2 layers, quadratic in depth. Schedules are recomputed in src/recompute.py.

Measured on a real model. The 8-block stack of section 8 on an Apple GPU (MPS), its allocator's count of allocated bytes read after every operation of one training step, each block run normally or wrapped in torch.utils.checkpoint.checkpoint(..., use_reentrant=False):

Store-everything held 422.1 MiB at the turn and peaked at 486.1 MiB; checkpointing every block held 52.0 MiB and peaked at 172.6 MiB, for 42.9 GFLOP of recomputation (20.8% more) and a backward pass of 0.288 s instead of 0.182 s; inference peaked at 68 MiB. At scale, activation memory per layer, full against selective recomputation and how checkpointing combines with parallelism are on Distributed Training; how torch.utils.checkpoint works inside is on Tensors, the dispatcher and autograd.

The measured table, where the 422 MiB go, and why the recompute is less than a forward pass (2 min)
runheld at the turn, MiBpeak, MiBextra FLOPsbackward time (CPU), s
inference (no grad)068n/an/a
training, store everything422.1486.100.182
checkpoint every other block237.1301.121.5 G (10.4%, derived: half the blocks)0.235
checkpoint every block52.0172.6+42.9 G (20.8%)0.288
  • Where the 422 MiB go. Walking the autograd graph and adding up every saved tensor (each storage once, weights excluded) gives 442,646,596 bytes, within 444 bytes of the allocator's count. Per block: eight width-512 tensors (the inputs of both layer norms and of three matrix products, plus copies of qq, kk and vv) at 2 MiB each, the GELU input and output at 8 MiB each, and the attention probabilities at 16 MiB; 48.25 MiB a block, 386 MiB for eight, plus 36 MiB for the output layer's log-probabilities and its input. The attention probabilities alone are 128 MiB and grow with the square of the sequence length: the reason FlashAttention recomputes them (6f).
  • Checkpointing every block keeps only each block's input (2 MiB) until the backward pass reaches it, so the held memory falls by a factor of 8. The peak falls less, to 173 MiB, because one block's activations are rebuilt at a time on top of the gradients being accumulated.
  • The extra compute is less than a forward pass. The counted recompute is 42.9 GFLOP, not the blocks' full forward 60.1, because non-reentrant checkpointing "stops recomputation as soon as all needed intermediate activations have been recomputed" (torch.utils.checkpoint docs): each block's last matrix product is never redone, since its saved input is the GELU output, already rebuilt. In time, the whole step went from 0.31 to 0.42 s, about 35% more.
  • The optimal schedule for a fixed number of checkpoints is Griewank and Walther's revolve, whose schedules are "provably optimal with regard to a primary and a secondary criterion" (ACM TOMS 26(1), 2000); recomputing attention inside the kernel is on the FlashAttention paper page.

Checkpointing every block cuts the memory held at the turn from 422 to 52 MiB

10. Vanishing and exploding gradients: a property of the product

By the chain rule, the gradient that reaches layer 0 of an nn-layer chain is a product of nn transposed Jacobians, h‾0=J1⊤J2⊤⋯Jn⊤h‾n\bar h_0 = J_1^\top J_2^\top \cdots J_n^\top\, \bar h_n, so its size is bounded by the product of their largest stretches (spectral norms):

‖h‾0‖≤‖J1‖‖J2‖⋯‖Jn‖‖h‾n‖\lVert \bar h_0 \rVert \le \lVert J_1 \rVert\, \lVert J_2 \rVert \cdots \lVert J_n \rVert\; \lVert \bar h_n \rVert

If each layer scales a typical vector by a factor gg, thirty layers scale it by about g30g^{30}: 0.930=0.0420.9^{30} = 0.042 and 1.130=17.41.1^{30} = 17.4. The gradient vanishes or explodes geometrically with depth, and no single layer is to blame: a 10% shortfall per layer is enough. Below, 30 layers of width 64 with random weights of standard deviation g/64g/\sqrt{64} illustrative, seeded, so each linear layer scales a typical vector by about gg.

Predict: at g=1g = 1 the linear chain's gradient stays near 1. What happens to the tanh chain at g=1g = 1, and at what gg does it stop vanishing? Then drag.

Tanh's slope is at most 1, so at g=1g = 1 every factor shrinks a little and the gradient at layer 0 is 0.039 of what entered; raising gg makes the weights larger but also pushes the units into saturation, where the slope is near 0. The cures all act on the factors: initialisation that sets g≈1g \approx 1 for the activation used, and normalisation that keeps it there (Normalisation and initialisation); residual connections, whose factor I+JFI + J_F keeps an identity path through every layer (section 3), with the branches scaled down at depth (Normalisation, residuals and stability); gradient clipping against the occasional explosion (Optimisers and learning-rate schedulers); and, in recurrent networks, where the same Jacobian is multiplied once per time step, gated cells (Sequence models: the pre-transformer lineage, backpropagation through time).

The toy's numbers at six gains (under 1 min)
gg0.50.91.01.11.52.0
gradient at layer 0, linear8.0e-100.03650.86115.01.65e59.24e8
gradient at layer 0, tanh6.7e-100.01050.03930.1763.4727.9
g30g^{30}9.3e-100.042117.41.92e51.07e9

The linear chain tracks g30g^{30} within the spread of one random draw (30 layers, width 64, seed 7); the tanh chain stays below it at every gain because each factor carries a slope 1−h2≤11 - h^2 \le 1.

The gradient at layer 0 is a product of 30 factors: move the per-layer gain

The loss's gradient enters at layer 30 as a random unit vector and is sent back through Wk⊤W_k^\top (linear) or through Wk⊤W_k^\top after multiplying by tanh's slope 1−hk21 - h_k^2. Log scale: each grid line is a factor of 100,000. Computed in the page (parts/22c_js_new.js), checked against src/two_layer.py.

11. Checking any gradient numerically

Compare the analytic gradient with a finite difference. A Taylor expansion, f(x±h)=f(x)±hf′(x)+h22f′′(x)±h36f′′′(x)+⋯f(x \pm h) = f(x) \pm h f'(x) + \tfrac{h^2}{2} f''(x) \pm \tfrac{h^3}{6} f'''(x) + \cdots, shows how differently the two common differences behave:

f(x+h)−f(x)h=f′(x)+h2f′′(x)+⋯,f(x+h)−f(x−h)2h=f′(x)+h26f′′′(x)+⋯\frac{f(x + h) - f(x)}{h} = f'(x) + \frac{h}{2} f''(x) + \cdots, \qquad \frac{f(x + h) - f(x - h)}{2h} = f'(x) + \frac{h^2}{6} f'''(x) + \cdots
  • Use float64. In float32 the rounding floor is about 10−710^{-7} relative, and a correct gradient can fail: the correct fused softmax cross-entropy below fails gradcheck in float32 with "Jacobian mismatch". The documentation warns: "The default values are designed for input of double precision" (torch.autograd.gradcheck; defaults eps 10−610^{-6}, atol 10−510^{-5}, rtol 10−310^{-3}). Machine epsilon and catastrophic cancellation are sections 2 and 4 of Numerical computing for ML.
  • Compare relatively: |a−n|/max⁡(1,|a|,|n|)|a - n| / \max(1, |a|, |n|), so that large and small gradients are judged alike.
  • Check a VJP with one random probe. To check a layer's backward without building its Jacobian, pick a random y‾\bar y and differentiate the scalar y‾⋅f(x)\bar y \cdot f(x) numerically: its gradient is exactly J⊤y‾J^\top \bar y. The workbench in section 6 checks every layer this way.
  • Avoid kinks: ReLU at exactly 0, max-pooling ties and absolute values make finite differences straddle a corner. Check at points away from them.

What a check catches. The most common bug in a hand-written backward rule is forgetting that a VJP must multiply by the incoming gradient. It goes unnoticed when the function is the last thing before .sum().backward() (the incoming gradient is then 1) and breaks as soon as anything is downstream; gradcheck reports it at once.

A custom backward for softmax cross-entropy, its gradcheck, and the buggy version, run for real (2 min)

Write your own backward when the composed rule is numerically poor (it divides by a tiny probability, as in 6d), when it saves more than needed (keep pp instead of every intermediate), when a fused kernel hides its inside from the framework, or when you deliberately want a different "gradient" (a straight-through estimator for rounding in quantisation-aware training). PyTorch's recipe: "Subclass Function and implement the forward(), (optional) setup_context() and backward() methods"; "backward() (or vjp()) defines the gradient formula. It will be given as many Tensor arguments as there were outputs, with each of them representing gradient w.r.t. that output ... It should return as many tensors as there were inputs"; and "save_for_backward() should be used to save any tensors needed for the backward pass" (Extending PyTorch). The mechanics of autograd.Function are on Tensors, the dispatcher and autograd.

class SoftmaxCE(torch.autograd.Function):
    @staticmethod
    def forward(z, y):
        logp = z - torch.logsumexp(z, dim=-1, keepdim=True)
        return -logp.gather(-1, y[..., None]).squeeze(-1)

    @staticmethod
    def setup_context(ctx, inputs, output):
        z, y = inputs
        ctx.save_for_backward(torch.softmax(z, dim=-1), y)   # keep p, not the logits

    @staticmethod
    def backward(ctx, gL):
        p, y = ctx.saved_tensors
        gz = p.clone()
        gz.scatter_add_(-1, y[..., None], -torch.ones_like(y, dtype=p.dtype)[..., None])  # p - onehot
        return gL[..., None] * gz, None                      # times the incoming gradient; y gets none

# on the rows (2, 1, 0) with target 2 and (0.5, -1, 3) with target 0, float64:
loss  [2.4076, 2.5957]
grad  [[0.6652, 0.2447, -0.9100], [-0.9254, 0.0166, 0.9088]]
gradcheck(SoftmaxCE.apply, (z, y))         -> True
# the same backward without "gL[..., None] *":
gradcheck(SoftmaxCEBuggy.apply, (z, y))    -> GradcheckError: Jacobian mismatch for output 0 with respect to input 0

Script and output: src/inputs/measure/custom_fn.py, custom_fn.out. The first row is the tiny model: loss 2.408, gradient p−yp - y. JAX's equivalent is jax.custom_vjp (forward returns the output and the residuals to save; backward maps residuals and cotangent to input cotangents).

The central difference's error falls a hundredfold per tenfold smaller step

hhone-sided errorcentral error
0.14.2e-31.1e-4
0.014.1e-41.1e-6
0.0014.1e-51.1e-8
0.00014.1e-61.1e-10

On the tiny model's ∂L/∂zsat=−0.90997\partial L/\partial z_{\text{sat}} = -0.90997, float64 (src/recompute.py): the one-sided error is proportional to hh, the central one to h2h^2, as the expansion predicts. Too small an hh loses again to rounding, because f(x+h)−f(x−h)f(x + h) - f(x - h) subtracts two nearly equal numbers; the root's Gradient lab plots the full V shape, where rounding takes over below about h=10−6h = 10^{-6}.

12. What autograd records

PyTorch's autograd is reverse-mode AD run on a graph recorded afresh on every forward pass (which is what lets ordinary Python control flow decide the graph): each operation adds a backward node, which is that operation's VJP rule from section 6, and saves the tensors the rule needs (section 9). loss.backward() starts at the root with gradient 1 and runs each node once all its incoming gradients have arrived; a parameter's node adds the result into .grad. Here is the tiny model, run for real (PyTorch 2.14.1, src/inputs/measure/tiny_autograd.py):

x = torch.tensor([2., 1.], requires_grad=True)
W = torch.tensor([[1., 0.], [0., 1.], [1., -2.]], requires_grad=True)
L = F.cross_entropy((W @ x)[None], torch.tensor([2]))
# walking L.grad_fn and each node's next_functions prints:
NllLossBackward0     -> LogSoftmaxBackward0   saved: self (1, 3), target (1,), total_weight ()
LogSoftmaxBackward0  -> UnsqueezeBackward0    saved: result (1, 3)
UnsqueezeBackward0   -> MvBackward0           saved: nothing
MvBackward0          -> AccumulateGrad (W), AccumulateGrad (x)   saved: self (3, 2), vec (2,)
# the saved tensors are the very objects W and x, not copies:
z.grad_fn._saved_self is W, z.grad_fn._saved_vec is x   ->  True True

MvBackward0 is rule 6a; LogSoftmaxBackward0 and NllLossBackward0 are the two halves of 6d. Saved tensors are references, so a saved weight costs nothing extra; a saved activation is the memory of section 9. How the engine schedules nodes, version counters for in-place safety, retain_graph, hooks and no_grad are Tensors, the dispatcher and autograd's subject. JAX and torch.func do the same as function transforms (closed block below; JAX core).

JAX and torch.func: the same rules as function transforms (1 min)

JAX traces the function into a jaxpr, applies forward mode with jax.jvp, extracts the linear map with jax.linearize and gets reverse mode by transposing it (jax.vjp; jax.grad is vjp with the cotangent 1); run on the tiny model in float64 it gives the same W‾\bar W and x‾\bar x as PyTorch to the last digit, and its backward dot_general contracts WW's rows where the forward one contracted its columns: the transpose of rule 6a, produced mechanically (JAX core). torch.func offers the same function transforms on PyTorch's engine: grad, vjp, jvp, jacrev, jacfwd, hessian and vmap, which gives per-example gradients in one call.

The real autograd graph of one transformer block: 71 nodes, what each saved, the engine's order (explore)

The graph PyTorch built, read back node by node: one pre-norm transformer block (layer norm, a 2-head causal self-attention written out as explicit matrix products and a softmax, a residual, layer norm, a GELU MLP, a residual), a final layer norm and a tied output layer, on the tokens [3, 1, 4, 1, 5] with width 8, MLP width 32 and a vocabulary of 16. The script walked loss.grad_fn through next_functions, read every _saved_ attribute, and recorded the order the engine ran the nodes during loss.backward() with a pre-hook on each node (src/inputs/measure/graph.py). 13 of the 71 nodes are AccumulateGrad, one per parameter; the tied embedding's runs last, after both of its uses have sent their gradients.

Click a node to see what it computes, what it saved and why.

    Nodes are listed in the order the engine executed them. Chips: activation saved is memory held for the backward pass; weight is a saved reference to a parameter, which costs nothing extra. Dimensions printed as -1 and -2 are stored by PyTorch as unsigned integers and converted here. Sizes in bytes (float32).

    Depth: second order, einsum, mistakes and research

    Hessian-vector products: curvature without the Hessian, measured (4 min)

    The Hessian HH of a scalar LL is the Jacobian of its gradient, Hij=∂2L/∂θi∂θjH_{ij} = \partial^2 L / \partial \theta_i \partial \theta_j, an n×nn \times n symmetric matrix; its meaning, its eigenvalues and Newton's method are on Calculus and optimisation for ML. Almost every use needs only products HvHv, which never need HH:

    Hv=∇θ(∇θL⋅v)=ddε∇θL(θ+εv)|ε=0Hv = \nabla_\theta\big(\nabla_\theta L \cdot v\big) = \frac{d}{d\varepsilon}\, \nabla_\theta L(\theta + \varepsilon v)\Big|_{\varepsilon = 0}

    Left: take the gradient, dot it with the fixed vector vv, and take the gradient of that: two reverse passes, "double backward". Right: the directional derivative of the gradient along vv: one forward-mode pass through the gradient computation, "forward-over-reverse". Pearlmutter's 1994 paper gives "an exact and numerically stable procedure for computing [HvHv], which takes about as much computation, and is about as local, as a gradient evaluation", in "O(n) time and space" against the O(n2)O(n^2) of forming HH (Pearlmutter 1994, abstract and section 1). JAX's cookbook recommends the second nesting: "forward-over-reverse is typically the most efficient" (The Autodiff Cookbook); Baydin et al. note that the nestings perform "the same arithmetic operation sequence" and differ in overheads (footnote 16).

    # PyTorch, double backward
    g, = torch.autograd.grad(loss_fn(theta), theta, create_graph=True)   # keep the graph of the gradient
    Hv, = torch.autograd.grad(g @ v, theta)
    # PyTorch or JAX, forward-over-reverse
    Hv = torch.func.jvp(torch.func.grad(loss_fn), (theta,), (v,))[1]
    Hv = jax.jvp(jax.grad(loss_fn), (theta,), (v,))[1]

    The tiny model. As a function of the input xx, the loss has Hessian W⊤(diag⁡(p)−pp⊤)WW^\top(\operatorname{diag}(p) - pp^\top)W: the softmax Jacobian sandwiched by the linear layer, with entries H11=0.1848H_{11} = 0.1848, H12=H21=−0.2289H_{12} = H_{21} = -0.2289, H22=0.6007H_{22} = 0.6007. The HVP along v=(1,0)v = (1, 0) is its first column, (0.1848,−0.2289)(0.1848, -0.2289); PyTorch's double backward, jax.jvp(jax.grad(...)) and jax.hessian all give these numbers.

    The explicit Hessian grows like nn gradients in time and n2n^2 in memory, so beyond a few thousand parameters only HVPs are practical. The advice on nesting is implementation-specific: in these PyTorch runs double backward was as fast as forward-over-reverse or faster at every size (16.4 against 19.9 ms at n=102,720n = 102{,}720), the opposite of JAX's recommendation for JAX, which is the "implementation-dependent" overhead Baydin et al.'s footnote warns about.

    What HVPs are used for: Newton-type steps without the matrix (solve Hδ=−gH\delta = -g by conjugate gradients: "Hessian-free" optimisation); the sharpness λmax⁡(H)\lambda_{\max}(H) by power iteration (v←Hv/‖Hv‖v \leftarrow Hv/\lVert Hv \rVert), behind the learning-rate ceiling 2/λmax⁡2/\lambda_{\max} and the edge-of-stability observations; the trace of HH by Hutchinson's estimator, the average of v⊤Hvv^\top H v over random sign vectors; and influence functions, which need H−1H^{-1} times a gradient. Second-order optimisers such as K-FAC and Shampoo instead approximate curvature with structured matrices built from gradients and activations (Optimisers and learning-rate schedulers).

    Einsum: one notation for every contraction, its FLOP count and its backward pass (3 min)

    Einsum labels every axis with a letter: a letter that appears in the inputs but not in the output is summed over, and the output's letters, in order, give its shape (so a transpose is a relabelling). Carried from the old Linear algebra page (checked):

    operationeinsum
    matrix productij,jk->ik
    batched matrix productbij,bjk->bik
    attention scores, per batch and headbhqd,bhkd->bhqk
    attention outputbhqk,bhkd->bhqd
    outer product; tracei,j->ij; ii->

    The cost falls out of the letters. A contraction does one multiply-add per combination of all its distinct letters. For attention scores with batch b=2b = 2, heads h=8h = 8, q=k=128q = k = 128 and head width d=64d = 64: 2⋅8⋅128⋅128⋅64=16,777,2162 \cdot 8 \cdot 128 \cdot 128 \cdot 64 = 16{,}777{,}216 multiply-adds (33.6 million FLOPs, NumPy's einsum_path count, 3.355e+07). Doubling the sequence length doubles both qq and kk, so the cost quadruples: attention's quadratic cost, read off the string.

    Order matters for three or more operands. ABvABv with 1000×10001000 \times 1000 matrices: NumPy's np.einsum_path('ij,jk,k->i', A, B, v, optimize='optimal') reports (NumPy 2.5.3) "Naive FLOP count: 3.000e+09", "Optimized FLOP count: 4.000e+06", "Theoretical speedup: 750.000", by contracting k,jk->j first. (NumPy's count is the multiply-adds times the number of operands, 3 here.) Its "optimal" strategy "combinatorially explores all possible ways of contracting the listed tensors"; the default "greedy" one is "Equivalent to the 'optimal' path for most contractions" (numpy.einsum_path). Section 3's lesson again: multiply by the vector first.

    The backward pass of an einsum is an einsum. For CC = einsum('ij,jk->ik', A, B), A‾\bar A = einsum('ik,jk->ij', C̄, B) =C‾B⊤= \bar C B^\top and B‾\bar B = einsum('ij,ik->jk', A, C̄) =A⊤C‾= A^\top \bar C, rule 6a with no transposes to remember. Each backward einsum has the same letters as the forward one, so the same cost: a two-operand contraction costs twice as much backward, section 8 again.

    Edit the sizes as letter=number pairs separated by spaces. The backward contractions are generated by the rule above (shown for two-operand contractions without a repeated letter inside one operand).

    Mistakes the sections above do not already show (1 min)
    • "Checkpointing costs one whole extra forward pass." At most one. Non-reentrant checkpointing stops recomputing early (20.8% extra FLOPs measured, against 33% for a full forward of the step), and selective recomputation of only the attention core costs 2 to 3% (Distributed Training).
    • Modifying a saved tensor in place raises an error only when the backward pass reaches that node, far from the line that caused it; torch.autograd.set_detect_anomaly(True) reports the forward operation responsible.
    • Gradient accumulation over micro-batches is the same mechanism as the bug of forgetting zero_grad(), used on purpose: divide the loss by the number of micro-batches.
    • Breaking the graph without noticing. .detach(), .item(), .numpy(), in-place writes to .data, and integer operations such as argmax and rounding all stop gradients: the parameters before them silently get zero or no gradient. A straight-through estimator (a custom backward that passes y‾\bar y through unchanged) is the deliberate version.
    • Mean against sum in the loss. With reduction="mean" each example's gradient carries a factor 1/B1/B (6d). Switching to a sum multiplies every gradient by the batch size, which acts like multiplying the learning rate by it.
    Where research is going: attacking the memory and the ordering of reverse mode (2 min)
    • Not storing activations at all. Reversible networks reconstruct each layer's input from its output during the backward pass: RevNet is "a variant of ResNets where each layer's activations can be reconstructed exactly from the next layer's", so "the activation storage requirements are independent of depth" (Gomez et al. 2017).
    • Differentiating a solution instead of the steps that found it. Implicit differentiation applies the implicit function theorem at a fixed point or an optimum. Deep equilibrium models "analytically backpropagate through the equilibrium point using implicit differentiation", so training needs "only constant memory, regardless of the effective "depth" of the network" (Bai, Kolter and Koltun 2019); JAXopt made the technique modular (Blondel et al. 2022).
    • Gradients from forward mode alone. The "forward gradient" multiplies a random direction vv by the JVP along it: "an unbiased estimate of the gradient that can be evaluated in a single forward run of the function, entirely eliminating the need for backpropagation" (Baydin et al. 2022). Its variance grows with the number of parameters, which is why it has not replaced backpropagation for large models.
    • Splitting the backward pass. Rule 6a's two products, X‾\bar X (needed at once by the previous layer) and W‾\bar W (needed only by the optimiser), can be scheduled separately. Zero Bubble pipeline parallelism does exactly this, "to split the backward computation into two parts, one that computes gradient for the input and another that computes for the parameters", to fill pipeline bubbles (Qi et al. 2023; see Distributed Training).
    • Letting the compiler choose what to save. torch.compile traces forward and backward together (AOTAutograd) and decides which activations to save and which to recompute by a min-cut over the joint graph: "a min-cut based recomputation pass with AOTAutograd + NVFuser that consistently improves both memory and runtime" (He 2022, PyTorch developer forum). Cheap elementwise operations are recomputed; matrix products and random operations are saved.