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.
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.
For a scalar 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 weight, is . With respect to the scores, the root page derives : raising the cat score by a small raises the loss by about ; raising the sat score lowers it by about .
A function has one slope per (output, input) pair. Arranged with one row per output, they form the Jacobian:
Row is the gradient of output , laid flat; column says how every output responds when only input moves. Three Jacobians cover most of a network:
| 0.2227 | −0.1628 | −0.0599 | |
| −0.1628 | 0.1848 | −0.0220 | |
| −0.0599 | −0.0220 | 0.0819 |
Write with . For the same index, the quotient rule (top' times bottom minus top times bottom', over bottom squared), with and :
For a different index , the top does not move, the bottom does:
Both cases at once: , that is , where the outer product is a column times a row, a square table whose entry is .
The shape of every derivative. The derivative of something with entries with respect to something with entries holds numbers ( here is ):
| derivative of ... with respect to ... | scalar | vector () | matrix () |
|---|---|---|---|
| scalar | scalar | vector, (the gradient) | matrix, |
| vector () | vector, | matrix, (the Jacobian) | 3-index array, |
| matrix () | matrix, | 3-index array | 4-index array, |
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.
Think of as the height of a landscape. The slope walking due east (only changes) and due north (only ) are the partial derivatives; every other direction's slope is a mix of them. Stacking them gives , and the best linear prediction of a small step is . The slope along a unit direction , the directional derivative, is ; it is largest along the gradient, which is why training steps the other way.
Worked example: at , where . and , so . Prediction for : ; the exact value is . Along the slope is , a little under the steepest possible slope .
What gradients are used for in ML: every optimiser step (, learning rate ); 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).
A paper writes and its shape is the transpose of W.grad. Neither is wrong: the slopes are the same numbers, written the other way round.
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.
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 and and a target , , so has rows , , , the same as PyTorch's autograd (checked in src/recompute.py). The root's Notation decoder has a second worked example, , on its layout card (Topic: math, Notation decoder).
Entry by entry they agree: , for example (highlighted). In symbols: for is () in numerator layout and () in denominator layout; is the row or the same numbers as a column; is , , or , , what W.grad holds.
Let and . A small step moves by about , and that moves by about times it:
The Jacobian of a chain is the product of the Jacobians, in the order of the chain; entry by entry, , the effect of on through every intermediate . The shapes line up by themselves, times , and is evaluated at the value that 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, . Written as gradients shaped like the variables, the chain rule becomes the vector-Jacobian product:
Order matters: multiply from the loss end. For layers, . Any bracketing gives the same answer, not the same cost. From the loss end every product is a row times a matrix: multiply-adds for width , in all. From the input end every product is a matrix times a matrix, each: at 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:
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:
Multiply-adds counted the same way in both modes: applying a matrix with rows and columns costs ; the shared forward pass is not counted. Forward mode: 16 per sweep, 96 for six; reverse mode: 16 for , 6 more for . Values from parts/22b_js_core.js, checked against src/recompute.py.
The rule. For the whole Jacobian costs forward-mode passes or reverse-mode passes. The standard survey's bound: "" in forward mode and "" 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 and in the billions, so reverse mode, by a factor of . 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 (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, , needs only the error 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 cheap gradient principle. Griewank calls a gradient at a small constant multiple of the function's cost, whatever , 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 with . Then for any smooth (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).
Put a ReLU layer in front of the scores: , , , cross-entropy on sat. This is the root page's Gradient lab network, () with rows , , and () with rows , , illustrative, chosen so the scores come out 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.
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 back through and gives its weight ; an elementwise function multiplies by its slope (a ReLU's is 0 or 1); and the loss starts the pass at . Unit 3 was off, so its row of and its column of 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.
, , , label 1. Forward: , , loss . Backward: ; the linear rule gives , and . One step with learning rate 0.1: , , new , : the right answer became more likely.
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 , 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.
is . One entry is ; appears only in output , times ; appears in every output, times ; once, with slope 1. So
A batch. PyTorch's nn.Linear stores as (out, in) and computes for of shape , one example per row:
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. 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 .
jax.grad give the same to 15 digits (src/recompute.py).The Jacobian is diagonal (section 1), so the VJP is an entry-by-entry product, :
| what PyTorch saves for it (derivatives.yaml, v2.14.1, lines 2132, 1788, 1550, 2160) | ||
|---|---|---|
| ReLU, | 1 where , else 0 | its output: threshold_backward(grad, result, 0) |
| tanh | its output: tanh_backward(grad, result) | |
| sigmoid | its output: sigmoid_backward(grad, result) | |
| GELU, | its input: gelu_backward(grad, self, approximate) |
is the standard normal cumulative distribution and 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 with : ReLU passes ; GELU's slopes are , so . GELU's slope is negative below about and above 1 near : it is not a monotone function.
The check nudges every input entry by and differences the probe loss , 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.
Multiply section 1's Jacobian (symmetric, so ) by an incoming and simplify:
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, , against 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 (_softmax_backward_data(grad, result, dim, ...), derivatives.yaml line 2237). On with : , so , which adds up to 0, as it must.
gives (the one-hot vector of the right word, divided by its probability, which can be tiny), so , and softmax's VJP gives
The division by cancels exactly. Computed separately, a probability that underflows to 0 would give 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 examples (reduction="mean") each row's gradient is ; with label smoothing or distillation targets , it is . The losses themselves, and the same result from , are on Loss functions and Calculus and optimisation for ML, section 2.
Layer norm (Ba, Kiros and Hinton 2016) rescales each token's vector ( entries) to mean 0 and variance 1, then applies a learned scale and shift : with (PyTorch's rstd; defaults to ), and . The backward rule, with :
Take the incoming gradient, remove its average (the output cannot respond to adding a constant to every entry of ), remove its component along (nor to scaling up), and scale by . The result always adds up to 0 and is orthogonal to . On , , : , , , and , the same as PyTorch's F.layer_norm.
On the numbers: , , , , so ; it adds up to 0 and its dot product with is 0.
The real kernel writes the same thing with two sums per row. From PyTorch v2.14.1's CPU kernel (scale is , a is , ds , db ):
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: , , , and reproduces (checked in src/recompute.py).
RMSNorm (used by Llama and most 2026 open models) drops the mean: , , and the same steps give with : only the scaling direction is removed. On the same numbers, . Why these norms are there is Normalisation and initialisation's subject.
One head: is , and are ; , , . Backward, each line one of the rules above, given :
One identity makes attention's backward pass cheap in memory. Substituting :
comes from the output and its gradient alone, one number per query, without the matrix . FlashAttention's backward pass uses exactly this and recomputes block by block instead of storing it (Dao et al. 2022 define in Eq. 4 of appendix B.2 and compute "" 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.
Numbers (workbench defaults). has rows and ; of the tiny model; . The first query is the root page's: scores , weights , output . With rows and : , rows and , rows , , . 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 the helpers' general case is grad.mm(mat2.t()) for and mat1.t().mm(grad) for : and , rule 6a. The result: line is the forward-mode rule (section 4): the tangent of is , the product rule.
Drawn to scale for positions and head width illustrative sizes. Forward: and make , softmax makes , times makes . Backward: gives and ; with , one number per query (gold), becomes ; gives and . Every gradient has its variable's shape.
Index-by-index derivations get long for expressions like or . Instead, take the differential , the first-order change in when the input changes by a small , with the familiar rules applied to whole matrices (keeping the order of factors). Since is exactly the linear prediction with slopes , the identification rule reads the gradient off:
The recipe: take the differential, use to move to the far right inside a trace, and read off what stands in front of it, transposed. For a linear layer, , so : section 6a in one line.
| rule | differential |
|---|---|
| sum, constant | , , for a constant |
| product | |
| transpose, trace | , |
| inverse | (differentiate ) |
| log-determinant | |
| elementwise function |
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, ; and . 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 with the derivative laid out by , so his is the transpose of the gradient here: the same rule in the other layout.
A quadratic form : (a scalar equals its transpose), so , which is when is symmetric. With rows , and : , and both routes give .
A log-determinant (in every Gaussian log-likelihood and in normalising flows): , so . With rows , : and has rows , . Check one entry: raising by makes the determinant , so rises by about .
Least squares , with the data matrix: , so , and setting it to zero gives the normal equations . Carried from the old Linear algebra page (checked): fit to ; has rows , and , so . The residuals add up to 0 and are orthogonal to , which is what says. Why solvers prefer QR to forming (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):
| gradient | ||
|---|---|---|
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).
Count one linear layer. Forward computes : one matrix product, multiply-adds. Backward (6a) computes two of the same size: and . Almost all of a transformer's arithmetic is matrix products, and a multiply-add is 2 FLOPs, so a model with weights spends about FLOPs per token forward and 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 floating point operators per training token" (Scaling Laws for Neural Language Models, section 2.1; paper page). Their forward count is (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.
By kind of product: mm 60.1 against 120.3 GFLOP, the attention bmm 8.6 against 17.2. Kaplan's 6N with = 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.
Every rule in section 6 needs something from the forward pass: a linear layer's weight gradient needs its input ; 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 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 layers into segments, keep the segment boundaries, and hold one segment's activations at a time; memory is about , smallest at , where it is instead of , and each segment is recomputed once, so the extra work is at most one forward pass.
A chain with a squared-error loss illustrative weights; the backward step through layer needs (for the weight's gradient) and (tanh's derivative is ), exactly what PyTorch saves for mul and tanh. Memory is counted in activations (the input included), compute in layer evaluations. Store-everything peaks at ; checkpointing with peaks near and recomputes fewer than layers; storing nothing needs only 4 but recomputes 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.
| run | held at the turn, MiB | peak, MiB | extra FLOPs | backward time (CPU), s |
|---|---|---|---|---|
| inference (no grad) | 0 | 68 | n/a | n/a |
| training, store everything | 422.1 | 486.1 | 0 | 0.182 |
| checkpoint every other block | 237.1 | 301.1 | 21.5 G (10.4%, derived: half the blocks) | 0.235 |
| checkpoint every block | 52.0 | 172.6 | +42.9 G (20.8%) | 0.288 |
By the chain rule, the gradient that reaches layer 0 of an -layer chain is a product of transposed Jacobians, , so its size is bounded by the product of their largest stretches (spectral norms):
If each layer scales a typical vector by a factor , thirty layers scale it by about : and . 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 illustrative, seeded, so each linear layer scales a typical vector by about .
Tanh's slope is at most 1, so at every factor shrinks a little and the gradient at layer 0 is 0.039 of what entered; raising 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 for the activation used, and normalisation that keeps it there (Normalisation and initialisation); residual connections, whose factor 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).
| 0.5 | 0.9 | 1.0 | 1.1 | 1.5 | 2.0 | |
|---|---|---|---|---|---|---|
| gradient at layer 0, linear | 8.0e-10 | 0.0365 | 0.861 | 15.0 | 1.65e5 | 9.24e8 |
| gradient at layer 0, tanh | 6.7e-10 | 0.0105 | 0.0393 | 0.176 | 3.47 | 27.9 |
| 9.3e-10 | 0.042 | 1 | 17.4 | 1.92e5 | 1.07e9 |
The linear chain tracks 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 .
The loss's gradient enters at layer 30 as a random unit vector and is sent back through (linear) or through after multiplying by tanh's slope . 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.
Compare the analytic gradient with a finite difference. A Taylor expansion, , shows how differently the two common differences behave:
gradcheck in float32 with "Jacobian mismatch". The documentation warns: "The default values are designed for input of double precision" (torch.autograd.gradcheck; defaults eps , atol , rtol ). Machine epsilon and catastrophic cancellation are sections 2 and 4 of Numerical computing for ML.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.
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 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 . JAX's equivalent is jax.custom_vjp (forward returns the output and the residuals to save; backward maps residuals and cotangent to input cotangents).
| one-sided error | central error | |
|---|---|---|
| 0.1 | 4.2e-3 | 1.1e-4 |
| 0.01 | 4.1e-4 | 1.1e-6 |
| 0.001 | 4.1e-5 | 1.1e-8 |
| 0.0001 | 4.1e-6 | 1.1e-10 |
On the tiny model's , float64 (src/recompute.py): the one-sided error is proportional to , the central one to , as the expansion predicts. Too small an loses again to rounding, because subtracts two nearly equal numbers; the root's Gradient lab plots the full V shape, where rounding takes over below about .
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 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 and as PyTorch to the last digit, and its backward dot_general contracts '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 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.
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).
The Hessian of a scalar is the Jacobian of its gradient, , an symmetric matrix; its meaning, its eigenvalues and Newton's method are on Calculus and optimisation for ML. Almost every use needs only products , which never need :
Left: take the gradient, dot it with the fixed vector , and take the gradient of that: two reverse passes, "double backward". Right: the directional derivative of the gradient along : one forward-mode pass through the gradient computation, "forward-over-reverse". Pearlmutter's 1994 paper gives "an exact and numerically stable procedure for computing [], which takes about as much computation, and is about as local, as a gradient evaluation", in "O(n) time and space" against the of forming (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 , the loss has Hessian : the softmax Jacobian sandwiched by the linear layer, with entries , , . The HVP along is its first column, ; PyTorch's double backward, jax.jvp(jax.grad(...)) and jax.hessian all give these numbers.
The explicit Hessian grows like gradients in time and 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 ), 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 by conjugate gradients: "Hessian-free" optimisation); the sharpness by power iteration (), behind the learning-rate ceiling and the edge-of-stability observations; the trace of by Hutchinson's estimator, the average of over random sign vectors; and influence functions, which need 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 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):
| operation | einsum |
|---|---|
| matrix product | ij,jk->ik |
| batched matrix product | bij,bjk->bik |
| attention scores, per batch and head | bhqd,bhkd->bhqk |
| attention output | bhqk,bhkd->bhqd |
| outer product; trace | i,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 , heads , and head width : multiply-adds (33.6 million FLOPs, NumPy's einsum_path count, 3.355e+07). Doubling the sequence length doubles both and , so the cost quadruples: attention's quadratic cost, read off the string.
Order matters for three or more operands. with 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 = einsum('ij,jk->ik', A, B), = einsum('ik,jk->ij', C̄, B) and = einsum('ij,ik->jk', A, 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).
torch.autograd.set_detect_anomaly(True) reports the forward operation responsible.zero_grad(), used on purpose: divide the loss by the number of micro-batches..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 through unchanged) is the deliberate version.reduction="mean" each example's gradient carries a factor (6d). Switching to a sum multiplies every gradient by the batch size, which acts like multiplying the learning rate by it.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.Times for knowledge base pages are their own stated reading times or, where none is stated, estimated from the length of the Reading tab (about 230 words a minute). Times for outside resources are for the part recommended, checked on 5 October 2026. Every link opens in a new tab.
The whole map: which maths each part of ML uses, and one prediction of the tiny model used here followed through one training step. Its Notation decoder tab has the layout-convention card; its Gradient lab has the backprop tape on the tiny model and a two-layer ReLU network, the finite-difference error curve and eight real gradient bugs.
Vectors to SVD, rank, conditioning, low-rank methods; least squares and why solvers use QR. Its old matrix-calculus material now lives here.
Derivatives to convexity, Hessians and their eigenvalues, Newton's method, Lagrange multipliers; the loss-by-loss gradient derivations. Its old backprop material now lives here.
Floating point, precision formats, stable softmax: why gradient checks need float64 and why fused losses matter.
Where each loss comes from (maximum likelihood), so where each gradient on this page starts.
Cross-entropy and KL divergence: the quantities whose gradients section 6d derives.
Estimation, bias and variance, bootstrap and tests.
ELBO, VAEs and diffusion, where gradients through sampling (the reparameterisation trick) are the next step after this page.
PyTorch's autograd engine: the graph and how the engine schedules it, saved tensors, version counters, hooks, custom autograd.Function, how torch.utils.checkpoint works. This page is the maths each node computes.
jaxprs, grad, jvp and vjp as transforms, linearize and transpose, custom rules.
Backpropagation through time and the vanishing gradient in recurrent networks, the case section 10 points to; LSTM and GRU gates.
Residual scaling, initialisation and loss spikes in transformers: how deep stacks keep their gradient products near 1.
Activation memory at scale (34sbh per layer), full against selective recomputation, and how checkpointing combines with data, tensor and pipeline parallelism; zero-bubble schedules that split the backward pass.
Attention's backward pass without storing the attention matrix: the D identity of section 6f, used in a tiled kernel.
Where 6N comes from and what it leaves out.
The other half of training memory: gradients and optimiser state, and how to shard them.
Why layer norm and RMSNorm are there; this page derives their backward passes.
ReLU, GELU, SwiGLU and their derivatives' shapes, dead units and saturation.
The catalogue of losses whose gradients start every backward pass.
What happens to the gradient after backprop: SGD, Adam, Muon, second-order preconditioners.
The forward against reverse mode picture with small graphs; the gentlest start (31 Aug 2015).
Builds a scalar reverse-mode engine from nothing; the code is micrograd.
Local gradients, gates and the patterns in backward flow, with the matrix-product rule derived from shapes.
Jacobians and the vector chain rule from scratch, in numerator layout (also arXiv 1802.01528).
Vector calculus: gradients (5.2), Jacobians and the numerator layout (5.3), gradients of matrices (5.4), backpropagation and automatic differentiation (5.6), higher-order derivatives (5.7). Free PDF.
The graph, saved tensors, in-place checks, multithreading; with Extending PyTorch (custom Functions, 30 min) and Hooks for autograd saved tensors (20 min).
grad, jvp, vjp, jacfwd, jacrev, Hessian-vector products, with the cost of each.
JMLR 2018. Sections 2 and 3 (what AD is and is not, forward and reverse mode, costs) are the core, about 45 minutes.
The differential method of section 7, with a table of canonical forms.
The modern textbook: differentiation (ch. 2), finite differences (ch. 7), automatic differentiation including checkpointing and linear transposition (ch. 8), second-order AD (ch. 9). 2024, free on arXiv.
The standard reference on AD: complexity bounds, checkpointing (revolve), higher derivatives.
The checkpointing argument (section 4.3).
Hessian-vector products at the cost of a gradient. Neural Computation 6(1).
The 6N accounting.
The memory-efficient attention backward pass.
The definition (section 3, Eq. 3; the paper's version has no ).
The history, and the cheap gradient principle.
Node perturbation with per-token credit scaled to transformers of up to 243M parameters: the third option of section 4, and how far it gets. Our article page counts its compute and reads its claims narrowly.
Identities for derivatives, inverses and decompositions: look up, do not memorise.
Type a matrix expression, get its derivative symbolically; good for checking a trace-trick derivation.
Every built-in operator's backward rule and forward-mode rule, as quoted in section 6.
Built from src/ in the knowledge base repository: recompute.py recomputes every number and checks the hand-derived gradients against PyTorch autograd and JAX; check_js.mjs checks this page's JavaScript against it; the measurement scripts and their outputs are in src/inputs/measure/.