TExcelTAD
Home › Math for Machine Learning › Gradients of Matrices and Useful Identities

Gradients of Matrices and Useful Identities

Weights in ML come as matrices, so we need derivatives of a scalar loss with respect to a whole matrix WW. The answer is a matrix of the same shape, and a handful of identities cover almost every case you will meet. This lesson derives the key ones and checks them numerically.

Gradient with respect to a matrix

For a scalar LL and W∈Rm×nW \in \mathbb{R}^{m \times n}, define ∂L∂W\frac{\partial L}{\partial W} as the m×nm \times n matrix with entries ∂L∂wij\frac{\partial L}{\partial w_{ij}}. (Gradients of a vector with respect to a matrix are 3-D tensors; we avoid them by keeping the output scalar, which a loss always is.)

The most important identity: a linear layer

Let y=Wx\mathbf{y} = W\mathbf{x} and suppose we already know g=∂L∂y\mathbf{g} = \frac{\partial L}{\partial \mathbf{y}} (as a column, same shape as y\mathbf{y}). Since yi=∑jwijxjy_i = \sum_j w_{ij}x_j, the weight wijw_{ij} only affects yiy_i, and ∂yi/∂wij=xj\partial y_i / \partial w_{ij} = x_j:

∂L∂wij=gi xj  ⟹  ∂L∂W=g xT,∂L∂x=WTg\frac{\partial L}{\partial w_{ij}} = g_i\,x_j \implies \frac{\partial L}{\partial W} = \mathbf{g}\,\mathbf{x}^T, \qquad \frac{\partial L}{\partial \mathbf{x}} = W^T\mathbf{g}

The weight gradient is an outer product of the upstream gradient and the input. For a mini-batch with inputs as rows of XX (N×nN \times n) and Y=XWTY = XW^T, the gradients of all examples add up: ∂L∂W=GTX\frac{\partial L}{\partial W} = G^TX.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
W, x, t = rng.normal(size=(2, 3)), rng.normal(size=3), np.array([1.0, -1.0])
L = lambda W: 0.5 * np.sum((W @ x - t) ** 2)      # squared error of a linear layer
g = W @ x - t                                      # dL/dy
grad_W = np.outer(g, x)
h = 1e-6
num = np.zeros_like(W)
for i in range(2):
    for j in range(3):
        E = np.zeros_like(W); E[i, j] = h
        num[i, j] = (L(W + E) - L(W - E)) / (2 * h)
print("g x^T:\n", np.round(grad_W, 6))
print("matches numeric:", np.allclose(grad_W, num, atol=1e-8))
g x^T:
 [[-1.841052 -1.337136  0.993568]
 [ 0.489     0.355156 -0.263901]]
matches numeric: True

A table of identities

With x,a\mathbf{x}, \mathbf{a} vectors, A,XA, X matrices (gradients written in the same shape as the variable):

Function Gradient
aTx\mathbf{a}^T\mathbf{x} ∂∂x=a\frac{\partial}{\partial \mathbf{x}} = \mathbf{a}
xTAx\mathbf{x}^TA\mathbf{x} ∂∂x=(A+AT)x\frac{\partial}{\partial \mathbf{x}} = (A + A^T)\mathbf{x}, which is 2Ax2A\mathbf{x} for symmetric AA
∥Ax−b∥2\lVert A\mathbf{x} - \mathbf{b} \rVert^2 ∂∂x=2AT(Ax−b)\frac{\partial}{\partial \mathbf{x}} = 2A^T(A\mathbf{x} - \mathbf{b})
aTXb\mathbf{a}^TX\mathbf{b} ∂∂X=abT\frac{\partial}{\partial X} = \mathbf{a}\mathbf{b}^T
tr⁡(AX)\operatorname{tr}(AX) ∂∂X=AT\frac{\partial}{\partial X} = A^T
tr⁡(XTAX)\operatorname{tr}(X^TAX) ∂∂X=(A+AT)X\frac{\partial}{\partial X} = (A + A^T)X
log⁡det⁡X\log\det X (XX SPD) ∂∂X=X−1\frac{\partial}{\partial X} = X^{-1}

The last one is what you need to find the maximum-likelihood covariance of a Gaussian. Derivations rely on the cyclic property of the trace: write the scalar as a trace, take a small change dXdX, and read off the coefficient.

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
M = rng.normal(size=(3, 3)); X = M @ M.T + 3 * np.eye(3)     # SPD
def num_grad(f, X, h=1e-6):
    G = np.zeros_like(X)
    for i in range(3):
        for j in range(3):
            E = np.zeros_like(X); E[i, j] = h
            G[i, j] = (f(X + E) - f(X - E)) / (2 * h)
    return G
