Skip to content

14.5 Matrix calculus problem set: differentials, trace trick, VJPs, SDPA Jacobian

By now you have a scalar autograd engine, Scalar reverse mode: the Value graph, that differentiates one number at a time. It is correct and hopeless at scale: applying one 576×576576 \times 576 weight to one vector would create a third of a million scalar multiplication nodes. Matrix differentials, the trace trick, and closed-form VJPs replaces it with closed-form vector-Jacobian products, one per operation, that take the upstream gradient as an array and return the input gradients as arrays, and The op library and gradcheck_all in AI Engineering registers them as the ops of the tensor autograd. Each closed form is a derivation to get right on paper first, because a gradient with the right shape and the wrong value trains, slowly and badly, rather than crashing.

Concepts from other sections (30)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

This problem set drills exactly those derivations: the shape bookkeeping, matrix differentials, the trace trick, the VJPs of softmax, log-softmax, cross-entropy, LayerNorm, and RMSNorm, the cost model of forward and reverse mode, and the attention backward that returns in Scaled dot-product attention (forward and backward) and in FlashAttention. It is a pen-and-paper set with no code to write. Every problem is followed by a collapsed worked answer with the final result, the derivation, and the common wrong answers and why they are wrong; 42 answers in all, counting lettered parts, including four proofs (q16, q20, q28, q34) whose model derivations are also in course/solutions/solve/S-M08/. Try each problem before opening its answer.

The proofs assume the habits of the Discrete math 1 problem set, and the set leans on the gradients and chain rule of the Calculus 3 problem set. The opening of this chapter, Matrix Calculus and Autodiff, gives the wider picture.

Learning objectives

  • Give the shape of any gradient and the strides of any row-major view, and turn broadcasting into a backward sum.
  • Differentiate matrix expressions with the product rule and read off gradients with the trace trick.
  • Compute the VJPs of matmul, softmax, log-softmax, cross-entropy, LayerNorm, and RMSNorm by hand, and check them with their invariances.
  • Count the passes, bytes, and FLOPs of forward and reverse mode.
  • Derive the backward of scaled dot-product attention from the matmul and softmax rules.

The problems use a small set of symbols, collected here.

SymbolMeaningType / shape
LLa scalar lossscalar
X∈Rm×kX \in \mathbb{R}^{m \times k}, W∈Rk×nW \in \mathbb{R}^{k \times n}matrices; Y=XW∈Rm×nY = XW \in \mathbb{R}^{m \times n}
G=∂L/∂YG = \partial L / \partial Yupstream gradient, same shape as YYm×nm \times n
dXdXdifferential: first-order change of XXlike XX
tr⁡(A)\operatorname{tr}(A)trace, ∑iAii\sum_i A_{ii}scalar
⟨A,B⟩\langle A, B \rangleFrobenius inner product, tr⁡(A⊤B)=∑ijAijBij\operatorname{tr}(A^\top B) = \sum_{ij} A_{ij} B_{ij}scalar
⊙\odotelementwise product
JfJ_fJacobian of f:Rn→Rmf: \mathbb{R}^n \to \mathbb{R}^m, (Jf)ij=∂fi/∂xj(J_f)_{ij} = \partial f_i / \partial x_jm×nm \times n
softmax(x)i\mathrm{softmax}(x)_iexi/∑kexke^{x_i} / \sum_k e^{x_k}vector
δij\delta_{ij}1 if i=ji = j, else 0
1\mathbf{1}the all-ones vector

The convention in this book (and in PyTorch) is the denominator layout: ∂L/∂X\partial L/\partial X has the shape of XX, entry by entry (∂L/∂X)ij=∂L/∂Xij(\partial L/\partial X)_{ij} = \partial L/\partial X_{ij}. A row-major array of shape (n0,n1,n2)(n_0, n_1, n_2) stores index (i,j,k)(i, j, k) at element offset i s0+j s1+k s2i\,s_0 + j\,s_1 + k\,s_2 with strides s=(n1n2,n2,1)s = (n_1 n_2, n_2, 1). A view reinterprets the same memory with other strides: swapping two axes swaps their strides and copies nothing. Broadcasting reuses one value along an axis; its backward is a sum over that axis, which the unbroadcast of the tensor engine in Tensor, broadcasting backward, and no_grad performs. A Jacobian of a map from Rn\mathbb{R}^n to Rm\mathbb{R}^m is m×nm \times n, which for a layer is enormous; reverse mode never builds it.

With shapes settled, the next tool is the differential. The differential of FF at XX is the linear part of F(X+dX)−F(X)F(X + dX) - F(X). It obeys the rules you know for scalars, with the order of factors kept: d(A+B)=dA+dBd(A + B) = dA + dB, d(AB)=(dA)B+A(dB)d(AB) = (dA)B + A(dB), d(A⊤)=(dA)⊤d(A^\top) = (dA)^\top, dtr⁡(A)=tr⁡(dA)d\operatorname{tr}(A) = \operatorname{tr}(dA), and d(X−1)=−X−1(dX)X−1d(X^{-1}) = -X^{-1}(dX)X^{-1} (q16). For log⁡det⁡X\log \det X the result is tr⁡(X−1dX)\operatorname{tr}(X^{-1} dX). For an elementwise function y=f(x)y = f(x), dy=f′(x)⊙dxdy = f'(x) \odot dx, so its Jacobian is diagonal.

A differential becomes a gradient through the trace. For a scalar LL of a matrix MM, dL=∑ij∂L∂Mij dMij=⟨∂L/∂M,dM⟩=tr⁡((∂L/∂M)⊤dM)dL = \sum_{ij} \frac{\partial L}{\partial M_{ij}}\, dM_{ij} = \langle \partial L/\partial M, dM \rangle = \operatorname{tr}((\partial L/\partial M)^\top dM). So once dLdL is written as tr⁡(N⊤dM)\operatorname{tr}(N^\top dM), the gradient is NN. The tool for getting there is the cyclic property: tr⁡(ABC)=tr⁡(BCA)=tr⁡(CAB)\operatorname{tr}(ABC) = \operatorname{tr}(BCA) = \operatorname{tr}(CAB) whenever the products are defined (a cyclic shift, never an arbitrary swap), together with tr⁡(A⊤)=tr⁡(A)\operatorname{tr}(A^\top) = \operatorname{tr}(A). A scalar is its own trace, so any scalar expression may be wrapped in one.

A vector-Jacobian product maps an upstream gradient g=∂L/∂yg = \partial L/\partial y to ∂L/∂x=J⊤g\partial L/\partial x = J^\top g without forming JJ. The table lists the ones implemented in Matrix differentials, the trace trick, and closed-form VJPs.

