Skip to content
BIASED

Matrix calculus

Gradients of vector and matrix expressions without indices: the differential method, the shape convention, the trace trick, and the gradients of least squares, the log-determinant and softmax cross-entropy.

Layout: the gradient has the shape of the variable

The topic Gradients, Jacobians and Hessians gave us the gradient of a scalar loss and the chain rule as a product of Jacobians. In principle that is enough. In practice, ∇x∥Ax−b∥2\nabla_x \lVert Ax - b \rVert^2 computed entry by entry is a page of double sums, and the derivative of a layer's output with respect to its weight matrix carries three indices at once, ∂zk/∂Wij\partial z_k / \partial W_{ij}. This topic computes such gradients in a few lines, without indices.

First we agree on shapes. Two conventions meet here.

  • A Jacobian is arranged outputs × inputs: for f:Rn→Rmf: \mathbb R^n \to \mathbb R^m, the matrix Jf(x)J_f(x) is m×nm \times n, as in the previous topic.
  • A gradient of a scalar has the shape of its variable: ∇xf\nabla_x f is a column in Rn\mathbb R^n for x∈Rnx \in \mathbb R^n, and ∇WL\nabla_W L is an m×nm \times n matrix for W∈Rm×nW \in \mathbb R^{m \times n}, with entries (∇WL)ij=∂L/∂Wij(\nabla_W L)_{ij} = \partial L / \partial W_{ij}.

For a scalar function of a vector the two differ only by a transpose: the Jacobian is the 1×n1 \times n row Jf=(∇f)⊤J_f = (\nabla f)^\top.

Why insist on the shape of the variable? Because of the update step. Gradient descent

W←W−η ∇WLW \leftarrow W - \eta\, \nabla_W L

subtracts the gradient from the weights, so the two must have the same shape.

One example pins the convention down. For f(x)=a⊤x=a1x1+⋯+anxnf(x) = a^\top x = a_1 x_1 + \dots + a_n x_n each partial derivative is ∂f/∂xi=ai\partial f / \partial x_i = a_i, so

∇x(a⊤x)=a,\nabla_x (a^\top x) = a,

a column, not the row a⊤a^\top. Some books and papers use the opposite layout, and then every formula comes out transposed. Before borrowing a formula, check how the source writes this one.

The differential method

Index-free computing rests on the differential. For a function ff of a vector xx, the differential dfdf is the linear part of the change of ff when xx moves by a small dxdx:

f(x+dx)=f(x)+df+o(∥dx∥).f(x + dx) = f(x) + df + o(\lVert dx \rVert).

For a scalar ff the previous topic already named this linear part: df=∇f(x)⊤dxdf = \nabla f(x)^\top dx. Read backwards, that is the whole method: compute dfdf, bring it to the form g⊤dxg^\top dx, and read off ∇f=g\nabla f = g.

Differentials obey the familiar rules. Here AA is a constant, and XX, YY are vector or matrix expressions of matching shapes:

dA=0,d(X+Y)=dX+dY,d(XY)=(dX) Y+X dY,d(X⊤)=(dX)⊤.dA = 0, \qquad d(X + Y) = dX + dY, \qquad d(XY) = (dX)\, Y + X\, dY, \qquad d(X^\top) = (dX)^\top.

The product rule keeps the factors in their order, because matrices do not commute.

Take the quadratic form f(x)=x⊤Axf(x) = x^\top A x with any square AA. The product rule gives two terms:

df=(dx)⊤Ax+x⊤A dx.df = (dx)^\top A x + x^\top A\, dx.

The first term is a number, so it equals its own transpose: (dx)⊤Ax=x⊤A⊤dx(dx)^\top A x = x^\top A^\top dx. Now both terms end in dxdx:

df=x⊤(A+A⊤) dx⟹∇x(x⊤Ax)=(A+A⊤) x.df = x^\top (A + A^\top)\, dx \quad\Longrightarrow\quad \nabla_x (x^\top A x) = (A + A^\top)\, x.

For a symmetric AA (see the topic Symmetric matrices and quadratic forms) this is 2Ax2Ax, the analogue of (ax2)′=2ax(a x^2)' = 2ax. For a non-symmetric AA the shortcut fails. With

A=(1203),x=(12),A = \begin{pmatrix} 1 & 2 \\ 0 & 3 \end{pmatrix}, \qquad x = \begin{pmatrix} 1 \\ 2 \end{pmatrix},

