Simple Algorithm
Deep Learning · Emergence · 28 min

Deriving Backward Passes

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)\mathbf s\odot(\bar{\mathbf s}-\langle\bar{\mathbf s},\mathbf s\rangle\mathbf 1) and the gradient p−y\mathbf p-\mathbf 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\langle A,B\rangle = \Tr(A^\top B) = \sum_{ij}A_{ij}B_{ij}. The gradient of a scalar loss LL with respect to a matrix YY is the matrix G=∂L/∂YG = \partial L/\partial Y of the same shape defined by dL=⟨G,dY⟩dL = \langle G, dY\rangle for every perturbation dYdY. To find ∂L/∂X\partial L/\partial X for Y=f(X)Y = f(X), compute the differential dYdY in terms of dXdX, substitute, and rearrange until dL=⟨ ⋅ ,dX⟩dL = \langle\,\cdot\,, dX\rangle. Whatever sits in the left slot is the answer.

DerivationProof, and the core rules
  1. ⟨G,dX W⟩=Tr⁡(G⊤dX W)=⟨GW⊤,dX⟩,⟨G,X dW⟩=⟨X⊤G,dW⟩ ⟹ Xˉ=GW⊤,  Wˉ=X⊤G\langle G, dX\,W\rangle = \Tr(G^\top dX\,W) = \langle GW^\top, dX\rangle,\quad\langle G, X\,dW\rangle = \langle X^\top G, dW\rangle\ \Longrightarrow\ \bar X = GW^\top,\ \ \bar W = X^\top G

    By the chain rule dL=⟨G,dY⟩=⟨G,A(dX)⟩=⟨A∗(G),dX⟩dL = \langle G, dY\rangle = \langle G,\mathcal A(dX)\rangle = \langle\mathcal A^*(G), dX\rangle for all dXdX, and the gradient is the unique matrix with this property. Now the rules. Matrix product Y=XWY = XW: dY=dX W+X dWdY = dX\,W + X\,dW, and the trace is cyclic:

  2. Xˉ=G⊙ϕ′(X)\bar X = G\odot\phi'(X)

    Elementwise maps Y=ϕ(X)Y = \phi(X): dY=ϕ′(X)⊙dXdY = \phi'(X)\odot dX, and ⟨G,ϕ′⊙dX⟩=⟨G⊙ϕ′,dX⟩\langle G, \phi'\odot dX\rangle = \langle G\odot\phi', dX\rangle:

  3. Xˉ=G,bˉ=G⊤1=∑rowsG\bar X = G,\qquad\bar{\mathbf b} = G^\top\mathbf 1 = \textstyle\sum_{\text{rows}}G

    Broadcasting. A bias added to every row, Y=X+1b⊤Y = X + \mathbf 1\mathbf b^\top, has dY=dX+1 db⊤dY = dX + \mathbf 1\,d\mathbf b^\top, and ⟨G,1 db⊤⟩=⟨G⊤1,db⟩\langle G,\mathbf 1\,d\mathbf b^\top\rangle = \langle G^\top\mathbf 1, d\mathbf b\rangle. The backward pass of a broadcast is a sum over the broadcast axis:

  4. s=X1 ⟹ Xˉ=sˉ 1⊤\mathbf s = X\mathbf 1\ \Longrightarrow\ \bar X = \bar{\mathbf s}\,\mathbf 1^\top

    Reductions are the mirror image: row sums s=X1\mathbf s = X\mathbf 1 give ⟨sˉ,dX 1⟩=⟨sˉ1⊤,dX⟩\langle\bar{\mathbf s}, dX\,\mathbf 1\rangle = \langle\bar{\mathbf s}\mathbf 1^\top, dX\rangle, 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.

