Math Fundamentals · lesson 09/15
The Jacobian Matrix
The gradient handles functions that return one number. Most layers return a vector, so their derivative is a matrix — the Jacobian. Autograd rarely builds it explicitly, but knowing its shape explains what a vector-Jacobian product is doing.
The idea
For , the Jacobian is the matrix
Each row is the gradient of one output; each column holds the partials with respect to one input. Note the shape convention: rows, columns — outputs first.
Two products with the Jacobian matter:
- VJP (reverse mode) — given an upstream row vector , compute . This is one backward pass, and it never forms .
- JVP (forward mode) — given a direction , compute . Cheap when is small.
A layer that maps element-wise, like ReLU, has a diagonal Jacobian, so the VJP is just an element-wise multiply — which is why activation layers are cheap.
Worked example
Let .
At : .
- VJP with , i.e. only matters: , the first row.
- VJP with : , the second row.
- VJP with : , the sum of the rows — gradients from both outputs accumulate.
That last case is the general rule: a downstream vector selects a weighted combination of Jacobian rows.
In code
import torch
from torch.func import jacrev
def f(x):
return torch.stack([x[0]**2 * x[1], x[0] + x[1]])
x = torch.tensor([2.0, 3.0])
print(jacrev(f)(x)) # tensor([[12., 4.], [1., 1.]])jacrev forms the full matrix for teaching purposes. In real training nobody does: reverse mode computes for the single upstream vector and skips the unused rows.
Check yourself
- What is the shape of the Jacobian of a function ?
- Under what condition is the Jacobian diagonal, and what does that imply about a VJP?
- Why is computing a single VJP far cheaper than materializing the Jacobian when is large?
Key takeaways
- The Jacobian stacks the gradients of every output of a vector function.
- Reverse mode computes without ever forming .
- Diagonal Jacobians (element-wise layers) make activation gradients cheap.