OpForwardVJP
matmulY=XWY = XW∂L/∂X=GW⊤\partial L/\partial X = G W^\top, ∂L/∂W=X⊤G\partial L/\partial W = X^\top G
softmaxy=softmax(x)y = \mathrm{softmax}(x)y⊙(g−⟨g,y⟩1)y \odot (g - \langle g, y \rangle \mathbf{1})
log-softmaxℓ=x−LSE(x)\ell = x - \mathrm{LSE}(x)g−softmax(x)∑igig - \mathrm{softmax}(x) \sum_i g_i
cross-entropyL=−log⁡softmax(z)tL = -\log \mathrm{softmax}(z)_tsoftmax(z)−et\mathrm{softmax}(z) - e_t; a mean over NN kept positions divides by NN
RMSNormy=w⊙x/ry = w \odot x / r, r=1n∑xi2+ϵr = \sqrt{\tfrac1n \sum x_i^2 + \epsilon}w⊙gr−x ⟨w⊙g,x⟩nr3\frac{w \odot g}{r} - x\,\frac{\langle w \odot g, x\rangle}{n r^3}
LayerNormx^=(x−μ)/σ\hat x = (x - \mu)/\sigma, y=γ⊙x^+βy = \gamma \odot \hat x + \betawith g^=γ⊙g\hat g = \gamma \odot g: 1σ(g^−g^‾−x^ g^⊙x^‾)\frac{1}{\sigma}\left(\hat g - \overline{\hat g} - \hat x\, \overline{\hat g \odot \hat x}\right)

Here v‾\overline{v} is the mean of the entries of vv, μ\mu the mean of xx, σ=1n∑(xi−μ)2+ϵ\sigma = \sqrt{\tfrac1n \sum (x_i - \mu)^2 + \epsilon}, and ete_t the one-hot vector of the target. LayerNorm and RMSNorm are functions of a whole row: LayerNorm centers and scales it to mean 0 and variance 1, RMSNorm only scales it to root-mean-square 1, and both then apply a learned gain. Because each normalizes by a statistic of its own input, the gradient has a correction term that a “treat the statistic as constant” derivation misses. Two checks catch it: LayerNorm’s input gradient sums to zero (shifting xx changes nothing), and RMSNorm’s is orthogonal to xx when ϵ=0\epsilon = 0 (scaling xx changes nothing).

Which mode to run is a question of counting. For f:Rn→Rmf: \mathbb{R}^n \to \mathbb{R}^m, forward mode (the dual numbers of Dual numbers and forward-mode autodiff) computes one Jacobian-vector product JvJ v per pass, so the full Jacobian takes nn passes. Reverse mode computes one J⊤uJ^\top u per pass, so it takes mm. A loss has m=1m = 1: one backward pass gives the gradient with respect to every parameter, at the price of storing the forward activations it needs. For a matrix product the backward computes two products of the same size as the forward one, so backward costs about twice the forward FLOPs, and a training step about three times: the 6N6N per token of q13 in the Discrete math 1 problem set.

Everything above comes together in attention. Scaled dot-product attention (SDPA) for TT positions computes scores S=QK⊤/dS = QK^\top/\sqrt{d}, weights P=softmax(S)P = \mathrm{softmax}(S) along each row, and output O=PVO = PV. Its backward chains the three rules above: matmul for O=PVO = PV, softmax row by row, matmul again for SS (q34).

Before the set itself, two warm-ups. They are siblings of q21 and q24, not problems of the set.

Softmax VJP. Let x=(0,0)x = (0, 0), so y=softmax(x)=(1/2,1/2)y = \mathrm{softmax}(x) = (1/2, 1/2), and let the upstream gradient be g=(1,3)g = (1, 3). Then ⟨g,y⟩=1⋅12+3⋅12=2\langle g, y \rangle = 1 \cdot \tfrac12 + 3 \cdot \tfrac12 = 2, so g−2⋅1=(−1,1)g - 2 \cdot \mathbf{1} = (-1, 1) and ∂L/∂x=y⊙(−1,1)=(−1/2,1/2)\partial L/\partial x = y \odot (-1, 1) = (-1/2, 1/2).

Check against the Jacobian: for two classes J=(y1(1−y1)−y1y2−y1y2y2(1−y2))=(1/4−1/4−1/41/4)J = \begin{pmatrix} y_1(1-y_1) & -y_1 y_2 \\ -y_1 y_2 & y_2(1 - y_2)\end{pmatrix} = \begin{pmatrix} 1/4 & -1/4 \\ -1/4 & 1/4 \end{pmatrix}, and J⊤g=(1/4−3/4, −1/4+3/4)=(−1/2,1/2)J^\top g = (1/4 - 3/4,\ -1/4 + 3/4) = (-1/2, 1/2). The entries sum to 0, as every softmax input gradient must.

Cross-entropy. Logits z=(log⁡3,0)z = (\log 3, 0), target class 0. Then softmax(z)=(3/4,1/4)\mathrm{softmax}(z) = (3/4, 1/4), L=−log⁡(3/4)=log⁡(4/3)L = -\log(3/4) = \log(4/3), and ∂L/∂z=(3/4−1,1/4−0)=(−1/4,1/4)\partial L/\partial z = (3/4 - 1, 1/4 - 0) = (-1/4, 1/4): lower the wrong logit, raise the right one, by how far the prediction is from the target.

Vectors are flat lists; matrices are lists of rows. A gradient answer has the variable’s shape. Answers are exact (2\sqrt2, ee), not decimals. Lettered parts are answered separately. The tag after each problem names the form the answer takes.

The first four problems are bookkeeping: before any derivative, you need to know what shape each gradient has and how arrays sit in memory.

A linear layer computes Y=XW⊤+bY = X W^\top + b for a batch XX of shape (B,T,din)=(2,3,4)(B, T, d_{in}) = (2, 3, 4), stored row-major in float32, with WW of shape (dout,din)=(5,4)(d_{out}, d_{in}) = (5, 4) and bb of shape (5)(5). LL is a scalar loss.

q1. Give the shape of (a) YY, (b) ∂L/∂W\partial L / \partial W, (c) ∂L/∂b\partial L / \partial b. [vector]

Answer

(a) (2,3,5)(2, 3, 5). (b) (5,4)(5, 4). (c) (5)(5). (a) The last axis din=4d_{in} = 4 is contracted against W⊤W^\top of shape (4,5)(4, 5), leaving (B,T,dout)(B, T, d_{out}). (b) A gradient has its variable’s shape, so ∂L/∂W\partial L/\partial W is (5,4)(5, 4) like WW. (c) Likewise (5)(5) like bb: the forward pass broadcast bb over BB and TT, so the backward sums those axes away (q3). Common mistakes: (2,3,4)(2, 3, 4) for (a), the input width; (4,5)(4, 5) for (b), the transpose; (2,3,5)(2, 3, 5) for (c), forgetting to sum over the broadcast axes.

q2. (a) At which element offset (counting from 0) is X[1,2,1]X[1, 2, 1] stored? [number] (b) Give the strides of XX in elements, one per axis. [vector] (c) Give the strides of the view that swaps the last two axes of XX (shape (2,4,3)(2, 4, 3), no copy). [vector]

Answer

(a) 2121. (b) (12,4,1)(12, 4, 1). (c) (12,1,4)(12, 1, 4). (b) Row-major strides are the products of the trailing dimensions: (3⋅4,4,1)(3 \cdot 4, 4, 1). (a) Offset =1⋅12+2⋅4+1⋅1=21= 1 \cdot 12 + 2 \cdot 4 + 1 \cdot 1 = 21. (c) A view that swaps the last two axes swaps their strides and copies nothing: (12,1,4)(12, 1, 4), now non-contiguous. Common mistakes: 1111 for (a), the column-major offset 1+2⋅2+1⋅61 + 2 \cdot 2 + 1 \cdot 6; (48,16,4)(48, 16, 4) for (b), strides in bytes rather than elements; (1,2,6)(1, 2, 6), column-major strides; (12,3,1)(12, 3, 1) for (c), the strides a fresh contiguous copy of shape (2,4,3)(2, 4, 3) would have.

