Module contents
Lesson 21 of 25Core 100 min

Matrix calculus I: differentials and gradients with respect to matrices

Training differentiates scalar loss with respect to weight matrices, and doing so entry by entry does not scale to ideas or code. Introduce derivatives as linear maps, gradients defined by the Frobenius inner product, differential rules and the trace trick, eliminating layout-convention ambiguity. Verify every result numerically.

After this lesson you can

  • Define a matrix gradient by df = tr((∇f)ᵀ dX) and explain why it has X's shape.
  • Apply differential rules for products, transposes, traces, inverses and determinants.
  • Derive gradients of xᵀAx, ‖XW - Y‖²_F, tr(AXB) and log det X using the trace trick.
  • Identify and convert between numerator and denominator layout conventions.
  • Implement a reliable finite-difference gradient check and choose step h.

Before you start

Motivation: training differentiates with respect to matrices

Training repeats an operation millions of times: compute scalar loss LL and move each weight matrix slightly against its gradient, W←W−η ∇WL\mat{W} \leftarrow \mat{W} - \eta\,\grad_{\mat{W}} L. In a GPT-2 small transformer MLP with dmodel=768d_{\text{model}} = 768, one such matrix is 3072×7683072\times 768: about 2.4 million partial derivatives needed together in a formula expressible as a couple of matrix products.

The naive route derives index by index. For least-squares loss L(W)=∥XW−Y∥F2L(\mat{W}) = \norm{\mat{X}\mat{W} - \mat{Y}}_F^2, residual R=XW−Y\mat{R} = \mat{X}\mat{W} - \mat{Y}, write sums and differentiate a specific entry WpqW_{pq}:

∂L∂Wpq=∑i,j2Rij ∂Rij∂Wpq=∑i,j2Rij ∂∂Wpq(∑lXilWlj)=∑i2RiqXip=2(X⊤R)pq.\pd{L}{W_{pq}} = \sum_{i,j} 2R_{ij}\,\pd{R_{ij}}{W_{pq}} = \sum_{i,j} 2R_{ij}\,\pd{}{W_{pq}}\Big(\sum_{l} X_{il}W_{lj}\Big) = \sum_{i} 2R_{iq}X_{ip} = 2(\mat{X}\T\mat{R})_{pq}.

It works, with elegant result ∇WL=2X⊤R\grad_{\mat{W}} L = 2\mat{X}\T\mat{R}. But it does not scale. Add an activation, product of three matrices, inverse or determinant, indices multiply, Kronecker deltas accumulate, and the final step—recognizing a matrix product, order and transposes in an indexed sum—is exactly where errors occur.

This lesson gives the specialists’ alternative: differentials. Instead of differentiating entrywise, ask how LL changes when W\mat{W} changes by a small matrix dWd\mat{W}, manipulate the change with a few algebraic rules (ordinary rules respecting noncommuting matrix products), and read off the gradient with a trace trick. The previous derivation becomes one line; the same method gives derivatives of X−1\mat{X}\inv and log⁡det⁡X\log\det\mat{X} found in Gaussian processes, normalizing flows and multivariate statistics.

You will also learn to check any gradient numerically with a reliable finite-difference checker: the safety net needed for a hand-written or copied gradient.

The derivative as a linear map

In one variable, f′(x)f'(x) is a number. In several, it is a matrix (the Jacobian). For matrix functions return to the definition underlying both, the Fréchet derivative: derivative as the best linear approximation to change.

Read dXd\mat{X} as “an arbitrary matrix imagined small” and dfdf as “the part of ff‘s change linear in dXd\mat{X}”. Discard order ∥dX∥2\norm{d\mat{X}}^2 and higher. Since all norms on Rm×n\R^{m\times n} are equivalent, the definition is norm-independent.

First example: f(X)=X2f(\mat{X}) = \mat{X}^2

Expand the square without false assumptions:

(X+E)2=X2+XE+EX+E2.(\mat{X} + \mat{E})^2 = \mat{X}^2 + \mat{X}\mat{E} + \mat{E}\mat{X} + \mat{E}^2.

The term E2\mat{E}^2 satisfies ∥E2∥F≤∥E∥F2\norm{\mat{E}^2}_F \le \norm{\mat{E}}_F^2, hence is o(∥E∥)o(\norm{\mat{E}}). The remainder, E↦XE+EX\mat{E} \mapsto \mat{X}\mat{E} + \mat{E}\mat{X}, is linear in E\mat{E}. Therefore

d(X2)=X dX+dX X.d(\mat{X}^2) = \mat{X}\,d\mat{X} + d\mat{X}\,\mat{X}.

Notice what it is not: 2X dX2\mat{X}\,d\mat{X}. Copying scalar rule (x2)′=2x(x^2)' = 2x requires X\mat{X} and dXd\mat{X} to commute; an arbitrary perturbation does not commute with X\mat{X}. The naive rule’s error EX−XE\mat{E}\mat{X} - \mat{X}\mat{E} is first order: it does not vanish faster than the perturbation.

Derivative f′(X)f'(\mat{X}) is a linear map from Rn×n\R^{n\times n} to Rn×n\R^{n\times n}. As a matrix it would be n2×n2n^2\times n^2: with the preceding lesson’s vec operator and Kronecker product, vec⁡(XE+EX)=(I⊗X+X⊤⊗I)vec⁡(E)\operatorname{vec}(\mat{X}\mat{E} + \mat{E}\mat{X}) = (\mat{I}\otimes\mat{X} + \mat{X}\T\otimes\mat{I})\operatorname{vec}(\mat{E}). It rarely needs forming. Thinking of the derivative as a map makes dX↦X dX+dX Xd\mat{X} \mapsto \mat{X}\,d\mat{X} + d\mat{X}\,\mat{X} compact and evaluable with two products, while its Jacobian stores n4n^4 numbers.

InteractiveLinearizing a matrix function
Drag column tips of X+dX\mat{X} + d\mat{X} on the input canvas: the perturbation deforms the grid. On output, arrows are exact columns of f(X+dX)f(\mat{X} + d\mat{X}), hollow circles the linear prediction f(X)+f′(X)[dX]f(\mat{X}) + f'(\mat{X})[d\mat{X}]; red segment is error. Shrink dXd\mat{X} with tt: correct derivative error falls with slope 2 (factor 10 in dXd\mat{X}, factor 100 in error), and error/∥dX∥F2/\norm{d\mat{X}}_F^2 stabilizes. Naive rule has slope 1. Select commuting dX for the sole case where the naive rule works.

