Module contents
Lesson 22 of 25Advanced 110 min

Matrix calculus II: the matrix chain rule and backpropagation by hand

Understand exactly what loss.backward() computes: the chain rule between matrix spaces, why full Jacobians are never formed, and how vector-Jacobian products yield gradients for linear layers, nonlinearities, softmax and arbitrary contractions. Derive a complete batch-vectorized MLP by hand and write a PyTorch layer with custom backward.

After this lesson you can

  • Apply the chain rule with differentials to compositions between matrix and tensor spaces.
  • Compute VJPs and JVPs without forming Jacobians and estimate their cost versus the full Jacobian.
  • Derive gradients of Y = XW + b, elementwise nonlinearities and softmax with cross-entropy.
  • Obtain VJPs for arbitrary einsum contractions and broadcasting.
  • Implement and check a full batch MLP backward pass and a custom PyTorch layer.

Before you start

Motivation: what loss.backward() computes

Training a network repeats three lines: loss = model(X, y), loss.backward() and optimizer.step(). The middle line leaves the gradient of the loss with respect to each set of weights in W.grad, as a matrix shaped like W. While it works, nobody looks inside. But in three situations, trust is not enough:

  • Debugging. The loss does not fall, or falls then explodes, or a gradient becomes NaN. To tell whether the problem is in the data, architecture or a numerically fragile operation, you need to know what each node computes in the backward pass. A bias gradient shaped (B, D) instead of (D,), or log applied to a probability that was already zero, is easy to spot when you know what should be there.
  • Writing custom layers. Attention with an unusual mask, a low-rank layer, a fused Triton kernel: once the forward pass is no longer a composition of standard operations, you must write the backward pass yourself. Much of FlashAttention consists of hand-written forward and backward passes that never store the attention matrix.
  • Reasoning about cost. Why does backward cost roughly twice as much as forward? Why does training memory grow with batch size even though the weights stay the same? Why does nobody compute a network’s Jacobians? The answers are linear algebra, and that is what this lesson covers.

In the previous lesson you learned to differentiate a scalar function of a matrix using the differential: write dfdf, rotate with the trace trick, and read off the gradient. Now we chain functions between matrix spaces. The chain rule written with Jacobians produces absurdly large objects; backpropagation avoids forming them and instead applies the adjoint of each differential from output to input. By the end you will have derived every gradient of a batch-vectorized multilayer perceptron (MLP), trained it with your own backward pass and written a layer with a custom backward pass in PyTorch.

The chain rule between matrix spaces

Recall the starting point. A function f:Rm×n→Rp×qf: \R^{m\times n} \to \R^{p\times q} is differentiable at X\mat{X} if there is a linear map f′(X):Rm×n→Rp×qf'(\mat{X}): \R^{m\times n} \to \R^{p\times q} such that

f(X+H)=f(X)+f′(X)[H]+o(∥H∥),f(\mat{X} + \mat{H}) = f(\mat{X}) + f'(\mat{X})[\mat{H}] + o(\norm{\mat{H}}),

and the differential is that linear part applied to a perturbation, dY=f′(X)[dX]d\mat{Y} = f'(\mat{X})[d\mat{X}]. What matters now is that f′(X)f'(\mat{X}) is a linear map between matrix spaces, not a table of numbers. Composing functions composes their linear parts.

Proof

Write A=f′(X)\mathcal{A} = f'(\mat{X}) and B=g′(Y)\mathcal{B} = g'(\mat{Y}) and use the Frobenius norm in every space. Since these are linear maps between finite-dimensional spaces, they are bounded: ∥A[H]∥≤∥A∥ ∥H∥\norm{\mathcal{A}[\mat{H}]} \le \norm{\mathcal{A}}\,\norm{\mat{H}} and likewise for B\mathcal{B}. By assumption,

f(X+H)=Y+A[H]+R1(H),g(Y+K)=g(Y)+B[K]+R2(K),f(\mat{X} + \mat{H}) = \mat{Y} + \mathcal{A}[\mat{H}] + \mat{R}_1(\mat{H}), \qquad g(\mat{Y} + \mat{K}) = g(\mat{Y}) + \mathcal{B}[\mat{K}] + \mat{R}_2(\mat{K}),

with ∥R1(H)∥≤ε1(H)∥H∥\norm{\mat{R}_1(\mat{H})} \le \eps_1(\mat{H})\norm{\mat{H}} and ∥R2(K)∥≤ε2(K)∥K∥\norm{\mat{R}_2(\mat{K})} \le \eps_2(\mat{K})\norm{\mat{K}}, where εi→0\eps_i \to 0 as its argument tends to 0\mat{0} (and ε2(0)=0\eps_2(\mat{0}) = 0). Take K=A[H]+R1(H)\mat{K} = \mathcal{A}[\mat{H}] + \mat{R}_1(\mat{H}), so f(X+H)=Y+Kf(\mat{X} + \mat{H}) = \mat{Y} + \mat{K}. Then

g(f(X+H))=g(Y)+B[A[H]]+B[R1(H)]+R2(K)⏟resto.g(f(\mat{X} + \mat{H})) = g(\mat{Y}) + \mathcal{B}\big[\mathcal{A}[\mat{H}]\big] + \underbrace{\mathcal{B}\big[\mat{R}_1(\mat{H})\big] + \mat{R}_2(\mat{K})}_{\text{resto}}.

The first remainder term is bounded by ∥B∥ ε1(H)∥H∥\norm{\mathcal{B}}\,\eps_1(\mat{H})\norm{\mat{H}}. For the second, if ∥H∥\norm{\mat{H}} is small enough, ε1(H)≤1\eps_1(\mat{H}) \le 1, so ∥K∥≤(∥A∥+1)∥H∥\norm{\mat{K}} \le (\norm{\mathcal{A}} + 1)\norm{\mat{H}}; in particular K→0\mat{K} \to \mat{0} and ∥R2(K)∥≤ε2(K)(∥A∥+1)∥H∥\norm{\mat{R}_2(\mat{K})} \le \eps_2(\mat{K})(\norm{\mathcal{A}} + 1)\norm{\mat{H}}. Both terms are o(∥H∥)o(\norm{\mat{H}}), and B∘A\mathcal{B}\circ\mathcal{A} is linear: it is the derivative of g∘fg\circ f at X\mat{X}.

∎

This is the matrix chain rule, and in practice you use it without naming it: write dYd\mat{Y} in terms of dXd\mat{X}, then dZd\mat{Z} in terms of dYd\mat{Y}, and substitute. It is the familiar multivariable chain rule without choosing coordinates.

In coordinates: giant Jacobians

If you choose coordinates, each linear map becomes a matrix. Flatten inputs and outputs with the vec operator, which stacks columns: the Jacobian matrix of ff is the matrix Jf∈Rpq×mn\mat{J}_f \in \R^{pq\times mn} satisfying