q3. bb is broadcast over the batch and time axes. How many entries of ∂L/∂Y\partial L / \partial Y are summed into each entry of ∂L/∂b\partial L / \partial b? [number]

Answer

66. bjb_j is added to Y[i,t,j]Y[i, t, j] for every (i,t)(i, t), B⋅T=2⋅3B \cdot T = 2 \cdot 3 entries, so ∂L/∂bj=∑i,t∂L/∂Y[i,t,j]\partial L/\partial b_j = \sum_{i,t} \partial L/\partial Y[i, t, j]: six terms. Common mistakes: 3030, every entry of YY; 22, summing over the batch axis only.

q4. Flatten XX and YY row-major into vectors. What is the shape of the Jacobian ∂ vec(Y)/∂ vec(X)\partial\, \mathrm{vec}(Y) / \partial\, \mathrm{vec}(X) (rows, columns)? [vector]

Answer

(30,24)(30, 24). A Jacobian has one row per output and one column per input: vec(Y)\mathrm{vec}(Y) has 2⋅3⋅5=302 \cdot 3 \cdot 5 = 30 entries and vec(X)\mathrm{vec}(X) has 2⋅3⋅4=242 \cdot 3 \cdot 4 = 24. Nobody builds this matrix (for a real layer it is enormous and mostly zeros); VJPs exist so that you never do. Common mistake: (24,30)(24, 30), (inputs, outputs).

The next group practices the differential rules on small expressions, ending with the proof of the inverse rule that q8 uses.

q5. f(x)=x⊤Axf(x) = x^\top A x with A=(1203)A = \begin{pmatrix} 1 & 2 \\ 0 & 3 \end{pmatrix} and x=(x1,x2)x = (x_1, x_2). Give ∇f\nabla f. [vector in x1, x2]

Answer

(2x1+2x2, 2x1+6x2)(2x_1 + 2x_2,\ 2x_1 + 6x_2). df=dx⊤Ax+x⊤A dx=x⊤(A⊤+A) dxdf = dx^\top A x + x^\top A\,dx = x^\top(A^\top + A)\,dx, so ∇f=(A+A⊤)x\nabla f = (A + A^\top)x, and A+A⊤=(2226)A + A^\top = \begin{pmatrix} 2 & 2 \\ 2 & 6 \end{pmatrix}. Common mistakes: 2Ax=(2x1+4x2,6x2)2Ax = (2x_1 + 4x_2, 6x_2), the formula that holds only for symmetric AA; AxAx, dropping one of the two terms of the product rule.

q6. f(X)=tr⁡(AX)f(X) = \operatorname{tr}(AX) with A=(1234)A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}. Give ∇Xf\nabla_X f. [matrix]

Answer

(1324)=A⊤\begin{pmatrix} 1 & 3 \\ 2 & 4 \end{pmatrix} = A^\top. df=tr⁡(A dX)=tr⁡((A⊤)⊤dX)df = \operatorname{tr}(A\,dX) = \operatorname{tr}((A^\top)^\top dX), so the trace trick reads off ∇Xf=A⊤\nabla_X f = A^\top. Entry by entry: tr⁡(AX)=∑ijAijXji\operatorname{tr}(AX) = \sum_{ij} A_{ij}X_{ji}, so ∂f/∂Xji=Aij\partial f/\partial X_{ji} = A_{ij}. Common mistake: AA itself.

q7. f(x)=∥Ax−b∥2f(x) = \lVert Ax - b \rVert^2 with A=(1011)A = \begin{pmatrix} 1 & 0 \\ 1 & 1 \end{pmatrix}, b=(1,0)b = (1, 0). Give ∇f\nabla f at x=(1,2)x = (1, 2). [vector]

Answer

(6,6)(6, 6). With r=Ax−br = Ax - b, f=r⊤rf = r^\top r, df=2r⊤A dxdf = 2r^\top A\,dx, so ∇f=2A⊤(Ax−b)\nabla f = 2A^\top(Ax - b). At x=(1,2)x = (1, 2): Ax=(1,3)Ax = (1, 3), r=(0,3)r = (0, 3), A⊤r=(0+3,0+3)=(3,3)A^\top r = (0 + 3, 0 + 3) = (3, 3), times 2. Common mistakes: (3,3)(3, 3), dropping the 2 from the square; (0,6)=2(Ax−b)(0, 6) = 2(Ax - b), forgetting the A⊤A^\top that the chain rule brings in.

q8. X(t)=(2t11)X(t) = \begin{pmatrix} 2 & t \\ 1 & 1 \end{pmatrix}. Give ddtX(t)−1\frac{d}{dt} X(t)^{-1} at t=0t = 0. [matrix]

Answer

(1/4−1/2−1/41/2)\begin{pmatrix} 1/4 & -1/2 \\ -1/4 & 1/2 \end{pmatrix}. Use d(X−1)=−X−1(dX)X−1d(X^{-1}) = -X^{-1}(dX)X^{-1} (q16) with X(0)=(2011)X(0) = \begin{pmatrix} 2 & 0 \\ 1 & 1 \end{pmatrix}, X(0)−1=(1/20−1/21)X(0)^{-1} = \begin{pmatrix} 1/2 & 0 \\ -1/2 & 1 \end{pmatrix}, and X˙=(0100)\dot X = \begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix}. Then X−1X˙=(01/20−1/2)X^{-1}\dot X = \begin{pmatrix} 0 & 1/2 \\ 0 & -1/2 \end{pmatrix}, times X−1X^{-1} gives (−1/41/21/4−1/2)\begin{pmatrix} -1/4 & 1/2 \\ 1/4 & -1/2 \end{pmatrix}, and the minus sign flips it. Common mistakes: the same matrix with the sign lost; −X˙=(0−100)-\dot X = \begin{pmatrix} 0 & -1 \\ 0 & 0 \end{pmatrix}, as if X−1X^{-1} were II.

q9. Give ∇Xlog⁡det⁡X\nabla_X \log \det X at X=(2103)X = \begin{pmatrix} 2 & 1 \\ 0 & 3 \end{pmatrix}. [matrix]

Answer

X−⊤=(1/20−1/61/3)X^{-\top} = \begin{pmatrix} 1/2 & 0 \\ -1/6 & 1/3 \end{pmatrix}. dlog⁡det⁡X=tr⁡(X−1dX)=tr⁡((X−⊤)⊤dX)d\log\det X = \operatorname{tr}(X^{-1}dX) = \operatorname{tr}((X^{-\top})^\top dX), so the gradient is X−⊤X^{-\top}. Here det⁡X=6\det X = 6 and X−1=16(3−102)=(1/2−1/601/3)X^{-1} = \frac16\begin{pmatrix} 3 & -1 \\ 0 & 2 \end{pmatrix} = \begin{pmatrix} 1/2 & -1/6 \\ 0 & 1/3 \end{pmatrix}; transpose it. Common mistake: X−1X^{-1}, not transposed (the two differ whenever XX is not symmetric).

