Skip to content

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.

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 JvJv and u⊤Ju^\top J. 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 (JvJv), and vjp_numeric (u⊤Ju^\top J); the typed interface is course/contracts/py/tinyllm/num/jacobian.pyi.

Learning objectives

  • Define the Jacobian of f:Rn→Rmf: \mathbb{R}^n \to \mathbb{R}^m, 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 JJ, and explain which one forward and reverse mode compute.
  • Use the identity u⊤(Jv)=(u⊤J)vu^\top(Jv) = (u^\top J)v as a consistency check.
  • Explain why the JVP step must scale with the size of vv.

These are the symbols the section uses, with the Python shapes they correspond to:

SymbolMeaningType / shape
f:Rn→Rmf: \mathbb{R}^n \to \mathbb{R}^ma function from nn numbers to mm numbersCallable[[NDArray], ArrayLike]
xxthe input; any shape, flattened row-major to nn numbersfloat64[...]
fif_ioutput ii of ff (row-major order of f(x)f(x))float
J=Jf(x)J = J_f(x)the Jacobian, Jij=∂fi/∂xjJ_{ij} = \partial f_i / \partial x_jfloat64[m, n]
v∈Rnv \in \mathbb{R}^na tangent: a direction to move the inputshape of xx
u∈Rmu \in \mathbb{R}^ma cotangent: a weighting of the outputsshape of f(x)f(x)
JvJvthe Jacobian-vector product (JVP)shape of f(x)f(x)
u⊤Ju^\top Jthe vector-Jacobian product (VJP)shape of xx
ϵ\epsilon, hhfinite-difference stepsfloat

Each output fif_i is a scalar function of xx, so it has a gradient. Stack those gradients as rows and you get the Jacobian:

J=(∂f1/∂x1⋯∂f1/∂xn⋮⋮∂fm/∂x1⋯∂fm/∂xn).J = \begin{pmatrix} \partial f_1/\partial x_1 & \cdots & \partial f_1/\partial x_n \\ \vdots & & \vdots \\ \partial f_m/\partial x_1 & \cdots & \partial f_m/\partial x_n \end{pmatrix} .

It is the best linear approximation of ff near xx: f(x+Δ)≈f(x)+JΔf(x + \Delta) \approx f(x) + J\Delta for small Δ\Delta, the several-variable version of the tangent line. Row ii is the gradient of output ii. Column jj is how the whole output moves per unit move of input jj, which is also how to compute it numerically:

J:,j≈f(x+ϵej)−f(x−ϵej)(xj+ϵ)−(xj−ϵ),J_{:, j} \approx \frac{f(x + \epsilon e_j) - f(x - \epsilon e_j)}{(x_j + \epsilon) - (x_j - \epsilon)} ,

which costs 2n2n evaluations of ff and divides by the step actually taken, as in Derivatives and Finite Differences.

Three examples recur throughout the book. A linear map f(x)=Axf(x) = Ax has J=AJ = A everywhere. An elementwise map like tanh⁡\tanh has a diagonal Jacobian, diag⁡(1−tanh⁡2x)\operatorname{diag}(1 - \tanh^2 x), because output ii depends only on input ii. Softmax, pi=ezi/∑kezkp_i = e^{z_i}/\sum_k e^{z_k}, couples everything: ∂pi/∂zj=pi(δij−pj)\partial p_i / \partial z_j = p_i(\delta_{ij} - p_j), so J=diag⁡(p)−pp⊤J = \operatorname{diag}(p) - pp^\top, 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 xx or f(x)f(x) is a matrix, flatten both in row-major order, as in the linear algebra chapter: the derivative with respect to X[1,2]X[1, 2] of a 2×32 \times 3 input is column 1⋅3+2=51 \cdot 3 + 2 = 5.

With the Jacobian in hand, composition becomes multiplication. If y=f(x)y = f(x) and z=g(y)z = g(y), then a small change Δ\Delta in xx moves yy by about JfΔJ_f \Delta, which moves zz by about Jg(JfΔ)J_g (J_f \Delta). So

Jg∘f(x)=Jg(f(x)) Jf(x),J_{g \circ f}(x) = J_g\bigl(f(x)\bigr)\, J_f(x) ,

a product of a p×mp \times m and an m×nm \times n matrix, with the outer function’s Jacobian on the left, evaluated at the inner function’s output. Entry by entry this is ∂zk∂xj=∑i∂zk∂yi∂yi∂xj\frac{\partial z_k}{\partial x_j} = \sum_i \frac{\partial z_k}{\partial y_i}\frac{\partial y_i}{\partial x_j}: add up every path from xjx_j to zkz_k. The one-variable chain rule is the 1×11 \times 1 case. A deep network is a long composition, and its Jacobian is a long product.

