The Math Behind the Methods

Jacobians and Vector-Jacobian Products in Deep Learning

See what a Jacobian holds, why backpropagation never builds it, and how vector-Jacobian products work for common layers.

Key takeaways

  • For a function with n inputs and m outputs, the Jacobian is an m by n matrix whose entry (i, j) is ∂yᵢ/∂xⱼ.
  • Backpropagation passes a gradient vector backward, and each operation turns it into gradients for its inputs through a VJP.
  • Elementwise operations, matrix products and softmax all have VJPs that cost about as much as the forward computation.
  • A Jacobian-vector product pushes a change forward, while a vector-Jacobian product pulls a sensitivity backward.
  • A numerical check with random vectors catches most mistakes in a hand-written backward rule.

A Jacobian is the table of every first partial derivative of a function that takes several numbers in and gives several numbers out. A vector-Jacobian product (VJP) is that table multiplied on the left by a vector, and it is what each layer actually computes during backpropagation.

The distinction matters because the full table is usually far too large to store. Deep learning works because the product can almost always be computed directly, with a short formula, without ever forming the matrix.

What the matrix contains

Let y = f(x), where x has n entries and y has m entries. The Jacobian J has one row per output and one column per input. Row i is the gradient of output i. Column j says how all outputs move when input j moves.

Take a function from two inputs to three outputs.

y₁ = x₁²          row 1 of J:  2x₁   0
y₂ = x₁ · x₂      row 2 of J:  x₂    x₁
y₃ = 3x₂          row 3 of J:  0     3

At x = (2, 3) the matrix is:

J = [ 4  0 ]
    [ 3  2 ]
    [ 0  3 ]

The Jacobian is the best linear approximation of f near that point. If you nudge x by a small vector Δx, then Δy ≈ J Δx. When m = 1, the Jacobian is a single row, which is the gradient written sideways. If partial derivatives of a loss are familiar, a Jacobian is just many of them arranged by output and input.

Two products, two directions

You can multiply J by a vector on either side, and the two products answer different questions.

A Jacobian-vector product (JVP) computes J u, where u has n entries. It answers: if the input moves in direction u, how do the outputs move? A vector-Jacobian product computes vᵀJ, where v has m entries. It answers: if the final loss changes at rate v with respect to each output, at what rate does it change with respect to each input?

With the matrix above, take u = (1, 1) and v = (1, −1, 2).

J u   = (4·1 + 0·1,  3·1 + 2·1,  0·1 + 3·1)              = (4, 5, 3)
vᵀ J  = (1·4 − 1·3 + 2·0,  1·0 − 1·2 + 2·3)              = (1, 4)

check:  v · (J u) = 4 − 5 + 6 = 5
        (vᵀ J) · u = 1 + 4    = 5

The two checks agree because both compute the single number vᵀJu. This identity is a handy test, as you will see below.

Two ways to use a Jacobian
Jacobian-vector product Computes J u u has one entry per input Moves a change forward Used by forward-mode differentiation Vector-Jacobian product Computes v transposed times J v has one entry per output Pulls a sensitivity backward Used by backpropagation VS Jacobian-vector product Computes J u u has one entry per input Moves a change forward Used by forward-mode differentiation Vector-Jacobian product Computes v transposed times J v has one entry per output Pulls a sensitivity backward Used by backpropagation

Why nobody builds the full matrix

Consider a linear layer that maps 4,096 features to 4,096 features, applied to a batch of 64 examples. The output holds 262,144 numbers, and so does the input. The Jacobian of one with respect to the other has 262,144² entries, about 69 billion. In 32-bit floating point that is roughly 275 GB, for one layer and one of its two inputs.

Almost all of those entries are zero, because one example in the batch does not affect another example's output through a linear layer. The nonzero blocks are all copies of the weight matrix. Storing the table would waste memory on structure you already know.

The training loss is a single number, so you only ever need its derivative with respect to each array. Those derivatives have the same shapes as the arrays themselves. A VJP goes straight from the gradient at the output to the gradient at the input.

Rules for common layers

In each rule, g is the gradient of the loss with respect to the operation's output.

Operation Gradient passed to the input Why it is cheap
Elementwise y = h(x) g ⊙ h′(x) The Jacobian is diagonal
y = Ax Aᵀg One transposed matrix product
s = sum of all xᵢ g copied into every position The Jacobian is a row of ones
y = x plus a constant g unchanged The Jacobian is the identity
Concatenation g split back into pieces Entries are only rearranged

Here ⊙ means elementwise multiplication. For a ReLU, h′(x) is 1 where x > 0 and 0 where x < 0. At exactly zero the derivative does not exist, and libraries choose a value by convention.

Matrix products

For Y = XW, let X have shape (n, d), with one example per row, and let W have shape (d, k). The incoming gradient G has shape (n, k).