q10. f(W)=∥Wx∥2f(W) = \lVert W x \rVert^2 with x=(1,2)x = (1, 2). Give ∇Wf\nabla_W f at W=I2W = I_2. [matrix]

Answer

(2448)\begin{pmatrix} 2 & 4 \\ 4 & 8 \end{pmatrix}. f=(Wx)⊤(Wx)f = (Wx)^\top(Wx), so df=2(Wx)⊤dW x=tr⁡(2x(Wx)⊤dW)df = 2(Wx)^\top dW\,x = \operatorname{tr}(2x(Wx)^\top dW) and ∇Wf=2(Wx)x⊤\nabla_W f = 2(Wx)x^\top. At W=IW = I this is 2xx⊤2xx^\top with x=(1,2)x = (1, 2). Common mistake: xx⊤xx^\top, dropping the 2.

q11. Give the derivative of the sigmoid σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}. [expr in z]

Answer

σ′(z)=e−z(1+e−z)2=σ(z)(1−σ(z))\sigma'(z) = \dfrac{e^{-z}}{(1 + e^{-z})^2} = \sigma(z)(1 - \sigma(z)). Chain rule on (1+e−z)−1(1 + e^{-z})^{-1}: −(1+e−z)−2⋅(−e−z)-(1 + e^{-z})^{-2} \cdot (-e^{-z}). The second form follows from 1−σ=e−z/(1+e−z)1 - \sigma = e^{-z}/(1 + e^{-z}), and is the one The op library and gradcheck_all uses because it reuses the forward output. Common mistakes: σ(z)\sigma(z) itself; the same fraction with a minus sign, losing the sign of the inner derivative −e−z-e^{-z}.

q12. Give the derivative of softplus, f(z)=log⁡(1+ez)f(z) = \log(1 + e^z). [expr in z]

Answer

σ(z)=11+e−z\sigma(z) = \dfrac{1}{1 + e^{-z}}. ddzlog⁡(1+ez)=ez1+ez\frac{d}{dz}\log(1 + e^z) = \frac{e^z}{1 + e^z}; divide top and bottom by eze^z. Softplus is the integral of the sigmoid. Common mistake: 1/(1+ez)=σ(−z)1/(1 + e^z) = \sigma(-z).

q13. Give the gradient of LSE(x1,x2)=log⁡(ex1+ex2)\mathrm{LSE}(x_1, x_2) = \log(e^{x_1} + e^{x_2}). [vector in x1, x2]

Answer

(ex1ex1+ex2, ex2ex1+ex2)=softmax(x)\left(\dfrac{e^{x_1}}{e^{x_1} + e^{x_2}},\ \dfrac{e^{x_2}}{e^{x_1} + e^{x_2}}\right) = \mathrm{softmax}(x). ∂/∂xi\partial/\partial x_i of log⁡Z\log Z is (∂Z/∂xi)/Z=exi/Z(\partial Z/\partial x_i)/Z = e^{x_i}/Z. The gradient of log-sum-exp is softmax, which Stable numerics: logsumexp, softmax, and compensated sums and Losses with a fused backward rest on. Common mistake: (ex1,ex2)(e^{x_1}, e^{x_2}), forgetting the derivative of the outer log.

q14. Give the gradient of f(x)=∥x∥2f(x) = \lVert x \rVert_2 at x=(3,4)x = (3, 4). [vector]

Answer

(3/5,4/5)(3/5, 4/5). ∥x∥=(x⊤x)1/2\lVert x\rVert = (x^\top x)^{1/2}, so ∇∥x∥=12(x⊤x)−1/2⋅2x=x/∥x∥\nabla\lVert x\rVert = \frac12(x^\top x)^{-1/2} \cdot 2x = x/\lVert x\rVert: the unit vector, with ∥(3,4)∥=5\lVert(3, 4)\rVert = 5. Common mistake: (6,8)=2x(6, 8) = 2x, the gradient of the squared norm.

q15. Give the Jacobian of elementwise ReLU\mathrm{ReLU} at x=(−1,2,1/2)x = (-1, 2, 1/2). [matrix]

Answer

diag⁡(0,1,1)\operatorname{diag}(0, 1, 1). An elementwise function has a diagonal Jacobian with f′(xi)f'(x_i) on the diagonal; ReLU′\mathrm{ReLU}' is 0 for negative inputs and 1 for positive ones. Common mistakes: diag⁡(0,2,1/2)\operatorname{diag}(0, 2, 1/2), the outputs on the diagonal instead of the slopes; a matrix of ones, as if each output depended on every input.

q16. Prove d(X−1)=−X−1(dX)X−1d(X^{-1}) = -X^{-1} (dX) X^{-1} for an invertible square matrix XX. [proof]

Answer

Claim. For an invertible n×nn \times n matrix XX, d(X−1)=−X−1(dX)X−1d(X^{-1}) = -X^{-1}(dX)X^{-1}.

Proof. The differential obeys the product rule d(AB)=(dA)B+A(dB)d(AB) = (dA)B + A(dB) (expand (A+dA)(B+dB)(A + dA)(B + dB) and drop the second-order dA dBdA\,dB), with the order of the factors kept because matrices do not commute. XX−1=IXX^{-1} = I for every invertible XX near the current one, and dI=0dI = 0, so (dX)X−1+X d(X−1)=0.(dX)X^{-1} + X\,d(X^{-1}) = 0 . Hence X d(X−1)=−(dX)X−1X\,d(X^{-1}) = -(dX)X^{-1}, and multiplying on the left by X−1X^{-1}, d(X−1)=−X−1(dX)X−1.d(X^{-1}) = -X^{-1}(dX)X^{-1} . For n=1n = 1 this is d(1/x)=−dx/x2d(1/x) = -dx/x^2. Entry by entry, ∂(X−1)ij/∂Xkl=−(X−1)ik(X−1)lj\partial(X^{-1})_{ij}/\partial X_{kl} = -(X^{-1})_{ik}(X^{-1})_{lj}.

A complete derivation starts from XX−1=IXX^{-1} = I, uses the product rule and dI=0dI = 0, and keeps the non-commuting order when solving. Model derivation also in q16.md.

These problems turn the differential into a gradient with the cyclic property, ending with the proof of the matmul VJP.

q17. For conformable matrices: (a) is tr⁡(ABC)=tr⁡(CAB)\operatorname{tr}(ABC) = \operatorname{tr}(CAB) always? (b) Is tr⁡(ABC)=tr⁡(BAC)\operatorname{tr}(ABC) = \operatorname{tr}(BAC) always? [bool]

Answer

(a) Yes. (b) No. (a) CABCAB is a cyclic shift of ABCABC, and tr⁡(MN)=tr⁡(NM)\operatorname{tr}(MN) = \operatorname{tr}(NM) with M=ABM = AB, N=CN = C gives it. (b) BACBAC swaps two factors without rotating; for example A=(0100)A = \begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix}, B=A⊤B = A^\top, C=(1000)C = \begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix} give tr⁡(ABC)=1\operatorname{tr}(ABC) = 1 but tr⁡(BAC)=0\operatorname{tr}(BAC) = 0. The trace is invariant under cyclic shifts only.