For f(X)=X2f(\mat{X}) = \mat{X}^2 linear prediction error is exactly dX2d\mat{X}^2, so the figure’s error/∥dX∥F2/\norm{d\mat{X}}_F^2 never exceeds 1. For inverse (switch to X−1\mat{X}\inv), derivative is −X−1dX X−1-\mat{X}\inv d\mat{X}\,\mat{X}\inv, proved in an exercise, and the error constant depends on how close X\mat{X} is to singular: in “almost singular” the linear prediction is good only for tiny perturbations because X−1\mat{X}\inv is enormous and changes quickly.

The gradient: the matrix representing dfdf

When ff is scalar, f:Rm×n→Rf: \R^{m\times n} \to \R (a loss), df=f′(X)[dX]df = f'(\mat{X})[d\mat{X}] is a linear form on Rm×n\R^{m\times n}. Representing it with a matrix requires an inner product; naturally use Frobenius, inducing the Frobenius norm:

⟨A,B⟩F=∑i,jAijBij=tr⁡(A⊤B).\inner{\mat{A}}{\mat{B}}_F = \sum_{i,j} A_{ij}B_{ij} = \tr(\mat{A}\T\mat{B}).

It is the ordinary dot product after flattening both matrices, vec⁡(A)⊤vec⁡(B)\operatorname{vec}(\mat{A})\T\operatorname{vec}(\mat{B}). Trace equality is direct: (A⊤B)jj=∑iAijBij(\mat{A}\T\mat{B})_{jj} = \sum_i A_{ij}B_{ij}, and trace sums those over jj.

Proof

Let Eij\mat{E}_{ij} have 11 at (i,j)(i, j) and zeros elsewhere. Define Gij=f′(X)[Eij]G_{ij} = f'(\mat{X})[\mat{E}_{ij}], the directional derivative along Eij\mat{E}_{ij}, i.e. ∂f∂Xij\pd{f}{X_{ij}}. Since dX=∑i,jdXij Eijd\mat{X} = \sum_{i,j} dX_{ij}\,\mat{E}_{ij} and f′(X)f'(\mat{X}) is linear,

f′(X)[dX]=∑i,jdXij Gij=⟨G,dX⟩F.f'(\mat{X})[d\mat{X}] = \sum_{i,j} dX_{ij}\,G_{ij} = \inner{\mat{G}}{d\mat{X}}_F.

This proves existence. If another G′\mat{G}' does the same, ⟨G−G′,dX⟩F=0\inner{\mat{G} - \mat{G}'}{d\mat{X}}_F = 0 for every dXd\mat{X}; take dX=G−G′d\mat{X} = \mat{G} - \mat{G}' to get ∥G−G′∥F2=0\norm{\mat{G} - \mat{G}'}_F^2 = 0.

∎

The gradient having X\mat{X}‘s shape is not cosmetic. It permits W−η ∇WL\mat{W} - \eta\,\grad_{\mat{W}} L. It has precise geometry: by Cauchy–Schwarz, among perturbations with ∥dX∥F=1\norm{d\mat{X}}_F = 1, the first-order greatest increase in ff is dX=∇f/∥∇f∥Fd\mat{X} = \grad f/\norm{\grad f}_F, the steepest ascent direction. “Steepest” is measured in Frobenius norm: changing inner product changes gradient. Natural gradient and optimizers measuring steps in spectral norm exploit this, as in lesson 25.

Key idea
The gradient of a scalar matrix function is defined by df=tr⁡((∇f)⊤dX)df = \tr\big((\grad f)\T d\mat{X}\big): the matrix representing the linear part of change under the Frobenius inner product. It has X\mat{X}‘s shape and partial derivatives as entries.

For vector x∈Rn\vb{x} \in \R^n (an n×1n\times 1 matrix) the definition reduces to df=(∇f)⊤dxdf = (\grad f)\T d\vb{x}, and gradient is the column vector of partials.

Layout conventions and how to avoid them

Consult multiple sources and sooner or later a gradient comes out transposed. The cause is layout conventions: two ways of arranging partial derivatives of one object with respect to another.

  • Numerator layout. Derivative follows the numerator’s shape and denominator transpose. For y∈Rm\vb{y} \in \R^m and x∈Rn\vb{x} \in \R^n, ∂y/∂x\partial\vb{y}/\partial\vb{x} is m×nm\times n, with (i,j)=∂yi/∂xj(i, j) = \partial y_i/\partial x_j: the Jacobian. Scalar by column vector gives a row.
  • Denominator layout. The transpose: ∂y/∂x\partial\vb{y}/\partial\vb{x} is n×mn\times m, and scalar by vector gives a column.

With matrices the disagreement becomes a visible shape issue:

Derivative ofwith respect toNumeratorDenominatorIn Oryon Learn
scalar ffx∈Rn\vb{x} \in \R^n1×n1\times nn×1n\times 1∇f\grad f: n×1n\times 1
y∈Rm\vb{y} \in \R^mx∈Rn\vb{x} \in \R^nm×nm\times nn×mn\times mJacobian J\mat{J}: m×nm\times n
scalar ffX∈Rm×n\mat{X} \in \R^{m\times n}n×mn\times mm×nm\times n∇Xf\grad_{\mat{X}} f: m×nm\times n

Oryon Learn deliberately mixes conventions: Jacobians use Jij=∂yi/∂xjJ_{ij} = \partial y_i/\partial x_j (as in calculus), and scalar-function gradients have the variable’s shape, defined by Frobenius product. They fit: for scalar ff of a vector, the Jacobian is row J=(∇f)⊤\mat{J} = (\grad f)\T, because df=J dx=(∇f)⊤dxdf = \mat{J}\,d\vb{x} = (\grad f)\T d\vb{x}. PyTorch and JAX follow this too: PyTorch W.grad always matches W’s shape, and JAX jax.grad returns an array shaped like the argument.

Sources disagree. The widely cited Matrix Cookbook gives scalar-by-matrix derivatives in X\mat{X}‘s shape (e.g. tr⁡(XA)\tr(\mat{X}\mat{A}) has derivative A⊤\mat{A}\T); some ML texts use numerator layout. Mixing formulas produces a transpose, and square matrices do not even trigger a shape error.

Escape by avoiding derivative tables: always write the differential. Equality df=tr⁡(G⊤dX)df = \tr(\mat{G}\T d\mat{X}) is unambiguous because dXd\mat{X} has X\mat{X}‘s shape and trace exists only when shapes fit.

