Vector–Jacobian products for matmul, softmax, normalization and convolution.
An autograd library is a table of backward rules, one per primitive, and every entry was derived by someone. This lesson gives you the one technique behind all of them, matrix differentials, and applies it to the primitives that matter: matrix products, broadcasting, softmax with cross-entropy, LayerNorm, attention and convolution. Along the way: what each backward pass must remember, why fused kernels exist, and how to invent a gradient where none exists.
What you’ll learn
Derive vector–Jacobian products with matrix differentials, and prove that the backward pass of a linear operation is its adjoint, which makes broadcasting and summation each other's backward passes.
Derive the softmax VJP s⊙(sˉ−⟨sˉ,s⟩1) and the gradient p−y of softmax cross-entropy, and explain why frameworks fuse them.
Derive the LayerNorm backward pass, prove that it is a projection that annihilates the directions LayerNorm ignores, and verify it with a custom autograd function and gradcheck.
Assemble the backward passes of attention, convolution and pooling, decide what each primitive must save, and explain straight-through estimators and their limits.
Differentials: one technique for every rule
For matrices of equal shape write ⟨A,B⟩=Tr(A⊤B)=∑ijAijBij. The gradient of a scalar loss L with respect to a matrix Y is the matrix G=∂L/∂Y of the same shape defined by dL=⟨G,dY⟩ for every perturbation dY. To find ∂L/∂X for Y=f(X), compute the differential dY in terms of dX, substitute, and rearrange until dL=⟨⋅,dX⟩. Whatever sits in the left slot is the answer.
By the chain rule dL=⟨G,dY⟩=⟨G,A(dX)⟩=⟨A∗(G),dX⟩ for all dX, and the gradient is the unique matrix with this property. Now the rules. Matrix productY=XW: dY=dXW+XdW, and the trace is cyclic:
Xˉ=G⊙ϕ′(X)
Elementwise mapsY=ϕ(X): dY=ϕ′(X)⊙dX, and ⟨G,ϕ′⊙dX⟩=⟨G⊙ϕ′,dX⟩:
Xˉ=G,bˉ=G⊤1=∑rowsG
Broadcasting. A bias added to every row, Y=X+1b⊤, has dY=dX+1db⊤, and ⟨G,1db⊤⟩=⟨G⊤1,db⟩. The backward pass of a broadcast is a sum over the broadcast axis:
s=X1⟹Xˉ=sˉ1⊤
Reductions are the mirror image: row sums s=X1 give ⟨sˉ,dX1⟩=⟨sˉ1⊤,dX⟩, so the backward pass of a sum is a broadcast. Broadcast and sum are adjoint to each other; so are gather and scatter-add, which is why an embedding table's gradient adds up the rows of every repeated token.
Primitive
Forward
Backward (given G)
Must keep
matrix product
Y=XW
Xˉ=GW⊤, Wˉ=X⊤G
X and W
elementwise
Y=ϕ(X)
Xˉ=G⊙ϕ′(X)
X, or Y when ϕ′ is a function of ϕ
broadcast add
Y=X+1b⊤
Xˉ=G, bˉ=G⊤1
nothing
sum over an axis
s=X1
Xˉ=sˉ1⊤
the shape
gather (embedding)
Yt=Eit
Eˉk=∑t:it=kGt (scatter-add)
the indices
transpose, reshape
Y=X⊤
Xˉ=G⊤
nothing
Every row is the theorem applied once. A gradient always has the shape of the thing it differentiates, the fastest way to catch a misplaced transpose.
Check your understanding
PyTorch's nn.Linear computes Y=XW⊤+1b⊤ with W∈Rout×in and X∈RB×in. Given G=∂L/∂Y, what is ∂L/∂W?
X⊤G
GW
G⊤X
G⊤1
Show the answer
C.G⊤X
dY=XdW⊤+… and ⟨G,XdW⊤⟩=Tr(G⊤XdW⊤)=⟨G⊤X,dW⟩ (a trace is unchanged by transposing its argument). G⊤X is out × in, the shape of W.
Softmax and cross-entropy
DerivationSoftmax VJP and the p − y gradient
ds=s⊙dz−s(s⊤dz),J=diag(s)−ss⊤=J⊤
For one row s=softmax(z), si=ezi/∑kezk. Differentiating gives dsi=sidzi−si∑kskdzk, so the Jacobian is symmetric:
zˉ=Jsˉ=s⊙sˉ−s⟨sˉ,s⟩=s⊙(sˉ−⟨sˉ,s⟩1)
The VJP never forms the n×n matrix J. It costs O(n) and needs only the outputs:
∂z∂ℓ=s−ey=p−y
Cross-entropy on the logits is ℓ=−logsy=−zy+LSE(z) with LSE(z)=log∑kezk. Since dLSE=⟨s,dz⟩, the gradient is the predicted distribution minus the one-hot target:
Predict before you look
Logits z=(2,1,0) and the true class is the first. What is ∂ℓ/∂z1 for the cross-entropy loss?
Show the answer
-0.33
p=softmax(2,1,0)≈(0.665,0.245,0.090), so ∂ℓ/∂z=p−y≈(−0.335,0.245,0.090). The entries sum to zero, since adding a constant to every logit changes nothing, and each lies in [−1,1] however wrong the prediction.
The bounded gradient is also the deeper reason cross-entropy trains classifiers better than squared error on sigmoid outputs. With squared error, ∂ℓ/∂z=2(σ(z)−y)σ′(z), and a confidently wrong unit sits in a flat tail where σ′(z)≈0: the error is large but the gradient vanishes. With cross-entropy the σ′ cancels and the gradient is σ(z)−y, largest exactly when the prediction is most wrong.
LayerNorm: a backward pass that projects
LayerNorm maps one token's vector x∈Rd to y=γ⊙x^+β with x^=(x−μ1)/σ, μ=d1∑ixi and σ=d1∑i(xi−μ)2+ϵ. Given g=∂L/∂y, the parameter gradients are immediate: βˉ=g and γˉ=g⊙x^, each summed over all tokens in the batch because the parameters are broadcast. The gradient reaching x^ is g^=γ⊙g. The interesting part is xˉ, because μ and σ depend on every coordinate.
DerivationProof
2σdσ=d2∑i(xi−μ)dxi⟹dσ=mean(x^⊙dx)
The mean moves by dμ=mean(dx). For σ2=d1∑i(xi−μ)2+ϵ, the dμ terms cancel because ∑i(xi−μ)=0:
dx^=σ1(dx−mean(dx)1−x^mean(x^⊙dx))
Differentiate x^=(x−μ1)/σ by the quotient rule:
⟨g^,dx^⟩=⟨σ1(g^−mean(g^)1−x^mean(g^⊙x^)),dx⟩
Pair with g^ and move every operator onto it: ⟨g^,mean(dx)1⟩=⟨mean(g^)1,dx⟩, and ⟨g^,x^⟩mean(x^⊙dx)=⟨mean(g^⊙x^)x^,dx⟩. This reads off xˉ. Summing its coordinates gives ∑ig^i−∑ig^i−mean(g^⊙x^)∑ix^i=0, since ∑ix^i=0.
x^⊤xˉ=σx^⊤g^(1−d∥x^∥2)=0when ϵ=0
With ϵ=0, x^⊥1 and ∥x^∥2=d, so d111⊤ and d1x^x^⊤ are orthogonal rank-one projectors and P is the projector onto the complement of their span. With ϵ>0, ∥x^∥2=dσ02/(σ02+ϵ)<d (where σ02 is the variance), and the second identity holds only approximately.
Check your understanding
LayerNorm with γ=1 and ϵ=0 receives x=(1,2,4), so x^≈(−1.069,−0.267,1.336) and σ≈1.247. The upstream gradient is g=(1,0,0). Which vector is xˉ?
(0.802,0,0)
(0.229,−0.344,0.115)
(0.535,−0.267,−0.267)
(0.229,−0.344,0.315)
Show the answer
B.(0.229,−0.344,0.115)
mean(g^)=31 and mean(g^⊙x^)≈−0.356, so xˉ=1.2471((1,0,0)−311+0.356x^)≈(0.229,−0.344,0.115). It sums to zero and is orthogonal to x^, as the theorem demands; a finite-difference check agrees to many digits.
Attention, convolution and pooling
Larger layers are compositions, so their backward passes are the rules above run in reverse order. One attention head computes S=QK⊤/dk (plus a mask), P=softmaxrows(S) and O=PV: two matrix products and a row-wise softmax. Given Oˉ:
DerivationThe attention backward pass
Pˉ=OˉV⊤,Vˉ=P⊤Oˉ
O=PV is a matrix product:
Sˉ=P⊙(Pˉ−D1⊤),Di=∑jPijPˉij
Each row of P is a softmax, so apply its VJP row by row. Masked entries have Pij=0 and therefore receive no gradient:
Di=oˉi⊤oi
The row statistic needs neither P nor Pˉ in full: Di=∑jPijoˉi⋅vj=oˉi⋅oi. FlashAttention's backward pass computes it this way, from the output and its gradient alone.
Qˉ=SˉK/dk,Kˉ=Sˉ⊤Q/dk
Finally S=QK⊤/dk is a scaled matrix product:
The backward pass has four n×n×dk products against the forward pass's two: twice the FLOPs again. The memory is the problem. Saving P for the backward pass costs n2 numbers per head and layer, so long contexts run out of memory long before they run out of compute. FlashAttention (Dao et al., 2022) keeps only O and the softmax's two normalization statistics per row (its running maximum and sum; FlashAttention-2 combines them into one log-sum-exp), then recomputes S and P tile by tile during the backward pass: one extra matrix product buys memory linear in n (FlashAttention in Depth).
Predict before you look
One layer has 32 heads and processes a single sequence of n=8,192 tokens in 16-bit precision. How many gigabytes would it take to store the attention probabilities P for the backward pass?
Show the answer
4.3 GB
32×8,1922×2 bytes ≈4.3×109 bytes (4 GiB), for one layer of one sequence. Multiply by dozens of layers and a batch, and storing P is out of the question; recomputing it is cheaper than moving it.
Convolution. Take a 1-D cross-correlation, as PyTorch's conv1d computes, yi=∑kwkxi+k with stride 1 and no padding. The rules for products and sums give
xˉj=i∑yˉiwj−i,wˉk=i∑yˉixi+k
The input gradient slides the kernel over the zero-padded output gradient, a "full" convolution, which is exactly what a transposed convolution with the same weights computes; the weight gradient correlates the input with the output gradient. A forward stride becomes zeros inserted between gradient entries in the backward pass (Dumoulin & Visin, 2016). Both are convolution-shaped and together cost about twice the forward pass, as for a dense layer.
Check your understanding
Max pooling with windows of 2 and stride 2 maps x=(1,5,3,2) to y=(5,3). The upstream gradient is yˉ=(0.1,−0.2). What is xˉ?
(0.05,0.05,−0.1,−0.1)
(0.1,0.1,−0.2,−0.2)
(0,0.5,−0.6,0)
(0,0.1,−0.2,0)
Show the answer
D.(0,0.1,−0.2,0)
Locally, each output equals one input, its window's maximum, so its derivative is 1 there and 0 elsewhere: the gradient is routed to the argmax. The forward pass saves the argmax indices; where windows overlap, routed gradients add.
Primitive
Saved for the backward pass
Why
ReLU
a sign mask (1 bit per entry), or the output
ϕ′=1[z>0] is readable from either
sigmoid, tanh, exp, softmax
the output
σ′=σ(1−σ), tanh′=1−tanh2, exp′=exp, softmax VJP uses s
GELU, SiLU
the input
the derivative is not a function of the output alone
LayerNorm, RMSNorm
x^ (or x) and 1/σ per row
the VJP above
dropout
the mask, or the random seed to regenerate it
the same units must be zeroed
max pooling
argmax indices
routing
attention
Q,K,V,O and the softmax statistics of each row (FlashAttention), or also P
P is recomputed or stored
Saving outputs instead of inputs is what makes in-place activations possible. PyTorch tracks a version counter on every saved tensor and raises an error if one was modified in place before the backward pass used it.
Writing a backward pass, and faking one
When a composition of primitives is slow, memory-hungry or numerically fragile, write its backward pass by hand. A torch.autograd.Function has a forward(ctx, ...) that computes the output and stashes what the backward pass needs with ctx.save_for_backward, and a backward(ctx, grad_output) that returns one gradient per input of forward. Then test it against finite differences in double precision. Here is the LayerNorm theorem, implemented and checked:
python
import torch
EPS = 1e-5
class LayerNormFn(torch.autograd.Function):
"""LayerNorm without the affine part, with the backward pass derived above."""
@staticmethod
def forward(ctx, x):
xc = x - x.mean(dim=-1, keepdim=True)
rstd = torch.rsqrt((xc * xc).mean(dim=-1, keepdim=True) + EPS) # 1/σ per row
xhat = xc * rstd
ctx.save_for_backward(xhat, rstd) # x itself is not needed later
return xhat
@staticmethod
def backward(ctx, g):
xhat, rstd = ctx.saved_tensors
return rstd * (g - g.mean(dim=-1, keepdim=True)
- xhat * (g * xhat).mean(dim=-1, keepdim=True))
x = torch.randn(8, 16, dtype=torch.double, requires_grad=True)
assert torch.autograd.gradcheck(LayerNormFn.apply, (x,)) # raises if backward is wrong
With γ=1, g^=g. Production kernels fuse this into one pass over each row and often recompute x^ from x instead of storing it.
Some operations have no useful derivative at all. Rounding, the sign function and the nearest-codeword lookup of vector quantization are piecewise constant: their derivative is 0 almost everywhere, so backpropagation through them returns nothing. The straight-through estimator (STE) runs the true function forward but uses a surrogate's derivative backward: the identity for rounding, or the clipped identity 1[∣x∣≤1] for the sign. In PyTorch, y = x + (torch.round(x) - x).detach() has the value of round(x) and the gradient of x. The trick is usually traced to Geoffrey Hinton's 2012 lectures; Bengio, Léonard and Courville (2013) compared it with other estimators for binary stochastic units, and in their conditional-computation experiment on MNIST it gave the best validation and test error. It is how quantization-aware training rounds weights (Quantization in Depth) and how VQ-VAEs pass gradients through their codebooks (Learned Tokenizers for Images & Audio).
Key takeaways
Write dL=⟨G,dY⟩, expand dY in terms of dX and move everything onto G: the backward pass of a linear map is its adjoint, so Y=XW gives Xˉ=GW⊤, Wˉ=X⊤G, and broadcasting and summation are each other's backward passes.
Softmax's VJP is s⊙(sˉ−⟨sˉ,s⟩1), linear in n and needing only the output; with cross-entropy on logits it collapses to p−y, which fused kernels compute directly for numerical safety.
LayerNorm's backward pass is σ1(g^−mean(g^)1−x^mean(g^⊙x^)): a projection that removes the directions the forward pass is invariant to, scaled by 1/σ.
Attention's backward pass needs four matrix products and Di=oˉi⊤oi; storing P costs n2 per head, which FlashAttention avoids by recomputation. A convolution's input gradient is a transposed convolution, and max pooling routes the gradient to the argmax.
Custom autograd.Functions let you control what is saved and how the gradient is computed; always gradcheck them in double precision. Straight-through estimators supply a surrogate gradient for piecewise-constant operations, useful in practice but not the gradient of anything.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Question 1
For Y=XW with X∈RB×m, W∈Rm×n and upstream gradient G∈RB×n, which pair is correct?
Xˉ=W⊤G, Wˉ=GX⊤
Xˉ=GW, Wˉ=XG⊤
Xˉ=G⊤W, Wˉ=X⊤G⊤
Xˉ=GW⊤, Wˉ=X⊤G
Show the answer
D.Xˉ=GW⊤, Wˉ=X⊤G
From dL=⟨G,dXW+XdW⟩=⟨GW⊤,dX⟩+⟨X⊤G,dW⟩. Check shapes: GW⊤ is B×m like X, and X⊤G is m×n like W.
Question 2
A bias b∈Rn is added to every row of a B×n activation matrix. How is ∂L/∂b computed from G=∂L/∂Y?
Sum G over the batch axis: bˉ=G⊤1
Take the first row of G
Average G over the feature axis
It is zero, since biases do not depend on the input
Show the answer
A. Sum G over the batch axis: bˉ=G⊤1
Broadcasting copies b into B rows, and the adjoint of copying is summing: each copy contributes its row of G.
Question 3
To backpropagate through a softmax over n logits, what must the forward pass keep, and what does the VJP cost?
The logits; O(n2), to build the Jacobian
Nothing; O(n)
The output probabilities s; O(n), via s⊙(sˉ−⟨sˉ,s⟩1)
The full Jacobian; O(n) to apply it
Show the answer
C. The output probabilities s; O(n), via s⊙(sˉ−⟨sˉ,s⟩1)
J=diag(s)−ss⊤ is never formed: its product with sˉ needs one inner product and one elementwise product. Only s is required.
Question 4
Why do the coordinates of LayerNorm's input gradient xˉ always sum to zero?
Because γ is initialized to ones
Because adding the same constant to every input coordinate leaves LayerNorm's output unchanged, so the loss has zero derivative along 1
Because the upstream gradient g always sums to zero
Because ϵ is small
Show the answer
B. Because adding the same constant to every input coordinate leaves LayerNorm's output unchanged, so the loss has zero derivative along 1
1⊤xˉ is the directional derivative of the loss along 1, and subtracting the mean makes the forward pass blind to that direction. This holds for any γ, any g and any ϵ.
Further reading
J. R. Magnus & H. Neudecker, Matrix Differential Calculus with Applications in Statistics and Econometrics (3rd ed., Wiley, 2019).
V. Dumoulin & F. Visin, "A guide to convolution arithmetic for deep learning," arXiv:1603.07285 (2016).
T. Dao, D. Y. Fu, S. Ermon, A. Rudra & C. Ré, "FlashAttention: Fast and memory-efficient exact attention with IO-awareness," NeurIPS (2022).
Y. Bengio, N. Léonard & A. Courville, "Estimating or propagating gradients through stochastic neurons for conditional computation," arXiv:1308.3432 (2013).
P. Yin, J. Lyu, S. Zhang, S. Osher, Y. Qi & J. Xin, "Understanding straight-through estimator in training activation quantized neural nets," ICLR (2019).