14.3 Matrix differentials, the trace trick, and closed-form VJPs
Scalar reverse mode: the Value graph gave you reverse mode one scalar at a time. That is enough to understand the mechanics and far too slow to train anything. A bigram model’s forward pass is a matmul followed by a softmax over 256 entries per row, about 16 million multiply-adds per step; spelled out as Python Value objects, that is minutes per step instead of milliseconds.
Concepts from other sections (20)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Reverse mode: automatic differentiation that records the computation and walks it backward once from the output, pushing adjoints into inputs. Read more: 14.2 Scalar reverse mode: the Value graph
- bigram model: a language model that predicts the next token from the current token alone, stored as a table. Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- op library (
F): the module of differentiable functions, each a NumPy forward plus one closed-form VJP joined byfrom_op. Read more: 6.3 The op library and gradcheck_all in AI Engineering - LayerNorm: per-row normalization by the population mean and variance with inside the square root, then an affine map. Read more: 6.5 Module system and basic layers in AI Engineering
- RMSNorm: divides a vector by its root mean square plus eps (inside the root) and multiplies by a learned gain; no mean subtraction, no bias. Read more: 13.1 Pre-LN and RMSNorm in AI Engineering
- Cross-entropy: , the average surprise when data from are predicted with . Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
- Vector-Jacobian product (VJP): , what one backward pass from leaves in the leaves. Read more: 14.2 Scalar reverse mode: the Value graph
- Gradcheck: a comparison of a hand-written gradient against central differences of . Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- stable softmax: softmax computed after subtracting the largest logit, so
expnever overflows. Read more: 25.6 Usage policy enforcement in AI Engineering - Inner product: . Read more: 9.6 Inner products, projections, cosine similarity, and top-k
- Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- Standard deviation: , the typical distance of a random variable from its mean, in the same units as the variable itself. Read more: Chapter 13: Probability and Statistics
- Chain rule: . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
- Product rule / quotient rule: and , the rules for differentiating a product or a ratio of two functions. Read more: Chapter 7: Calculus 1
- Jacobian: the matrix of partial derivatives of a function . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
- Log-sum-exp (LSE): , computed stably as . Read more: 15.2 Stable numerics: logsumexp, softmax, and compensated sums
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- direct path: the optional linear map from the embeddings straight to the logits, in parallel with the hidden layer. Read more: 8.2 Bengio’s neural probabilistic language model in AI Engineering
- Pure function: a function whose output depends only on its inputs and which mutates nothing. Read more: Chapter 4: Coding and Design Patterns in Software Engineering
- softmax VJP: with , the backward of a row-wise softmax. Read more: 11.1 Scaled dot-product attention (forward and backward) in AI Engineering
Real engines work with whole arrays instead. In AI Engineering, The op library and gradcheck_all builds a tensor op library where each op (matmul, softmax, log-softmax, LayerNorm, RMSNorm, cross-entropy) has one backward function written in numpy. Each of those needs a closed-form vector-Jacobian product, derived once on paper and proven by gradcheck. This section derives and implements them, so the op library only wires them into the graph, Losses with a fused backward fuses softmax with cross-entropy, Vanilla RNN with manual BPTT and truncation reuses them to backpropagate through time by hand, and the RMSNorm of Pre-LN and RMSNorm has its backward ready.
The one tool you need is the differential, together with the trace trick, and it produces every rule in a few lines. You will also use the stable softmax from Stable numerics: logsumexp, softmax, and compensated sums (implemented in stable.py), the cross-entropy loss of Entropy, cross-entropy, KL, JS, and the k3 estimator, the numeric VJP of Jacobians, the multivariable chain rule, and numeric JVP/VJP, and the matmul shapes of Vectors, matrices, row-major layout, and matmul. The complete implementation is vjp.py, with its interface in the contract course/contracts/py/tinyllm/autograd/vjp.pyi.
Learning objectives
- Use and the cyclic property of the trace to derive the VJP of a matrix operation.
- Derive and verify by hand the VJPs of matmul, softmax, log-softmax, fused cross-entropy, LayerNorm, and RMSNorm.
- Implement
unbroadcastand explain why a broadcast input receives the sum of its copies’ gradients.- Explain why normalization VJPs carry correction terms, and why padded positions receive exactly zero gradient.
Notation
Section titled “Notation”The derivations use the following symbols; the table gives each one’s meaning and shape.
| Symbol | Meaning | Type / shape |
|---|---|---|
| a scalar loss | float | |
| an op’s input and output | arrays | |
| the upstream gradient: same shape as | array | |
| the VJP’s result: same shape as | array | |
| a differential: an arbitrary small change of | same shape as | |
| the inner product of two same-shape arrays | float | |
| elementwise product | ||
| the vector of ones | float[D] | |
| the size of the normalized (last) axis | int | |
| mean and variance of a row over its entries | float per row | |
| small constant added to the variance ( for LayerNorm, for RMSNorm in this book’s models) | float | |
(rstd) | reciprocal standard deviation, (LayerNorm) or (RMSNorm) | float per row |
| the normalized row | float[D] | |
| learned scale and shift (LayerNorm), learned scale (RMSNorm) | float[D] | |
| , | probabilities and log-probabilities of a row | float[V] |
| , | a row’s target class; the number of rows whose target is not ignore_index | int |
The differential method
Section titled “The differential method”Start with a convention. Whatever layout a textbook uses, here is stored with exactly the shape of , and the entry is . Then the first-order change of the loss is
This gives a recipe. For , the chain rule says . Write as a linear expression in , then rearrange into the form . Since this holds for every , the something is . Two tools do the rearranging. The first is the cyclic property of the trace: , and . The second is moving factors across the inner product: .
Matmul and broadcasting
Section titled “Matmul and broadcasting”Apply the recipe to the most important op first. Let with , . The product rule holds for matrices as long as you keep the order: . Then
so and . Check the shapes: is and is , so is like . Shape-checking catches many mistakes but not all: if is square, has the right shape and the wrong values.
numpy’s matmul also broadcasts batch axes: a weight of shape times activations is the same used times. Each use contributes a gradient, so is the sum over the batch axis. In general, if the forward pass broadcast from shape to a larger shape, unbroadcast sums the gradient over every axis that was added in front and over every axis where has size 1 (keeping it as size 1).
Softmax, log-softmax, and cross-entropy
Section titled “Softmax, log-softmax, and cross-entropy”The same method handles the nonlinear row operations. For one row, . Differentiating the quotient gives , that is, ; the Jacobian is . Then
so . The VJP needs only the saved output . Watch out for the common half-derivation that keeps only the diagonal term, .
Log-softmax is simpler still. and (the gradient of log-sum-exp is softmax), so and
The function receives the saved log-probabilities and exponentiates them.
Cross-entropy then falls out of log-softmax. For logits (one row per position) and targets , the loss is the mean over the valid rows of . For a valid row the upstream gradient of is (a one-hot vector scaled), with . Plug that into the log-softmax VJP:
Rows whose target is ignore_index (padding, as in PyTorch) are not in the loss, so their gradient is exactly 0 and they do not count in . Compute the softmax with the stable, max-subtracted version so that logits near give a finite gradient. A target outside that is not ignore_index is a data bug, not a class: numpy would quietly wrap to the last column.
LayerNorm and RMSNorm
Section titled “LayerNorm and RMSNorm”Normalization layers are where hand derivations most often go wrong, because they divide by a statistic of every input. Define them first.
LayerNorm (Ba, Kiros, and Hinton, 2016) standardizes each row of features, then applies a learned scale and shift:
Every token’s features come out with mean 0 and variance about 1 before the scale, which keeps activations in a range where training is stable; the 2017 transformer of Encoder-decoder Transformer: post-LN and pre-LN, Noam, label smoothing uses it. The forward pass saves and .
The parameter gradients are immediate from : summing over every row, and . For , let be the gradient reaching . Both and depend on every :
So . Taking and moving to the right:
There are three terms: the direct path, the path through the mean, and the path through the variance. Dropping either correction is “treating (or ) as a constant”, and gradcheck catches it immediately. A consequence worth noticing: , because adding a constant to does not change .
RMSNorm (Zhang and Sennrich, 2019) drops the mean and the shift and divides by the root mean square:
It is cheaper and works as well in practice; Llama-family models (SmolLM2 among them) use it before every attention and MLP block. With and :
and . Here when : scaling does not change the output.
One last principle applies to all of these: VJPs are pure functions. A VJP reads the saved values and the upstream gradient and returns new arrays. Writing into its arguments (subtracting the one-hot from a softmax buffer passed in, updating g in place) corrupts values the graph still needs.
Working it by hand
Section titled “Working it by hand”Every rule above deserves a check on numbers small enough to follow. These values become the first tests of the implementation.
Start with matmul. Take , , and , so . Directly: , , , , everything else 0. The formulas agree: and . Using instead gives : the right shape, the wrong gradient.
For softmax, take : , . With , , so . The entries sum to 0, as they must: adding a constant to does not change .
For cross-entropy, use the same logits with target 1 and : . The loss is .
LayerNorm takes more steps. Normalize with , , ; the table follows the formula term by term.
| quantity | value |
|---|---|
| , | 3, |
| , | , |
| , | , |
| $d - \mathrm{mean}(d) - $ that | |
| that |
The entries of sum to 0. The parameter gradients are and .
Finally RMSNorm of with , , : , , . Then , , , , and . Check: . And .
Designing the interface
Section titled “Designing the interface”The module is a set of pure functions, one per rule:
def unbroadcast(g, shape: tuple[int, ...]) -> NDArraydef matmul_vjp(g, A, B) -> tuple[NDArray, NDArray] # A [..., m, k], B [..., k, n]def softmax_vjp(g, y, axis: int = -1) -> NDArray # y = softmax(x)def log_softmax_vjp(g, y, axis: int = -1) -> NDArray # y = log_softmax(x)def layernorm_vjp(g, xhat, rstd, gamma) -> tuple[NDArray, NDArray, NDArray] # dx, dgamma, dbetadef rmsnorm_vjp(g, x, rstd, w) -> tuple[NDArray, NDArray] # dx, dwdef cross_entropy_vjp(logits, targets, ignore_index: int = -100) -> NDArrayLayerNorm and RMSNorm normalize the last axis; rstd may be passed with shape x.shape[:-1] or x.shape[:-1] + (1,), and the parameter gradients sum over every leading axis. matmul_vjp needs at least 2-D operands and unbroadcasts both gradients. The forward passes are not part of this code: the op library writes them and saves y, xhat, and rstd.
Building it step by step
Section titled “Building it step by step”The derivations translate into code through six decisions.
- A VJP returns with the shape of such that for every . Each function is therefore the closed form derived above, written with whole-array numpy operations, never a Jacobian.
- Most ops act on the last axis of a batch of rows. Reductions over that axis use
keepdims=True, so a per-row scalar (, ) broadcasts back over the row without reshaping. - Parameters (, , ) are shared by every row, so their gradients sum over all leading axes. Batched matmul operands may be broadcast too, so both matmul gradients pass through
unbroadcast. unbroadcastinverts numpy’s broadcasting rule: first sum away the axes added in front, then sum (keeping size 1) every axis where the target shape has size 1. Anything that still does not match could never have broadcast, and is an error.- The fused cross-entropy is the log-softmax VJP with , which simplifies to . Computing the softmax with the max-subtracted version keeps it finite; ignored rows are zeroed and excluded from .
- Every function builds new arrays from its inputs and never writes into them.
A shared conversion comes first: float inputs keep their dtype (float32 stays float32), and anything else becomes float64.
def _f64(x): a = np.asarray(x) return a if np.issubdtype(a.dtype, np.floating) else a.astype(np.float64)Then unbroadcast and the matmul rule:
def unbroadcast(g, shape): out = _f64(g) shape = tuple(shape) extra = out.ndim - len(shape) if extra < 0: # a gradient cannot have fewer axes raise ValueError(...) if extra: # axes numpy added in front: sum away out = out.sum(axis=tuple(range(extra))) for i, n in enumerate(shape): if n == 1 and out.shape[i] != 1: # a size-1 axis was stretched: sum, keep it out = out.sum(axis=i, keepdims=True) if out.shape != shape: # e.g. (3,) -> (2,): never a broadcast raise ValueError(...) return out
def matmul_vjp(g, A, B): g, A, B = _f64(g), _f64(A), _f64(B) if A.ndim < 2 or B.ndim < 2: # 1-D matmul drops axes; make callers reshape raise ValueError(...) dA = g @ np.swapaxes(B, -1, -2) # G B^T, transposing only the matrix axes dB = np.swapaxes(A, -1, -2) @ g # A^T G # a [k, n] weight used across a [T, m, k] batch gets the sum over T return unbroadcast(dA, A.shape), unbroadcast(dB, B.shape)Note swapaxes(B, -1, -2) and not B.T: for a batched B of shape [T, k, n], .T would reverse every axis.
The two softmax rules use only the saved output:
def softmax_vjp(g, y, axis=-1): g, y = _f64(g), _f64(y) # y * (g - <g, y>): the second term is the off-diagonal -y y^T part return y * (g - np.sum(g * y, axis=axis, keepdims=True))
def log_softmax_vjp(g, y, axis=-1): g, y = _f64(g), _f64(y) # y here is the saved log-softmax; exp(y) is the softmax return g - np.exp(y) * np.sum(g, axis=axis, keepdims=True)The normalizations accept rstd in either per-row shape:
def _rows(rstd, like): """rstd reshaped to like.shape[:-1] + (1,), so it broadcasts over the last axis.""" return _f64(rstd).reshape(like.shape[:-1] + (1,))
def layernorm_vjp(g, xhat, rstd, gamma): g, xhat, gamma = _f64(g), _f64(xhat), _f64(gamma) r = _rows(rstd, xhat) d = g * gamma # gradient reaching xhat # direct path, minus the path through the mean, minus the path through r dx = r * (d - d.mean(axis=-1, keepdims=True) - xhat * (d * xhat).mean(axis=-1, keepdims=True)) lead = tuple(range(g.ndim - 1)) # every axis but the feature axis return dx, (g * xhat).sum(axis=lead), g.sum(axis=lead) # dx, dgamma, dbeta
def rmsnorm_vjp(g, x, rstd, w): g, x, w = _f64(g), _f64(x), _f64(w) r = _rows(rstd, x) d = g * w # direct path minus the path through r; no mean term, RMSNorm does not center dx = r * (d - x * (r * r) * (d * x).mean(axis=-1, keepdims=True)) lead = tuple(range(g.ndim - 1)) return dx, (g * x * r).sum(axis=lead) # dx, dwAnd the fused cross-entropy:
def cross_entropy_vjp(logits, targets, ignore_index=-100): z = _f64(logits) t = np.asarray(targets) if t.shape != z.shape[:-1]: # one target per row raise ValueError(...) v = z.shape[-1] valid = t != ignore_index # -1 would silently index the last class; a bad target is a data bug if ((t[valid] < 0) | (t[valid] >= v)).any(): raise ValueError(...) n = int(valid.sum()) # the mean is over kept rows only if n == 0: return np.zeros_like(z) # nothing in the loss: no gradient grad = softmax(z, axis=-1) # M09.2: max-subtracted, finite at 1e4; a new array rows = np.nonzero(valid) grad[rows + (t[valid],)] -= 1.0 # minus the one-hot, on kept rows grad[~valid] = 0.0 # padding gets exactly 0 return grad / nThe in-place -= is safe because softmax returned a fresh array, not one of the caller’s. On the hand example, softmax([0, ln 3]) is , subtracting 1 at target 1 gives , and . The full solution is vjp.py.
Why this design
Section titled “Why this design”Every rule is apart from matmul, whose two products cost FLOPs each, twice the forward product. The softmax rules need one reduction per row instead of a Jacobian: for that is 256 multiply-adds per row instead of 65 536.
The rules take saved outputs rather than inputs because that is where they are cheapest. Softmax and log-softmax VJPs are simplest in terms of (or ), and LayerNorm’s in terms of and ; saving those avoids recomputing exponentials and statistics in the backward pass.
Cross-entropy is fused because chaining log-softmax and a one-hot pick would compute the same thing in two steps with an intermediate gradient. The fused form is one subtraction, and computing it from logits with the stable softmax avoids ever taking of a probability that underflowed.
The functions raise on bad shapes and targets because a gradient with the wrong shape, or a target of that numpy wraps to the last class, does not crash later: it trains the wrong thing. Raising at the boundary turns a silent error into a loud one.
The tradeoff accepted is that inputs keep their float dtype rather than being promoted to float64, so a float32 graph stays float32 and its gradients carry float32 rounding. Gradcheck therefore runs in float64.
What a correct implementation must handle
Section titled “What a correct implementation must handle”The tests begin with every hand-computed number above, which pins each rule, and with PyTorch golden values: torch.autograd’s gradients for all seven functions, in float64, since PyTorch is the framework the op library is compared against. Gradchecks then cover each rule broadly: matmul in 2-D, square, and batched products with either operand broadcast (every linear layer); softmax and log-softmax along the last axis and along axis 0 (attention weights, the loss); LayerNorm for , , and on shape [2, 3, 8] with rstd in both shapes; RMSNorm for and with rstd in both shapes; and the gradient of the information-theory chapter’s cross-entropy, with ignored rows. Softmax is also checked against vjp_numeric on one row, the same computed two ways, and a property test confirms the trace identity along 20 directions, which is the definition of a VJP.
The boundary cases protect against silent errors. unbroadcast is checked on seven broadcast patterns, counted with a gradient of ones (biases and shared weights), and shapes that could not have broadcast must raise ValueError. 1-D matmul operands must raise, so vectors are reshaped explicitly. For cross-entropy, ignored rows must get 0, the mean must count only valid rows, out-of-range targets must raise, and logits near (a confident model) must give a finite gradient. Finally, a unit test checks that no saved value or upstream gradient is mutated, because the graph reuses them.
The pitfalls below are the mistakes these tests exist to catch.
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| instead of | correct shape for square , wrong values | g @ np.swapaxes(B, -1, -2) |
| A transposed gradient | where belongs | dB = np.swapaxes(A, -1, -2) @ g, the shape of B |
| Not summing over broadcast axes | a bias or shared weight gets a batch of gradients | both matmul gradients go through unbroadcast; parameter gradients sum over lead |
| The softmax Jacobian’s diagonal only | subtracts per row before multiplying by | |
| Log-softmax VJP with where belongs | log-probabilities used as probabilities | np.exp(y) turns the saved log-softmax back into probabilities |
| Treating or as a constant | missing correction terms in LayerNorm or RMSNorm | the mean and variance terms in LayerNorm, the term in RMSNorm |
| the scale learns like a shift | dgamma = (g * xhat).sum(...); only dbeta is g.sum(...) | |
| Averaging over every row, or letting padding through | gradients scaled by the padding ratio; padding tokens trained | divides by the kept count n; sets ignored rows to 0 |
exp(z) / sum(exp(z)) inside the loss gradient | NaN once a logit passes 709 | the max-subtracted softmax |
| Updating the upstream gradient in place | the caller’s g changes under it | every rule builds new arrays; the one -= writes into the fresh softmax |
Where this leads
Section titled “Where this leads”This section draws on four earlier ones: softmax from Stable numerics: logsumexp, softmax, and compensated sums inside cross_entropy_vjp; the cross_entropy of Entropy, cross-entropy, KL, JS, and the k3 estimator, whose gradient cross_entropy_vjp is; vjp_numeric from Jacobians, the multivariable chain rule, and numeric JVP/VJP, which checks the softmax VJP numerically; and the row-major matrices and matmul shapes of Vectors, matrices, row-major layout, and matmul.
In AI Engineering, the tensor’s backward in Tensor, broadcasting backward, and no_grad sums broadcast gradients back to each input’s shape with unbroadcast; each op of The op library and gradcheck_all registers one of these VJPs; Losses with a fused backward uses the fused ; Vanilla RNN with manual BPTT and truncation chains matmul_vjp over time steps; and rmsnorm_vjp is the backward of Pre-LN and RMSNorm. Within this chapter, Hessian-vector products and the recompute-versus-memory schedule builds second-order information and memory schedules on top of these first-order rules, and the chapter problem set drills the derivations.
Production code uses exactly these formulas. PyTorch keeps one backward formula per op in a derivative table from which its autograd code is generated (tools/autograd/derivatives.yaml). llm.c writes the same three-term LayerNorm backward in plain C, fused over a batch (train_gpt2.c, layernorm_backward). Liger Kernel fuses the linear layer, softmax, and cross-entropy in chunks, so the logits never exist in memory (src/liger_kernel/ops/fused_linear_cross_entropy.py). PyTorch’s F.rms_norm uses fused kernels with the saved rstd and the same formula (aten/src/ATen/native/layer_norm.cpp).
Further reading:
- Parr and Howard, The Matrix Calculus You Need for Deep Learning.
- Minka, “Old and New Matrix Algebra Useful for Statistics” (the differential method).
- Petersen and Pedersen, The Matrix Cookbook, sections 2 and 4.
Key terms
Section titled “Key terms”- Differential: , an arbitrary small change of ; the first-order change of the loss is .
- Trace trick: rewriting with the cyclic property of the trace until it reads .
- Upstream gradient: , the gradient arriving at an op’s output.
- Unbroadcast: summing a gradient over the axes along which the forward pass broadcast an input, to recover that input’s shape.
- Fused cross-entropy: the gradient computed directly from logits.
rstd: the saved reciprocal standard deviation of a row, reused by the normalization VJPs.
Summary
Section titled “Summary”- For a scalar loss, with ; write in terms of , move to the right with the cyclic property of the trace, and the matrix in front of it is .
- That gives every rule in a few lines: and for a matmul, for softmax, for cross-entropy.
- LayerNorm and RMSNorm divide by a statistic of every input, so their VJPs carry correction terms that a “treat the statistic as a constant” derivation drops.
- A broadcast input receives the sum of its copies’ gradients, and padded positions receive exactly zero.
- VJPs are pure functions of saved values and the upstream gradient, and they raise on shapes or targets that would otherwise train the wrong thing.
Review questions
Section titled “Review questions”-
Bis a[k, n]weight andAa[T, m, k]batch. Why doesmatmul_vjpstill needunbroadcastondB?Answer
With a batched
Aof shape[T, m, k]and a weightBof shape[k, n],swapaxes(A) @ ghas shape[T, k, n]: one gradient per use ofB. The weight’s gradient is the sum over the uses, whichunbroadcastperforms. -
In
softmax_vjp, what does thenp.sum(g * y, ..., keepdims=True)term correspond to in the Jacobian, and what is wrong without it?Answer
It is the part of . Without it the result is , only the diagonal. In the hand example that gives instead of , and the gradients no longer sum to zero.
-
LayerNorm’s
dxhas three terms and RMSNorm’s has two. Where does the missing one go?Answer
LayerNorm subtracts the mean, so a change in also changes ; that path is the
- d.mean(...)term. RMSNorm never centers, so there is no path through a mean. Both divide by a statistic of , which gives the last term in each. -
Why does
cross_entropy_vjpdivide byn = valid.sum()and not by the number of rows?Answer
The loss is the mean over the kept rows, so its derivative carries for those rows. Dividing by all rows would scale every gradient by the fraction of non-padding tokens, so batches with more padding would train with a smaller effective learning rate.
-
Why compute the softmax with the stable
softmaxinstead ofnp.exp(z) / np.exp(z).sum()?Answer
np.exp(z)overflows toinfin float64 once a logit passes about 709, andinf / infis NaN. The stable softmax subtracts the row maximum first, so every exponent is at most 0 and the result is finite for logits near . -
With and square, why is a shape check not enough to validate ?
Answer
and have the same shape when is square. In the hand example, while the correct . Only a value check (gradcheck or a hand example) distinguishes them.