Differential rules

Every rule follows the same idea: expand f(X+dX)f(\mat{X} + d\mat{X}) and keep terms linear in dXd\mat{X}.

The product rule is proved as in one variable, without commuting any factors:

(X+dX)(Y+dY)−XY=dX Y+X dY+dX dY⏟second order.(\mat{X} + d\mat{X})(\mat{Y} + d\mat{Y}) - \mat{X}\mat{Y} = d\mat{X}\,\mat{Y} + \mat{X}\,d\mat{Y} + \underbrace{d\mat{X}\,d\mat{Y}}_{\text{second order}}.

The order of the factors is always preserved: dXd\mat{X} occupies the place formerly occupied by X\mat{X}. Transposition and trace are linear, so their differential is the same operation applied to dXd\mat{X}. The Hadamard product ⊙\odot (entrywise) does commute, so its rules are the scalar rules applied at each position.

The last two rules are the derivatives of the inverse and log determinant, and deserve separate treatment. For the inverse, differentiate the identity XX−1=I\mat{X}\mat{X}\inv = \mat{I} with the product rule. For the determinant, the cofactor expansion gives the partial derivative directly: expanding along row ii,

det⁡X=∑jXij Cij,\det\mat{X} = \sum_{j} X_{ij}\,C_{ij},

and no cofactor CijC_{ij} in that row depends on the entries in row ii (it is computed by deleting that row). Thus ∂det⁡X/∂Xij=Cij\partial\det\mat{X}/\partial X_{ij} = C_{ij}, and the matrix of partial derivatives is the cofactor matrix C\mat{C}. Since adj⁡(X)=C⊤=det⁡(X) X−1\operatorname{adj}(\mat{X}) = \mat{C}\T = \det(\mat{X})\,\mat{X}\inv, we obtain Jacobi’s formula:

ddet⁡X=⟨C,dX⟩F=tr⁡(adj⁡(X) dX)=det⁡X tr⁡(X−1dX).d\det\mat{X} = \inner{\mat{C}}{d\mat{X}}_F = \tr(\operatorname{adj}(\mat{X})\,d\mat{X}) = \det\mat{X}\,\tr(\mat{X}\inv d\mat{X}).

Dividing by det⁡X\det\mat{X} (the chain rule with the logarithm) gives dlog⁡det⁡X=tr⁡(X−1dX)d\log\det\mat{X} = \tr(\mat{X}\inv d\mat{X}). If det⁡X<0\det\mat{X} < 0, the same holds for log⁡∣det⁡X∣\log\abs{\det\mat{X}}. A second proof, without cofactors, appears in the exercises.

The chain rule also holds in this notation: if Y=g(X)\mat{Y} = g(\mat{X}) and ff depends on Y\mat{Y}, then df=f′(Y)[dY]df = f'(\mat{Y})[d\mat{Y}] with dY=g′(X)[dX]d\mat{Y} = g'(\mat{X})[d\mat{X}]. This is the multivariable chain rule written without indices; in practice it means substituting, as you did above when dividing by det⁡X\det\mat{X}. In the next lesson you will turn it into the backpropagation algorithm.

The trace trick

The rules give dfdf as an expression with dXd\mat{X} buried inside products. To read off the gradient, bring it to the form tr⁡(M dX)\tr(\mat{M}\,d\mat{X}), with dXd\mat{X} alone at the end; then ∇f=M⊤\grad f = \mat{M}\T. The tools are four properties of the trace:

  1. A scalar is its own trace: s=tr⁡(s)s = \tr(s).
  2. Cyclic invariance: tr⁡(ABC)=tr⁡(CAB)=tr⁡(BCA)\tr(\mat{A}\mat{B}\mat{C}) = \tr(\mat{C}\mat{A}\mat{B}) = \tr(\mat{B}\mat{C}\mat{A}), whenever the products make sense. The matrices need not be square.
  3. Transpose: tr⁡(A⊤)=tr⁡(A)\tr(\mat{A}\T) = \tr(\mat{A}).
  4. Hadamard: ⟨A,B⊙C⟩F=⟨A⊙B,C⟩F\inner{\mat{A}}{\mat{B}\odot\mat{C}}_F = \inner{\mat{A}\odot\mat{B}}{\mat{C}}_F (both equal ∑ijAijBijCij\sum_{ij}A_{ij}B_{ij}C_{ij}).

Together these form the trace trick: write dfdf, wrap it in a trace, rotate until dXd\mat{X} is on the right, and read off ∇f=M⊤\grad f = \mat{M}\T. Here are four examples.

The incorrect formula 2Ax2\mat{A}\vb{x} is not merely a notational detail: it is a different vector field, and in general is not even perpendicular to the level curves.

Interactive2Ax2\mat{A}\vb{x} or (A+A⊤)x(\mat{A} + \mat{A}\T)\vb{x}?
Level curves of f(x)=x⊤Axf(\vb{x}) = \vb{x}\T\mat{A}\vb{x} with nonsymmetric A\mat{A}, and the two gradient candidates at x\vb{x}. The blue one, (A+A⊤)x(\mat{A} + \mat{A}\T)\vb{x}, is always perpendicular to the level curve (90° to the dashed tangent). The red one, 2Ax2\mat{A}\vb{x}, deviates by exactly 2Kx2\mat{K}\vb{x} (magenta). Drag the point, change the displayed field, and try «Antisimetría dominante»: the curves are circles and the incorrect field spirals. Enable descent paths to see where each formula leads.

A tiny network: the Hadamard rule in action

Activations enter the calculation through d σ(Z)=σ′(Z)⊙dZd\,\sigma(\mat{Z}) = \sigma'(\mat{Z})\odot d\mat{Z} and property 4. Take a neuron with activation σ\sigma and squared loss L(w)=∥σ(Xw)−y∥2L(\vb{w}) = \norm{\sigma(\mat{X}\vb{w}) - \vb{y}}^2. Let z=Xw\vb{z} = \mat{X}\vb{w} and δ=2(σ(z)−y)\boldsymbol{\delta} = 2(\sigma(\vb{z}) - \vb{y}). Then

dL=δ⊤dσ(z)=δ⊤(σ′(z)⊙X dw)=(σ′(z)⊙δ)⊤X dw,dL = \boldsymbol{\delta}\T d\sigma(\vb{z}) = \boldsymbol{\delta}\T\big(\sigma'(\vb{z})\odot\mat{X}\,d\vb{w}\big) = \big(\sigma'(\vb{z})\odot\boldsymbol{\delta}\big)\T\mat{X}\,d\vb{w},

