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 . 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 and , define as the matrix with entries . (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 and suppose we already know (as a column, same shape as ). Since , the weight only affects , and :
The weight gradient is an outer product of the upstream gradient and the input. For a mini-batch with inputs as rows of () and , the gradients of all examples add up: .
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 vectors, matrices (gradients written in the same shape as the variable):
| Function | Gradient |
|---|---|
| , which is for symmetric | |
| ( SPD) |
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 , and read off the coefficient.
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 produces the wrong shape, it is wrong; if it has the right shape, there is often only one way to arrange the factors. For , and , only is .
In software
- Every framework's linear layer computes
grad_W = grad_out.T @ inputsandgrad_inputs = grad_out @ Won 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 and inverse identities.
Exercises
Exercise 1: Linear function
Find using the table.
Answer
.
Solution
The function is with , so the gradient is .
Exercise 2: Weight gradient by hand
For with and upstream gradient , what is ?
Answer
.
Solution
: row is . The third output had zero gradient, so its weights get no update.
Exercise 3: Least squares gradient (code)
Check for a random matrix.
Answer
The identity holds (True).
Solution
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 with upstream gradient , the gradient is…
for SPD is…
The gradient of a scalar loss with respect to has shape…