logdet = lambda X: np.linalg.slogdet(X)[1]
print("d logdet / dX = X^-1:", np.allclose(num_grad(logdet, X), np.linalg.inv(X), atol=1e-6))
A = rng.normal(size=(3, 3))
print("d tr(AX) / dX = A^T:", np.allclose(num_grad(lambda X: np.trace(A @ X), X), A.T, atol=1e-6))
d logdet / dX = X^-1: True
d tr(AX) / dX = A^T: True

Shape checking as a debugging tool

The gradient always has the shape of the variable. If your formula for ∂L/∂W\partial L / \partial W produces the wrong shape, it is wrong; if it has the right shape, there is often only one way to arrange the factors. For W∈Rm×nW \in \mathbb{R}^{m \times n}, g∈Rm\mathbf{g} \in \mathbb{R}^m and x∈Rn\mathbf{x} \in \mathbb{R}^n, only gxT\mathbf{g}\mathbf{x}^T is m×nm \times n.

In software

  • Every framework's linear layer computes grad_W = grad_out.T @ inputs and grad_inputs = grad_out @ W on mini-batches.
  • The Matrix Cookbook (Petersen and Pedersen) is the classic free reference for matrix identities.
  • Gaussian log-likelihood gradients (for GMMs, Gaussian processes) use the log⁡det⁡\log\det and inverse identities.

Exercises

Exercise 1: Linear function

Find ∂∂x(3x1−x2+2x3)\frac{\partial}{\partial \mathbf{x}}(3x_1 - x_2 + 2x_3) using the table.

Answer

(3,−1,2)(3, -1, 2).

Solution

The function is aTx\mathbf{a}^T\mathbf{x} with a=(3,−1,2)\mathbf{a} = (3, -1, 2), so the gradient is a\mathbf{a}.

Exercise 2: Weight gradient by hand

For y=Wx\mathbf{y} = W\mathbf{x} with x=(1,2)\mathbf{x} = (1, 2) and upstream gradient g=(3,−1,0)\mathbf{g} = (3, -1, 0), what is ∂L/∂W\partial L / \partial W?

Answer

[36−1−200]\begin{bmatrix} 3 & 6 \\ -1 & -2 \\ 0 & 0 \end{bmatrix}.

Solution

gxT\mathbf{g}\mathbf{x}^T: row ii is gi(1,2)g_i(1, 2). The third output had zero gradient, so its weights get no update.

Exercise 3: Least squares gradient (code)

Check ∇x∥Ax−b∥2=2AT(Ax−b)\nabla_{\mathbf{x}}\lVert A\mathbf{x} - \mathbf{b} \rVert^2 = 2A^T(A\mathbf{x} - \mathbf{b}) for a random 4×24 \times 2 matrix.

Answer

The identity holds (True).

Solution
python · try it yourself
import numpy as np
rng = np.random.default_rng(5)
A, b, x = rng.normal(size=(4, 2)), rng.normal(size=4), rng.normal(size=2)
f = lambda v: np.sum((A @ v - b) ** 2)
num = np.array([(f(x + 1e-6 * e) - f(x - 1e-6 * e)) / 2e-6 for e in np.eye(2)])
print(np.allclose(num, 2 * A.T @ (A @ x - b), atol=1e-6))
True

Test yourself

For y=Wx\mathbf{y} = W\mathbf{x} with upstream gradient g=∂L/∂y\mathbf{g} = \partial L / \partial \mathbf{y}, the gradient ∂L/∂W\partial L / \partial W is…

  1. WTgW^T\mathbf{g}
  2. gxT\mathbf{g}\mathbf{x}^T
  3. xgT\mathbf{x}\mathbf{g}^T
  4. gTx\mathbf{g}^T\mathbf{x}

∂∂Xlog⁡det⁡X\frac{\partial}{\partial X}\log\det X for SPD XX is…

  1. XX
  2. X−1X^{-1}
  3. det⁡X\det X
  4. II

The gradient of a scalar loss with respect to W∈Rm×nW \in \mathbb{R}^{m \times n} has shape…

  1. n×mn \times m
  2. m×nm \times n
  3. mn×1mn \times 1
  4. 1×11 \times 1