we get x⊤Ax=17x^\top A x = 17 and ∇f=(A+A⊤) x=(6,14)\nabla f = (A + A^\top)\, x = (6, 14), while 2Ax=(10,12)2Ax = (10, 12) is wrong.

The chain rule turns into substitution. If ff depends on uu and uu depends on xx, write dfdf through dudu, then replace dudu by its own expression through dxdx.

The gradient of least squares

Least squares (see the topic Inner products, norms and orthogonality) minimizes

f(x)=∥Ax−b∥2=r⊤r,r=Ax−b.f(x) = \lVert Ax - b \rVert^2 = r^\top r, \qquad r = Ax - b.

In linear regression the rows of AA are the examples, xx holds the weights and bb the targets. The residual rr is an intermediate variable, so we substitute in two steps. First, d(r⊤r)=(dr)⊤r+r⊤dr=2 r⊤drd(r^\top r) = (dr)^\top r + r^\top dr = 2\, r^\top dr, because the two terms are the same number. Second, dr=A dxdr = A\, dx, because bb is a constant. Together:

df=2 r⊤A dx=(2A⊤r)⊤dx⟹∇x∥Ax−b∥2=2A⊤(Ax−b).df = 2\, r^\top A\, dx = \big(2 A^\top r\big)^\top dx \quad\Longrightarrow\quad \nabla_x \lVert Ax - b \rVert^2 = 2 A^\top (Ax - b).

The shapes agree: A⊤A^\top is n×mn \times m and the residual lives in Rm\mathbb R^m, so the gradient lives in Rn\mathbb R^n, like xx.

Setting the gradient to zero gives A⊤A x=A⊤bA^\top A\, x = A^\top b. These are the normal equations, which the earlier topic found from geometry; here they come from calculus.

With the matrix AA from the previous block, b=(1,1)b = (1, 1) and x=(1,2)x = (1, 2), the residual is r=(4,5)r = (4, 5) and the gradient is 2A⊤r=(8,46)2 A^\top r = (8, 46). The large second entry says that the loss is most sensitive to x2x_2, which enters both rows of AA.

Matrix variables and the trace trick

Now let the variable be a matrix X∈Rm×nX \in \mathbb R^{m \times n}. We need an inner product for matrices: multiply matching entries and add them up. The trace writes it compactly:

⟨A,B⟩=∑i,jAijBij=tr⁡(A⊤B).\langle A, B \rangle = \sum_{i, j} A_{ij} B_{ij} = \operatorname{tr}(A^\top B).

The jj-th diagonal entry of A⊤BA^\top B is ∑iAijBij\sum_i A_{ij} B_{ij}, and the trace adds these up over jj.

The differential has one term per entry, df=∑i,j(∂f/∂Xij) dXijdf = \sum_{i, j} (\partial f / \partial X_{ij})\, dX_{ij}, and this sum is the inner product of the gradient with dXdX, exactly as for vectors:

df=tr⁡((∇Xf)⊤dX).df = \operatorname{tr}\big( (\nabla_X f)^\top dX \big).

So the job is to bring dfdf to the form tr⁡(M dX)\operatorname{tr}(M\, dX); then ∇Xf=M⊤\nabla_X f = M^\top. Two facts do the moving. A number equals its own trace, c=tr⁡cc = \operatorname{tr} c. And the trace is cyclic: tr⁡(AB)=tr⁡(BA)\operatorname{tr}(AB) = \operatorname{tr}(BA) whenever both products exist, since both equal ∑i,jAijBji\sum_{i, j} A_{ij} B_{ji}. So a factor may travel from the front of a product to its back. This is the trace trick.

The simplest case is dtr⁡(AX)=tr⁡(A dX)d \operatorname{tr}(AX) = \operatorname{tr}(A\, dX), so ∇Xtr⁡(AX)=A⊤\nabla_X \operatorname{tr}(AX) = A^\top. A check with A=(1234)A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}: tr⁡(AX)=X11+2X21+3X12+4X22\operatorname{tr}(AX) = X_{11} + 2 X_{21} + 3 X_{12} + 4 X_{22}, and the coefficient of X12X_{12} is 3=(A⊤)123 = (A^\top)_{12}.