PrimitiveForwardBackward (given GG)Must keep
matrix productY=XWY = XWXˉ=GW⊤\bar X = GW^\top, Wˉ=X⊤G\bar W = X^\top GXX and WW
elementwiseY=ϕ(X)Y = \phi(X)Xˉ=G⊙ϕ′(X)\bar X = G\odot\phi'(X)XX, or YY when ϕ′\phi' is a function of ϕ\phi
broadcast addY=X+1b⊤Y = X + \mathbf 1\mathbf b^\topXˉ=G\bar X = G, bˉ=G⊤1\bar{\mathbf b} = G^\top\mathbf 1nothing
sum over an axiss=X1\mathbf s = X\mathbf 1Xˉ=sˉ1⊤\bar X = \bar{\mathbf s}\mathbf 1^\topthe shape
gather (embedding)Yt=EitY_t = E_{i_t}Eˉk=∑t: it=kGt\bar E_k = \sum_{t:\,i_t = k}G_t (scatter-add)the indices
transpose, reshapeY=X⊤Y = X^\topXˉ=G⊤\bar X = G^\topnothing
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⊤Y = XW^\top + \mathbf 1\mathbf b^\top with W∈Rout×inW\in\R^{\text{out}\times\text{in}} and X∈RB×inX\in\R^{B\times\text{in}}. Given G=∂L/∂YG = \partial L/\partial Y, what is ∂L/∂W\partial L/\partial W?

  1. X⊤GX^\top G
  2. GWGW
  3. G⊤XG^\top X
  4. G⊤1G^\top\mathbf 1
Show the answer

C. G⊤XG^\top X

dY=X dW⊤+…dY = X\,dW^\top + \dots and ⟨G,X dW⊤⟩=Tr⁡(G⊤X dW⊤)=⟨G⊤X,dW⟩\langle G, X\,dW^\top\rangle = \Tr(G^\top X\,dW^\top) = \langle G^\top X, dW\rangle (a trace is unchanged by transposing its argument). G⊤XG^\top X is out × in, the shape of WW.

Softmax and cross-entropy

DerivationSoftmax VJP and the p − y gradient
  1. ds=s⊙dz−s (s⊤dz),J=diag⁡(s)−ss⊤=J⊤d\mathbf s = \mathbf s\odot d\mathbf z - \mathbf s\,(\mathbf s^\top d\mathbf z),\qquad J = \diag(\mathbf s) - \mathbf s\mathbf s^\top = J^\top

    For one row s=softmax⁡(z)\mathbf s = \softmax(\mathbf z), si=ezi/∑kezks_i = e^{z_i}/\sum_ke^{z_k}. Differentiating gives dsi=si dzi−si∑ksk dzkds_i = s_i\,dz_i - s_i\sum_ks_k\,dz_k, so the Jacobian is symmetric:

  2. zˉ=Jsˉ=s⊙sˉ−s ⟨sˉ,s⟩=s⊙(sˉ−⟨sˉ,s⟩1)\bar{\mathbf z} = J\bar{\mathbf s} = \mathbf s\odot\bar{\mathbf s} - \mathbf s\,\langle\bar{\mathbf s},\mathbf s\rangle = \mathbf s\odot\big(\bar{\mathbf s} - \langle\bar{\mathbf s},\mathbf s\rangle\mathbf 1\big)

    The VJP never forms the n×nn\times n matrix JJ. It costs O(n)\order{n} and needs only the output s\mathbf s:

  3. ∂ℓ∂z=s−ey=p−y\frac{\partial\ell}{\partial\mathbf z} = \mathbf s - \mathbf e_y = \mathbf p - \mathbf y

    Cross-entropy on the logits is ℓ=−log⁡sy=−zy+LSE⁡(z)\ell = -\log s_y = -z_y + \operatorname{LSE}(\mathbf z) with LSE⁡(z)=log⁡∑kezk\operatorname{LSE}(\mathbf z) = \log\sum_ke^{z_k}. Since dLSE⁡=⟨s,dz⟩d\operatorname{LSE} = \langle\mathbf s, d\mathbf z\rangle, the gradient is the predicted distribution minus the one-hot target:

Predict before you look

Logits z=(2,1,0)\mathbf z = (2, 1, 0) and the true class is the first. What is ∂ℓ/∂z1\partial\ell/\partial z_1 for the cross-entropy loss?

Show the answer

-0.33

p=softmax⁡(2,1,0)≈(0.665,0.245,0.090)\mathbf p = \softmax(2,1,0) \approx (0.665, 0.245, 0.090), so ∂ℓ/∂z=p−y≈(−0.335,0.245,0.090)\partial\ell/\partial\mathbf z = \mathbf p - \mathbf y \approx (-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][-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)\partial\ell/\partial z = 2(\sigma(z) - y)\,\sigma'(z), and a confidently wrong unit sits in a flat tail where σ′(z)≈0\sigma'(z)\approx0: the error is large but the gradient vanishes. With cross-entropy the σ′\sigma' cancels and the gradient is σ(z)−y\sigma(z) - y, largest exactly when the prediction is most wrong.