q18. Y=XWY = XW with X=(1234)X = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}, W=(1102)W = \begin{pmatrix} 1 & 1 \\ 0 & 2 \end{pmatrix}, and upstream gradient G=∂L/∂Y=I2G = \partial L / \partial Y = I_2. Give (a) ∂L/∂W\partial L / \partial W and (b) ∂L/∂X\partial L / \partial X. [matrix]

Answer

(a) (1324)\begin{pmatrix} 1 & 3 \\ 2 & 4 \end{pmatrix}. (b) (1012)\begin{pmatrix} 1 & 0 \\ 1 & 2 \end{pmatrix}. By q20, ∂L/∂W=X⊤G=X⊤\partial L/\partial W = X^\top G = X^\top and ∂L/∂X=GW⊤=W⊤\partial L/\partial X = GW^\top = W^\top when G=IG = I. The matmul_vjp of Matrix differentials, the trace trick, and closed-form VJPs returns exactly these two. Common mistakes: GX=XGX = X for (a), the factors in the wrong order and untransposed; the ∂L/∂X\partial L/\partial X answer given for (a); GW=WGW = W for (b), forgetting the transpose.

q19. The Frobenius inner product is ⟨A,B⟩=tr⁡(A⊤B)\langle A, B \rangle = \operatorname{tr}(A^\top B). Give it for A=(1234)A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}, B=(0110)B = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}. [number]

Answer

55. ⟨A,B⟩=∑ijAijBij\langle A, B\rangle = \sum_{ij}A_{ij}B_{ij}; BB picks out the off-diagonal entries, 2+32 + 3. Common mistakes: 0=tr⁡(A)tr⁡(B)0 = \operatorname{tr}(A)\operatorname{tr}(B), which is not the inner product; 1010, the sum of AA‘s entries.

q20. Let Y=XWY = XW and LL a scalar with dL=tr⁡(G⊤dY)dL = \operatorname{tr}(G^\top dY), G=∂L/∂YG = \partial L / \partial Y. Prove ∂L/∂W=X⊤G\partial L / \partial W = X^\top G and ∂L/∂X=GW⊤\partial L / \partial X = G W^\top. [proof]

Answer

Claim. If Y=XWY = XW and dL=tr⁡(G⊤dY)dL = \operatorname{tr}(G^\top dY) with G=∂L/∂YG = \partial L/\partial Y, then ∂L/∂W=X⊤G\partial L/\partial W = X^\top G and ∂L/∂X=GW⊤\partial L/\partial X = GW^\top.

Proof. For a scalar LL of a matrix MM, dL=∑ij∂L∂MijdMij=tr⁡((∂L/∂M)⊤dM)dL = \sum_{ij}\frac{\partial L}{\partial M_{ij}}dM_{ij} = \operatorname{tr}((\partial L/\partial M)^\top dM), so once dLdL is written as tr⁡(N⊤dM)\operatorname{tr}(N^\top dM) the gradient is NN (unique, because the dMijdM_{ij} are independent). By the product rule dY=(dX)W+X(dW)dY = (dX)W + X(dW), and by linearity of the trace dL=tr⁡(G⊤(dX)W)+tr⁡(G⊤X dW).dL = \operatorname{tr}(G^\top(dX)W) + \operatorname{tr}(G^\top X\,dW). Second term: tr⁡(G⊤X dW)=tr⁡((X⊤G)⊤dW)\operatorname{tr}(G^\top X\,dW) = \operatorname{tr}((X^\top G)^\top dW), so ∂L/∂W=X⊤G\partial L/\partial W = X^\top G. First term: by the cyclic property, tr⁡(G⊤(dX)W)=tr⁡(WG⊤dX)=tr⁡((GW⊤)⊤dX)\operatorname{tr}(G^\top(dX)W) = \operatorname{tr}(WG^\top dX) = \operatorname{tr}((GW^\top)^\top dX), so ∂L/∂X=GW⊤\partial L/\partial X = GW^\top.

Shapes check: XX is m×km \times k, WW is k×nk \times n, GG is m×nm \times n; X⊤GX^\top G is k×nk \times n like WW, and GW⊤GW^\top is m×km \times k like XX. A complete derivation writes dYdY by the product rule, splits the trace, rotates each term into tr⁡(N⊤dM)\operatorname{tr}(N^\top dM) form, and reads off both gradients. Model derivation also in q20.md.

Now the rules the op library registers, each on numbers small enough to check by hand, ending with the proof of the softmax VJP.

q21. y=softmax(x)=(1/2,1/4,1/4)y = \mathrm{softmax}(x) = (1/2, 1/4, 1/4) and the upstream gradient is g=(1,0,0)g = (1, 0, 0). Give ∂L/∂x\partial L / \partial x. [vector]

Answer

(1/4,−1/8,−1/8)(1/4, -1/8, -1/8). ⟨g,y⟩=1/2\langle g, y\rangle = 1/2, g−121=(12,−12,−12)g - \frac12\mathbf 1 = (\frac12, -\frac12, -\frac12), and multiplying by yy gives the answer. The entries sum to 0, as every softmax input gradient must. Common mistakes: (1/2,0,0)=y⊙g(1/2, 0, 0) = y \odot g, dropping the ⟨g,y⟩\langle g, y\rangle term; (1/2,−1/4,−1/4)=g−y(1/2, -1/4, -1/4) = g - y, which confuses softmax with cross-entropy.

q22. Give the Jacobian ∂y/∂x\partial y / \partial x of a 2-class softmax at y=(1/4,3/4)y = (1/4, 3/4). [matrix]

Answer

(3/16−3/16−3/163/16)\begin{pmatrix} 3/16 & -3/16 \\ -3/16 & 3/16 \end{pmatrix}. J=diag⁡(y)−yy⊤J = \operatorname{diag}(y) - yy^\top, entry yi(δij−yj)y_i(\delta_{ij} - y_j): diagonal yi(1−yi)=14⋅34y_i(1 - y_i) = \frac14 \cdot \frac34, off-diagonal −y1y2=−316-y_1y_2 = -\frac3{16}. Rows sum to 0 because softmax ignores a common shift. Common mistakes: diag⁡(y)\operatorname{diag}(y), dropping yy⊤yy^\top; all entries +3/16+3/16, losing the off-diagonal minus.

q23. ℓ=log_softmax(x)\ell = \mathrm{log\_softmax}(x) with softmax(x)=(1/2,1/4,1/4)\mathrm{softmax}(x) = (1/2, 1/4, 1/4) and upstream gradient g=(0,1,0)g = (0, 1, 0). Give ∂L/∂x\partial L / \partial x. [vector]

Answer

(−1/2,3/4,−1/4)(-1/2, 3/4, -1/4). The log-softmax VJP is g−softmax(x)∑igig - \mathrm{softmax}(x)\sum_i g_i; ∑igi=1\sum_i g_i = 1, so it is (0,1,0)−(12,14,14)(0, 1, 0) - (\frac12, \frac14, \frac14). Common mistakes: (0,3/4,0)=g−y⊙g(0, 3/4, 0) = g - y \odot g, mixing the softmax and log-softmax rules; the same vector with the sign flipped.

q24. Cross-entropy with logits z=(0,log⁡2,log⁡2)z = (0, \log 2, \log 2) and target class 1 (counting from 0): L=−log⁡softmax(z)1L = -\log \mathrm{softmax}(z)_1. (a) Give ∂L/∂z\partial L / \partial z. [vector] (b) Give LL. [number]