The case that matters most is a linear layer. Let z=Wxz = Wx, and let the loss depend on WW only through zz, with g=∇zLg = \nabla_z L already known. Then dL=g⊤dzdL = g^\top dz and dz=(dW) xdz = (dW)\, x. The number g⊤(dW) xg^\top (dW)\, x is its own trace, and the cyclic property moves xx to the front:

dL=tr⁡(g⊤(dW) x)=tr⁡(x g⊤dW)⟹∇WL=g x⊤.dL = \operatorname{tr}\big( g^\top (dW)\, x \big) = \operatorname{tr}\big( x\, g^\top dW \big) \quad\Longrightarrow\quad \nabla_W L = g\, x^\top.

The weight gradient is an outer product: the column gg, one entry per output, times the row x⊤x^\top, one entry per input. That is exactly the shape of WW. With a bias, z=Wx+bz = Wx + b, the same steps give ∇bL=g\nabla_b L = g.

One more identity for later. The Frobenius norm ∥X∥F\lVert X \rVert_F is the ℓ2\ell_2 norm of all entries, ∥X∥F2=tr⁡(X⊤X)\lVert X \rVert_F^2 = \operatorname{tr}(X^\top X), and its gradient is ∇X∥X∥F2=2X\nabla_X \lVert X \rVert_F^2 = 2X. This is the gradient of the weight-decay penalty.

The log-determinant

Some losses contain a determinant. The log-density of a Gaussian with covariance Σ\Sigma has the term −12log⁡det⁡Σ-\tfrac12 \log \det \Sigma, and the log-likelihood of a normalizing flow contains log⁡∣det⁡J∣\log \lvert \det J \rvert. We need its gradient.

For a small dXdX, factor XX out of the determinant:

det⁡(X+dX)=det⁡X⋅det⁡(I+X−1dX).\det(X + dX) = \det X \cdot \det(I + X^{-1} dX).

For a small matrix EE, det⁡(I+E)≈1+tr⁡E\det(I + E) \approx 1 + \operatorname{tr} E. The reason is in the topic Determinants and eigenvalues: the eigenvalues of I+EI + E are 1+εi1 + \varepsilon_i, their product is 1+∑iεi1 + \sum_i \varepsilon_i plus products of small numbers, and ∑iεi=tr⁡E\sum_i \varepsilon_i = \operatorname{tr} E. Hence

ddet⁡X=det⁡X⋅tr⁡(X−1dX),dlog⁡det⁡X=tr⁡(X−1dX).d \det X = \det X \cdot \operatorname{tr}(X^{-1} dX), \qquad d \log \det X = \operatorname{tr}(X^{-1} dX).

This is already the form tr⁡(M dX)\operatorname{tr}(M\, dX) with M=X−1M = X^{-1}, so

∇Xlog⁡det⁡X=X−⊤,\nabla_X \log \det X = X^{-\top},

where X−⊤=(X−1)⊤X^{-\top} = (X^{-1})^\top. The same formula holds for log⁡∣det⁡X∣\log \lvert \det X \rvert when det⁡X<0\det X < 0. For a symmetric covariance it is simply Σ−1\Sigma^{-1}.

A numerical check. Take

X=(210.51.5),det⁡X=2.5,∇Xdet⁡X=det⁡X⋅X−⊤=(1.5−0.5−12).X = \begin{pmatrix} 2 & 1 \\ 0.5 & 1.5 \end{pmatrix}, \qquad \det X = 2.5, \qquad \nabla_X \det X = \det X \cdot X^{-\top} = \begin{pmatrix} 1.5 & -0.5 \\ -1 & 2 \end{pmatrix}.

Move XX by dX=(0.10.05−0.050.1)dX = \begin{pmatrix} 0.1 & 0.05 \\ -0.05 & 0.1 \end{pmatrix}. The first-order prediction is 2.5+⟨∇Xdet⁡X,dX⟩=2.5+0.375=2.8752.5 + \langle \nabla_X \det X, dX \rangle = 2.5 + 0.375 = 2.875. The exact value is det⁡(X+dX)=2.8875\det(X + dX) = 2.8875. The gap 0.01250.0125 is second order: for 2×22 \times 2 matrices it equals det⁡(dX)\det(dX).

Softmax cross-entropy

A classifier with KK classes computes logits z=Wx+b∈RKz = Wx + b \in \mathbb R^K, turns them into probabilities with softmax, and pays the cross-entropy of the true class cc:

pk=ezk∑jezj,L=−log⁡pc=−zc+log⁡∑jezj.p_k = \frac{e^{z_k}}{\sum_j e^{z_j}}, \qquad L = -\log p_c = -z_c + \log \sum_j e^{z_j}.

Let yy be the one-hot vector of class cc, so that zc=y⊤zz_c = y^\top z. The first term contributes −y⊤dz-y^\top dz. For the second, the differential of a logarithm is the differential of its argument divided by the argument:

dlog⁡∑jezj=∑jezj dzj∑jezj=p⊤dz.d \log \sum_j e^{z_j} = \frac{\sum_j e^{z_j}\, dz_j}{\sum_j e^{z_j}} = p^\top dz.

Together:

dL=(p−y)⊤dz⟹∇zL=p−y.dL = (p - y)^\top dz \quad\Longrightarrow\quad \nabla_z L = p - y.

Prediction minus target, as with the residual in least squares. The linear-layer rule from the trace-trick block, with g=p−yg = p - y, finishes the job:

∇WL=(p−y) x⊤,∇bL=p−y.\nabla_W L = (p - y)\, x^\top, \qquad \nabla_b L = p - y.

An example with z=(2,1,0.1)z = (2, 1, 0.1) and true class c=1c = 1: p≈(0.659,0.242,0.099)p \approx (0.659, 0.242, 0.099), L=−log⁡0.659≈0.417L = -\log 0.659 \approx 0.417 and ∇zL≈(−0.341,0.242,0.099)\nabla_z L \approx (-0.341, 0.242, 0.099). With the input x=(1,−2)x = (1, -2), the first row of ∇WL\nabla_W L is −0.341⋅(1,−2)=(−0.341,0.682)-0.341 \cdot (1, -2) = (-0.341, 0.682).

Note what we never built: the K×KK \times K Jacobian of the softmax. The chain ended at a scalar, so the differentials collapsed to a vector before any big matrix appeared. Deep learning frameworks fuse softmax and cross-entropy for the same reason, and for numerical stability as well.

How to check a formula

Three habits catch most mistakes in matrix calculus.

  • Shapes. The gradient has the shape of the variable. A formula that returns a 2×32 \times 3 matrix for a 3×23 \times 2 variable is transposed somewhere.
  • The 1-D case. Set every size to 1. Then 2A⊤(Ax−b)2 A^\top (Ax - b) becomes 2a(ax−b)2a(ax - b), the ordinary derivative of (ax−b)2(ax - b)^2.
  • Finite differences. Nudge one entry by a small hh in both directions and compare (f(X+hEij)−f(X−hEij))/2h\big(f(X + h E_{ij}) - f(X - h E_{ij})\big) / 2h with the entry (i,j)(i, j) of the formula. Here EijE_{ij} has a single 11 in position (i,j)(i, j). Every formula of this topic was checked this way.

The results of the topic in one table:

ff gradient
a⊤xa^\top x aa
x⊤Axx^\top A x (A+A⊤) x(A + A^\top)\, x
∥Ax−b∥2\lVert Ax - b \rVert^2 2A⊤(Ax−b)2 A^\top (Ax - b)
tr⁡(AX)\operatorname{tr}(AX) A⊤A^\top
L(Wx+b)L(Wx + b), with g=∇zLg = \nabla_z L ∇WL=g x⊤\nabla_W L = g\, x^\top, ∇bL=g\nabla_b L = g
log⁡det⁡X\log \det X X−⊤X^{-\top}
softmax cross-entropy ∇zL=p−y\nabla_z L = p - y

Two caveats. The formulas treat all entries of XX as independent, so a symmetric matrix, whose X12X_{12} and X21X_{21} move together, needs care: the derivative in their shared value is the sum of the two entries of the formula, as in the log-determinant check. And in code, automatic differentiation computes all of this for you. Closed forms are for understanding, for checking code and for second-order methods.

We can now write a loss and its gradient. But many losses come from probabilities, and the probability of a vector is an integral over many variables: the normalizing constant of a Gaussian, the expected loss over the data. Change the variables, say x=Wzx = Wz in a flow, and a determinant ∣det⁡J∣\lvert \det J \rvert appears. It is where the log⁡det⁡\log \det of this topic comes from. That is the next topic, Multiple integrals and change of variables.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.