LayerNorm: a backward pass that projects

LayerNorm maps one token's vector x∈Rd\mathbf x\in\R^d to y=γ⊙x^+β\mathbf y = \boldsymbol\gamma\odot\hat{\mathbf x} + \boldsymbol\beta with x^=(x−μ1)/σ\hat{\mathbf x} = (\mathbf x - \mu\mathbf 1)/\sigma, μ=1d∑ixi\mu = \frac1d\sum_ix_i and σ=1d∑i(xi−μ)2+ϵ\sigma = \sqrt{\frac1d\sum_i(x_i - \mu)^2 + \epsilon}. Given g=∂L/∂y\mathbf g = \partial L/\partial\mathbf y, the parameter gradients are immediate: βˉ=g\bar{\boldsymbol\beta} = \mathbf g and γˉ=g⊙x^\bar{\boldsymbol\gamma} = \mathbf g\odot\hat{\mathbf x}, each summed over all tokens in the batch because the parameters are broadcast. The gradient reaching x^\hat{\mathbf x} is g^=γ⊙g\hat{\mathbf g} = \boldsymbol\gamma\odot\mathbf g. The interesting part is xˉ\bar{\mathbf x}, because μ\mu and σ\sigma depend on every coordinate.

DerivationProof
  1. 2σ dσ=2d∑i(xi−μ) dxi⟹dσ=mean⁡(x^⊙dx)2\sigma\,d\sigma = \tfrac2d\textstyle\sum_i(x_i - \mu)\,dx_i\quad\Longrightarrow\quad d\sigma = \operatorname{mean}(\hat{\mathbf x}\odot d\mathbf x)

    The mean moves by dμ=mean⁡(dx)d\mu = \operatorname{mean}(d\mathbf x). For σ2=1d∑i(xi−μ)2+ϵ\sigma^2 = \frac1d\sum_i(x_i - \mu)^2 + \epsilon, the dμd\mu terms cancel because ∑i(xi−μ)=0\sum_i(x_i - \mu) = 0:

  2. dx^=1σ(dx−mean⁡(dx) 1−x^ mean⁡(x^⊙dx))d\hat{\mathbf x} = \frac1\sigma\Big(d\mathbf x - \operatorname{mean}(d\mathbf x)\,\mathbf 1 - \hat{\mathbf x}\,\operatorname{mean}(\hat{\mathbf x}\odot d\mathbf x)\Big)

    Differentiate x^=(x−μ1)/σ\hat{\mathbf x} = (\mathbf x - \mu\mathbf 1)/\sigma by the quotient rule:

  3. ⟨g^,dx^⟩=⟨1σ(g^−mean⁡(g^)1−x^mean⁡(g^⊙x^)), dx⟩\langle\hat{\mathbf g}, d\hat{\mathbf x}\rangle = \Big\langle\tfrac1\sigma\big(\hat{\mathbf g} - \operatorname{mean}(\hat{\mathbf g})\mathbf 1 - \hat{\mathbf x}\operatorname{mean}(\hat{\mathbf g}\odot\hat{\mathbf x})\big),\,d\mathbf x\Big\rangle

    Pair with g^\hat{\mathbf g} and move every operator onto it: ⟨g^,mean⁡(dx)1⟩=⟨mean⁡(g^)1,dx⟩\langle\hat{\mathbf g},\operatorname{mean}(d\mathbf x)\mathbf 1\rangle = \langle\operatorname{mean}(\hat{\mathbf g})\mathbf 1, d\mathbf x\rangle, and ⟨g^,x^⟩mean⁡(x^⊙dx)=⟨mean⁡(g^⊙x^) x^,dx⟩\langle\hat{\mathbf g},\hat{\mathbf x}\rangle\operatorname{mean}(\hat{\mathbf x}\odot d\mathbf x) = \langle\operatorname{mean}(\hat{\mathbf g}\odot\hat{\mathbf x})\,\hat{\mathbf x}, d\mathbf x\rangle. This reads off xˉ\bar{\mathbf x}. Summing its coordinates gives ∑ig^i−∑ig^i−mean⁡(g^⊙x^)∑ix^i=0\sum_i\hat g_i - \sum_i\hat g_i - \operatorname{mean}(\hat{\mathbf g}\odot\hat{\mathbf x})\sum_i\hat x_i = 0, since ∑ix^i=0\sum_i\hat x_i = 0.

  4. x^⊤xˉ=x^⊤g^σ(1−∥x^∥2d)=0when ϵ=0\hat{\mathbf x}^\top\bar{\mathbf x} = \frac{\hat{\mathbf x}^\top\hat{\mathbf g}}{\sigma}\Big(1 - \frac{\norm{\hat{\mathbf x}}^2}{d}\Big) = 0\quad\text{when }\epsilon = 0

    With ϵ=0\epsilon = 0, x^⊥1\hat{\mathbf x}\perp\mathbf 1 and ∥x^∥2=d\norm{\hat{\mathbf x}}^2 = d, so 1d11⊤\frac1d\mathbf 1\mathbf 1^\top and 1dx^x^⊤\frac1d\hat{\mathbf x}\hat{\mathbf x}^\top are orthogonal rank-one projectors and PP is the projector onto the complement of their span. With ϵ>0\epsilon > 0, ∥x^∥2=d σ02/(σ02+ϵ)<d\norm{\hat{\mathbf x}}^2 = d\,\sigma_0^2/(\sigma_0^2 + \epsilon) < d (where σ02\sigma_0^2 is the variance), and the second identity holds only approximately.