vec⁡(f′(X)[H])=Jf vec⁡H,\operatorname{vec}\big(f'(\mat{X})[\mat{H}]\big) = \mat{J}_f\,\operatorname{vec}\mat{H},

and because composition of linear maps is multiplication of their matrices, the chain rule reads Jg∘f=Jg Jf\mat{J}_{g\circ f} = \mat{J}_g\,\mat{J}_f. To compute these matrices, use the Kronecker product identity

vec⁡(AXB)=(B⊤⊗A)vec⁡X.\operatorname{vec}(\mat{A}\mat{X}\mat{B}) = (\mat{B}\T\otimes\mat{A})\operatorname{vec}\mat{X}.

Apply it to the most important deep learning function, Y=XW\mat{Y} = \mat{X}\mat{W}, with X∈Rn×d\mat{X} \in \R^{n\times d} (a batch of nn examples in rows) and W∈Rd×p\mat{W} \in \R^{d\times p}. As a function of W\mat{W}, XW=XWIp\mat{X}\mat{W} = \mat{X}\mat{W}\mat{I}_p, so

vec⁡Y=(Ip⊗X)vec⁡W,JW=Ip⊗X∈Rnp×dp,\operatorname{vec}\mat{Y} = (\mat{I}_p\otimes\mat{X})\operatorname{vec}\mat{W}, \qquad \mat{J}_{\mat{W}} = \mat{I}_p\otimes\mat{X} \in \R^{np\times dp},

and as a function of X\mat{X}, XW=InXW\mat{X}\mat{W} = \mat{I}_n\mat{X}\mat{W} gives JX=W⊤⊗In∈Rnp×nd\mat{J}_{\mat{X}} = \mat{W}\T\otimes\mat{I}_n \in \R^{np\times nd}. The Jacobian has one row for each output entry and one column for each variable entry: its size is the product of the two sizes. With respect to the weights, JW\mat{J}_{\mat{W}} has npnp times as many entries as W\mat{W}.

That factor npnp is the number of entries in Y\mat{Y} and is enormous in a real network. Calculate how much space it takes with realistic dimensions.

InteractiveThe Jacobian that does not fit in the universe
The first GPT-2 small MLP layer (768→3072768 \to 3072) over one 1024-token sequence.
Weights W\mat{W}9.44 MB
Input X\mat{X}3.15 MB
Incoming gradient, ∇YL\grad_{\mat{Y}} L12.6 MB
VJP: ∇WL=X⊤∇YL\grad_{\mat{W}} L = \mat{X}\T\grad_{\mat{Y}} L9.44 MB
Jacobian, nonzero entries only (doutd_{\text{out}} copies of X\mat{X})9.66 GB
Full Jacobian ∂vec⁡Y/∂vec⁡W\partial\operatorname{vec}\mat{Y}/\partial\operatorname{vec}\mat{W}29.7 TB
Dashed lines:laptop, 16 GBGPU, 80 GB
3072 blocks (5 shown)X00000X00000X00000X00000Xrows: n·d_out
vec⁡Y=(I3072⊗X)vec⁡W\operatorname{vec}\mat{Y} = (\mat{I}_{3072} \otimes \mat{X})\operatorname{vec}\mat{W}
The Jacobian has 3 145 728 rows and 2 359 296 columns. Almost all are zero; the nonzeros are 3 072 copies of X\mat{X}. The VJP uses the information without copying it.
The full Jacobian occupies 29.7 TB, 3 145 728 times the weights. The VJP occupies 9.44 MB.
Examples
Precision
Dimensions of Y=XW\mat{Y} = \mat{X}\mat{W}
1 024
768
3 072
Full Jacobian29.7 TB
VJP, same as W\mat{W}9.44 MB
Jacobian / weights =n dout= n\,d_{\text{out}}3 145 728 ×
Jacobian zeros =1−1/dout= 1 - 1/d_{\text{out}}99.967 %
Reading alone at 3 TB/s9.90 s
Memory of each object involved in the gradient of Y=XW\mat{Y} = \mat{X}\mat{W} with respect to W\mat{W}, on a logarithmic scale (a factor of 1000 between marks). The full Jacobian takes n doutn\,d_{\text{out}} times as much space as the weights; its nonzero entries take doutd_{\text{out}} copies of X\mat{X}; the VJP takes the same space as W\mat{W}. Try the examples: with GPT-2 layer dimensions and one sequence, the Jacobian takes about 30 TB in float32. Below is the block structure of I⊗X\mat{I}\otimes\mat{X}.

Three observations you will use throughout the lesson:

  • The Jacobian is almost all zeros. Ip⊗X\mat{I}_p\otimes\mat{X} is block diagonal: pp copies of X\mat{X} along the diagonal and zeros elsewhere. The fraction of zeros is 1−1/p1 - 1/p. But storing only the nonzeros does not save you: that would be pp copies of X\mat{X} when all the information is already in one.
  • Nobody needs the Jacobian. The optimizer needs ∇WL\grad_{\mat{W}} L, a matrix shaped like W\mat{W}. The Jacobian is a tool for going from ∇YL\grad_{\mat{Y}} L to ∇WL\grad_{\mat{W}} L, and can be applied without constructing it.
  • Time also explodes. Multiplying a vector by a dense Jacobian of np×dpnp\times dp costs about 2 np⋅dp2\,np\cdot dp operations, pp times more than the product X⊤G\mat{X}\T\mat{G} replacing it, without counting the cost of reading tens of terabytes from memory.

JVP and VJP: the adjoint of the differential

There are two ways to use a linear map without writing its matrix: apply it, or apply its adjoint. Defining the adjoint requires the Frobenius inner product, ⟨A,B⟩F=tr⁡(A⊤B)=∑ijAijBij\inner{\mat{A}}{\mat{B}}_F = \tr(\mat{A}\T\mat{B}) = \sum_{ij}A_{ij}B_{ij}, the same one used to define the gradient.

Existence and uniqueness follow from the same argument as for the gradient: H↦⟨U,f′(X)[H]⟩F\mat{H} \mapsto \inner{\mat{U}}{f'(\mat{X})[\mat{H}]}_F is a linear form on Rm×n\R^{m\times n}, and every linear form is represented by a unique matrix under the Frobenius product. The coordinate formula comes from writing both sides with vec: (vec⁡U)⊤Jfvec⁡H=(Jf⊤vec⁡U)⊤vec⁡H(\operatorname{vec}\mat{U})\T\mat{J}_f\operatorname{vec}\mat{H} = (\mat{J}_f\T\operatorname{vec}\mat{U})\T\operatorname{vec}\mat{H}. In the calculus module you saw these two operations with vectors, as JVP and VJP; with matrices nothing changes except that each object’s shape is preserved.

Notice the shapes: the JVP goes from input space to output space, like the forward pass; the VJP goes from output to input, backward. And that is exactly what the gradient needs.

Proof

By the chain rule, dL=⟨∇Yℓ,dY⟩F=⟨∇Yℓ,f′(X)[dX]⟩F=⟨f′(X)∗[∇Yℓ],dX⟩FdL = \inner{\grad_{\mat{Y}}\ell}{d\mat{Y}}_F = \inner{\grad_{\mat{Y}}\ell}{f'(\mat{X})[d\mat{X}]}_F = \inner{f'(\mat{X})^{*}[\grad_{\mat{Y}}\ell]}{d\mat{X}}_F for every dXd\mat{X}, and the gradient is the unique matrix with that property. For the chain, observe that the adjoint of a composition is the composition of the adjoints in reverse order: if A\mathcal{A} and B\mathcal{B} are composable linear maps, ⟨U,B[A[H]]⟩=⟨B∗[U],A[H]⟩=⟨A∗[B∗[U]],H⟩\inner{\mat{U}}{\mathcal{B}[\mathcal{A}[\mat{H}]]} = \inner{\mathcal{B}^{*}[\mat{U}]}{\mathcal{A}[\mat{H}]} = \inner{\mathcal{A}^{*}[\mathcal{B}^{*}[\mat{U}]]}{\mat{H}}, hence (B∘A)∗=A∗∘B∗(\mathcal{B}\circ\mathcal{A})^{*} = \mathcal{A}^{*}\circ\mathcal{B}^{*}. Applied to (fk′∘⋯∘f1′)∗(f_k'\circ\cdots\circ f_1')^{*} this yields the formula. In coordinates it is (Jk⋯J1)⊤=J1⊤⋯Jk⊤(\mat{J}_k\cdots\mat{J}_1)\T = \mat{J}_1\T\cdots\mat{J}_k\T.

∎
Key idea
Backpropagation means starting with ∇Xkℓ\grad_{\mat{X}_k}\ell at the output and applying each operation’s VJP node by node, working backward. Each VJP receives a matrix shaped like the node’s output and returns one shaped like its input. No Jacobian is formed.

The recipe for the VJP of any operation is the trace trick with an incoming gradient G\mat{G} instead of a scalar: write dYd\mat{Y} in terms of dXd\mat{X}, form ⟨G,dY⟩F=tr⁡(G⊤dY)\inner{\mat{G}}{d\mat{Y}}_F = \tr(\mat{G}\T d\mat{Y}), rotate until dXd\mat{X} is on the right, tr⁡(M dX)\tr(\mat{M}\,d\mat{X}), and read off ∇X=M⊤\grad_{\mat{X}} = \mat{M}\T. This yields every rule in the lesson.

The cost of each mode

Suppose F:RN→RMF: \R^N \to \R^M (inputs and outputs flattened) and evaluating FF costs cc. A JVP gives one column of JF\mat{J}_F (the derivative in one direction); a VJP gives one row. Both cost a small multiple of cc, as you will see layer by layer. Thus:

  • Forward mode, which propagates JVPs, needs NN passes for the full Jacobian.
  • Reverse mode, which propagates VJPs, needs MM passes.

A loss has M=1M = 1 and NN equal to the number of parameters, which may be 10910^9. Reverse mode obtains the full gradient in one backward pass, at a cost bounded by a small multiple of the forward pass and independent of NN: the cheap gradient principle. Forward mode would need a billion passes. Conversely, for a function with few inputs and many outputs (for example, the trajectory of a dynamical system as a function of three parameters), forward mode wins. The general algorithms for both modes are studied in reverse-mode automatic differentiation in the numerical methods module.

Reverse mode has a cost: each node’s VJP needs forward values (f′(Xj−1)∗f'(\mat{X}_{j-1})^{*} depends on Xj−1\mat{X}_{j-1}), which were calculated in the opposite direction. They must be stored during the forward pass. This activation memory grows with batch size and motivates techniques such as gradient checkpointing, which stores only some activations and recomputes the rest. You will see exactly what must be stored for each operation.

The linear layer

Every network consists of linear layers interleaved with elementwise operations, so this is the rule you will use most often. With the batch in rows, as in PyTorch,

Y=XW+1b⊤,X∈RB×din,W∈Rdin×dout,b∈Rdout,1∈RB,\mat{Y} = \mat{X}\mat{W} + \vb{1}\vb{b}\T, \qquad \mat{X} \in \R^{B\times d_{\text{in}}},\quad \mat{W} \in \R^{d_{\text{in}}\times d_{\text{out}}},\quad \vb{b} \in \R^{d_{\text{out}}},\quad \vb{1} \in \R^{B},

where 1b⊤\vb{1}\vb{b}\T is the B×doutB\times d_{\text{out}} matrix with b⊤\vb{b}\T in every row: bias broadcasting written as a product.

These are the linear layer gradients. You prove the first two formulas with differentials in the exercise below. The bias formula takes one line: dY=1 db⊤d\mat{Y} = \vb{1}\,d\vb{b}\T, so tr⁡(G⊤1 db⊤)=db⊤G⊤1\tr(\mat{G}\T\vb{1}\,d\vb{b}\T) = d\vb{b}\T\mat{G}\T\vb{1} (the trace of a number is the number itself, and can be transposed), that is, ⟨G⊤1,db⟩\inner{\mat{G}\T\vb{1}}{d\vb{b}}.

ProofThe linear layer with differentials
Prove: If Y=XW\mat{Y} = \mat{X}\mat{W} and G=∇YL\mat{G} = \grad_{\mat{Y}} L, then ∇WL=X⊤G\grad_{\mat{W}} L = \mat{X}\T\mat{G} and ∇XL=GW⊤\grad_{\mat{X}} L = \mat{G}\mat{W}\T.
0
Start from dL=tr⁡(G⊤dY)dL = \tr(\mat{G}\T d\mat{Y}), the definition of the gradient with respect to Y\mat{Y}, and the product rule for differentials.

Step 1 of 4. What is dYd\mat{Y}?

The same formula follows from the Jacobian without forming it. With JW=I⊗X\mat{J}_{\mat{W}} = \mat{I}\otimes\mat{X} and the rule (A⊗B)⊤=A⊤⊗B⊤(\mat{A}\otimes\mat{B})\T = \mat{A}\T\otimes\mat{B}\T,

JW⊤vec⁡G=(I⊗X⊤)vec⁡G=vec⁡(X⊤G I)=vec⁡(X⊤G),\mat{J}_{\mat{W}}\T\operatorname{vec}\mat{G} = (\mat{I}\otimes\mat{X}\T)\operatorname{vec}\mat{G} = \operatorname{vec}(\mat{X}\T\mat{G}\,\mat{I}) = \operatorname{vec}(\mat{X}\T\mat{G}),

and with JX=W⊤⊗I\mat{J}_{\mat{X}} = \mat{W}\T\otimes\mat{I}, JX⊤vec⁡G=(W⊗I)vec⁡G=vec⁡(GW⊤)\mat{J}_{\mat{X}}\T\operatorname{vec}\mat{G} = (\mat{W}\otimes\mat{I})\operatorname{vec}\mat{G} = \operatorname{vec}(\mat{G}\mat{W}\T). Read from right to left, the Kronecker identity turns the giant product into an ordinary-sized matrix product.

There are four readings of these formulas that specialists keep in mind:

  1. Shapes almost decide the formula. ∇WL\grad_{\mat{W}} L must have shape din×doutd_{\text{in}}\times d_{\text{out}}, and with X\mat{X} (B×dinB\times d_{\text{in}}) and G\mat{G} (B×doutB\times d_{\text{out}}) only one product has that shape: the one contracting the batch index, X⊤G\mat{X}\T\mat{G}. Likewise for GW⊤\mat{G}\mat{W}\T. But only almost: if din=doutd_{\text{in}} = d_{\text{out}}, GW\mat{G}\mat{W} also has the correct shape and is wrong. Shapes rule out mistakes; they do not prove correctness.
  2. The weight gradient is a sum of rank-one matrices. X⊤G=∑ixigi⊤\mat{X}\T\mat{G} = \sum_i \vb{x}_i\vb{g}_i\T: each example contributes a rank-one matrix, the outer product of the input and the output gradient. Thus the rank of ∇WL\grad_{\mat{W}} L is at most BB. The norm of each example’s gradient comes for free, ∥xigi⊤∥F=∥xi∥ ∥gi∥\norm{\vb{x}_i\vb{g}_i\T}_F = \norm{\vb{x}_i}\,\norm{\vb{g}_i}, without forming a matrix: this is Goodfellow’s (2015) trick for per-example gradient clipping, needed for training with differential privacy.
  3. Propagating backward means multiplying by W⊤\mat{W}\T. The input gradient, GW⊤\mat{G}\mat{W}\T, is the transposed linear layer applied to the gradient. A deep network multiplies the gradient by Wℓ⊤\mat{W}_\ell\T once per layer (and by the diagonal of each activation’s derivatives); the singular values of these products determine whether the gradient vanishes or explodes (vanishing gradients).
  4. The backward pass costs twice as much. The forward pass performs one product costing 2Bdindout2Bd_{\text{in}}d_{\text{out}} operations; the backward pass performs two of the same size, X⊤G\mat{X}\T\mat{G} and GW⊤\mat{G}\mat{W}\T. It needs W\mat{W} for the second and X\mat{X} for the first: each layer’s input is what must be stored.

Structured Jacobians

The linear layer has a giant but highly structured Jacobian (I⊗X\mat{I}\otimes\mat{X}). So do the other pieces of a network: their Jacobians are diagonal, or diagonal plus a rank-one matrix. These are structured Jacobians, and their structure makes the VJP cost the same as the forward pass, O(taman˜o)\bigO(\text{tamaño}) instead of O(taman˜o2)\bigO(\text{tamaño}^2).

Elementwise nonlinearities

If A=σ(Z)\mat{A} = \sigma(\mat{Z}) is applied elementwise, dA=σ′(Z)⊙dZd\mat{A} = \sigma'(\mat{Z})\odot d\mat{Z}. The Jacobian is the diagonal matrix diag⁡(vec⁡σ′(Z))\diag(\operatorname{vec}\sigma'(\mat{Z})), with side length equal to the number of entries, and the VJP is

∇ZL=σ′(Z)⊙∇AL,\grad_{\mat{Z}} L = \sigma'(\mat{Z})\odot\grad_{\mat{A}} L,

because elementwise multiplication by a fixed matrix is self-adjoint: ⟨G,D⊙H⟩F=∑ijGijDijHij=⟨D⊙G,H⟩F\inner{\mat{G}}{\mat{D}\odot\mat{H}}_F = \sum_{ij}G_{ij}D_{ij}H_{ij} = \inner{\mat{D}\odot\mat{G}}{\mat{H}}_F. What matters is what must be saved in the forward pass:

  • ReLU: ReLU⁡′(z)=1[z>0]\relu'(z) = \ind[z > 0] (at z=0z = 0 PyTorch takes 00). It suffices to save the mask, one bit per entry. A neuron whose mask is always zero never receives a gradient: it is a dead ReLU.
  • Sigmoid and tanh: σ′=a(1−a)\sigmoid' = a(1 - a) and tanh⁡′=1−a2\tanh' = 1 - a^2 can be written using the output aa, so saving A\mat{A} is enough; the next layer already needed it anyway.
  • GELU: its derivative needs Z\mat{Z}. Each activation determines what gets saved, and that takes memory.

Softmax

Softmax does not act elementwise: each probability depends on all logits, pi=ezi/∑jezjp_i = e^{z_i}/\sum_j e^{z_j}. Its Jacobian is dense but highly structured. Differentiate by taking logarithms, turning the quotient into a subtraction:

log⁡pi=zi−log⁡∑jezj\log p_i = z_i - \log\textstyle\sum_j e^{z_j}
The logarithm of a quotient is the difference of logarithms.
1/4
Proof

You prove point 1 in the exercise below. For 2, D1/2ID1/2=D\mat{D}^{1/2}\mat{I}\mat{D}^{1/2} = \mat{D} and D1/2q=p\mat{D}^{1/2}\vb{q} = \vb{p}, so D1/2qq⊤D1/2=pp⊤\mat{D}^{1/2}\vb{q}\vb{q}\T\mat{D}^{1/2} = \vb{p}\vb{p}\T; moreover ∥q∥2=∑ipi=1\norm{\vb{q}}^2 = \sum_i p_i = 1. Thus P=I−qq⊤\mat{P} = \mat{I} - \vb{q}\vb{q}\T is the orthogonal projection onto q⊥\vb{q}^\perp, symmetric and idempotent.

For 3, v⊤Jv=v⊤D1/2P⊤PD1/2v=∥PD1/2v∥2\vb{v}\T\mat{J}\vb{v} = \vb{v}\T\mat{D}^{1/2}\mat{P}\T\mat{P}\mat{D}^{1/2}\vb{v} = \norm{\mat{P}\mat{D}^{1/2}\vb{v}}^2. Since J\mat{J} is positive semidefinite, Jv=0\mat{J}\vb{v} = \vb{0} if and only if v⊤Jv=0\vb{v}\T\mat{J}\vb{v} = 0, that is, if D1/2v\mat{D}^{1/2}\vb{v} is a multiple of q=D1/21\vb{q} = \mat{D}^{1/2}\vb{1}. All pip_i are positive, so D1/2\mat{D}^{1/2} is invertible and that is equivalent to v∈span⁡{1}\vb{v} \in \spn\{\vb{1}\}. The rank follows from the rank theorem.

For 4, v⊤Jv=∑ipivi2−(∑ipivi)2\vb{v}\T\mat{J}\vb{v} = \sum_i p_iv_i^2 - \big(\sum_i p_iv_i\big)^2 is the variance of vIv_I when index II is chosen with probabilities p\vb{p}. For any constant cc, the variance is at most ∑ipi(vi−c)2\sum_i p_i(v_i - c)^2. Take ∥v∥=1\norm{\vb{v}} = 1, so (vi−vj)2≤2(vi2+vj2)≤2(v_i - v_j)^2 \le 2(v_i^2 + v_j^2) \le 2 for every i,ji, j. With cc the midpoint between the largest and smallest viv_i, each (vi−c)2≤14⋅2=12(v_i - c)^2 \le \tfrac14\cdot 2 = \tfrac12. With c=vkc = v_k, where pk=pmax⁡p_k = p_{\max}, the term i=ki = k vanishes and ∑i≠kpi(vi−vk)2≤2(1−pmax⁡)\sum_{i\ne k}p_i(v_i - v_k)^2 \le 2(1 - p_{\max}) remains. The Rayleigh quotient of J\mat{J} is bounded by both quantities.

∎
ProofThe softmax Jacobian is positive semidefinite
Prove: For p=softmax⁡(z)\vb{p} = \softmax(\vb{z}), the Jacobian J=diag⁡(p)−pp⊤\mat{J} = \diag(\vb{p}) - \vb{p}\vb{p}\T is symmetric, positive semidefinite and satisfies J1=0\mat{J}\vb{1} = \vb{0}.
0
The pip_i are positive and sum to 11.

Step 1 of 4. Where does symmetry come from?

Before looking at the consequences, experiment with it.

InteractiveThe softmax Jacobian
J=1τ(diag⁡(p)−pp⊤)\mat{J} = \tfrac{1}{\tau}\big(\diag(\vb{p}) - \vb{p}\vb{p}\T\big)
z₁p₁z₂p₂z₃p₃0.214−0.175−0.039−0.1750.189−0.014−0.039−0.0140.053Σ row0.0000.0000.000
  • column kk: ∂p/∂zk\partial\vb{p}/\partial z_k (×2.5)
  • path as τ\tau varies
Each arrow is the velocity of p\vb{p} as a logit rises, and all three sum to 0\vb{0}. Dashed arrows are clipped to fit.
Logits
1.50
0.50
−1.00
Temperature and examples
1.00
p\vb{p}(0.690, 0.254, 0.057)
Eigenvalues of J\mat{J}0.000, 0.079, 0.378
Bound min⁡(12, 2(1−pmax⁡))/τ\min(\tfrac12,\, 2(1 - p_{\max}))/\tau0.500
∥J∥F\norm{\mat{J}}_F0.386
Rows sum to zero: J1=0\mat{J}\vb{1} = \vb{0}. Raising every logit together does not change p\vb{p}.
Three logits, or drag p\vb{p} directly over the simplex. The arrows are the columns of the Jacobian: the velocity at which p\vb{p} moves when each logit increases; since J1=0\mat{J}\vb{1} = \vb{0}, they sum to zero. On the right, J\mat{J} as a heat map (red positive, blue negative) with row sums. Move p\vb{p} near a vertex: everything fades, quantified by the bound 2(1−pmax⁡)2(1 - p_{\max}) on the largest eigenvalue. Lower temperature and p\vb{p} follows the dashed curve toward the winning vertex. Press ‘Add 1 to all’ and check that p\vb{p} does not move.

What you should have seen:

  • One eigenvalue is always 00, with eigenvector 1\vb{1}: logits are defined only up to an additive constant. The other two are positive while no pip_i is zero.
  • With two tied classes and the third negligible, the largest eigenvalue approaches 12\tfrac12, the universal bound. This is maximum sensitivity: a change in the difference between the two tied logits moves the probabilities substantially.
  • When one logit dominates, the entire Jacobian fades, with λmax⁡≤2(1−pmax⁡)\lambda_{\max} \le 2(1 - p_{\max}). This is saturation: the gradient reaching p\vb{p} barely passes to the logits. In transformer attention this occurs when a row of the attention matrix concentrates on one position, and is why dot products are divided by dk\sqrt{d_k}, as you will see in attention backpropagation.
  • Temperature scales the Jacobian by 1/τ1/\tau, because softmax⁡(z/τ)\softmax(\vb{z}/\tau) has Jacobian 1τ(diag⁡p−pp⊤)\tfrac1\tau(\diag\vb{p} - \vb{p}\vb{p}\T) with respect to z\vb{z}. As τ\tau falls that factor grows, but saturation wins: if the difference between the two largest logits is Δ\Delta, 1−pmax⁡1 - p_{\max} decays like e−Δ/τe^{-\Delta/\tau}, much faster than 1/τ1/\tau grows.

The softmax VJP does not need the Jacobian. If g=∇pL\vb{g} = \grad_{\vb{p}} L,

∇zL=Jg=p⊙g−p (p⊤g)=p⊙(g−(p⊤g) 1),\grad_{\vb{z}} L = \mat{J}\vb{g} = \vb{p}\odot\vb{g} - \vb{p}\,(\vb{p}\T\vb{g}) = \vb{p}\odot\big(\vb{g} - (\vb{p}\T\vb{g})\,\vb{1}\big),

which costs O(K)\bigO(K): center g\vb{g} with the mean weighted by p\vb{p}, then multiply by p\vb{p}. Forming J\mat{J} would cost K2K^2, and with the GPT-2 vocabulary, K=50257K = 50257, that is about 2.5⋅1092.5\cdot 10^9 numbers, 10 GB in float32, per token. Batched, with one row per example, ∇ZL=P⊙(G−s1⊤)\grad_{\mat{Z}} L = \mat{P}\odot(\mat{G} - \vb{s}\vb{1}\T) with si=∑kPikGiks_i = \sum_k P_{ik}G_{ik}: the rowwise softmax VJP rule used by attention’s backward pass.

Softmax with cross-entropy

In the last layer, softmax is rarely alone: it is followed by cross-entropy with a target distribution y\vb{y} (one-hot or smoothed, with ∑kyk=1\sum_k y_k = 1). The composition simplifies spectacularly:

ℓ(z)=−∑kyklog⁡pk=−∑kyk(zk−log⁡∑jezj)=−y⊤z+log⁡∑jezj,\ell(\vb{z}) = -\sum_k y_k\log p_k = -\sum_k y_k\Big(z_k - \log\sum_j e^{z_j}\Big) = -\vb{y}\T\vb{z} + \log\sum_j e^{z_j},

using ∑kyk=1\sum_k y_k = 1. The gradient of the first term is −y-\vb{y} and that of log-sum-exp is p\vb{p}:

∇z ℓ=p−y.\grad_{\vb{z}}\,\ell = \vb{p} - \vb{y}.

This is the gradient of softmax cross-entropy: prediction minus target. It also follows by chaining VJPs: the gradient of −∑kyklog⁡pk-\sum_k y_k\log p_k with respect to p\vb{p} is −y/p-\vb{y}/\vb{p} (elementwise), and the softmax VJP turns it into p⊙(−y/p+(p⊤(y/p))1)=−y+p∑kyk=p−y\vb{p}\odot\big(-\vb{y}/\vb{p} + (\vb{p}\T(\vb{y}/\vb{p}))\vb{1}\big) = -\vb{y} + \vb{p}\sum_k y_k = \vb{p} - \vb{y}. The two routes agree exactly, but not in floating point: the second divides by p\vb{p}, and if a probability rounds to zero the quotient becomes infinity and the product NaN. The first divides by nothing and its entries lie in [−1,1][-1, 1]. That is why libraries fuse the operations (F.cross_entropy takes logits, not probabilities) and compute log-sum-exp by subtracting the maximum, using the log-sum-exp trick. With the mean loss of a batch of BB examples, the gradient with respect to the logits matrix is 1B(P−Y)\tfrac1B(\mat{P} - \mat{Y}).

Contractions and broadcasting

Every multilinear tensor operation can be written in einsum notation: matrix multiplication, batched products, attention dot products and multi-head projections. Its backward pass has a rule that fits in one sentence.

Proof

By definition, C[σC]=∑∏jAj[σj]C[\sigma_C] = \sum \prod_j A_j[\sigma_j], where the sum runs over indices not in σC\sigma_C. C\mat{C} is linear in Ak\mat{A}_k, so dCd\mat{C} is the same expression with dAkd\mat{A}_k in place of Ak\mat{A}_k, and

dL=∑σCG[σC] dC[σC]=∑todos los ıˊndicesG[σC]  dAk[σk]∏j≠kAj[σj],dL = \sum_{\sigma_C} G[\sigma_C]\,dC[\sigma_C] = \sum_{\text{todos los índices}} G[\sigma_C]\;dA_k[\sigma_k]\prod_{j\ne k}A_j[\sigma_j],

where each letter is summed only once over its range. Group terms by the values of the indices of σk\sigma_k:

dL=∑σkdAk[σk] (∑resto de ıˊndicesG[σC]∏j≠kAj[σj]).dL = \sum_{\sigma_k} dA_k[\sigma_k]\,\Big(\sum_{\text{resto de índices}} G[\sigma_C]\prod_{j\ne k}A_j[\sigma_j]\Big).

The expression in parentheses is a function of the indices of σk\sigma_k, and is exactly the stated einsum. If a letter of σk\sigma_k does not appear in the parentheses, the expression does not depend on it: the gradient is constant along that axis. Since dL=⟨pareˊntesis,dAk⟩dL = \inner{\text{paréntesis}}{d\mat{A}_k}, the expression in parentheses is the gradient.

∎

Remember this VJP of a contraction as follows: for the gradient of an operand, exchange its role with the output’s. Indices contracted by the forward pass become free, and the other operand’s free indices become contracted; indices everywhere (batch, heads) remain everywhere because each batch element is independent.

ForwardGradient of firstGradient of second
ik,kj->ij (AB\mat{A}\mat{B})ij,kj->ik (GB⊤\mat{G}\mat{B}\T)ik,ij->kj (A⊤G\mat{A}\T\mat{G})
bik,bkj->bij (batched)bij,bkj->bikbik,bij->bkj
bhqd,bhkd->bhqk (scores QK⊤\mat{Q}\mat{K}\T)bhqk,bhkd->bhqd (GK\mat{G}\mat{K})bhqk,bhqd->bhkd (G⊤Q\mat{G}\T\mat{Q})
i,j->ij (ab⊤\vb{a}\vb{b}\T)ij,j->i (Gb\mat{G}\vb{b})ij,i->j (G⊤a\mat{G}\T\vb{a})
ij->i (sum rows)G\mat{G} extended along j

The first row is the linear layer again, now without thinking. The last shows the solitary-index case: forward sums over j, and backward copies the gradient along j. The assumption that indices do not repeat within an operand matters: trace ii-> has gradient I⋅G\mat{I}\cdot G, with GG only on the diagonal, and that is not an einsum of the theorem’s form.

Forward broadcasting becomes a backward sum

The opposite of copying is summing, and this duality explains the bias gradient. Adding bias b∈RD\vb{b} \in \R^D to a tensor of shape (B,T,D)(B, T, D) first applies the copy E:RD→RB×T×DE: \R^D \to \R^{B\times T\times D}, E(b)[β,t,d]=bdE(\vb{b})[\beta, t, d] = b_d, which is linear.

Proof

⟨G,E(b)⟩=∑β,t,dGβtd bd=∑dbd∑β,tGβtd=⟨E∗(G),b⟩\inner{\mat{G}}{E(\vb{b})} = \sum_{\beta, t, d} G_{\beta t d}\,b_d = \sum_d b_d\sum_{\beta, t}G_{\beta t d} = \inner{E^{*}(\mat{G})}{\vb{b}}. The general case is identical: each entry of the smaller tensor appears in the inner product multiplied by every entry of G\mat{G} to which it was copied. This is also a case of the previous theorem in a broad sense: the copy is d->btd, with indices only in the output (NumPy does not permit that einsum, but the proof’s formula still holds), and its VJP is btd->d.

∎
InteractiveBroadcasting becomes summation
Backward complete. Each bias entry received the sum of 6 gradients from same-colored cells. Press play to see each copy.
∇YL\grad_{\mat{Y}} L: color identifies each gradient’s bias entry
example 1−3−3−12−3−233322−3example 23−23−3−3−233−12−13
b\vb{b}, shape (4,)
b1b_{1}
b2b_{2}
b3b_{3}
b4b_{4}
∇bL\grad_{\vb{b}} L accumulated
−4
−5
9
5
(∇bL)d=∑β,tGβtd(\grad_{\vb{b}} L)_d = \textstyle\sum_{\beta,t} G_{\beta td}
copy 6/6
Bias shape
Shape of X\mat{X}: (B,T,D)(B, T, D)
2
3
4
Copies of each bias entry6
Shape of b\vb{b} and ∇bL\grad_{\vb{b}} L(4,)
In NumPygrad_b = G.sum(axis=(0, 1))
Done: summed over axes BB and TT, added by broadcasting. Without that sum, the “gradient” would have the shape (2,3,4)(2, 3, 4) of X\mat{X}.
A bias is broadcast and added to a tensor (B,T,D)(B, T, D). In the forward pass, each cell receives the bias entry of its color. Press play and the backward pass traverses the copies: each returns its part of ∇YL\grad_{\mat{Y}} L, accumulated in the same-colored bias entry. Change bias shape: with (T,1)(T, 1), sum over BB, the added axis which disappears, and over DD, stretched from 1 and retained with keepdims; with (B,1,1)(B, 1, 1), sum over TT and DD. The number of copies is the number of terms in each gradient.

This appears everywhere in a network. A linear layer’s bias is copied into the BB batch rows, and its gradient is G⊤1\mat{G}\T\vb{1}, the sum over the batch. Positional embeddings, of shape (T,D)(T, D), are added to each sequence in a batch (B,T,D)(B, T, D), and their gradient sums over BB. Normalization scale parameters of shape (D,)(D,) sum over batch and positions. Libraries do this automatically (in PyTorch, with sum_to_size), but it is the most common mistake in a hand-written backward pass: if you forget the sum, the bias “gradient” has the shape of the output.

Complete example: a two-layer MLP by hand

You now have the three rules: linear layer, elementwise nonlinearity and softmax with cross-entropy. A classification MLP with one hidden layer, for a batch X∈RB×D\mat{X} \in \R^{B\times D} with one-hot labels Y∈RB×K\mat{Y} \in \R^{B\times K}, computes

Z1=XW1+1b1⊤,A1=ReLU⁡(Z1),Z2=A1W2+1b2⊤,L=−1B∑i,kYiklog⁡softmax⁡(Z2)ik,\mat{Z}_1 = \mat{X}\mat{W}_1 + \vb{1}\vb{b}_1\T,\quad \mat{A}_1 = \relu(\mat{Z}_1),\quad \mat{Z}_2 = \mat{A}_1\mat{W}_2 + \vb{1}\vb{b}_2\T,\quad L = -\frac1B\sum_{i,k}Y_{ik}\log\softmax(\mat{Z}_2)_{ik},

with W1∈RD×H\mat{W}_1 \in \R^{D\times H} and W2∈RH×K\mat{W}_2 \in \R^{H\times K}. Backward applies the VJPs in reverse order, with P=softmax⁡(Z2)\mat{P} = \softmax(\mat{Z}_2) rowwise:

∇Z2L=1B(P−Y),∇W2L=A1⊤∇Z2L,∇b2L=(∇Z2L)⊤1,∇A1L=∇Z2L  W2⊤,∇Z1L=∇A1L⊙1[Z1>0],∇W1L=X⊤∇Z1L,∇b1L=(∇Z1L)⊤1.\begin{aligned} \grad_{\mat{Z}_2} L &= \tfrac1B(\mat{P} - \mat{Y}), \\ \grad_{\mat{W}_2} L &= \mat{A}_1\T\grad_{\mat{Z}_2} L, \qquad \grad_{\vb{b}_2} L = (\grad_{\mat{Z}_2} L)\T\vb{1}, \\ \grad_{\mat{A}_1} L &= \grad_{\mat{Z}_2} L\;\mat{W}_2\T, \\ \grad_{\mat{Z}_1} L &= \grad_{\mat{A}_1} L\odot\ind[\mat{Z}_1 > 0], \\ \grad_{\mat{W}_1} L &= \mat{X}\T\grad_{\mat{Z}_1} L, \qquad \grad_{\vb{b}_1} L = (\grad_{\mat{Z}_1} L)\T\vb{1}. \end{aligned}

Six lines, each a local rule knowing nothing about the rest of the network. That modularity makes automatic differentiation possible: each operation records in the forward pass what its VJP will need, and the backward pass traverses the graph in reverse applying them. That is backpropagation, and nothing more is needed.

InteractiveShapes flowing backward
parameters
forward ↓
backward ↑
X\mat{X}
32×64
W1\mat{W}_1
64×128
b1\vb{b}_1
128
∇W1L\grad_{\mat{W}_1} L
64×128
∇b1L\grad_{\vb{b}_1} L
128
⋅ W1+b1\cdot\,\mat{W}_1 + \vb{b}_1
Z1\mat{Z}_1
32×128
∇Z1L\grad_{\mat{Z}_1} L
32×128
save the mask
ReLU⁡\relu
A1\mat{A}_1
32×128
∇A1L\grad_{\mat{A}_1} L
32×128
W2\mat{W}_2
128×10
b2\vb{b}_2
10
∇W2L\grad_{\mat{W}_2} L
128×10
∇b2L\grad_{\vb{b}_2} L
10
⋅ W2+b2\cdot\,\mat{W}_2 + \vb{b}_2
Z2\mat{Z}_2
32×10
∇Z2L\grad_{\mat{Z}_2} L
32×10
Y\mat{Y}
32×10
softmax + cross-entropy
LL
scalar
11
∂L/∂L
backwardAnother sum over the batch.
∇b1L=(∇Z1L)⊤1\grad_{\vb{b}_1} L = (\grad_{\mat{Z}_1} L)\T\vb{1}
128 = shape of b1\vb{b}_1 ✓
backward 7/7
Every gradient has its variable’s shape. Backward matrix products cost 1.14 times forward.
Dimensions
32
64
128
10
Options
Parameters9 610
Saved for backward: X\mat{X}, mask, A1\mat{A}_1, P\mat{P}10.6 mil values
Product FLOPs, forward606 mil
Product FLOPs, backward688 mil (1.14 ×)
The MLP graph with each node's shape: middle column for forward, right for gradients, left for parameters and their gradients. Press play: four forward steps and seven backward steps, each with its rule, numerical shapes and, for matrix products, a scale diagram with the contracted dimension in yellow. Change BB, DD, HH and KK at any time: each gradient has the shape of its variable. Readouts count what must be saved for backward and the operations in each direction.

Two calculations the interactive performs live deserve a look:

  • Cost. Forward products total 2B(DH+HK)2B(DH + HK) operations. Backward computes A1⊤∇Z2\mat{A}_1\T\grad_{\mat{Z}_2} and ∇Z2W2⊤\grad_{\mat{Z}_2}\mat{W}_2\T (each the size of A1W2\mat{A}_1\mat{W}_2) and X⊤∇Z1\mat{X}\T\grad_{\mat{Z}_1}: 2B(DH+2HK)2B(DH + 2HK) in total, somewhat less than twice as much because the first layer does not need ∇XL\grad_{\mat{X}} L. An intermediate layer in a deep network does need it, and the count is exactly twice as much. This is why a training step costs roughly three forward passes.
  • Memory. Backward needs X\mat{X} (for ∇W1\grad_{\mat{W}_1}), the mask of Z1\mat{Z}_1, A1\mat{A}_1 (for ∇W2\grad_{\mat{W}_2}) and P\mat{P}: about B(D+2H+K)B(D + 2H + K) numbers, proportional to batch size. With a many-layer transformer and long sequences, this activation memory easily exceeds weight memory; checkpointing and kernels such as FlashAttention that recompute instead of storing target it.

Implementation from scratch

First, just once, form the full Jacobian of a tiny layer to see that Kronecker theory is literal and the VJP agrees. In NumPy, the column-major flattening used in the text is reshape(-1, order="F").

[ ]A layer's Jacobian, formed onceBrowser
import numpy as np

rng = np.random.default_rng(0)
n, d, p = 4, 3, 2
X = rng.standard_normal((n, d))
W = rng.standard_normal((d, p))
G = rng.standard_normal((n, p))            # gradiente que llega a Y
V = rng.standard_normal((d, p))            # una dirección para el JVP
vec = lambda M: M.reshape(-1, order="F")   # vec por columnas, como en el texto

J_W = np.kron(np.eye(p), X)                # ∂vec(Y)/∂vec(W) = I ⊗ X
J_X = np.kron(W.T, np.eye(n))              # ∂vec(Y)/∂vec(X) = Wᵀ ⊗ I
print("forma de J_W:", J_W.shape, "  no nulos:", np.count_nonzero(J_W), "de", J_W.size)
print("JVP:  J_W vec(V)  = vec(X V)   ", np.allclose(J_W @ vec(V), vec(X @ V)))
print("VJP:  J_Wᵀ vec(G) = vec(Xᵀ G)  ", np.allclose(J_W.T @ vec(G), vec(X.T @ G)))
print("VJP:  J_Xᵀ vec(G) = vec(G Wᵀ)  ", np.allclose(J_X.T @ vec(G), vec(G @ W.T)))

Now the MLP pieces. Each is a pair of functions: forward returns the output and a cache of what the VJP will need; the VJP receives the cache and output gradient and returns input gradients. To check a VJP without writing the full loss, use a trick: if L=⟨C,f(X)⟩FL = \inner{\mat{C}}{f(\mat{X})}_F with random C\mat{C}, then ∇YL=C\grad_{\mat{Y}} L = \mat{C}, so the VJP with C\mat{C} must match the gradient of that LL, compared with a centered difference in random directions in float64 (the previous lesson’s gradient checking).

[ ]Each piece with its VJPBrowser
def linear_fwd(X, W, b):
    return X @ W + b, (X, W)

def linear_vjp(cache, G):
    X, W = cache
    return G @ W.T, X.T @ G, G.sum(axis=0)              # ∇X, ∇W, ∇b

def relu_fwd(Z):
    mask = Z > 0
    return Z * mask, mask                                # solo se guarda la máscara

def relu_vjp(mask, G):
    return G * mask

def softmax_ce_fwd(Z, y):
    """Entropía cruzada media con etiquetas enteras y, vía log-sum-exp estable."""
    Zs = Z - Z.max(axis=1, keepdims=True)
    logP = Zs - np.log(np.exp(Zs).sum(axis=1, keepdims=True))
    B = Z.shape[0]
    return -logP[np.arange(B), y].mean(), (np.exp(logP), y)

def softmax_ce_vjp(cache):
    P, y = cache
    B = P.shape[0]
    G = P.copy()
    G[np.arange(B), y] -= 1.0                            # P − Y sin formar Y
    return G / B

def dir_check(f, x, grad, h=1e-6, n_dirs=4, seed=1):
    """Peor error relativo entre <grad, V> y la diferencia centrada de f en direcciones aleatorias V."""
    r = np.random.default_rng(seed)
    worst = 0.0
    for _ in range(n_dirs):
        V = r.standard_normal(np.shape(x))
        fd = (f(x + h * V) - f(x - h * V)) / (2 * h)
        an = np.sum(grad * V)
        worst = max(worst, abs(fd - an) / max(1e-15, abs(fd) + abs(an)))
    return worst

B, Din, Dout = 8, 5, 4
X = rng.standard_normal((B, Din)); W = rng.standard_normal((Din, Dout)); b = rng.standard_normal(Dout)
C = rng.standard_normal((B, Dout))                       # L = <C, salida>, así que ∇_salida L = C
gX, gW, gb = linear_vjp((X, W), C)
print("lineal ∇X ", f"{dir_check(lambda X_: np.sum(C * linear_fwd(X_, W, b)[0]), X, gX):.1e}")
print("lineal ∇W ", f"{dir_check(lambda W_: np.sum(C * linear_fwd(X, W_, b)[0]), W, gW):.1e}")
print("lineal ∇b ", f"{dir_check(lambda b_: np.sum(C * linear_fwd(X, W, b_)[0]), b, gb):.1e}")
Z = rng.standard_normal((B, Dout))
_, mask = relu_fwd(Z)
print("relu      ", f"{dir_check(lambda Z_: np.sum(C * relu_fwd(Z_)[0]), Z, relu_vjp(mask, C)):.1e}")
y = rng.integers(0, Dout, B)
_, cache = softmax_ce_fwd(Z, y)
print("softmax-CE", f"{dir_check(lambda Z_: softmax_ce_fwd(Z_, y)[0], Z, softmax_ce_vjp(cache)):.1e}")

All relative errors are of order 10−910^{-9} or smaller: finite-difference rounding, not a bug. With the pieces verified, the MLP chains them in the order of the six equations.

[ ]The full batch-vectorized MLPBrowser
def mlp_loss_grads(params, X, y):
    W1, b1, W2, b2 = params
    Z1, c1 = linear_fwd(X, W1, b1)
    A1, m1 = relu_fwd(Z1)
    Z2, c2 = linear_fwd(A1, W2, b2)
    L, c3 = softmax_ce_fwd(Z2, y)
    G2 = softmax_ce_vjp(c3)                  # (P − Y) / B
    GA1, gW2, gb2 = linear_vjp(c2, G2)
    GZ1 = relu_vjp(m1, GA1)
    _, gW1, gb1 = linear_vjp(c1, GZ1)        # ∇X no hace falta en la primera capa
    return L, [gW1, gb1, gW2, gb2]

def init(D, H, K, seed=0):
    r = np.random.default_rng(seed)
    return [r.standard_normal((D, H)) * np.sqrt(2 / D), np.zeros(H),
            r.standard_normal((H, K)) * np.sqrt(1 / H), np.zeros(K)]

Xs = rng.standard_normal((16, 6)); ys = rng.integers(0, 3, 16)
params = init(6, 7, 3, seed=1)
L, grads = mlp_loss_grads(params, Xs, ys)
for i, name in enumerate(["W1", "b1", "W2", "b2"]):
    def f(P_, i=i):
        ps = list(params); ps[i] = P_
        return mlp_loss_grads(ps, Xs, ys)[0]
    print(f"{name}: forma {grads[i].shape} = {params[i].shape}   error relativo {dir_check(f, params[i], grads[i]):.1e}")

Now what really matters: training with your own backward pass. Scikit-learn’s handwritten digits are 1797 images of 8×88\times 8; with 64 hidden neurons and stochastic gradient descent with momentum, a few passes suffice.

[ ]Scikit-learn digitsBrowser
from sklearn.datasets import load_digits

dig = load_digits()
Xd, yd = dig.data / 16.0, dig.target
perm = np.random.default_rng(0).permutation(len(yd))
tr, te = perm[:1347], perm[1347:]
mu, sd = Xd[tr].mean(axis=0), Xd[tr].std(axis=0) + 1e-6
Xtr, Xte = (Xd[tr] - mu) / sd, (Xd[te] - mu) / sd
ytr, yte = yd[tr], yd[te]
print("entrenamiento:", Xtr.shape, "  test:", Xte.shape)
[ ]Train an MLP with your backward passBrowser
params = init(64, 64, 10, seed=0)
vel = [np.zeros_like(p) for p in params]
lr, mom, bs = 0.05, 0.9, 32
for epoch in range(6):
    order = np.random.default_rng(epoch).permutation(len(ytr))
    for s in range(0, len(ytr), bs):
        idx = order[s:s + bs]
        L, g = mlp_loss_grads(params, Xtr[idx], ytr[idx])
        for p, v, gp in zip(params, vel, g):
            v *= mom
            v -= lr * gp
            p += v                                      # actualización en el sitio
    W1, b1, W2, b2 = params
    acc = np.mean((np.maximum(Xte @ W1 + b1, 0) @ W2 + b2).argmax(axis=1) == yte)
    if epoch % 2 == 0 or epoch == 5:
        print(f"época {epoch:2d}   acierto en test {acc:.3f}")
assert acc > 0.95

Accuracy on the 450 test images exceeds 95% in the first epochs and ends above 97%. No line in that loop knows what a Jacobian is.

The second lab turns the contraction theorem into code. einsum_vjp receives the specification, operands and output gradient, then builds the einsum with exchanged roles for each operand; indices present only in that operand are recovered by broadcasting.

[ ]The generic einsum VJPBrowser
def einsum_vjp(spec, operands, grad_out):
    """Gradientes de L respecto a cada operando de C = einsum(spec, *operands), dado grad_out = ∇_C L."""
    ins, out = spec.replace(" ", "").split("->")
    terms = ins.split(",")
    grads = []
    for k, term in enumerate(terms):
        assert len(set(term)) == len(term), "índices repetidos dentro de un operando: fuera del teorema"
        others = [t for j, t in enumerate(terms) if j != k]
        rest = [op for j, op in enumerate(operands) if j != k]
        visible = set(out).union(*others)
        kept = "".join(c for c in term if c in visible)      # índices que el einsum puede producir
        g = np.einsum(",".join([out] + others) + "->" + kept, grad_out, *rest)
        # índices solo de este operando: el forward los sumaba; el gradiente es constante a lo largo de ellos
        g = g.reshape([g.shape[kept.index(c)] if c in visible else 1 for c in term])
        grads.append(np.broadcast_to(g, operands[k].shape).copy())
    return grads

casos = {
    "bij,bjk->bik":    [(3, 4, 5), (3, 5, 2)],           # producto por lotes
    "bhqd,bhkd->bhqk": [(2, 3, 4, 5), (2, 3, 6, 5)],     # puntuaciones de atención Q Kᵀ
    "bhqk,bhkd->bhqd": [(2, 3, 4, 6), (2, 3, 6, 5)],     # pesos de atención por valores
    "bthd,hde->bte":   [(2, 4, 3, 5), (3, 5, 7)],        # proyección de salida que suma las cabezas
    "i,j->ij":         [(3,), (4,)],                     # producto exterior
    "ijk,k->j":        [(2, 3, 4), (4,)],                # i solo en el primer operando
}
for spec, shapes in casos.items():
    ops = [rng.standard_normal(s) for s in shapes]
    C = rng.standard_normal(np.einsum(spec, *ops).shape)
    gs = einsum_vjp(spec, ops, C)
    errs = []
    for k in range(len(ops)):
        def f(x, k=k):
            o = list(ops); o[k] = x
            return np.sum(C * np.einsum(spec, *o))
        errs.append(dir_check(f, ops[k], gs[k]))
    print(f"{spec:17s}", "  ".join(f"{e:.1e}" for e in errs))

And the adjoint of broadcasting, the piece libraries use internally to return a gradient of the right shape to each tensor:

[ ]The adjoint of broadcastingBrowser
def sum_to_shape(G, shape):
    """VJP del broadcasting de un tensor de forma `shape` a la forma de G."""
    G = G.sum(axis=tuple(range(G.ndim - len(shape))))     # ejes añadidos por la izquierda
    stretched = tuple(i for i, s in enumerate(shape) if s == 1 and G.shape[i] != 1)
    return G.sum(axis=stretched, keepdims=True)           # ejes estirados desde 1

for xs, bs in [((2, 3, 4), (4,)), ((2, 3, 4), (3, 1)), ((2, 3, 4), (2, 1, 1)), ((5, 4), (1, 4))]:
    x, bias = rng.standard_normal(xs), rng.standard_normal(bs)
    C = rng.standard_normal(np.broadcast_shapes(xs, bs))
    g = sum_to_shape(C, bs)
    err = dir_check(lambda b_: np.sum(C * (x + b_)), bias, g)
    print(f"x {str(xs):10s} + b {str(bs):10s} -> ∇b de forma {str(g.shape):10s} error {err:.1e}")

The professional version: PyTorch

PyTorch exposes the lesson’s two operations as functions: torch.autograd.functional.jvp and vjp, plus jacobian, which forms the full Jacobian (one VJP per output or one JVP per input, depending on mode). First verify the theory. PyTorch flattens by rows, not columns, and with that ordering the identity changes sides: vec⁡filas(AXB)=(A⊗B⊤)vec⁡filasX\operatorname{vec}_{\text{filas}}(\mat{A}\mat{X}\mat{B}) = (\mat{A}\otimes\mat{B}\T)\operatorname{vec}_{\text{filas}}\mat{X}, so the Jacobian of XW\mat{X}\mat{W} with respect to W\mat{W} is X⊗I\mat{X}\otimes\mat{I}. The cell requires PyTorch and runs in the local lab.

[ ]JVP, VJP and the Jacobian in PyTorchLocal GPU
import time
import torch
from torch.autograd.functional import jacobian, vjp, jvp

torch.manual_seed(0)
dev = "cuda" if torch.cuda.is_available() else "cpu"
n, d, p = 4, 3, 2
X = torch.randn(n, d, dtype=torch.float64, device=dev)
W = torch.randn(d, p, dtype=torch.float64, device=dev)
f = lambda W_: X @ W_

J = jacobian(f, W)                                   # forma (n, p, d, p): ∂Y[i, j] / ∂W[k, l]
print("forma del jacobiano:", tuple(J.shape))
I = torch.eye(p, dtype=X.dtype, device=dev)
print("por filas:    J = X ⊗ I ", torch.allclose(J.reshape(n * p, d * p), torch.kron(X, I)))
Jc = J.permute(1, 0, 3, 2).reshape(n * p, d * p)     # aplanado por columnas, el vec del texto
print("por columnas: J = I ⊗ X ", torch.allclose(Jc, torch.kron(I, X)))

G = torch.randn(n, p, dtype=torch.float64, device=dev)
_, gW = vjp(f, W, G)
print("vjp = Xᵀ G             ", torch.allclose(gW, X.T @ G))
V = torch.randn(d, p, dtype=torch.float64, device=dev)
_, jv = jvp(f, W, V)
print("jvp = X V              ", torch.allclose(jv, X @ V))

# una capa todavía pequeña: jacobiano completo frente a un VJP
n, d, p = 64, 128, 128
X = torch.randn(n, d, device=dev); W = torch.randn(d, p, device=dev); G = torch.randn(n, p, device=dev)
f = lambda W_: X @ W_
for name, fn in [("jacobiano completo", lambda: jacobian(f, W, vectorize=True)), ("un VJP", lambda: vjp(f, W, G)[1])]:
    fn()                                             # calentamiento
    if dev == "cuda": torch.cuda.synchronize()
    t = time.perf_counter()
    out = fn()
    if dev == "cuda": torch.cuda.synchronize()
    print(f"{name:20s} {(time.perf_counter() - t) * 1e3:8.2f} ms   {out.numel() * out.element_size() / 1e6:8.2f} MB")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Even for a toy layer (64×12864\times 128 by 128×128128\times 128) the Jacobian occupies 537 MB in float32, versus 0.07 MB for the VJP, and takes several times longer (around ten times on a consumer GPU), although at this size VJP time is almost entirely fixed operation-launch overhead. With torch.func you get the same in functional style (vjp, jvp, jacrev, jacfwd): jacrev constructs the Jacobian with one VJP per output, and jacfwd with one JVP per input, the mode choice from the cost section.

Next write a layer with a custom backward pass. A torch.autograd.Function has two static methods: forward computes output and saves in ctx what backward needs, and backward receives G\mat{G} and returns one gradient per forward input (or None). We write the text’s linear layer and a low-rank layer Y=XUV⊤+1b⊤\mat{Y} = \mat{X}\mat{U}\mat{V}\T + \vb{1}\vb{b}\T, with U∈Rdin×r\mat{U} \in \R^{d_{\text{in}}\times r} and V∈Rdout×r\mat{V} \in \R^{d_{\text{out}}\times r}, the structure of LoRA. Its gradients follow from the trace trick: with T=XU\mat{T} = \mat{X}\mat{U}, ∇X=GVU⊤\grad_{\mat{X}} = \mat{G}\mat{V}\mat{U}\T, ∇U=X⊤GV\grad_{\mat{U}} = \mat{X}\T\mat{G}\mat{V} and ∇V=G⊤T\grad_{\mat{V}} = \mat{G}\T\mat{T}. The backward pass never forms UV⊤\mat{U}\mat{V}\T, which would be an din×doutd_{\text{in}}\times d_{\text{out}} matrix.

[ ]Layers with custom backward and GPU gradcheckLocal GPU
import warnings
import torch
from torch.autograd import gradcheck

warnings.filterwarnings("ignore", message=".*no current CUDA context.*")

class LinearFn(torch.autograd.Function):
    """Y = X W + b con W de forma (d_in, d_out), como en el texto."""
    @staticmethod
    def forward(ctx, X, W, b):
        ctx.save_for_backward(X, W)
        return X @ W + b

    @staticmethod
    def backward(ctx, G):
        X, W = ctx.saved_tensors
        gX = G @ W.T if ctx.needs_input_grad[0] else None
        gW = X.T @ G if ctx.needs_input_grad[1] else None
        gb = G.sum(dim=0) if ctx.needs_input_grad[2] else None
        return gX, gW, gb

class LowRankFn(torch.autograd.Function):
    """Y = X U Vᵀ + b sin formar nunca U Vᵀ: solo productos de rango r."""
    @staticmethod
    def forward(ctx, X, U, V, b):
        T = X @ U                                    # (B, r)
        ctx.save_for_backward(X, U, V, T)
        return T @ V.T + b

    @staticmethod
    def backward(ctx, G):
        X, U, V, T = ctx.saved_tensors
        GV = G @ V                                   # (B, r): se reutiliza dos veces
        gX = GV @ U.T if ctx.needs_input_grad[0] else None   # como nn.Linear, solo si hace falta
        return gX, X.T @ GV, G.T @ T, G.sum(dim=0)   # ∇X, ∇U, ∇V, ∇b

dev = "cuda"
torch.manual_seed(0)
kw = dict(dtype=torch.float64, device=dev, requires_grad=True)
X, W, b = torch.randn(6, 5, **kw), torch.randn(5, 4, **kw), torch.randn(4, **kw)
U, V = torch.randn(5, 2, **kw), torch.randn(4, 2, **kw)
print("gradcheck LinearFn  (float64, GPU):", gradcheck(LinearFn.apply, (X, W, b)))
print("gradcheck LowRankFn (float64, GPU):", gradcheck(LowRankFn.apply, (X, U, V, b)))

import time
def bench(make, steps=30):
    torch.cuda.synchronize(); torch.cuda.reset_peak_memory_stats()
    base = torch.cuda.memory_allocated()
    params, layer = make()
    Xb = torch.randn(4096, 4096, device=dev)
    for _ in range(3):
        layer(Xb).sum().backward()
    torch.cuda.synchronize(); t = time.perf_counter()
    for _ in range(steps):
        layer(Xb).sum().backward()
    torch.cuda.synchronize()
    ms = (time.perf_counter() - t) / steps * 1e3
    return ms, sum(p.numel() for p in params), (torch.cuda.max_memory_allocated() - base) / 1e6

def make_linear():
    lin = torch.nn.Linear(4096, 4096, device=dev)
    return list(lin.parameters()), lin

def make_lowrank(r=64):
    U = (torch.randn(4096, r, device=dev) / 64).requires_grad_()
    V = (torch.randn(4096, r, device=dev) / 8).requires_grad_()
    b = torch.zeros(4096, device=dev, requires_grad=True)
    return [U, V, b], lambda X_: LowRankFn.apply(X_, U, V, b)

for name, mk in [("nn.Linear 4096→4096", make_linear), ("LowRankFn, r = 64", make_lowrank)]:
    ms, n_par, peak = bench(mk)
    print(f"{name:22s} {ms:7.2f} ms por paso   {n_par / 1e6:6.2f} M parámetros   pico {peak:7.1f} MB")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

gradcheck compares your backward pass with elementwise finite differences and passes in float64. The speed comparison follows from operation counts: with din=dout=4096d_{\text{in}} = d_{\text{out}} = 4096 and r=64r = 64, the low-rank layer forward performs r(din+dout)/(dindout)=1/32r(d_{\text{in}} + d_{\text{out}})/(d_{\text{in}}d_{\text{out}}) = 1/32 of the dense layer’s operations and has 32 times fewer parameters (0.53 M versus 16.78 M). The full step, in which neither computes ∇X\grad_{\mat{X}} because the input does not request it (hence needs_input_grad), performs five skinny products versus two dense ones, 5r/(2din)≈1/265r/(2d_{\text{in}}) \approx 1/26 of the operations, and time per step falls by a similar ratio. Peak memory drops less, because it is dominated by 4096×40964096\times 4096 input and output, the same for both layers.

Common mistakes

Exercises

NumericHow much space does the Jacobian take?
For Y=XW\mat{Y} = \mat{X}\mat{W} with X\mat{X} of size 512×1024512\times 1024 and W\mat{W} of size 1024×40961024\times 4096 in float32 (4 bytes per number), how many terabytes (101210^{12} bytes) would the full Jacobian of Y\mat{Y} with respect to W\mat{W} occupy?
QuizThe gradient of a stretched tensor
In the forward pass, a tensor c\mat{c} of shape (1,D)(1, D) is added by broadcasting to a tensor of shape (B,D)(B, D), and the result receives gradient G\mat{G} of shape (B,D)(B, D). What must the backward pass do to obtain the gradient of c\mat{c}?
QuizWhich mode, how many passes?
A network has N=108N = 10^8 parameters and a scalar loss. Separately, a simulation g:R3→R1000g: \R^3 \to \R^{1000} returns a trajectory as a function of three parameters. How many passes (JVP or VJP) does each mode need for the loss gradient and the full Jacobian of gg?
QuizThe keys' gradient
In attention, the scores are S=einsum(bhqd,bhkd->bhqk)(Q,K)\mat{S} = \texttt{einsum}(\texttt{bhqd,bhkd->bhqk})(\mat{Q}, \mat{K}), and you receive G=∇SL\mat{G} = \grad_{\mat{S}} L of shape (B,h,Tq,Tk)(B, h, T_q, T_k). What is ∇KL\grad_{\mat{K}} L?
QuizWeights of nn.Linear
A layer nn.Linear(d_in, d_out) stores weight with shape (d_out, d_in) and computes Y = X @ weight.T + bias for a batch X of shape (B, d_in). If G is the loss gradient with respect to Y, what does backward() leave in weight.grad?
NumericRank one per example
A layer Y=XW\mat{Y} = \mat{X}\mat{W} processes a batch of two examples, x1=(1,2,2)\vb{x}_1 = (1, 2, 2) and x2=(0,3,4)\vb{x}_2 = (0, 3, 4), and receives gradients g1=(3,4)\vb{g}_1 = (3, 4) and g2=(1,0)\vb{g}_2 = (1, 0) at its output rows. Compute ∥∇WL∥F\norm{\grad_{\mat{W}} L}_F.
NumericA softmax VJP by hand
With p=softmax⁡(z)=(0.5,0.3,0.2)\vb{p} = \softmax(\vb{z}) = (0.5, 0.3, 0.2) you receive g=∇pL=(2,−1,0)\vb{g} = \grad_{\vb{p}} L = (2, -1, 0). Compute ∂L/∂z2\partial L/\partial z_2.
CodeThe softmax VJP without a Jacobian
Implement softmax_vjp(p, dy): given probabilities p = softmax(z) and gradient dy with respect to p, both shaped (..., K) (softmax along the last axis), return the gradient with respect to z with the same shape, p⊙(dy−⟨dy,p⟩)\vb{p}\odot(\vb{dy} - \inner{\vb{dy}}{\vb{p}}) rowwise. Do not form the Jacobian: tests include a case with K=20000K = 20000. Hidden tests compare with the explicit Jacobian at small sizes.
import numpy as np

def softmax_vjp(p, dy):
  # p, dy: forma (..., K). Devuelve dx con la misma forma, sin formar matrices K x K.
  pass
Shift+Enter to run
CodeComplete MLP backward pass
Implement mlp_grads(X, Y, W1, b1, W2, b2) for the MLP Z1=XW1+b1\mat{Z}_1 = \mat{X}\mat{W}_1 + \vb{b}_1, A1=ReLU⁡(Z1)\mat{A}_1 = \relu(\mat{Z}_1), Z2=A1W2+b2\mat{Z}_2 = \mat{A}_1\mat{W}_2 + \vb{b}_2 with loss L=−1B∑i,kYiklog⁡softmax⁡(Z2)ikL = -\frac1B\sum_{i,k}Y_{ik}\log\softmax(\mat{Z}_2)_{ik}. X is (B, D), Y is (B, K) with rows summing to 1 (one-hot or smoothed), W1 is (D, H), b1 is (H,), W2 is (H, K) and b2 is (K,). Return the tuple (dW1, db1, dW2, db2) with parameter shapes. Hidden tests compare with float64 finite differences.
import numpy as np

def mlp_grads(X, Y, W1, b1, W2, b2):
  # forward: guarda lo que necesitará el backward
  # backward: aplica los VJP en orden inverso
  pass
Shift+Enter to run

Summary

Key idea
The derivative of a composition is the composition of derivatives, but its Jacobians have size (output) × (input) and do not fit in memory. Backpropagation avoids forming them: it propagates the loss gradient using the adjoint of each differential, the VJP, which has the shape of the node’s input and costs the same as its forward pass.
  • Chain rule: d(g∘f)=g′(Y)[f′(X)[dX]]d(g\circ f) = g'(\mat{Y})[f'(\mat{X})[d\mat{X}]]. In coordinates, Jg∘f=JgJf\mat{J}_{g\circ f} = \mat{J}_g\mat{J}_f, and with vec⁡(AXB)=(B⊤⊗A)vec⁡X\operatorname{vec}(\mat{A}\mat{X}\mat{B}) = (\mat{B}\T\otimes\mat{A})\operatorname{vec}\mat{X} the Jacobian of XW\mat{X}\mat{W} with respect to W\mat{W} is I⊗X\mat{I}\otimes\mat{X}: n doutn\,d_{\text{out}} times the size of the weights.
  • VJP: ⟨U,f′[H]⟩=⟨f′∗[U],H⟩\inner{\mat{U}}{f'[\mat{H}]} = \inner{f'^{*}[\mat{U}]}{\mat{H}}. The gradient is the VJP of the output gradient, and in a chain VJPs are applied in reverse order. One reverse pass gives a scalar loss’s gradient with respect to all parameters, at the cost of storing activations.
  • Linear layer: ∇X=GW⊤\grad_{\mat{X}} = \mat{G}\mat{W}\T, ∇W=X⊤G=∑ixigi⊤\grad_{\mat{W}} = \mat{X}\T\mat{G} = \sum_i\vb{x}_i\vb{g}_i\T, ∇b=G⊤1\grad_{\vb{b}} = \mat{G}\T\vb{1}. Two products the size of the forward pass.
  • Structured Jacobians: elementwise activations have diagonal Jacobians and VJP σ′(Z)⊙G\sigma'(\mat{Z})\odot\mat{G}; softmax has diag⁡(p)−pp⊤\diag(\vb{p}) - \vb{p}\vb{p}\T, symmetric positive semidefinite, with null space span⁡{1}\spn\{\vb{1}\} and VJP p⊙(g−p⊤g)\vb{p}\odot(\vb{g} - \vb{p}\T\vb{g}); with cross-entropy, p−y\vb{p} - \vb{y}.
  • Contractions and broadcasting: an einsum’s VJP is another einsum with operand and output roles exchanged; forward broadcasting becomes a sum over stretched axes in the backward pass.