Forming JJ costs nn forward passes and mnmn memory. Two products avoid it.

The JVP, JvJv, is the derivative of t↦f(x+tv)t \mapsto f(x + tv) at t=0t = 0: the rate at which the output moves when the input moves in direction vv. One central difference computes it, f(x+hv)−f(x−hv)2h\frac{f(x + hv) - f(x - hv)}{2h}. Forward-mode autodiff (Dual numbers and forward-mode autodiff) computes it exactly by carrying a tangent alongside every value. Along a chain, JgJfv=Jg(Jfv)J_g J_f v = J_g (J_f v): you push vv through one layer at a time.

The VJP, u⊤Ju^\top J, is the gradient of the scalar u⋅f(x)=∑iuifi(x)u \cdot f(x) = \sum_i u_i f_i(x), since ∂∂xj∑iuifi=∑iuiJij\frac{\partial}{\partial x_j}\sum_i u_i f_i = \sum_i u_i J_{ij}. 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 uu back one layer at a time: u⊤JgJf=(u⊤Jg)Jfu^\top J_g J_f = (u^\top J_g) J_f. With u=1u = 1 and a scalar loss, the VJP is the gradient, and that is why training uses reverse mode.

Both products describe the same JJ, so for every uu and vv, u⊤(Jv)=(u⊤J)vu^\top(Jv) = (u^\top J)v: one number computed two ways, which makes a good check at random uu, vv, xx. Mixing them up (returning JuJu for a VJP) gives the right shape whenever JJ is square and the wrong numbers unless it is symmetric.

One practical detail matters for the JVP: scale the step to vv. hh multiplies vv, so the input moves by hmax⁡∣v∣h\max|v|. A fixed h=10−6h = 10^{-6} with ∣v∣=106|v| = 10^6 moves xx by 1 and measures a secant over a whole unit. Choosing h=10−6/max⁡∣v∣h = 10^{-6}/\max|v| keeps the largest coordinate’s move at 10−610^{-6}; then J(cv)=c JvJ(cv) = c\,Jv to rounding, and v=0v = 0 returns 0 without computing 0/00/0.

Take f(x,y)=(x2y,  5x+sin⁡y)f(x, y) = (x^2 y,\; 5x + \sin y) at (1,2)(1, 2). The partial derivatives give

J=(∂x(x2y)∂y(x2y)∂x(5x+sin⁡y)∂y(5x+sin⁡y))=(2xyx25cos⁡y)=(415−0.4161468).J = \begin{pmatrix} \partial_x(x^2 y) & \partial_y(x^2 y) \\ \partial_x(5x + \sin y) & \partial_y(5x + \sin y) \end{pmatrix} = \begin{pmatrix} 2xy & x^2 \\ 5 & \cos y \end{pmatrix} = \begin{pmatrix} 4 & 1 \\ 5 & -0.4161468 \end{pmatrix} .

With v=(1,0)v = (1, 0), Jv=(4,5)Jv = (4, 5), the first column: moving xx moves the outputs at rates 4 and 5. With u=(1,0)u = (1, 0), u⊤J=(4,1)u^\top J = (4, 1), the first row: the gradient of the first output. JJ is not symmetric, so the two differ, and a transposed Jacobian would swap them.

Now check the identity with u=(1,1)u = (1, 1) and v=(0,1)v = (0, 1). On one side, Jv=(1,−0.4161468)Jv = (1, -0.4161468) and u⋅Jv=0.5838532u \cdot Jv = 0.5838532. On the other, u⊤J=(9,0.5838532)u^\top J = (9, 0.5838532) and (u⊤J)⋅v=0.5838532(u^\top J) \cdot v = 0.5838532. They agree.

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).shape
def vjp_numeric(f, x: ArrayLike, u: ArrayLike) -> NDArray: ... # u^T J, shape x.shape

All 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:

CaseKind of checkChecksWhy it matters downstream
Hand example, JJunitthe worked example’s JJpins rows and columns
Hand example, productsunitJv=(4,5)Jv = (4, 5) and u⊤J=(4,1)u^\top J = (4, 1)forward and reverse mode are different products
Matrix-shaped xxunitxx of shape (2,3)(2, 3) gives JJ of shape (4,6)(4, 6) in row-major columns; product shapes; shape errorsbackward passes return gradients in the input’s shape
Linear mapgoldenJAx=AJ_{Ax} = Amatmul is every layer’s first step
Softmaxgoldendiag⁡(p)−pp⊤\operatorname{diag}(p) - pp^\top, columns sum to 0chapter 8 derives this VJP by hand
Elementwise mapgoldenJtanh⁡=diag⁡(1−tanh⁡2)J_{\tanh} = \operatorname{diag}(1 - \tanh^2); its VJP is elementwiseactivation backward passes (Activation Functions and Their Derivatives)
CompositiondifferentialJg∘f=Jg(f(x))Jf(x)J_{g \circ f} = J_g(f(x)) J_f(x)the rule backpropagation applies
Random uu, vv, xxpropertyJvJv, u⊤Ju^\top J, and u⊤(Jv)=(u⊤J)vu^\top(Jv) = (u^\top J)vforward and reverse oracles agree
Tangent sizeboundaryJ(106v)=106JvJ(10^6 v) = 10^6 Jv, J(10−6v)=10−6JvJ(10^{-6}v) = 10^{-6}Jv, J0=0J0 = 0tangents of any size
Caller’s xx and dtypeunitxx is untouched; ff sees float64 even for int xxparameters are not perturbed in place
Bad eps, changing shapesboundaryeps = 0 and an ff whose output shape changes raiseno ragged Jacobians

The implementation follows from the principles in five steps.

  1. Column jj of JJ is the rate of change of every output with input jj. So jacobian loops over input elements, perturbs one at a time by ±ϵ\pm\epsilon, and stores the central difference of the whole output as column jj. Stacking columns along axis=1 gives the m×nm \times n orientation; stacking them as rows would give J⊤J^\top.
  2. 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 ff sees, and the caller’s array is never touched. Each coordinate is restored before the next.
  3. The divisor is the step actually taken, (x_j + eps) - (x_j - eps).
  4. A JVP is the derivative of t↦f(x+tv)t \mapsto f(x + tv) at 0: one central difference along vv, with h=10−6/max⁡∣v∣h = 10^{-6}/\max|v| so the input moves by 10−610^{-6} whatever vv‘s size. v=0v = 0 returns 0 directly.
  5. A VJP is the gradient of the scalar u⋅f(x)u \cdot f(x), so vjp_numeric is one call to numerical_grad on that scalar: no new differencing code, and the result is already in xx‘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 (x2y,5x+sin⁡y)(x^2 y, 5x + \sin y) when xx moves, (4,5)(4, 5), and column 1 is (1,cos⁡2)(1, \cos 2).

The JVP scales its step to vv:

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 u=(1,0)u = (1, 0) on the worked example, the scalar is x2yx^2 y and its gradient is (4,1)(4, 1), the first row of JJ. The full solution is in jacobian.py.

On cost: jacobian takes 2n2n evaluations and O(mn)O(mn) memory. jvp_numeric takes 2 evaluations whatever nn and mm. vjp_numeric takes 2n+12n + 1 (one to check u’s shape, then numerical_grad’s 2n2n), but stores only O(n)O(n).

You could compute the VJP as u @ jacobian(f, x). It gives the same numbers but stores the whole m×nm \times n 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 O(ϵ)O(\epsilon) error, about 10−610^{-6}, 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 hh makes the distance proportional to ∣v∣\lvert v\rvert.

The tradeoff accepted is that these are oracles, not autodiff: their accuracy is about 10−1010^{-10} on well-scaled functions. That is enough to confirm the exact forward- and reverse-mode results of chapter 8.

Most of the bugs here produce arrays of the right shape with the wrong numbers, which is why they survive casual testing:

PitfallSymptomHow the solution avoids it
the Jacobian transposed (columns stacked as rows)J⊤J^\top: right shape for square JJ, wrong numbers, and a chain rule product in the wrong orderstacks columns with axis=1 (step 1)
perturbing the caller’s xx and not restoring itthe input array changes during a checkworks on np.array(x, dtype=np.float64, copy=True)
leaving coordinate jj at xj−ϵx_j - \epsilonevery later column is taken at a shifted pointsets flat[j] = orig after both evaluations
a fixed JVP step whatever the size of vvJ(106v)J(10^6 v) is a secant over a unit step`h = JVP_STEP / max
a VJP that computes JuJu instead of u⊤Ju^\top Jthe column (4,5)(4, 5) where the row (4,1)(4, 1) was wanteddifferentiates the scalar u⋅f(x)u \cdot f(x) (step 5)
one-sided differences for the columnserrors near 10−610^{-6}; softmax’s closed form missedevaluates both xj±ϵx_j \pm \epsilon
dividing the JVP by hh instead of 2h2hevery JVP doubleddivides by 2.0 * h
flattening xx through a copythe perturbations never reach ff: J=0J = 0uses xw.reshape(-1), a view of the copy
the column difference reversed−J-Jcomputes hi - lo
a VJP that ignores uuthe gradient of ∑ifi\sum_i f_i for every uumultiplies by ua inside the scalar

Warning: xw.flatten() and xw.reshape(-1) look interchangeable, but flatten always copies. Perturbing a copy never reaches ff, and the Jacobian silently comes out all zeros.

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 JvJv exactly and its tests compare against jvp_numeric; Scalar reverse mode: the Value graph computes u⊤Ju^\top J 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.

  • JAX jax.jvp and jax.vjp (jax/_src/api.py): exact products by forward and reverse mode, composable with jit and vmap.
  • PyTorch torch.autograd.functional.jacobian with vectorize=True (torch/autograd/functional.py), and JAX jacfwd and jacrev: the full Jacobian from nn JVPs or mm VJPs, batched. Pick forward when n<mn < m, reverse when m<nm < n.
  • 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 u⊤(Jv)=(u⊤J)vu^\top(Jv) = (u^\top J)v to check a whole backward with one random uu and vv instead of mnmn 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.
  • Jacobian: the m×nm \times n matrix of partial derivatives Jij=∂fi/∂xjJ_{ij} = \partial f_i / \partial x_j of a function f:Rn→Rmf: \mathbb{R}^n \to \mathbb{R}^m.
  • Tangent: a direction vv in input space along which the input is moved.
  • Cotangent: a weighting uu of the outputs, pulled back through a function by a VJP.
  • JVP (Jacobian-vector product): JvJv, the rate of change of the output along vv; what forward mode computes.
  • VJP (vector-Jacobian product): u⊤Ju^\top J, the gradient of u⋅f(x)u \cdot f(x); what reverse mode computes.
  • Chain rule: Jg∘f(x)=Jg(f(x)) Jf(x)J_{g \circ f}(x) = J_g(f(x))\,J_f(x).
  • For f:Rn→Rmf: \mathbb{R}^n \to \mathbb{R}^m the Jacobian JJ is the m×nm \times n matrix of partial derivatives, Jij=∂fi/∂xjJ_{ij} = \partial f_i / \partial x_j: row ii is the gradient of output ii, column jj is how every output moves with input jj.
  • The chain rule in several variables is a matrix product, outer function on the left: Jg∘f(x)=Jg(f(x)) Jf(x)J_{g \circ f}(x) = J_g(f(x))\,J_f(x).
  • Autodiff never forms JJ. Forward mode pushes a direction through, JvJv; reverse mode pulls a cotangent back, u⊤Ju^\top J, which is the gradient of the scalar u⋅f(x)u \cdot f(x).
  • The two products are consistent: u⊤(Jv)=(u⊤J)vu^\top(Jv) = (u^\top J)v for every uu and vv.
  • The JVP step must scale with vv: h=10−6/max⁡∣v∣h = 10^{-6}/\max|v|, so the input moves by 10−610^{-6} whatever the size of vv.
  1. Why does jacobian stack the columns with axis=1 and not axis=0?

    Answer

    Each computed vector is how all mm outputs move with one input: a column of JJ. Stacking along axis=0 would place it as a row and return J⊤J^\top, which has the right shape whenever m=nm = n and wrong numbers unless JJ is symmetric. On the worked example it would give rows (4,5)(4, 5) and (1,−0.416)(1, -0.416).

  2. What happens if flat is xw.flatten() instead of xw.reshape(-1)?

    Answer

    flatten returns a copy, so writing flat[j] never changes xw, ff always sees the unperturbed input, hi == lo, and every column is 0.

  3. Why is h=10−6/max⁡∣v∣h = 10^{-6}/\max|v| and not a fixed 10−610^{-6}?

    Answer

    The input moves by hvh v. With ∣v∣=106|v| = 10^6 a fixed hh moves xx by a whole unit, and the quotient is a secant over that unit, not a derivative. Dividing by max⁡∣v∣\max|v| keeps the largest coordinate’s move at 10−610^{-6}, so J(cv)=c JvJ(cv) = c\,Jv to rounding.

  4. Why is the VJP the gradient of u⋅f(x)u \cdot f(x)?

    Answer

    ∂(∑iuifi)/∂xj=∑iui ∂fi/∂xj=(u⊤J)j\partial(\sum_i u_i f_i)/\partial x_j = \sum_i u_i \,\partial f_i/\partial x_j = (u^\top J)_j. So the row vector u⊤Ju^\top J is exactly the gradient of that scalar, and one gradient computation replaces mm rows.

  5. What does u⊤(Jv)=(u⊤J)vu^\top(Jv) = (u^\top J)v check that neither product checks alone?

    Answer

    That the forward and reverse products describe the same matrix. A VJP that returned JuJu or a JVP that used J⊤J^\top could each look plausible, but would break the identity for generic uu and vv.