Check your understanding

LayerNorm with γ=1\boldsymbol\gamma = \mathbf 1 and ϵ=0\epsilon = 0 receives x=(1,2,4)\mathbf x = (1, 2, 4), so x^≈(−1.069,−0.267,1.336)\hat{\mathbf x}\approx(-1.069, -0.267, 1.336) and σ≈1.247\sigma\approx1.247. The upstream gradient is g=(1,0,0)\mathbf g = (1, 0, 0). Which vector is xˉ\bar{\mathbf x}?

  1. (0.802,0,0)(0.802, 0, 0)
  2. (0.229,−0.344,0.115)(0.229, -0.344, 0.115)
  3. (0.535,−0.267,−0.267)(0.535, -0.267, -0.267)
  4. (0.229,−0.344,0.315)(0.229, -0.344, 0.315)
Show the answer

B. (0.229,−0.344,0.115)(0.229, -0.344, 0.115)

mean⁡(g^)=13\operatorname{mean}(\hat{\mathbf g}) = \tfrac13 and mean⁡(g^⊙x^)≈−0.356\operatorname{mean}(\hat{\mathbf g}\odot\hat{\mathbf x}) \approx -0.356, so xˉ=11.247((1,0,0)−131+0.356 x^)≈(0.229,−0.344,0.115)\bar{\mathbf x} = \tfrac1{1.247}\big((1,0,0) - \tfrac13\mathbf 1 + 0.356\,\hat{\mathbf x}\big)\approx(0.229, -0.344, 0.115). It sums to zero and is orthogonal to x^\hat{\mathbf 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⊤/dkS = QK^\top/\sqrt{d_k} (plus a mask), P=softmax⁡rows(S)P = \softmax_{\text{rows}}(S) and O=PVO = PV: two matrix products and a row-wise softmax. Given Oˉ\bar O:

DerivationThe attention backward pass
  1. Pˉ=Oˉ V⊤,Vˉ=P⊤Oˉ\bar P = \bar O\,V^\top,\qquad\bar V = P^\top\bar O

    O=PVO = PV is a matrix product:

  2. Sˉ=P⊙(Pˉ−D 1⊤),Di=∑jPijPˉij\bar S = P\odot\big(\bar P - \mathbf D\,\mathbf 1^\top\big),\qquad D_i = \textstyle\sum_jP_{ij}\bar P_{ij}

    Each row of PP is a softmax, so apply its VJP row by row. Masked entries have Pij=0P_{ij} = 0 and therefore receive no gradient:

  3. Di=oˉi⊤oiD_i = \bar{\mathbf o}_i^\top\mathbf o_i

    The row statistic needs neither PP nor Pˉ\bar P in full: Di=∑jPij oˉi⋅vj=oˉi⋅oiD_i = \sum_jP_{ij}\,\bar{\mathbf o}_i\cdot\mathbf v_j = \bar{\mathbf o}_i\cdot\mathbf o_i. FlashAttention's backward pass computes it this way, from the output and its gradient alone.

  4. Qˉ=SˉK/dk,Kˉ=Sˉ⊤Q/dk\bar Q = \bar SK/\sqrt{d_k},\qquad\bar K = \bar S^\top Q/\sqrt{d_k}

    Finally S=QK⊤/dkS = QK^\top/\sqrt{d_k} is a scaled matrix product:

The backward pass has four n×n×dkn\times n\times d_k products against the forward pass's two: twice the FLOPs again. The memory is the problem. Saving PP for the backward pass costs n2n^2 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 OO 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 SS and PP tile by tile during the backward pass: one extra matrix product buys memory linear in nn (FlashAttention in Depth).

Predict before you look

One layer has 32 heads and processes a single sequence of n=8,192n = 8{,}192 tokens in 16-bit precision. How many gigabytes would it take to store the attention probabilities PP for the backward pass?

Show the answer

4.3 GB

32×8,1922×232\times8{,}192^2\times2 bytes ≈4.3×109\approx4.3\times10^9 bytes (44 GiB), for one layer of one sequence. Multiply by dozens of layers and a batch, and storing PP 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+ky_i = \sum_kw_kx_{i+k} with stride 1 and no padding. The rules for products and sums give

xˉj=∑iyˉi wj−i,wˉk=∑iyˉi xi+k\bar x_j = \sum_i\bar y_i\,w_{j-i},\qquad\bar w_k = \sum_i\bar y_i\,x_{i+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)\mathbf x = (1, 5, 3, 2) to y=(5,3)\mathbf y = (5, 3). The upstream gradient is yˉ=(0.1,−0.2)\bar{\mathbf y} = (0.1, -0.2). What is xˉ\bar{\mathbf x}?

  1. (0.05,0.05,−0.1,−0.1)(0.05, 0.05, -0.1, -0.1)
  2. (0.1,0.1,−0.2,−0.2)(0.1, 0.1, -0.2, -0.2)
  3. (0,0.5,−0.6,0)(0, 0.5, -0.6, 0)
  4. (0,0.1,−0.2,0)(0, 0.1, -0.2, 0)
Show the answer

D. (0,0.1,−0.2,0)(0, 0.1, -0.2, 0)

Locally, each output equals one input, its window's maximum, so its derivative is 11 there and 00 elsewhere: the gradient is routed to the argmax. The forward pass saves the argmax indices; where windows overlap, routed gradients add.

PrimitiveSaved for the backward passWhy
ReLUa sign mask (1 bit per entry), or the outputϕ′=1[z>0]\phi' = \mathbb 1[z > 0] is readable from either
sigmoid, tanh, exp, softmaxthe outputσ′=σ(1−σ)\sigma' = \sigma(1 - \sigma), tanh⁡′=1−tanh⁡2\tanh' = 1 - \tanh^2, exp⁡′=exp⁡\exp' = \exp, softmax VJP uses s\mathbf s
GELU, SiLUthe inputthe derivative is not a function of the output alone
LayerNorm, RMSNormx^\hat{\mathbf x} (or x\mathbf x) and 1/σ1/\sigma per rowthe VJP above
dropoutthe mask, or the random seed to regenerate itthe same units must be zeroed
max poolingargmax indicesrouting
attentionQ,K,V,OQ, K, V, O and the softmax statistics of each row (FlashAttention), or also PPPP 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\boldsymbol\gamma = \mathbf 1, g^=g\hat{\mathbf g} = \mathbf g. Production kernels fuse this into one pass over each row and often recompute x^\hat{\mathbf x} from x\mathbf 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 00 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]\mathbb 1[\abs{x}\le1] for the sign. In PyTorch, y = x + (torch.round(x) - x).detach() has the value of round⁡(x)\operatorname{round}(x) and the gradient of xx. 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⟩dL = \langle G, dY\rangle, expand dYdY in terms of dXdX and move everything onto GG: the backward pass of a linear map is its adjoint, so Y=XWY = XW gives Xˉ=GW⊤\bar X = GW^\top, Wˉ=X⊤G\bar W = X^\top G, and broadcasting and summation are each other's backward passes.
  • Softmax's VJP is s⊙(sˉ−⟨sˉ,s⟩1)\mathbf s\odot(\bar{\mathbf s} - \langle\bar{\mathbf s},\mathbf s\rangle\mathbf 1), linear in nn and needing only the output; with cross-entropy on logits it collapses to p−y\mathbf p - \mathbf y, which fused kernels compute directly for numerical safety.
  • LayerNorm's backward pass is 1σ(g^−mean⁡(g^)1−x^mean⁡(g^⊙x^))\frac1\sigma\big(\hat{\mathbf g} - \operatorname{mean}(\hat{\mathbf g})\mathbf 1 - \hat{\mathbf x}\operatorname{mean}(\hat{\mathbf g}\odot\hat{\mathbf x})\big): a projection that removes the directions the forward pass is invariant to, scaled by 1/σ1/\sigma.
  • Attention's backward pass needs four matrix products and Di=oˉi⊤oiD_i = \bar{\mathbf o}_i^\top\mathbf o_i; storing PP costs n2n^2 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=XWY = XW with X∈RB×mX\in\R^{B\times m}, W∈Rm×nW\in\R^{m\times n} and upstream gradient G∈RB×nG\in\R^{B\times n}, which pair is correct?

  1. Xˉ=W⊤G\bar X = W^\top G, Wˉ=GX⊤\bar W = GX^\top
  2. Xˉ=GW\bar X = GW, Wˉ=XG⊤\bar W = XG^\top
  3. Xˉ=G⊤W\bar X = G^\top W, Wˉ=X⊤G⊤\bar W = X^\top G^\top
  4. Xˉ=GW⊤\bar X = GW^\top, Wˉ=X⊤G\bar W = X^\top G