gradient for W:  Xᵀ G      (d, n) · (n, k) = (d, k)
gradient for X:  G Wᵀ      (n, k) · (k, d) = (n, d)

You can recover both from shapes alone, since only one arrangement of these three matrices fits each target. A bias b of shape (k,) is copied to all n rows in the forward pass, so its gradient is G summed over the row axis. The rule is general: whatever was broadcast forward gets summed backward. Reading tensor shapes makes these cases easier to spot.

Softmax, where the Jacobian is dense

Softmax turns a vector of scores z into positive numbers p that sum to 1. Every output depends on every input.

∂pᵢ/∂zⱼ = pᵢ (δᵢⱼ − pⱼ)          δᵢⱼ is 1 when i = j, else 0
J = diag(p) − p pᵀ

For K classes that is a K by K matrix, but the product with an incoming vector g simplifies.

gradient for z = p ⊙ g − p (p · g) = p ⊙ (g − p · g)

Say p = (0.5, 0.3, 0.2) and g = (1, 0, 0). The scalar p · g is 0.5, so the result is (0.5 · 0.5, 0.3 · (−0.5), 0.2 · (−0.5)) = (0.25, −0.15, −0.10). The entries sum to zero, which makes sense: adding the same constant to every score leaves softmax unchanged. The work grows with K, not with K².

When softmax feeds a cross-entropy loss, the combined gradient with respect to z is even simpler, p minus the one-hot target. Softmax and numerical stability explains why libraries fuse the two.

Chaining products through a network

A network is a composition f = f₃ ∘ f₂ ∘ f₁, so its Jacobian is the matrix product J₃J₂J₁. Matrix multiplication is associative, and the order you choose changes the cost enormously.

For a scalar loss, J₃ is a single row. Multiplying from the left keeps the running result a row vector: first vᵀJ₃, then times J₂, then times J₁. Starting from the right would build large matrix-by-matrix products first. Backpropagation is simply the cheap order. The chain rule on computation graphs shows the same idea node by node.

The price is memory. Most VJPs need values from the forward pass, such as X for the weight gradient or p for softmax, so those must be kept until the backward pass reaches them.

Writing and checking a VJP

A convenient pattern is a function that returns the output together with a closure that computes the VJP. This example applies a tanh layer.

import numpy as np

def tanh_layer(X, W):                  # X: (n, d), W: (d, k)
    Y = np.tanh(X @ W)                 # (n, k)
    def vjp(G):                        # G: (n, k)
        H = G * (1.0 - Y**2)
        return H @ W.T, X.T @ H        # for X, for W
    return Y, vjp

rng = np.random.default_rng(0)
X, W = rng.normal(size=(4, 3)), rng.normal(size=(3, 2))
G = rng.normal(size=(4, 2))
U = rng.normal(size=W.shape)

_, vjp = tanh_layer(X, W)
analytic = np.sum(vjp(G)[1] * U)
h = 1e-6
numeric = np.sum(G * (tanh_layer(X, W + h*U)[0]
                      - tanh_layer(X, W - h*U)[0])) / (2*h)
print(analytic, numeric)               # should agree closely

The test compares the two sides of the identity from earlier. The numeric side estimates J U by a central difference and then takes its inner product with G. The analytic side applies your VJP to G and takes the inner product with U. One random pair of directions tests every entry at once. Use double precision, and repeat the test for the gradient with respect to X.

When you do want the Jacobian

Some tasks need the matrix itself, or parts of it. You might study how sensitive outputs are to inputs, solve a least squares problem with a Gauss-Newton method, or analyze a small physical model.

Reverse mode builds J one row at a time, using one VJP per output. Forward mode builds it one column at a time, using one JVP per input. Pick the direction with fewer passes: reverse for few outputs, forward for few inputs. Forward and reverse mode compares them in detail.

For large problems, people often estimate a summary instead. The squared Frobenius norm of J, which is the sum of its squared entries, equals the expected value of the squared length of vᵀJ when v is a random vector with independent entries of mean 0 and variance 1. A few VJPs give a noisy but usable estimate.

Common questions

Why does my library complain about backward on a non-scalar?

Calling backward on an array output is ambiguous, because there is no single loss. You must supply the vector v, often called the upstream gradient or the seed. Passing all ones is the same as differentiating the sum of the outputs, which may or may not be what you intended.

Is the transpose in these formulas a convention?

Partly. If you treat gradients as column vectors, you write Jᵀv, and if you treat them as rows, you write vᵀJ. The numbers are identical. Check which layout a text uses before copying a formula into code.

Does a VJP cost more than the forward pass?

For most standard operations it costs a similar amount of arithmetic, often within a small constant factor. A matrix product has two inputs, so computing both gradients takes two matrix products of the same size as the forward one.

Written for 4MachineLearning with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 26 articles in The Math Behind the Methods →

Latest news on this topic