Answer

(a) (1/5,−3/5,2/5)(1/5, -3/5, 2/5). (b) log⁡(5/2)\log(5/2). ez=(1,2,2)e^z = (1, 2, 2), sum 5, so softmax(z)=(1/5,2/5,2/5)\mathrm{softmax}(z) = (1/5, 2/5, 2/5). (a) Softmax minus the one-hot of class 1: (1/5,2/5−1,2/5)(1/5, 2/5 - 1, 2/5). (b) L=−log⁡(2/5)=log⁡(5/2)≈0.916L = -\log(2/5) = \log(5/2) \approx 0.916. Common mistakes: (1/5,2/5,2/5)(1/5, 2/5, 2/5), forgetting the one-hot; (−1/5,3/5,−2/5)(-1/5, 3/5, -2/5), one-hot minus softmax, which is the gradient of the log-likelihood and makes descent climb the loss; log⁡(2/5)\log(2/5), the minus sign missing (a negative loss); 2/52/5, the probability rather than the loss.

q25. A batch has 4 positions; one has the target ignore_index and the loss is the mean over the other positions. By what factor is each kept position’s per-position gradient softmax(z)−onehot(y)\mathrm{softmax}(z) - \mathrm{onehot}(y) scaled? [number]

Answer

1/31/3. The mean is over the N=3N = 3 kept positions, so each kept per-position gradient is divided by 3, and the ignored position contributes nothing. Common mistake: 1/41/4, dividing by all positions including the ignored one, which scales the gradient down by the padding fraction.

q26. RMSNorm with ϵ=0\epsilon = 0: y=w⊙x/ry = w \odot x / r, r=1n∑ixi2r = \sqrt{\frac{1}{n} \sum_i x_i^2}. (a) For x=(3,4)x = (3, 4), w=(1,1)w = (1, 1), and upstream g=(1,0)g = (1, 0), give ∂L/∂x\partial L / \partial x. [vector] (b) Is x⋅∂L/∂x=0x \cdot \partial L / \partial x = 0 for every gg and every ww? [bool]

Answer

(a) (162125,−122125)\left(\dfrac{16\sqrt2}{125}, -\dfrac{12\sqrt2}{125}\right). (b) Yes. (a) r=(9+16)/2=5/2r = \sqrt{(9 + 16)/2} = 5/\sqrt2, w⊙g=(1,0)w \odot g = (1, 0), ⟨w⊙g,x⟩=3\langle w \odot g, x\rangle = 3, and nr3=2⋅12522=1252nr^3 = 2 \cdot \frac{125}{2\sqrt2} = \frac{125}{\sqrt2}. First term: (1,0)/r=(25,0)=(252125,0)(1, 0)/r = (\frac{\sqrt2}5, 0) = (\frac{25\sqrt2}{125}, 0). Correction: x⋅32125=(92125,122125)x \cdot \frac{3\sqrt2}{125} = (\frac{9\sqrt2}{125}, \frac{12\sqrt2}{125}). Subtract. (b) x⋅∂L/∂x=⟨w⊙g,x⟩r−∥x∥2⟨w⊙g,x⟩nr3x \cdot \partial L/\partial x = \frac{\langle w \odot g, x\rangle}{r} - \lVert x\rVert^2\frac{\langle w \odot g, x\rangle}{nr^3}, and ∥x∥2=nr2\lVert x\rVert^2 = nr^2 when ϵ=0\epsilon = 0, so the two terms cancel for every gg and ww. This is scale invariance: y(cx)=y(x)y(cx) = y(x) for c>0c > 0, so the derivative along xx is 0; check (a): 3⋅16−4⋅12=03 \cdot 16 - 4 \cdot 12 = 0. Common mistakes: (2/5,0)(\sqrt2/5, 0), treating rr as a constant; (−92/125,−122/125)(-9\sqrt2/125, -12\sqrt2/125), keeping only the rr-dependent term.

q27. LayerNorm with ϵ=0\epsilon = 0, γ=1\gamma = 1, β=0\beta = 0: y=(x−μ)/σy = (x - \mu)/\sigma with μ\mu the mean and σ2=1n∑i(xi−μ)2\sigma^2 = \frac{1}{n}\sum_i (x_i - \mu)^2. For x=(0,1,2)x = (0, 1, 2) and upstream g=(1,0,0)g = (1, 0, 0), give ∂L/∂x\partial L / \partial x. [vector]

Answer

(612,−66,612)\left(\dfrac{\sqrt6}{12}, -\dfrac{\sqrt6}{6}, \dfrac{\sqrt6}{12}\right). μ=1\mu = 1, σ2=1+0+13=23\sigma^2 = \frac{1 + 0 + 1}3 = \frac23, so 1/σ=3/2=6/21/\sigma = \sqrt{3/2} = \sqrt6/2 and x^=(−3/2,0,3/2)\hat x = (-\sqrt{3/2}, 0, \sqrt{3/2}). With g^=g=(1,0,0)\hat g = g = (1, 0, 0): g^‾=13\overline{\hat g} = \frac13 and g^⊙x^‾=−3/23\overline{\hat g \odot \hat x} = -\frac{\sqrt{3/2}}3, so x^ g^⊙x^‾=(12,0,−12)\hat x\,\overline{\hat g \odot \hat x} = (\frac12, 0, -\frac12). Then g^−g^‾−x^ g^⊙x^‾=(23−12,−13,−13+12)=(16,−13,16)\hat g - \overline{\hat g} - \hat x\,\overline{\hat g \odot \hat x} = (\frac23 - \frac12, -\frac13, -\frac13 + \frac12) = (\frac16, -\frac13, \frac16); multiply by 6/2\sqrt6/2. The entries sum to 0 (shift invariance) and the gradient is orthogonal to x^\hat x (scale invariance). Common mistakes: (6/2,0,0)=g/σ(\sqrt6/2, 0, 0) = g/\sigma, treating both μ\mu and σ\sigma as constants; (6/3,−6/6,−6/6)(\sqrt6/3, -\sqrt6/6, -\sqrt6/6), keeping the mean’s dependence but dropping the variance’s.

q28. Prove the softmax VJP: if y=softmax(x)y = \mathrm{softmax}(x) and g=∂L/∂yg = \partial L / \partial y, then ∂L/∂x=y⊙(g−⟨g,y⟩1)\partial L / \partial x = y \odot (g - \langle g, y \rangle \mathbf{1}). [proof]

Answer

Claim. For y=softmax(x)y = \mathrm{softmax}(x) and g=∂L/∂yg = \partial L/\partial y, ∂L/∂x=y⊙(g−⟨g,y⟩1)\partial L/\partial x = y \odot (g - \langle g, y\rangle\mathbf 1).