Show the answer

D. Xˉ=GW⊤\bar X = GW^\top, Wˉ=X⊤G\bar W = X^\top G

From dL=⟨G,dX W+X dW⟩=⟨GW⊤,dX⟩+⟨X⊤G,dW⟩dL = \langle G, dX\,W + X\,dW\rangle = \langle GW^\top, dX\rangle + \langle X^\top G, dW\rangle. Check shapes: GW⊤GW^\top is B×mB\times m like XX, and X⊤GX^\top G is m×nm\times n like WW.

Question 2

A bias b∈Rn\mathbf b\in\R^n is added to every row of a B×nB\times n activation matrix. How is ∂L/∂b\partial L/\partial\mathbf b computed from G=∂L/∂YG = \partial L/\partial Y?

  1. Sum GG over the batch axis: bˉ=G⊤1\bar{\mathbf b} = G^\top\mathbf 1
  2. Take the first row of GG
  3. Average GG over the feature axis
  4. It is zero, since biases do not depend on the input
Show the answer

A. Sum GG over the batch axis: bˉ=G⊤1\bar{\mathbf b} = G^\top\mathbf 1

Broadcasting copies b\mathbf b into BB rows, and the adjoint of copying is summing: each copy contributes its row of GG.

Question 3

To backpropagate through a softmax over nn logits, what must the forward pass keep, and what does the VJP cost?

  1. The logits; O(n2)\order{n^2}, to build the Jacobian
  2. Nothing; O(n)\order{n}
  3. The output probabilities s\mathbf s; O(n)\order{n}, via s⊙(sˉ−⟨sˉ,s⟩1)\mathbf s\odot(\bar{\mathbf s} - \langle\bar{\mathbf s},\mathbf s\rangle\mathbf 1)
  4. The full Jacobian; O(n)\order{n} to apply it
Show the answer

C. The output probabilities s\mathbf s; O(n)\order{n}, via s⊙(sˉ−⟨sˉ,s⟩1)\mathbf s\odot(\bar{\mathbf s} - \langle\bar{\mathbf s},\mathbf s\rangle\mathbf 1)

J=diag⁡(s)−ss⊤J = \diag(\mathbf s) - \mathbf s\mathbf s^\top is never formed: its product with sˉ\bar{\mathbf s} needs one inner product and one elementwise product. Only s\mathbf s is required.

Question 4

Why do the coordinates of LayerNorm's input gradient xˉ\bar{\mathbf x} always sum to zero?

  1. Because γ\boldsymbol\gamma is initialized to ones
  2. Because adding the same constant to every input coordinate leaves LayerNorm's output unchanged, so the loss has zero derivative along 1\mathbf 1
  3. Because the upstream gradient g\mathbf g always sums to zero
  4. Because ϵ\epsilon 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\mathbf 1

1⊤xˉ\mathbf 1^\top\bar{\mathbf x} is the directional derivative of the loss along 1\mathbf 1, and subtracting the mean makes the forward pass blind to that direction. This holds for any γ\boldsymbol\gamma, any g\mathbf g and any ϵ\epsilon.

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).