10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
The previous section checked the gradient of a scalar loss. But an autodiff engine never handles the loss as one formula. It handles a chain of layers, each mapping arrays to arrays, and its backward pass multiplies through them one at a time. The objects being multiplied are Jacobians, or rather products with Jacobians, because the matrices themselves are far too large to form: a layer from 4096 to 4096 numbers has a Jacobian of 16 million entries per token.
Concepts from other sections (17)
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.
- 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. Read more: Chapter 14: Matrix Calculus and Autodiff
- 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
- 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
- Partial derivative: the ordinary derivative of along one coordinate with every other coordinate frozen. Read more: 10.1 Partial derivatives, gradients, and gradcheck
- Consistency check: a follower accepts entries only if it holds the entry just before them with the same term. Read more: 7.10 Raft high availability for the durable log (optional) in Systems Engineering
- 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
- Vector-Jacobian product (VJP): , one step of reverse-mode differentiation. Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
- Linear map: a function between vector spaces with ; once bases are chosen, every linear map is a matrix. Read more: Chapter 9: Linear Algebra
- central difference: , a second-order approximation of . Read more: 7.1 Derivatives and Finite Differences
- Backpropagation: reverse-mode automatic differentiation that computes all parameter gradients in one backward pass. Read more: Chapter 2: Deep Learning in AI Engineering
- Rate of change: how much the output changes per unit change in the input; for it is 4 per person. Read more: Chapter 2: Change and growth
- 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
- 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
- backpropagation through time (BPTT): backpropagation over an RNN unrolled into one layer per timestep. Read more: Chapter 3: Neural Architectures and Their History in AI Engineering
- Transformation (JAX): a function such as
jit,grad,vmap, orpmapthat takes a pure function and returns a compiled, differentiated, batched, or parallel version of it. Read more: 16.3 Embeddings, small models, and platforms in AI Engineering
Chapter 8 of this book builds automatic differentiation three ways: dual numbers (forward mode), a scalar Value graph (reverse mode), and closed-form VJPs of matrix expressions. Each needs an independent numeric oracle for the products and . This section defines the Jacobian and the chain rule from partial derivatives and builds those oracles.
You will need numerical_grad from the previous section, on which vjp_numeric is built, and it helps to have Vectors, matrices, row-major layout, and matmul fresh for matrices and their product. The solution is jacobian.py, with jacobian, jvp_numeric (), and vjp_numeric (); the typed interface is course/contracts/py/tinyllm/num/jacobian.pyi.
Learning objectives
- Define the Jacobian of , compute it by hand and numerically, and read its rows and columns.
- State the multivariable chain rule as a matrix product and explain the order of the factors.
- Compute a JVP and a VJP without forming , and explain which one forward and reverse mode compute.
- Use the identity as a consistency check.
- Explain why the JVP step must scale with the size of .
Notation
Section titled “Notation”These are the symbols the section uses, with the Python shapes they correspond to:
| Symbol | Meaning | Type / shape |
|---|---|---|
| a function from numbers to numbers | Callable[[NDArray], ArrayLike] | |
| the input; any shape, flattened row-major to numbers | float64[...] | |
| output of (row-major order of ) | float | |
| the Jacobian, | float64[m, n] | |
| a tangent: a direction to move the input | shape of | |
| a cotangent: a weighting of the outputs | shape of | |
| the Jacobian-vector product (JVP) | shape of | |
| the vector-Jacobian product (VJP) | shape of | |
| , | finite-difference steps | float |
The Jacobian
Section titled “The Jacobian”Each output is a scalar function of , so it has a gradient. Stack those gradients as rows and you get the Jacobian:
It is the best linear approximation of near : for small , the several-variable version of the tangent line. Row is the gradient of output . Column is how the whole output moves per unit move of input , which is also how to compute it numerically:
which costs evaluations of and divides by the step actually taken, as in Derivatives and Finite Differences.
Three examples recur throughout the book. A linear map has everywhere. An elementwise map like has a diagonal Jacobian, , because output depends only on input . Softmax, , couples everything: , so , symmetric with columns summing to 0 (the probabilities always add to 1). Matrix differentials, the trace trick, and closed-form VJPs derives that one by hand.
When or is a matrix, flatten both in row-major order, as in the linear algebra chapter: the derivative with respect to of a input is column .
The chain rule
Section titled “The chain rule”With the Jacobian in hand, composition becomes multiplication. If and , then a small change in moves by about , which moves by about . So
a product of a and an matrix, with the outer function’s Jacobian on the left, evaluated at the inner function’s output. Entry by entry this is : add up every path from to . The one-variable chain rule is the case. A deep network is a long composition, and its Jacobian is a long product.
Products without the matrix
Section titled “Products without the matrix”Forming costs forward passes and memory. Two products avoid it.
The JVP, , is the derivative of at : the rate at which the output moves when the input moves in direction . One central difference computes it, . Forward-mode autodiff (Dual numbers and forward-mode autodiff) computes it exactly by carrying a tangent alongside every value. Along a chain, : you push through one layer at a time.
The VJP, , is the gradient of the scalar , since . vjp_numeric computes it with the previous section’s numerical_grad. Reverse-mode autodiff, which is backpropagation (Scalar reverse mode: the Value graph, and Tensor, broadcasting backward, and no_grad in AI Engineering), computes it exactly by pulling back one layer at a time: . With and a scalar loss, the VJP is the gradient, and that is why training uses reverse mode.
Both products describe the same , so for every and , : one number computed two ways, which makes a good check at random , , . Mixing them up (returning for a VJP) gives the right shape whenever is square and the wrong numbers unless it is symmetric.
One practical detail matters for the JVP: scale the step to . multiplies , so the input moves by . A fixed with moves by 1 and measures a secant over a whole unit. Choosing keeps the largest coordinate’s move at ; then to rounding, and returns 0 without computing .
Working it by hand
Section titled “Working it by hand”Take at . The partial derivatives give
With , , the first column: moving moves the outputs at rates 4 and 5. With , , the first row: the gradient of the first output. is not symmetric, so the two differ, and a transposed Jacobian would swap them.
Now check the identity with and . On one side, and . On the other, and . They agree.
Designing the interface
Section titled “Designing the interface”Three functions cover it:
def jacobian(f, x: ArrayLike, eps: float = 1e-6) -> NDArray: ... # [f(x).size, x.size]def jvp_numeric(f, x: ArrayLike, v: ArrayLike) -> NDArray: ... # J v, shape f(x).shapedef vjp_numeric(f, x: ArrayLike, u: ArrayLike) -> NDArray: ... # u^T J, shape x.shapeAll arithmetic is float64 on a private copy of x. jacobian raises ValueError for a bad eps or when f’s output shape changes; the products raise it when v does not have x’s shape or u does not have f(x)’s.
The cases a correct solution must handle, and why each matters later, are these:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| Hand example, | unit | the worked example’s | pins rows and columns |
| Hand example, products | unit | and | forward and reverse mode are different products |
| Matrix-shaped | unit | of shape gives of shape in row-major columns; product shapes; shape errors | backward passes return gradients in the input’s shape |
| Linear map | golden | matmul is every layer’s first step | |
| Softmax | golden | , columns sum to 0 | chapter 8 derives this VJP by hand |
| Elementwise map | golden | ; its VJP is elementwise | activation backward passes (Activation Functions and Their Derivatives) |
| Composition | differential | the rule backpropagation applies | |
| Random , , | property | , , and | forward and reverse oracles agree |
| Tangent size | boundary | , , | tangents of any size |
| Caller’s and dtype | unit | is untouched; sees float64 even for int | parameters are not perturbed in place |
Bad eps, changing shapes | boundary | eps = 0 and an whose output shape changes raise | no ragged Jacobians |
Building it step by step
Section titled “Building it step by step”The implementation follows from the principles in five steps.
- Column of is the rate of change of every output with input . So
jacobianloops over input elements, perturbs one at a time by , and stores the central difference of the whole output as column . Stacking columns alongaxis=1gives the orientation; stacking them as rows would give . - Inputs of any shape are flattened row-major. The flattening must be a view of a private float64 copy, so that writing
flat[j]actually changes what sees, and the caller’s array is never touched. Each coordinate is restored before the next. - The divisor is the step actually taken,
(x_j + eps) - (x_j - eps). - A JVP is the derivative of at 0: one central difference along , with so the input moves by whatever ‘s size. returns 0 directly.
- A VJP is the gradient of the scalar , so
vjp_numericis one call tonumerical_gradon that scalar: no new differencing code, and the result is already in ‘s shape.
The Jacobian is built one column per input element:
def jacobian(f, x, eps=1e-6): if not (math.isfinite(eps) and eps > 0): raise ValueError(f"eps must be finite and > 0, got {eps}") xw = np.array(x, dtype=np.float64, copy=True) # private float64 copy flat = xw.reshape(-1) # a view: writing flat[j] moves xw shape = None cols = [] for j in range(flat.size): orig = flat[j] hi_x, lo_x = orig + eps, orig - eps flat[j] = hi_x hi = _eval(f, xw) flat[j] = lo_x lo = _eval(f, xw) flat[j] = orig # restore before the next column if shape is None: shape = hi.shape if hi.shape != shape or lo.shape != shape: # no ragged Jacobians raise ValueError( f"f returned shapes {hi.shape} and {lo.shape}, earlier {shape}" ) # Column j: how every output moves when input j moves (hi minus lo, # divided by the step actually taken). cols.append((hi - lo).reshape(-1) / (hi_x - lo_x)) if not cols: m = _eval(f, xw).size return np.zeros((m, 0)) # an empty input still has m rows return np.stack(cols, axis=1) # columns, so J is [m, n]On the worked example, column 0 is the change in when moves, , and column 1 is .
The JVP scales its step to :
JVP_STEP = 1e-6
def jvp_numeric(f, x, v): xw = np.array(x, dtype=np.float64, copy=True) va = np.asarray(v, dtype=np.float64) if va.shape != xw.shape: raise ValueError(f"v has shape {va.shape}, x has {xw.shape}") scale = float(np.max(np.abs(va))) if va.size else 0.0 if scale == 0.0: return np.zeros_like(_eval(f, xw)) # J 0 = 0, no 0/0 # The largest coordinate of x moves by JVP_STEP whatever the size of v. h = JVP_STEP / scale return (_eval(f, xw + h * va) - _eval(f, xw - h * va)) / (2.0 * h)And the VJP is a gradient of a scalar:
def vjp_numeric(f, x, u): xw = np.array(x, dtype=np.float64, copy=True) ua = np.asarray(u, dtype=np.float64) fx = _eval(f, xw) if ua.shape != fx.shape: raise ValueError(f"u has shape {ua.shape}, f(x) has {fx.shape}") # u^T J is the gradient of the scalar u . f(x): one gradient, not m rows. return numerical_grad(lambda z: float(np.sum(ua * _eval(f, z))), [xw])[0]With on the worked example, the scalar is and its gradient is , the first row of . The full solution is in jacobian.py.
Why this design
Section titled “Why this design”On cost: jacobian takes evaluations and memory. jvp_numeric takes 2 evaluations whatever and . vjp_numeric takes (one to check u’s shape, then numerical_grad’s ), but stores only .
You could compute the VJP as u @ jacobian(f, x). It gives the same numbers but stores the whole matrix. Building it on numerical_grad also makes it the same code that gradcheck already trusts.
Central differences are needed because one-sided differences have error, about , too coarse to confirm closed forms such as softmax’s Jacobian. And the JVP step is scaled because a finite difference approximates the derivative only if the input moves a small distance; a fixed makes the distance proportional to .
The tradeoff accepted is that these are oracles, not autodiff: their accuracy is about on well-scaled functions. That is enough to confirm the exact forward- and reverse-mode results of chapter 8.
What can go wrong
Section titled “What can go wrong”Most of the bugs here produce arrays of the right shape with the wrong numbers, which is why they survive casual testing:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| the Jacobian transposed (columns stacked as rows) | : right shape for square , wrong numbers, and a chain rule product in the wrong order | stacks columns with axis=1 (step 1) |
| perturbing the caller’s and not restoring it | the input array changes during a check | works on np.array(x, dtype=np.float64, copy=True) |
| leaving coordinate at | every later column is taken at a shifted point | sets flat[j] = orig after both evaluations |
| a fixed JVP step whatever the size of | is a secant over a unit step | `h = JVP_STEP / max |
| a VJP that computes instead of | the column where the row was wanted | differentiates the scalar (step 5) |
| one-sided differences for the columns | errors near ; softmax’s closed form missed | evaluates both |
| dividing the JVP by instead of | every JVP doubled | divides by 2.0 * h |
| flattening through a copy | the perturbations never reach : | uses xw.reshape(-1), a view of the copy |
| the column difference reversed | computes hi - lo | |
| a VJP that ignores | the gradient of for every | multiplies by ua inside the scalar |
Warning:
xw.flatten()andxw.reshape(-1)look interchangeable, butflattenalways copies. Perturbing a copy never reaches , and the Jacobian silently comes out all zeros.
Where this leads
Section titled “Where this leads”Looking back, vjp_numeric is numerical_grad(lambda z: sum(u * f(z)), [x]) from the previous section. Looking forward, the oracles built here referee everything in chapter 8: Dual numbers and forward-mode autodiff computes exactly and its tests compare against jvp_numeric; Scalar reverse mode: the Value graph computes by backpropagation, checked against vjp_numeric; and Matrix differentials, the trace trick, and closed-form VJPs derives closed-form VJPs of matmul, softmax, LayerNorm, RMSNorm, and cross-entropy, checked against jacobian and vjp_numeric. In AI Engineering, Vanilla RNN with manual BPTT and truncation does manual backpropagation through time, a chain of Jacobians over time steps.
Further reading
Section titled “Further reading”- JAX
jax.jvpandjax.vjp(jax/_src/api.py): exact products by forward and reverse mode, composable withjitandvmap. - PyTorch
torch.autograd.functional.jacobianwithvectorize=True(torch/autograd/functional.py), and JAXjacfwdandjacrev: the full Jacobian from JVPs or VJPs, batched. Pick forward when , reverse when . - Reverse-mode autodiff in production does one VJP per layer, in reverse order, storing the forward values it needs; see Tensor, broadcasting backward, and no_grad and Baydin et al. below.
- PyTorch
gradcheck(fast_mode=True)(torch/autograd/gradcheck.py) uses to check a whole backward with one random and instead of entries. - OpenStax, Calculus Volume 3 (free), section 4.5, on the chain rule for several variables.
- Baydin et al., “Automatic Differentiation in Machine Learning: a Survey” (2018), sections 3.1 and 3.2, on forward and reverse mode.
Key terms
Section titled “Key terms”- Jacobian: the matrix of partial derivatives of a function .
- Tangent: a direction in input space along which the input is moved.
- Cotangent: a weighting of the outputs, pulled back through a function by a VJP.
- JVP (Jacobian-vector product): , the rate of change of the output along ; what forward mode computes.
- VJP (vector-Jacobian product): , the gradient of ; what reverse mode computes.
- Chain rule: .
Summary
Section titled “Summary”- For the Jacobian is the matrix of partial derivatives, : row is the gradient of output , column is how every output moves with input .
- The chain rule in several variables is a matrix product, outer function on the left: .
- Autodiff never forms . Forward mode pushes a direction through, ; reverse mode pulls a cotangent back, , which is the gradient of the scalar .
- The two products are consistent: for every and .
- The JVP step must scale with : , so the input moves by whatever the size of .
Review questions
Section titled “Review questions”-
Why does
jacobianstack the columns withaxis=1and notaxis=0?Answer
Each computed vector is how all outputs move with one input: a column of . Stacking along
axis=0would place it as a row and return , which has the right shape whenever and wrong numbers unless is symmetric. On the worked example it would give rows and . -
What happens if
flatisxw.flatten()instead ofxw.reshape(-1)?Answer
flattenreturns a copy, so writingflat[j]never changesxw, always sees the unperturbed input,hi == lo, and every column is 0. -
Why is and not a fixed ?
Answer
The input moves by . With a fixed moves by a whole unit, and the quotient is a secant over that unit, not a derivative. Dividing by keeps the largest coordinate’s move at , so to rounding.
-
Why is the VJP the gradient of ?
Answer
. So the row vector is exactly the gradient of that scalar, and one gradient computation replaces rows.
-
What does check that neither product checks alone?
Answer
That the forward and reverse products describe the same matrix. A VJP that returned or a JVP that used could each look plausible, but would break the identity for generic and .