Proof. Let Z=∑kexkZ = \sum_k e^{x_k}, so ∂Z/∂xj=exj\partial Z/\partial x_j = e^{x_j}. By the quotient rule, ∂yi∂xj=δijexiZ−exiexjZ2=yi(δij−yj).\frac{\partial y_i}{\partial x_j} = \frac{\delta_{ij}e^{x_i}Z - e^{x_i}e^{x_j}}{Z^2} = y_i(\delta_{ij} - y_j). By the chain rule, (∂L∂x)j=∑igi∂yi∂xj=∑igiyi(δij−yj)=gjyj−yj∑igiyi=yj(gj−⟨g,y⟩).\Bigl(\frac{\partial L}{\partial x}\Bigr)_j = \sum_i g_i\frac{\partial y_i}{\partial x_j} = \sum_i g_iy_i(\delta_{ij} - y_j) = g_jy_j - y_j\sum_i g_iy_i = y_j(g_j - \langle g, y\rangle). In vector form, y⊙(g−⟨g,y⟩1)y \odot (g - \langle g, y\rangle\mathbf 1). It costs O(V)O(V) time and memory and never forms the V×VV \times V Jacobian diag⁡(y)−yy⊤\operatorname{diag}(y) - yy^\top. Its entries sum to ⟨y,g⟩−⟨g,y⟩∑jyj=0\langle y, g\rangle - \langle g, y\rangle\sum_j y_j = 0, as they must, since softmax is unchanged by adding a constant to every xjx_j.

A complete derivation gets the Jacobian from the quotient rule, contracts it with gg, and states the vector form and its cost. Model derivation also in q28.md.

Four short problems on what each mode costs, in passes, bytes, and FLOPs.

q29. A loss f:Rn→Rf: \mathbb{R}^n \to \mathbb{R} has n=106n = 10^6 parameters. How many (a) Jacobian-vector products (forward mode) and (b) vector-Jacobian products (reverse mode) give the full gradient? [number]

Answer

(a) 10610^6. (b) 11. Forward mode gives one column JvJv per pass, so the 1×1061 \times 10^6 Jacobian needs one pass per parameter. Reverse mode gives one row J⊤uJ^\top u per pass, and a scalar loss has one row. This is why training uses reverse mode.

q30. You need the full Jacobian of f:R3→R1000f: \mathbb{R}^3 \to \mathbb{R}^{1000}. Which mode needs fewer passes? (a) forward (b) reverse [choice]

Answer

(a) forward. Forward mode needs one pass per input (3); reverse mode needs one per output (1000). The rule: pick the mode whose count of passes is the smaller dimension.

q31. Backward of a 16-layer MLP stores each layer’s input: a batch of 32 rows of width 1024 in float32. How many bytes of activations does it keep? [number]

Answer

2 097 1522\,097\,152 bytes (2 MiB). 16 layers×32 rows×1024 columns×4 bytes16 \text{ layers} \times 32 \text{ rows} \times 1024 \text{ columns} \times 4 \text{ bytes}. Memory that grows with depth and batch is what the checkpointing of Hessian-vector products and the recompute-versus-memory schedule trades for recompute. Common mistake: 524 288524\,288, counting floats rather than bytes.

q32. Y=XWY = XW with XX of shape m×km \times k and WW of shape k×nk \times n. (a) How many FLOPs does backward take to compute both ∂L/∂X\partial L/\partial X and ∂L/∂W\partial L/\partial W? [expr in m, k, n] (b) What is the ratio (forward + backward) / forward? [number]

Answer

(a) 4mkn4mkn. (b) 33. Forward: XWXW costs 2mkn2mkn FLOPs (mnmn outputs, kk multiply-adds each). Backward computes two products of the same size: GW⊤GW^\top (m×nm \times n times n×kn \times k) and X⊤GX^\top G (k×mk \times m times m×nm \times n), 2mkn2mkn each. (b) (2+4)/2=3(2 + 4)/2 = 3: the 6N6N FLOPs per token of q13 in the Discrete math 1 problem set. Common mistakes: 2mkn2mkn, counting only one of the two products; mknmkn, counting multiply-adds as one FLOP; 22 for (b), the backward-to-forward ratio rather than the total.

The set closes by chaining the matmul and softmax rules through scaled dot-product attention.

Scaled dot-product attention: S=QK⊤/dS = Q K^\top / \sqrt{d}, P=softmax(S)P = \mathrm{softmax}(S) row by row, O=PVO = P V. Take T=2T = 2 positions, d=1d = 1, Q=(10)Q = \begin{pmatrix} 1 \\ 0 \end{pmatrix}, K=(01)K = \begin{pmatrix} 0 \\ 1 \end{pmatrix}, V=(13)V = \begin{pmatrix} 1 \\ 3 \end{pmatrix}, no mask.

q33. (a) Give OO. [matrix] With upstream gradient ∂L/∂O=(10)\partial L / \partial O = \begin{pmatrix} 1 \\ 0 \end{pmatrix}, give (b) ∂L/∂V\partial L / \partial V and (c) ∂L/∂Q\partial L / \partial Q. [matrix]

Answer

(a) ((1+3e)/(1+e)2)\begin{pmatrix} (1 + 3e)/(1 + e) \\ 2 \end{pmatrix}. (b) (1/(1+e)e/(1+e))\begin{pmatrix} 1/(1 + e) \\ e/(1 + e) \end{pmatrix}. (c) (2e/(1+e)20)\begin{pmatrix} 2e/(1 + e)^2 \\ 0 \end{pmatrix}. (a) S=QK⊤=(0100)S = QK^\top = \begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix}, so row 0 of PP is (11+e,e1+e)(\frac1{1 + e}, \frac e{1 + e}) and row 1 is (12,12)(\frac12, \frac12). O=PVO = PV: row 0 is 1+3e1+e≈2.46\frac{1 + 3e}{1 + e} \approx 2.46, row 1 is 22. (b) dV=P⊤dOdV = P^\top dO, which with dO=(1,0)⊤dO = (1, 0)^\top is row 0 of PP as a column. (c) dP=dO V⊤=(1300)dP = dO\,V^\top = \begin{pmatrix} 1 & 3 \\ 0 & 0 \end{pmatrix}. Row 0 through the softmax VJP: ⟨dP0,P0⟩=O0=1+3e1+e\langle dP_0, P_0\rangle = O_0 = \frac{1 + 3e}{1 + e}, so dP0−O0=(−2e1+e,21+e)dP_0 - O_0 = (\frac{-2e}{1 + e}, \frac{2}{1 + e}) and dS0=P0⊙dS_0 = P_0 \odot that =(−2e(1+e)2,2e(1+e)2)= (\frac{-2e}{(1 + e)^2}, \frac{2e}{(1 + e)^2}); row 1 is 0. dQ=dS K/ddQ = dS\,K/\sqrt d picks column 1 of dSdS (since K=(0,1)⊤K = (0, 1)^\top): (2e(1+e)2,0)(\frac{2e}{(1 + e)^2}, 0). Common mistakes: (3+e)/(1+e)(3 + e)/(1 + e) for (a), the softmax weights put on the wrong keys; (3,2)(3, 2), argmax instead of softmax; (11+e,12)(\frac1{1 + e}, \frac12) for (b), P dOP\,dO instead of P⊤dOP^\top dO; (3,0)(3, 0) for (c), dP KdP\,K with the softmax VJP skipped; the right magnitude with the sign lost.

q34. Prove the SDPA backward rules: with dO=∂L/∂OdO = \partial L / \partial O, dV=P⊤dOdV = P^\top dO, dP=dO V⊤dP = dO\, V^\top, dSij=Pij(dPij−∑kdPikPik)dS_{ij} = P_{ij} (dP_{ij} - \sum_k dP_{ik} P_{ik}), dQ=dS K/ddQ = dS\, K / \sqrt{d}, and dK=dS⊤Q/ddK = dS^\top Q / \sqrt{d}. [proof]