and the gradient is ∇wL=X⊤(σ′(z)⊙δ)=X⊤diag⁡(σ′(z)) δ\grad_{\vb{w}} L = \mat{X}\T(\sigma'(\vb{z})\odot\boldsymbol{\delta}) = \mat{X}\T\diag(\sigma'(\vb{z}))\,\boldsymbol{\delta}. The three pieces have an interpretation you will recognize in backpropagation: the output error (δ\boldsymbol{\delta}), filtered by the local activation slope (σ′\sigma'), and returned to the weights through the input (X⊤\mat{X}\T).

The next interactive is a test bench. Each tile knows its shape, so an impossible composition is marked red at the exact join, while one with the right shape is checked numerically. The second filter matters: some expressions have the right shape and the wrong value.

InteractiveThe shape game
Build the requested gradient with the tiles: click or drag them into the row. Each tile shows its shape; if a product is impossible, the join turns red. Once the shape matches the variable, the expression is compared with the true gradient and a finite difference in a random direction V\mat{V}. Start with challenge 1, which already has a malformed expression. In challenge 3, try 2Ax2\mat{A}\vb{x}: correct shape, wrong value. Challenge 5 is a hidden layer with a linear readout: you will need ⊙\odot and parentheses.

Least squares and ridge solved by differentials

With ridge regularization, the loss is L(W)=∥XW−Y∥F2+λ∥W∥F2L(\mat{W}) = \norm{\mat{X}\mat{W} - \mat{Y}}_F^2 + \lambda\norm{\mat{W}}_F^2, where X∈Rn×d\mat{X} \in \R^{n\times d}, Y∈Rn×k\mat{Y} \in \R^{n\times k} and λ≥0\lambda \ge 0. The second term is λtr⁡(W⊤W)\lambda\tr(\mat{W}\T\mat{W}), with differential 2λtr⁡(W⊤dW)2\lambda\tr(\mat{W}\T d\mat{W}). Adding the previous example:

∇WL=2X⊤(XW−Y)+2λW.\grad_{\mat{W}} L = 2\mat{X}\T(\mat{X}\mat{W} - \mat{Y}) + 2\lambda\mat{W}.

Setting it equal to zero gives the system

(X⊤X+λI) W=X⊤Y.(\mat{X}\T\mat{X} + \lambda\mat{I})\,\mat{W} = \mat{X}\T\mat{Y}.

With λ=0\lambda = 0 these are the normal equations from lesson 8, now for kk outputs at once. This is no coincidence: ∥⋅∥F2\norm{\cdot}_F^2 sums over columns, so the problem separates into kk independent least-squares problems, one per column of Y\mat{Y}, sharing the matrix X⊤X\mat{X}\T\mat{X}.

Is it a minimum? Differentiate the gradient again: d(∇L)=2(X⊤X+λI) dWd(\grad L) = 2(\mat{X}\T\mat{X} + \lambda\mat{I})\,d\mat{W}. The Hessian is the linear map dW↦2(X⊤X+λI) dWd\mat{W} \mapsto 2(\mat{X}\T\mat{X} + \lambda\mat{I})\,d\mat{W} (with vec, the matrix 2 Ik⊗(X⊤X+λI)2\,\mat{I}_k\otimes(\mat{X}\T\mat{X} + \lambda\mat{I}), block diagonal because the columns do not interact), and the quadratic form it defines is

⟨dW,2(X⊤X+λI) dW⟩F=2(∥X dW∥F2+λ∥dW∥F2).\inner{d\mat{W}}{2(\mat{X}\T\mat{X} + \lambda\mat{I})\,d\mat{W}}_F = 2\big(\norm{\mat{X}\,d\mat{W}}_F^2 + \lambda\norm{d\mat{W}}_F^2\big).

It is positive for every dW≠0d\mat{W} \neq \mat{0} if λ>0\lambda > 0, or if λ=0\lambda = 0 and X\mat{X} has full column rank. Then LL is strictly convex, X⊤X+λI\mat{X}\T\mat{X} + \lambda\mat{I} is positive definite, and the solution is unique. All this, again, without a single index.

The second differential: curvature without indices

What you just did is a general method. Fix a direction dXd\mat{X} and differentiate dfdf again, treating dXd\mat{X} as constant: the result, d2fd^2f, is the quadratic form of the Hessian evaluated at dXd\mat{X}, that is, the curvature of ff in that direction. There is no need to write the Hessian as an mn×mnmn\times mn matrix.

The log determinant is an instructive example. Starting from dlog⁡det⁡X=tr⁡(X−1dX)d\log\det\mat{X} = \tr(\mat{X}\inv d\mat{X}) and using the inverse rule,

d2log⁡det⁡X=tr⁡(d(X−1) dX)=−tr⁡(X−1dX X−1dX).d^2\log\det\mat{X} = \tr\big(d(\mat{X}\inv)\,d\mat{X}\big) = -\tr(\mat{X}\inv d\mat{X}\,\mat{X}\inv d\mat{X}).

If X\mat{X} is symmetric positive definite and dXd\mat{X} is symmetric, set M=X−1/2 dX X−1/2\mat{M} = \mat{X}^{-1/2}\,d\mat{X}\,\mat{X}^{-1/2} (symmetric); cyclic invariance gives d2log⁡det⁡X=−tr⁡(M2)=−∥M∥F2<0d^2\log\det\mat{X} = -\tr(\mat{M}^2) = -\norm{\mat{M}}_F^2 < 0 for every dX≠0d\mat{X} \neq \mat{0}. Therefore log⁡det⁡\log\det is strictly concave on the cone of positive definite matrices. This makes estimation of a Gaussian in terms of its precision matrix Θ=Σ−1\mat{\Theta} = \mat{\Sigma}\inv well posed: up to an additive constant, the log likelihood N2(log⁡det⁡Θ−tr⁡(ΘS))\tfrac{N}{2}\big(\log\det\mat{\Theta} - \tr(\mat{\Theta}\mat{S})\big) for NN observations and sample covariance S\mat{S} (centered at the true or sample mean) is concave in Θ\mat{\Theta} (the second term is linear), so it has no spurious local maxima. Adding an ℓ1\ell_1 penalty on Θ\mat{\Theta} keeps the problem convex: this is the graphical lasso.

Differentiating with respect to a symmetric matrix

There is a case where the definition of gradient requires care: when the variable is constrained to be symmetric, such as a covariance matrix Σ\mat{\Sigma}. Then admissible perturbations are symmetric too, and df=⟨G,dX⟩Fdf = \inner{\mat{G}}{d\mat{X}}_F is required only for symmetric dXd\mat{X}. Since ⟨G,dX⟩F=⟨sym⁡(G),dX⟩F\inner{\mat{G}}{d\mat{X}}_F = \inner{\operatorname{sym}(\mat{G})}{d\mat{X}}_F for every symmetric dXd\mat{X}, with sym⁡(G)=(G+G⊤)/2\operatorname{sym}(\mat{G}) = (\mat{G} + \mat{G}\T)/2, the gradient in the space of symmetric matrices is

∇symf=sym⁡(G).\grad^{\text{sym}} f = \operatorname{sym}(\mat{G}).

Many references give another formula, G+G⊤−G⊙I\mat{G} + \mat{G}\T - \mat{G}\odot\mat{I}, obtained by treating only entries XijX_{ij} with i≤ji \le j as variables: off the diagonal, moving XijX_{ij} also moves XjiX_{ji}, so the partial derivative sums both contributions. As a list of partial derivatives with respect to those n(n+1)/2n(n+1)/2 parameters it is correct. As a gradient with respect to the Frobenius inner product it is not: it does not reproduce dfdf, and gives incorrect results in a descent step or a check with symmetric perturbations. Srinivasan and Panda (2019) analyze this confusion in detail and show that the correct symmetric gradient is sym⁡(G)\operatorname{sym}(\mat{G}). You will check it numerically in the lab.

Numerical verification: the gradient checker

However carefully you work, a hand-written gradient needs a test. The tool is gradient checking with finite differences; do it carefully, because a poorly designed check produces false positives and false negatives.

Random directions, not entries. Checking each partial derivative costs two evaluations of ff per entry: 2mn2mn evaluations for an m×nm\times n matrix. Instead, choose a random (Gaussian) direction V\mat{V} and compare

f(X+hV)−f(X−hV)2hwith⟨∇f,V⟩F.\frac{f(\mat{X} + h\mat{V}) - f(\mat{X} - h\mat{V})}{2h} \quad\text{with}\quad \inner{\grad f}{\mat{V}}_F.

That is two evaluations per direction, regardless of the size of X\mat{X}. And they suffice: if your gradient G~\tilde{\mat{G}} differs from the true one, ⟨G~−G,V⟩F\inner{\tilde{\mat{G}} - \mat{G}}{\mat{V}}_F is a normal random variable with standard deviation ∥G~−G∥F>0\norm{\tilde{\mat{G}} - \mat{G}}_F > 0, so it differs from zero with probability 1. A few directions reveal the error.

Relative error. Compare using ∣a−b∣/max⁡(∣a∣,∣b∣)\abs{a - b}/\max(\abs{a}, \abs{b}), not the absolute difference: a gradient of size 10410^4 with absolute error 10−610^{-6} is excellent, while one of size 10−810^{-8} with the same error is completely wrong.

Choosing hh. The centered difference error has two sources. By Taylor’s theorem (Taylor remainder), with φ(t)=f(X+tV)\varphi(t) = f(\mat{X} + t\mat{V}),

φ(h)−φ(−h)2h=φ′(0)+φ′′′(0)6h2+O(h4),\frac{\varphi(h) - \varphi(-h)}{2h} = \varphi'(0) + \frac{\varphi'''(0)}{6}h^2 + O(h^4),

