Chapter 14: Matrix Calculus and Autodiff
A gradient is a linear map, and a program is a composition of small differentiable steps. Automatic differentiation is the chain rule applied to a program rather than to a formula. Forward mode pushes a tangent through each step, a Jacobian-vector product; reverse mode records the computation and pulls a cotangent back through each step, a vector-Jacobian product (VJP). If you know the VJP of each primitive, you can differentiate any program built from them, and knowing it in closed form is what makes it fast and stable.
Concepts from other sections (23)
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.
- Linear map: a function between vector spaces with ; once bases are chosen, every linear map is a matrix. Read more: Chapter 9: Linear Algebra
- Chain rule: . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
- Forward mode: automatic differentiation that carries tangents alongside values, costing one pass per input direction. Read more: 14.1 Dual numbers and forward-mode autodiff
- Jacobian-vector product (JVP): , the directional derivative of a vector function, computed by one forward-mode pass. Read more: 14.1 Dual numbers and forward-mode autodiff
- 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
- Cotangent: a weighting of the outputs, pulled back through a function by a VJP. Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
- Vector-Jacobian product (VJP): , what one backward pass from leaves in the leaves. Read more: 14.2 Scalar reverse mode: the Value graph
- dual numbers: forward-mode autodiff values that carry an exact derivative alongside each number. Read more: 6.3 The op library and gradcheck_all 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
- 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
- Trace trick: rewriting with the cyclic property of the trace until it reads . Read more: 14.3 Matrix differentials, the trace trick, and closed-form VJPs
- Hessian-vector product: , the derivative of the gradient along , computed without forming . Read more: 14.4 Hessian-vector products and the recompute-versus-memory schedule
- Hessian: the symmetric matrix of second partial derivatives, whose eigenvalues classify a critical point. Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
- Activation checkpointing: saving only some layer inputs in the forward pass and recomputing the rest during backward. Read more: 14.4 Hessian-vector products and the recompute-versus-memory schedule
- central differences: the numerical derivative , used as an oracle for analytic gradients. Read more: 6.3 The op library and gradcheck_all in AI Engineering
- Reverse topological order: an ordering in which every node comes before the nodes it was computed from. Read more: 14.2 Scalar reverse mode: the Value graph
- Jacobian: the matrix of partial derivatives of a function . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
- stable softmax: softmax computed after subtracting the largest logit, so
expnever overflows. Read more: 25.6 Usage policy enforcement in AI Engineering - Log-sum-exp (LSE): , computed stably as . Read more: 15.2 Stable numerics: logsumexp, softmax, and compensated sums
- Topological order: a list of the vertices in which every edge points from an earlier vertex to a later one. Read more: 12.1 Graphs, DAGs, and an iterative topological sort
- Fused cross-entropy: the gradient computed directly from logits. Read more: 14.3 Matrix differentials, the trace trick, and closed-form VJPs
- Backpropagation: reverse-mode automatic differentiation that computes all parameter gradients in one backward pass. Read more: Chapter 2: Deep Learning in AI Engineering
This chapter builds that machinery from first principles, in the order you would build an autograd engine. It starts with dual numbers, which carry a derivative alongside each value and give exact derivatives with no step size; they become the oracle that every later rule is checked against. It then builds reverse mode one scalar at a time, where the graph and the backward walk are small enough to print. Because reverse mode costs about one extra forward pass per scalar output, it is how every neural network trains: one loss, millions of parameters. Scalars are too slow for real work, so the third section derives closed-form VJPs for matmul, softmax, log-softmax, cross-entropy, LayerNorm, and RMSNorm with matrix differentials and the trace trick, a few lines each. The last section turns to the costs of reverse mode: Hessian-vector products that give curvature without forming the Hessian, and activation checkpointing, which trades recomputation for memory on a -type schedule. A problem set drills the derivations on paper.
Two habits run through the whole chapter. Gradients are checked, never trusted: central differences in float64 against the analytic VJP catch nearly every wrong rule. And every rule is worked by hand on small numbers before it is coded.
Learning objectives
- Compute derivatives and Jacobian-vector products with dual numbers, and explain why they are exact to rounding.
- Implement scalar reverse mode over a recorded graph and explain why adjoints accumulate and why the walk follows reverse topological order.
- Derive closed-form VJPs with matrix differentials and the trace trick, including the correction terms of normalization layers and the sum over broadcast axes.
- Compute Hessian-vector products from two gradient calls, and plan an optimal activation-checkpointing schedule under a memory budget.
- Choose between forward and reverse mode by counting passes, and estimate the FLOPs and memory of a backward pass.
Before you begin
Section titled “Before you begin”You should be comfortable with the chain rule from Calculus 1, gradients and Jacobians from Calculus 3, matrix products and shapes from Linear Algebra, and topological sorting from Discrete Math 2, which orders the backward walk. The stable softmax and log-sum-exp from Numerical Methods and Floating Point appear inside the VJPs. A good companion read is Parr and Howard’s The Matrix Calculus You Need for Deep Learning, deriving every identity by hand, followed by sections 2 and 3 of the Baydin survey. If you have never built micrograd, doing so once from memory is excellent preparation.
In this chapter
Section titled “In this chapter”- Dual numbers and forward-mode autodiff. Dual numbers with turn Taylor’s theorem into an identity, so one evaluation returns a value and its exact derivative; the section builds a numpy-compatible
Dualand its JVP. - Scalar reverse mode: the Value graph. A scalar
Valuerecords each operation and its local rule, andbackwardwalks the graph once in reverse topological order to give the gradient with respect to every input. - Matrix differentials, the trace trick, and closed-form VJPs. The differential method derives the VJPs of matmul, softmax, log-softmax, fused cross-entropy, LayerNorm, and RMSNorm, and
unbroadcastsums gradients over broadcast axes. - Hessian-vector products and the recompute-versus-memory schedule. Two gradient calls give to ; a counting argument gives the least peak memory of activation checkpointing and the optimal schedule under a budget.
- Matrix calculus problem set: differentials, trace trick, VJPs, SDPA Jacobian. Pen-and-paper problems with worked answers on shapes, differentials, the trace trick, VJPs, forward versus reverse cost, and the attention backward.
Key terms
Section titled “Key terms”- Automatic differentiation / autodiff: computing exact derivatives of a program by applying the chain rule to each primitive operation it executes, in forward mode (Jacobian-vector products) or reverse mode (vector-Jacobian products); it is how neural networks get their gradients, with no step size and no symbolic formula.
Where this chapter leads
Section titled “Where this chapter leads”The gradients built here feed the optimizers of Optimization. In AI Engineering, the Foundations chapter turns these rules into a tensor autograd engine, registering each VJP as an op. In AI Engineering, Deep Learning treats backpropagation in the textbook setting.
Further reading
Section titled “Further reading”- Parr and Howard, The Matrix Calculus You Need for Deep Learning (free).
- Baydin, Pearlmutter, Radul, and Siskind, Automatic Differentiation in Machine Learning: a Survey (JMLR 2018, free).
- Griewank and Walther, Evaluating Derivatives (SIAM, 2nd ed.).
- Petersen and Pedersen, The Matrix Cookbook (free).
- Karpathy, micrograd (free).
- Chen et al., Training Deep Nets with Sublinear Memory Cost (free).