Answer

Claim. For S=QK⊤/dS = QK^\top/\sqrt d, P=softmax(S)P = \mathrm{softmax}(S) by rows, O=PVO = PV, and dO=∂L/∂OdO = \partial L/\partial O: dV=P⊤dOdV = P^\top dO, dP=dO V⊤dP = dO\,V^\top, dSij=Pij(dPij−∑kdPikPik)dS_{ij} = P_{ij}(dP_{ij} - \sum_k dP_{ik}P_{ik}), dQ=dS K/ddQ = dS\,K/\sqrt d, dK=dS⊤Q/ddK = dS^\top Q/\sqrt d.

Shapes: Q,KQ, K are T×dT \times d, VV is T×dvT \times d_v, SS and PP are T×TT \times T, OO and dOdO are T×dvT \times d_v.

Proof. Reverse mode through the three steps, each a rule already proved.

  1. O=PVO = PV is a matrix product. By q20 with X=PX = P, W=VW = V: dV=P⊤dOdV = P^\top dO (T×dvT \times d_v, like VV) and dP=dO V⊤dP = dO\,V^\top (T×TT \times T, like PP).
  2. Row ii of PP is the softmax of row ii of SS, and rows do not interact. By q28 on row ii with upstream dPi,:dP_{i,:}: dSij=Pij(dPij−⟨dPi,:,Pi,:⟩)dS_{ij} = P_{ij}(dP_{ij} - \langle dP_{i,:}, P_{i,:}\rangle).
  3. S=QK⊤/dS = QK^\top/\sqrt d is a scaled product. By q20 with X=QX = Q, W=K⊤W = K^\top, and the constant 1/d1/\sqrt d carried through: dQ=dS (K⊤)⊤/d=dS K/ddQ = dS\,(K^\top)^\top/\sqrt d = dS\,K/\sqrt d (T×dT \times d, like QQ), and d(K⊤)=Q⊤dS/dd(K^\top) = Q^\top dS/\sqrt d, so dK=dS⊤Q/ddK = dS^\top Q/\sqrt d (T×dT \times d, like KK).

Every gradient has its variable’s shape. A causal mask sets masked SijS_{ij} to −∞-\infty, so Pij=0P_{ij} = 0 there and step 2 gives dSij=0dS_{ij} = 0: no gradient flows through masked entries. FlashAttention’s backward recomputes PP tile by tile and applies these rules, with ∑kdPikPik=∑kdOikOik\sum_k dP_{ik}P_{ik} = \sum_k dO_{ik}O_{ik} precomputed per row.

A complete derivation gets dVdV and dPdP from the matmul rule, applies the softmax VJP row by row, gets dQdQ and dKdK from the scaled product, and checks every shape. Model derivation also in q34.md.

The wrong answers listed under each problem cluster into a handful of recurring errors. The table collects them, with the problems where each one shows up.

MistakeSymptomThe fix
Gradient transposed relative to its variableshape error in the optimizer, or a silently wrong square gradientgive every gradient its variable’s shape (q1 b); X−⊤X^{-\top}, not X−1X^{-1} (q9)
Not summing over broadcast axesbias gradient of shape (B, T, d)sum ∂L/∂Y\partial L/\partial Y over BB and TT, six terms per entry (q1 c, q3)
Counting bytes as strides, or using a contiguous copy’s strides for a viewwrong element read through a viewstrides in elements; a transpose view swaps strides (q2)
∇x⊤Ax=2Ax\nabla x^\top A x = 2Ax for a non-symmetric AAwrong gradient for asymmetric forms(A+A⊤)x(A + A^\top)x from both terms of the product rule (q5)
Dropping the factor 2 of a squaregradients half as large; learning rates tuned to hide itkeep the 2 from d(r⊤r)=2r⊤drd(r^\top r) = 2r^\top dr (q7, q10)
Swapping a non-cyclic order inside a tracean identity that holds only for commuting matricesrotate cyclically only (q17, q20)
Softmax VJP without the ⟨g,y⟩\langle g, y\rangle terminput gradients that do not sum to zeroy⊙(g−⟨g,y⟩1)y \odot (g - \langle g, y\rangle\mathbf 1) (q21, q28)
One-hot minus softmaxgradient ascent on the losssoftmax minus one-hot (q24 a)
Mean over all positions including ignored onesloss and gradient scaled down by the padding fractiondivide by the kept count (q25)
Treating a normalization’s statistics as constantsRMSNorm or LayerNorm gradients without the correction termdifferentiate through rr, μ\mu, and σ\sigma; check orthogonality and zero sum (q26, q27)
Using P dOP\,dO for dVdVvalue gradients from the wrong positionsdV=P⊤dOdV = P^\top dO from the matmul rule (q33 b, q34)

Every derivation here becomes code. The dual numbers of Dual numbers and forward-mode autodiff compute the JVPs of the forward-versus-reverse discussion; Scalar reverse mode: the Value graph is the oracle against which the closed-form VJPs are tested; and Matrix differentials, the trace trick, and closed-form VJPs turns the VJP table into code, gradchecked rule by rule. In AI Engineering, The op library and gradcheck_all registers those VJPs as tensor ops, with the unbroadcast of q1 and q3; Losses with a fused backward implements fused cross-entropy with ignore_index (q24, q25); Pre-LN and RMSNorm puts RMSNorm in the modern block (q26); the attention of the Attention Origins chapter and Scaled dot-product attention (forward and backward) use the backward of q33 and q34; and FlashAttention, whose forward pass is built in FlashAttention forward in C, recomputes PP in its backward and applies q34’s rules tile by tile.

Further reading:

  • Parr and Howard, “The Matrix Calculus You Need for Deep Learning” (2018).
  • Minka, “Old and New Matrix Algebra Useful for Statistics” (2000).
  • Baydin et al., “Automatic Differentiation in Machine Learning: a Survey” (2018), sections 2 and 3.
  • Dao et al., “FlashAttention” (2022), appendix B.
  • A gradient has the shape of its variable, and broadcasting in the forward pass becomes a sum over the broadcast axes in the backward pass (q1, q3).
  • Write the differential dL=tr⁡(G⊤dY)dL = \operatorname{tr}(G^\top dY), push dYdY through the product rule, rotate with the cyclic trace, and read off the gradient: ∂L/∂W=X⊤G\partial L/\partial W = X^\top G, ∂L/∂X=GW⊤\partial L/\partial X = G W^\top (q18, q20).
  • Softmax’s VJP is y⊙(g−⟨g,y⟩)y \odot (g - \langle g, y\rangle) and cross-entropy’s gradient with respect to logits is softmax(z)−onehot(y)\mathrm{softmax}(z) - \mathrm{onehot}(y), both O(V)O(V) (q21, q24, q28).
  • Normalizations differentiate through their statistics: LayerNorm’s input gradient sums to zero, and RMSNorm’s is orthogonal to xx (q26, q27).
  • Reverse mode costs one pass per output, so one backward pass gives a million-parameter gradient, at about twice the forward FLOPs (q29, q32).