so the truncation error is of order ∣φ′′′∣h2/6\abs{\varphi'''}h^2/6. But φ(±h)\varphi(\pm h) is computed in floating point, with relative error of the order of unit roundoff uu (2−53≈1.1×10−162^{-53} \approx 1.1\times 10^{-16} in float64, 2−24≈6×10−82^{-24} \approx 6\times 10^{-8} in float32; see machine epsilon). Subtracting two nearly equal numbers preserves their absolute error, of order u∣f∣u\abs{f}, and divides it by 2h2h: this is catastrophic cancellation, producing roundoff error of order u∣f∣/hu\abs{f}/h. The total,

E(h)≈∣φ′′′∣6h2+u∣f∣h,E(h) \approx \frac{\abs{\varphi'''}}{6}h^2 + \frac{u\abs{f}}{h},

is a V on a logarithmic scale, with minimum at h⋆=(3u∣f∣/∣φ′′′∣)1/3h^\star = (3u\abs{f}/\abs{\varphi'''})^{1/3} and minimum error of order u2/3u^{2/3}. With constants of order 1, this gives h⋆∼10−5h^\star \sim 10^{-5} and relative errors from 10−1010^{-10} to 10−1110^{-11} in float64, but h⋆∼10−3h^\star \sim 10^{-3} and errors of 10−510^{-5} at best in float32. The forward difference, (φ(h)−φ(0))/h(\varphi(h) - \varphi(0))/h, has truncation of order hh: its optimum is h⋆∼uh^\star \sim \sqrt{u} and its minimum error is of order u≈10−8\sqrt{u} \approx 10^{-8} in float64. That is why the centered difference is used.

InteractiveThe finite-difference V
Relative finite-difference error against hh, actually computed in your browser in float64 (blue) and float32 (orange, emulated). On the right truncation dominates (slope 2 for centered, 1 for forward); on the left, roundoff (slope −1). Find the bottom of each V and compare it with the theoretical h⋆h^\star. For the quadratic the right branch disappears: its third derivative is zero. Enable «Gradiente con un fallo sutil»: in float64 the error rises above the floor of the V; in float32, with the popular h=10−5h = 10^{-5}, it is buried in noise.

The figure gives three practical rules:

  1. Check in float64. In float32 the floor of the V is so high that an error of relative size 10−310^{-3} may be indistinguishable from noise. If your model trains in float32 or bf16, check a float64 copy.
  2. Use centered differences with hh between 10−610^{-6} and 10−410^{-4} (in float64, with reasonably scaled data). Neither 10−1010^{-10} “just in case”, which leaves you on the roundoff branch, nor 10−110^{-1}.
  3. Interpret the number with the V in mind. In float64, with a well-chosen hh, a correct gradient gives relative errors of 10−810^{-8} or less, while a flawed one gives errors comparable to the size of the flaw. Beware nondifferentiable functions (ReLU, maxima, absolute values): if X±hV\mat{X} \pm h\mat{V} crosses an edge, the check fails even if the gradient is correct.

Implementation from scratch

Start with the analytic gradients of the lesson’s four functions, as obtained from the trace trick.

[ ]Analytic gradientsBrowser
import numpy as np

rng = np.random.default_rng(0)

def f_ridge(W, X, Y, lam):
    R = X @ W - Y
    return np.sum(R * R) + lam * np.sum(W * W)

def g_ridge(W, X, Y, lam):
    return 2 * X.T @ (X @ W - Y) + 2 * lam * W   # 2 Xᵀ(XW − Y) + 2λW

def f_quad(x, A):
    return x @ A @ x

def g_quad(x, A):
    return (A + A.T) @ x                          # no 2Ax

def f_logdet(X):
    sign, ld = np.linalg.slogdet(X)               # estable: nunca forma det(X)
    return ld

def g_logdet(X):
    return np.linalg.inv(X).T                     # X^{-T}

def f_trace(X, A, B):
    return np.trace(A @ X @ B)

def g_trace(X, A, B):
    return A.T @ B.T

# datos de prueba
n, d, k = 30, 5, 3
Xd = rng.standard_normal((n, d)); Yd = rng.standard_normal((n, k)); W0 = rng.standard_normal((d, k))
A = rng.standard_normal((4, 4)); x0 = rng.standard_normal(4)
M = rng.standard_normal((4, 4)) + 4 * np.eye(4)          # bien condicionada, det > 0
At = rng.standard_normal((2, 4)); Bt = rng.standard_normal((5, 2)); Xt = rng.standard_normal((4, 5))
print("forma del gradiente de ridge:", g_ridge(W0, Xd, Yd, 0.1).shape, "  forma de W:", W0.shape)
print("forma del gradiente de tr(AXB):", g_trace(Xt, At, Bt).shape, "  forma de X:", Xt.shape)

The checker is generic: it takes ff, its gradient and a point, and returns the worst relative error across several random directions.

[ ]A generic gradient checkerBrowser
def grad_check(f, grad_f, X, h=1e-5, n_dirs=5, seed=0):
    """Peor error relativo entre <grad_f(X), V> y la diferencia centrada en direcciones aleatorias V."""
    r = np.random.default_rng(seed)
    G = grad_f(X)
    assert G.shape == np.shape(X), f"el gradiente tiene forma {G.shape} y la variable {np.shape(X)}"
    peor = 0.0
    for _ in range(n_dirs):
        V = r.standard_normal(np.shape(X))
        fd = (f(X + h * V) - f(X - h * V)) / (2 * h)
        an = np.sum(G * V)
        peor = max(peor, abs(fd - an) / max(abs(fd), abs(an), 1e-300))
    return peor

import pandas as pd

casos = {
    "ridge  2Xᵀ(XW−Y) + 2λW": (lambda W: f_ridge(W, Xd, Yd, 0.1), lambda W: g_ridge(W, Xd, Yd, 0.1), W0),
    "xᵀAx  (A + Aᵀ)x": (lambda x: f_quad(x, A), lambda x: g_quad(x, A), x0),
    "log det X  X⁻ᵀ": (f_logdet, g_logdet, M),
    "tr(AXB)  AᵀBᵀ": (lambda X: f_trace(X, At, Bt), lambda X: g_trace(X, At, Bt), Xt),
    "MAL: xᵀAx con 2Ax": (lambda x: f_quad(x, A), lambda x: 2 * A @ x, x0),
    "MAL: log det con X⁻¹": (f_logdet, lambda X: np.linalg.inv(X), M),
    "MAL: ridge sin 2λW": (lambda W: f_ridge(W, Xd, Yd, 0.1), lambda W: 2 * Xd.T @ (Xd @ W - Yd), W0),
}
tabla = pd.DataFrame({"error relativo": {k: grad_check(*v) for k, v in casos.items()}})
tabla["veredicto"] = np.where(tabla["error relativo"] < 1e-6, "correcto", "FALLO")
tabla["error relativo"] = tabla["error relativo"].map("{:.1e}".format)
tabla

The four correct gradients give relative errors of 10−910^{-9} or less, and the three incorrect ones errors of order 10−310^{-3} to 11. The ridge error is the smallest because the missing term, 2λW2\lambda\mat{W}, is small compared with the data term; even so, it remains several orders of magnitude above the float64 floor.

Now reproduce the V. NumPy computes in float32 if the data are float32, so converting the matrix and direction suffices.

[ ]The V in float64 and float32Browser
import matplotlib.pyplot as plt

Vd = np.random.default_rng(1).standard_normal(M.shape)
exacta = np.sum(g_logdet(M) * Vd)
hs = 10.0 ** np.arange(-14, 0.01, 0.25)

def curva(dtype, centrada=True):
    Mx, Vx = M.astype(dtype), Vd.astype(dtype)
    errs = []
    for h in hs:
        h = dtype(h)
        if centrada:
            fd = (f_logdet(Mx + h * Vx) - f_logdet(Mx - h * Vx)) / (2 * h)
        else:
            fd = (f_logdet(Mx + h * Vx) - f_logdet(Mx)) / h
        errs.append(max(abs(float(fd) - exacta) / abs(exacta), 1e-17))
    return np.array(errs)

fig, ax = plt.subplots(figsize=(7, 4))
for dtype, nombre in [(np.float64, "float64"), (np.float32, "float32")]:
    e = curva(dtype)
    ax.loglog(hs, e, label=f"centrada, {nombre}")
    print(f"{nombre}: mejor h = {hs[e.argmin()]:.0e}, error relativo mínimo = {e.min():.1e}")
e = curva(np.float64, centrada=False)
ax.loglog(hs, e, "--", label="hacia delante, float64")
print(f"hacia delante float64: mejor h = {hs[e.argmin()]:.0e}, error relativo mínimo = {e.min():.1e}")
ax.set_xlabel("h"); ax.set_ylabel("error relativo"); ax.legend()
plt.show()

The minimum of each curve falls where the analysis predicts: around 10−510^{-5} in float64 with the centered difference, around 10−810^{-8} with the forward difference, and between 10−310^{-3} and 10−110^{-1} in float32 (the h⋆h^\star calculation gives only the order of magnitude), with a floor five or six orders of magnitude higher than in float64.

Finally, the section on symmetric matrices in numbers. For f(X)=log⁡det⁡Xf(\mat{X}) = \log\det\mat{X} the gradient G=X−⊤\mat{G} = \mat{X}^{-\top} is already symmetric if X\mat{X} is, so use a function with nonsymmetric G\mat{G}: f(X)=a⊤Xb+log⁡det⁡Xf(\mat{X}) = \vb{a}\T\mat{X}\vb{b} + \log\det\mat{X}.

[ ]Gradient with respect to a symmetric matrixBrowser
r = np.random.default_rng(3)
B = r.standard_normal((4, 4)); S = B @ B.T + 4 * np.eye(4)      # simétrica definida positiva
a, b = r.standard_normal(4), r.standard_normal(4)
f_sim = lambda X: a @ X @ b + f_logdet(X)
G = np.outer(a, b) + np.linalg.inv(S)                           # gradiente "libre"
sym = lambda Z: (Z + Z.T) / 2
candidatos = {"G (libre)": G, "sym(G)": sym(G), "G + Gᵀ − G∘I": G + G.T - G * np.eye(4)}

V = sym(r.standard_normal((4, 4)))                              # perturbación simétrica
h = 1e-5
fd = (f_sim(S + h * V) - f_sim(S - h * V)) / (2 * h)
for nombre, Gc in candidatos.items():
    an = np.sum(Gc * V)
    print(f"{nombre:14s} <G, V> = {an:+.6f}   error relativo = {abs(an - fd) / abs(fd):.1e}   ¿simétrico? {np.allclose(Gc, Gc.T)}")

G\mat{G} and sym⁡(G)\operatorname{sym}(\mat{G}) correctly predict the directional derivative (both have the same inner product with symmetric V\mat{V}), but only sym⁡(G)\operatorname{sym}(\mat{G}) is symmetric: a step X−ηG\mat{X} - \eta\mat{G} would leave the set of symmetric matrices. The formula G+G⊤−G⊙I\mat{G} + \mat{G}\T - \mat{G}\odot\mat{I} is symmetric but incorrectly predicts the derivative.

CodeGradient checker and ridge gradient
Implement grad_check(f, grad_f, X, eps=1e-6, n_dirs=10, seed=0), returning (as float) the worst relative error ∣a−b∣/max⁡(∣a∣,∣b∣)\abs{a - b}/\max(\abs{a}, \abs{b}) between the centered difference in a Gaussian direction V and ⟨grad_f(X),V⟩F\inner{\texttt{grad\_f(X)}}{\mat{V}}_F, over n_dirs directions generated with np.random.default_rng(seed). It must not modify X. Also implement ridge_grad(W, X, Y, lam), the gradient of ∥XW−Y∥F2+λ∥W∥F2\norm{\mat{X}\mat{W} - \mat{Y}}_F^2 + \lambda\norm{\mat{W}}_F^2 with respect to W\mat{W}. The tests check that your checker accepts a correct gradient and detects two incorrect ones: one without the regularization term and another transposed in a square matrix, where shape reveals nothing.
import numpy as np

def grad_check(f, grad_f, X, eps=1e-6, n_dirs=10, seed=0):
  """Peor error relativo entre <grad_f(X), V> y la diferencia centrada."""
  # tu código
  ...

def ridge_grad(W, X, Y, lam):
  """Gradiente de ||XW - Y||_F^2 + lam ||W||_F^2 respecto a W."""
  # tu código
  ...
Shift+Enter to run

The professional version: autograd

Deep learning libraries do not differentiate using finite differences or symbolic algebra: they apply reverse-mode automatic differentiation, exactly the systematic composition of the rules in this lesson (you will see the algorithm in the next lesson and in backpropagation). PyTorch implements the differentials of logdet, inv and the like; your formulas should match them up to roundoff. The cell needs PyTorch, so it runs in the local lab.

[ ]Your gradients versus torch.autogradLocal GPU
import warnings
import torch
from torch.autograd import gradcheck

torch.manual_seed(0)
n, d, k, lam = 64, 8, 3, 0.1
X = torch.randn(n, d, dtype=torch.float64)
Y = torch.randn(n, k, dtype=torch.float64)
W = torch.randn(d, k, dtype=torch.float64, requires_grad=True)

L = ((X @ W - Y) ** 2).sum() + lam * (W ** 2).sum()
L.backward()
G_mano = 2 * X.T @ (X @ W.detach() - Y) + 2 * lam * W.detach()
print("ridge, autograd = 2Xᵀ(XW − Y) + 2λW:", torch.allclose(W.grad, G_mano))

B = torch.randn(5, 5, dtype=torch.float64)
S = (B @ B.T + 5 * torch.eye(5, dtype=torch.float64)).requires_grad_()
torch.logdet(S).backward()
print("log det, autograd = X⁻ᵀ:", torch.allclose(S.grad, torch.linalg.inv(S.detach()).T))

Mt = (torch.randn(4, 4, dtype=torch.float64) + 4 * torch.eye(4, dtype=torch.float64)).requires_grad_()
C = torch.randn(4, 4, dtype=torch.float64)
torch.trace(C @ torch.linalg.inv(Mt)).backward()
Mi = torch.linalg.inv(Mt.detach())
print("tr(C X⁻¹), autograd = −(X⁻¹ C X⁻¹)ᵀ:", torch.allclose(Mt.grad, -(Mi @ C @ Mi).T))

# gradcheck compara autograd con diferencias finitas, entrada a entrada
f = lambda Z: torch.logdet(Z @ Z.T + torch.eye(4, dtype=Z.dtype))
Z64 = torch.randn(4, 4, dtype=torch.float64, requires_grad=True)
print("gradcheck en float64:", gradcheck(f, (Z64,), eps=1e-6, atol=1e-8, rtol=1e-6))
Z32 = Z64.detach().float().requires_grad_()
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    print("gradcheck en float32, mismas tolerancias:", gradcheck(f, (Z32,), eps=1e-6, atol=1e-8, rtol=1e-6, raise_exception=False))
    print("gradcheck en float32, h = 1e-2 y tolerancias laxas:", gradcheck(f, (Z32,), eps=1e-2, atol=1e-3, rtol=1e-2, raise_exception=False))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

All three comparisons give True: autograd and your formulas are the same. gradcheck passes in float64 and fails in float32 with the same tolerances, although the autograd gradient is perfectly correct: this is the left branch of the V. With h=10−2h = 10^{-2} and tolerances of order 10−310^{-3} it passes again, but now with a threshold that would miss errors of that size. That is why the gradcheck documentation asks for double-precision inputs.

Cookbooks and how not to depend on them

The Matrix Cookbook by Petersen and Pedersen is a useful reference: dozens of pages of identities, including derivatives of determinants, inverses and traces. But as a source of truth it has three problems. Its layout need not match that of the source for the other half of your calculation. Its formulas for structured matrices (symmetric, diagonal) require interpreting what “derivative” means there. And a formula found in a table does not adapt to your case: it almost never contains your exact loss.

With what you know, you no longer need the table. Any entry can be rederived in two or three lines: write dfdf using the rules, apply the trace trick and read off the gradient. And every formula, your own or copied, passes the same quality checks:

  1. Shape: ∇Xf\grad_{\mat{X}} f has the shape of X\mat{X}.
  2. Scalar case: for 1×11\times 1 matrices it must reduce to the familiar derivative. ∇log⁡det⁡X=X−⊤\grad\log\det\mat{X} = \mat{X}^{-\top} gives 1/x1/x. (A+A⊤)x(\mat{A} + \mat{A}\T)\vb{x} gives 2ax2ax.
  3. Numerical check in float64, using centered differences in random directions.

The third step is the only one you cannot skip: the first two miss a transpose in a square matrix or σ\sigma where σ′\sigma' belongs.

Common mistakes

Exercises

NumericA nonsymmetric quadratic
Let f(x)=x⊤Axf(\vb{x}) = \vb{x}\T\mat{A}\vb{x} with A=[1203]\mat{A} = \begin{bmatrix} 1 & 2 \\ 0 & 3 \end{bmatrix}. Calculate the second component of ∇f\grad f at x=(1,2)\vb{x} = (1, 2).
QuizShapes and conventions
W\mat{W} has shape (d,k)(d, k) and LL is scalar. What is the shape of ∇WL\grad_{\mat{W}} L in the Oryon Learn convention (that of W.grad in PyTorch) and what is the shape of the derivative ∂L/∂W\partial L/\partial\mat{W} in numerator layout?
NumericThe gradient of a trace
Let f(X)=tr⁡(AXB)f(\mat{X}) = \tr(\mat{A}\mat{X}\mat{B}) with A=[1234]\mat{A} = \begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} and B=[0121]\mat{B} = \begin{bmatrix} 0 & 1 \\ 2 & 1 \end{bmatrix}. What is entry (1,2)(1, 2) of ∇Xf\grad_{\mat{X}} f, that is, ∂f/∂X12\partial f/\partial X_{12}?
NumericAn entry of X⁻ᵀ
For X=[2103]\mat{X} = \begin{bmatrix} 2 & 1 \\ 0 & 3 \end{bmatrix}, calculate ∂log⁡det⁡X/∂X21\partial \log\det\mat{X} / \partial X_{21}.
ProofThe differential of the inverse
Prove: If X\mat{X} is invertible, d(X−1)=−X−1 dX X−1d(\mat{X}\inv) = -\mat{X}\inv\,d\mat{X}\,\mat{X}\inv.
0
Let X\mat{X} be invertible. Assume X↦X−1\mat{X}\mapsto\mat{X}\inv is differentiable at X\mat{X} (its entries are quotients of polynomials with denominator det⁡X≠0\det\mat{X} \ne 0).

Step 1 of 3. Which identity is a useful starting point?

ProofThe log determinant gradient without cofactors
Prove: If det⁡X>0\det\mat{X} > 0, then dlog⁡det⁡X=tr⁡(X−1dX)d\log\det\mat{X} = \tr(\mat{X}\inv d\mat{X}), and therefore ∇Xlog⁡det⁡X=X−⊤\grad_{\mat{X}}\log\det\mat{X} = \mat{X}^{-\top}.
0
Let X∈Rn×n\mat{X} \in \R^{n\times n} with det⁡X>0\det\mat{X} > 0. Use the multiplicativity of determinants and the fact that det⁡(I+E)\det(\mat{I} + \mat{E}) is the product of 1+μi1 + \mu_i, where μi\mu_i are the (generally complex) eigenvalues of E\mat{E}.

Step 1 of 4. How do you factor the perturbation in det⁡(X+dX)\det(\mat{X} + d\mat{X})?

QuizWhich differentials are correct?
X\mat{X} is square, n×nn\times n with n≥2n \ge 2, invertible and satisfying the conditions needed for everything to be defined. Which equalities hold for every perturbation dXd\mat{X}?

More than one answer may be correct.

QuizReading a gradient check
You implement a new layer and its gradient by hand. The model uses float32 and you check in float32 with centered differences and h=10−6h = 10^{-6}: the relative error is 4×10−24\times 10^{-2}. What do you conclude?
QuizA covariance as variable
You optimize f(Σ)f(\mat{\Sigma}) over symmetric positive definite matrices. Treating Σ\mat{\Sigma} as an arbitrary matrix gives df=tr⁡(G⊤dΣ)df = \tr(\mat{G}\T d\mat{\Sigma}) with G\mat{G} not symmetric. Which statements are true?

More than one answer may be correct.

Summary

  • The derivative of a matrix function is a linear map: df=f′(X)[dX]df = f'(\mat{X})[d\mat{X}] is the part of the change linear in dXd\mat{X}. Thus d(X2)=X dX+dX Xd(\mat{X}^2) = \mat{X}\,d\mat{X} + d\mat{X}\,\mat{X}, without forming a Jacobian.
  • For a scalar function, the gradient is the matrix defined by df=tr⁡((∇f)⊤dX)df = \tr\big((\grad f)\T d\mat{X}\big). It has the shape of X\mat{X} and its entries are the partial derivatives.
  • The differential rules (product preserving order, transpose, trace, Hadamard, d(X−1)=−X−1dX X−1d(\mat{X}\inv) = -\mat{X}\inv d\mat{X}\,\mat{X}\inv and dlog⁡det⁡X=tr⁡(X−1dX)d\log\det\mat{X} = \tr(\mat{X}\inv d\mat{X})) suffice for almost any loss.
  • The trace trick brings dfdf to the form tr⁡(M dX)\tr(\mat{M}\,d\mat{X}), from which ∇f=M⊤\grad f = \mat{M}\T can be read. This yields (A+A⊤)x(\mat{A} + \mat{A}\T)\vb{x}, 2X⊤(XW−Y)2\mat{X}\T(\mat{X}\mat{W} - \mat{Y}), A⊤B⊤\mat{A}\T\mat{B}\T and X−⊤\mat{X}^{-\top} without layout ambiguity.
  • Every hand-written gradient is checked with centered differences in random directions, in float64 and with hh at the bottom of the V. The correct shape is necessary but not sufficient.
Key idea
Do not differentiate index by index or copy from a table: write the differential, rotate the trace until dXd\mat{X} is on the right, read off the gradient, and check it numerically.