Linear algebra for machine learning
Take the matrix and multiply it into the vector , then multiply the result by the same matrix again, twenty times in all. Two things happen. The vector swings around until it points along , and after that every multiplication makes it three times longer, to many decimal places, so by the end it is about 2.5 billion times longer than it started. Start from almost any other vector and the same thing happens.
That small experiment contains most of this section. The direction the vector settles into is an eigenvector, the factor of three is its eigenvalue, and the procedure itself is power iteration, the algorithm that estimates the spectral norm inside spectral normalization. Swap "twenty multiplications" for "twenty steps of a recurrent network" and you have the reason RNN gradients explode or vanish.
The rest of the book keeps asking questions of this kind. Why do gradients through fifty steps of an RNN die (§3.3)? Why can LoRA fine-tune a matrix by training only 65,536 numbers (§14.5)? Why does the Muon optimizer throw away the singular values of its update (§8.6)? What exactly does PCA keep (§1.6)? Each one is a question about what a matrix does to directions. We will answer them with a handful of ideas (eigenvalues, the singular value decomposition, norms, and conditioning), building each from a picture you can draw, to a proof, to NumPy, to the weight matrices of a trained Transformer.
A matrix is a map you can draw
A matrix sends each vector to , and its columns tell you where the two basis vectors go. For our matrix, lands on the first column and on the second column . Every other vector follows by linearity, , so the whole map is fixed by two arrows.
A good way to see a matrix is to watch what it does to the unit circle. A linear map sends the circle to an ellipse (flattened to a line segment if the matrix is singular), and the unit square to a parallelogram whose area is . For our matrix the determinant is , so areas triple. A negative determinant means the map also flips orientation, like a mirror.
The widget below lets you set the four entries and watch the circle deform. It also draws two special pairs of directions, which the rest of this section explains. The eigenvectors are the directions that the map only stretches, without turning. The singular vectors are the directions on the circle that land on the axes of the ellipse.
The shear leaves exactly one direction unturned, the axis, and the ellipse's axes point somewhere else entirely. The rotation turns every direction, so it has no real eigenvectors at all, yet its "ellipse" is the circle itself, with every direction an axis. Eigenvectors and the axes of the ellipse are different objects, and they agree only for special matrices. We take them one at a time.
Eigenvectors, the directions a matrix only stretches
An eigenvector of a square matrix is a nonzero vector that maps to a multiple of itself, and the multiple is its eigenvalue,
In plain words, along an eigenvector the matrix acts like the single number . It stretches (if ), shrinks (if ), or flips (if ), and never turns.
How do we find them? Rewrite the equation as . A nonzero solution exists exactly when is singular, that is, when . For a matrix this determinant is , which expands to
where is the trace. Comparing with shows that the eigenvalues add up to the trace and multiply to the determinant. Both facts hold for matrices too.
A worked example. For the trace is 4 and the determinant is 3, so and the eigenvalues are 3 and 1. For , , whose null space is spanned by , so . For , has every entry equal to 1, and . Now the opening experiment makes sense. The starting vector is . After multiplications it is , so the part wins by a factor of , and the tangent of the angle to is exactly .
Three other matrices show everything that can go wrong.
- A rotation by 90 degrees, , has trace 0 and determinant 1, so and . No real direction survives a quarter turn unturned. The eigenvalues are complex, of absolute value 1, because a rotation neither stretches nor shrinks.
- A shear, , has , a double eigenvalue of 1, but has only a one-dimensional null space, the axis. There is one eigenvector where we needed two. Such a matrix is called defective.
- A triangular matrix, , has eigenvalues 3 and 5 (for a triangular matrix they are the diagonal entries). Its eigenvectors are and , which meet at about 27 degrees instead of 90. Real eigenvalues, but skewed eigenvectors. We will meet this matrix again.
Diagonalization and powers
If has linearly independent eigenvectors, collect them as the columns of and the eigenvalues in the diagonal matrix . The equations say, column by column, . Multiplying on the right by gives the eigendecomposition
The second identity follows because the inner factors cancel in pairs, , and so on. In plain words, change to the eigenvector coordinates, where the matrix is a separate scalar on each axis, raise each scalar to the -th power, and change back. Powers of a matrix are powers of its eigenvalues.
So the long-run behavior of is set by the spectral radius . If , every component shrinks and . If , the component along the largest eigenvalue grows without bound. You have already used this. Gradient descent on a quadratic in §0.6 multiplies the error by every step, whose eigenvalues are , and the stability condition is exactly .
Eigenvalues and eigenvector of a symmetric 2-by-2, by hand
For the symmetric matrix , implement eig_sym_2x2(a, b, c) returning (lam1, lam2, v1) with lam1 >= lam2 and v1 a unit eigenvector (shape (2,)) for lam1. Use the closed form, without np.linalg. It must work when , including when .
Symmetric matrices and the spectral theorem
The rotation, the shear, and the triangular matrix all misbehave in some way. Symmetric matrices, with , never do, and they are everywhere in machine learning. Covariance matrices, Hessians, Gram matrices , and kernel matrices are all symmetric. Their good behavior is a theorem.
The spectral theorem. Every real symmetric matrix can be written as
with real eigenvalues and orthonormal eigenvectors (the columns of ). In plain words, a symmetric matrix is a rotation into a special set of perpendicular axes, a separate stretch along each axis, and a rotation back. Since is orthogonal, its inverse is its transpose, and the second form writes as a weighted sum of rank-one matrices , each of which projects onto one axis.
∂ Proof of the spectral theorem
Three steps. Throughout, is real and symmetric, and a bar denotes complex conjugation.
1. Every eigenvalue is real. Suppose with , allowing and to be complex. Multiply on the left by to get . Conjugating the eigen-equation gives (since is real), and transposing it gives (since ). Multiply that on the right by , so . The two expressions for the same number give . Since , we get , so is real. A real eigenvalue makes a real singular matrix, so a real eigenvector exists too.
2. Eigenvectors for different eigenvalues are orthogonal. Let and with . Then . So , which forces .
3. There is a full orthonormal basis of eigenvectors, even with repeated eigenvalues. Induct on . For there is nothing to prove. For general , the characteristic polynomial has at least one complex root, which by step 1 is real, with a real unit eigenvector . Let be the -dimensional subspace of vectors orthogonal to . The key observation is that maps into itself. If , then , so as well. Choose an orthonormal basis of , the columns of . Then is a symmetric matrix that represents on , and by the induction hypothesis it has an orthonormal basis of eigenvectors . The vectors are orthonormal, orthogonal to , and eigenvectors of (because lies in , it equals ). Together with they form the basis. ∎
The Rayleigh quotient
How much does a symmetric matrix stretch a given direction? The Rayleigh quotient answers it,
Expand in the eigenvector basis. Orthonormality makes the cross terms vanish, so and , and
In plain words, the Rayleigh quotient is a weighted average of the eigenvalues, with weights saying how much of lies along each eigenvector. So it can never leave the range of the eigenvalues, and it reaches exactly at the top eigenvector. This gives the most useful characterization of the extreme eigenvalues, and .
When is a Hessian, is the curvature of the loss along direction , and is the curvature of the steepest direction, often called the sharpness. §0.6 showed that gradient descent is stable only if . Cohen et al. (2021) found empirically that in full-batch training of neural networks, the sharpness rises until it reaches about and then hovers there, a regime they called the edge of stability.
Positive definite matrices
A symmetric matrix is positive definite (PD) if for every , and positive semidefinite (PSD) if . Geometrically, the quadratic is a bowl that curves upward in every direction, and its level set is an ellipse with axes along the eigenvectors and half-lengths .
Several conditions are equivalent, and each is useful in a different place.
- All eigenvalues are positive. By the Rayleigh quotient, , which is positive for every nonzero exactly when .
- A Cholesky factor exists, with lower triangular and a positive diagonal. You used it in §0.4 to sample from a multivariate Gaussian. Trying a Cholesky factorization is also the standard numerical test for positive definiteness, since it fails partway through if the matrix is not PD and costs a small fraction of an eigendecomposition.
- It is a Gram matrix of independent vectors, with of full column rank.
That last form shows where PSD matrices come from. For any , , so every Gram matrix is PSD, and it is PD exactly when no nonzero has . That fails whenever there are more features than examples (), which is why the least-squares matrix can be singular. A covariance matrix is PSD for the same reason, since , a variance. And adding shifts every eigenvalue up by without changing the eigenvectors, because . That is the one-line reason ridge regression in §0.4 always has a unique solution. Finally, at a strict local minimum the Hessian is PSD, and at a saddle point it has eigenvalues of both signs (§0.6).
The singular value decomposition
Eigenvectors need a square matrix, and even then they can be complex, missing, or skewed. The singular value decomposition (SVD) works for every matrix, of any shape, with no exceptions. It says that every matrix has an orthonormal basis of its input space and an orthonormal basis of its output space such that
where , and are orthogonal, and holds the singular values on its diagonal and zeros elsewhere. In plain words, every linear map is a rotation of the input (), a stretch of each axis by (which also drops or pads dimensions to change the shape), and a rotation into the output (). The are the right singular vectors, the the left singular vectors.
In two dimensions this is the ellipse in the widget. The right singular vectors are the two perpendicular directions on the unit circle that land on the ellipse's axes, the left singular vectors point along those axes, and the singular values are the semi-axis lengths. The number of nonzero singular values is the rank . The first left singular vectors span the column space (everything can output), and the last right singular vectors span the null space (everything it sends to zero). In code you almost always want the thin SVD, which keeps only columns, , , .
∂ Why the SVD exists, from the spectral theorem
The matrix is symmetric and PSD, since . By the spectral theorem, with orthonormal and eigenvalues . Define .
Note that . For each with , define . These are orthonormal, because
For with , , so for any choice of . Complete the 's to an orthonormal basis of (by Gram-Schmidt). Now holds for every , which in matrix form is . Multiply on the right by . ∎
The proof also shows the connection to eigenvalues. The squared singular values of are the eigenvalues of (and of , apart from extra zeros), the right singular vectors are its eigenvectors, and the left singular vectors are the eigenvectors of .
A worked example you can check by hand. Take the triangular matrix again. Then , with eigenvalues and and eigenvectors and . So and . The left singular vectors are and . As a check, , the area scaling.
Compare with the eigenvalues, 3 and 5. The matrix stretches some direction by 6.7, far more than its largest eigenvalue suggests, because its eigenvectors are skewed. For a symmetric matrix the two decompositions agree (the singular values are and the singular vectors are eigenvectors, up to sign), but in general they answer different questions. Eigenvalues govern what happens after many repeated applications, . Singular values govern what one application can do. One inequality always holds, , since for any eigenpair.
Matrix norms
How big is a matrix? There are several honest answers, and the three that matter most are all functions of the singular values.
- The spectral norm, , the largest stretch of any direction (also called the operator norm). To see that it equals , write , a Rayleigh quotient of , whose maximum is its top eigenvalue .
- The Frobenius norm, , the Euclidean length of all entries. The second equality holds because , and the trace of a symmetric matrix is the sum of its eigenvalues, here the .
- The nuclear norm, , the sum of all stretches.
In plain words, the spectral norm is the worst case over directions, the Frobenius norm is a root-mean-square over directions times a constant, and the nuclear norm is the total. All three are unchanged by rotations on either side, for orthogonal , because rotations do not change singular values.
For a matrix of rank they are tied together by and (the upper bounds are Cauchy-Schwarz on the nonzero singular values). The ratio
is the stable rank, a count of "how many directions really matter" that, unlike the rank, does not jump when tiny singular values appear or vanish. The spectral norm is also submultiplicative, , since stretching by at most and then at most stretches by at most their product.
| norm | in singular values | what it measures | where you meet it |
|---|---|---|---|
| spectral | largest stretch, the Lipschitz constant of | RNN gradient bounds (§3.3), spectral normalization, σReparam (§5.7), Muon (§8.6) | |
| Frobenius | total energy, the length of the entries as one vector | weight decay, low-rank approximation error, gradient clipping (§0.6) | |
| nuclear | total stretch, the tightest convex stand-in for rank | low-rank matrix recovery, the dual of the spectral norm in Muon |
The spectral norm deserves one more sentence, because it bounds how much a whole network can amplify a perturbation. With activations whose slopes are at most 1 (ReLU and tanh, for example), a stack of linear layers satisfies . Spectral normalization (Miyato et al., 2018) divides each weight matrix by an estimate of its spectral norm, so every layer is at most 1-Lipschitz, which stabilized GAN training. The σReparam fix for attention entropy collapse in §5.7 uses the same estimate.
Low-rank approximation and the Eckart-Young theorem
The SVD writes a matrix as a sum of rank-one pieces, , ordered from the largest stretch to the smallest. The obvious way to compress it is to keep the first pieces,
the truncated SVD. It needs numbers instead of . The Eckart-Young theorem says that nothing of rank does better.
The Eckart-Young theorem (Eckart & Young, 1936, for the Frobenius norm, and Mirsky, 1960, for every rotation-invariant norm). For every matrix of rank at most ,
and the truncated SVD achieves both bounds. In plain words, the best rank- approximation keeps the largest stretches, and its error is exactly what was thrown away, the next singular value in the spectral norm and the root of the sum of the remaining squared singular values in the Frobenius norm.
The equality part needs no work. is itself written as an SVD, with singular values , so its spectral norm is and its Frobenius norm is . The lower bounds are the real content.
∂ Proof of the Eckart-Young theorem
The spectral norm. Let have rank at most . Its null space has dimension at least . The span of the top right singular vectors, , has dimension . Two subspaces of whose dimensions add up to more than must share a nonzero vector, so there is a unit vector with and . Then
A consequence, Weyl's inequality for singular values. For any matrices of the same shape and indices , . To prove it, let and be the truncated SVDs of ranks and . Their sum has rank at most , so by the spectral-norm bound just proved, applied to ,
The Frobenius norm. Apply Weyl with , , and . Since has rank at most , , so for every . Square and sum over ,
The fraction of the squared Frobenius norm that the rank- approximation keeps, , is often called the energy it captures, and one minus it is the squared relative error. So everything about how compressible a matrix is lives in how fast its singular values fall. The cell builds a matrix whose singular values decay like , checks that the truncated SVD's errors are exactly the predicted tails, and then tilts the kept subspace slightly in 2,000 random ways. Every tilt is worse.
Best low-rank approximation and its error
Implement three functions.
low_rank(M, r)returns the best rank-rapproximation ofM(shape(m, n)) in the Frobenius and spectral norms.low_rank_errors(s, r)takes the singular valuessof a matrix (descending) and returns(spectral_error, frobenius_error)of its best rank-rapproximation, from the singular values alone, without building any matrix. Forr >= len(s)both are 0.rank_for_energy(s, frac)returns the smallestrwhose best rank-rapproximation keeps at least the fractionfracof the squared Frobenius norm.
How low rank is a real model's weight matrix?
Random matrices are not compressible. The singular values of an Gaussian matrix spread fairly evenly over a band (the Marchenko-Pastur law describes the shape), so a small rank keeps only a small share of the energy. Trained weights are different, and how different depends on the matrix. The widget computes the full spectrum of every weight matrix of a real trained Transformer, the two-layer character-level GPT that Chapter 6 trains on Shakespeare's sonnets, and compares each with a random Gaussian matrix of the same shape and Frobenius norm.
The differences are large. The learned position embeddings (a matrix) have a stable rank of 1.4 and 99% of their energy in eight directions. Adjacent positions have an average cosine similarity of 0.98, so the 128 vectors trace a smooth curve through a few dimensions, and position 0, whose vector is about twice as long as the rest, supplies much of the top direction. The query and key matrices of the first layer keep 71% and 83% of their energy at rank 8, against 38% for a random matrix, which suggests that this model's attention compares characters along only a few directions. The value and output matrices sit much closer to random. At real scale the same questions matter in two ways. Trained weight matrices of large models have heavy-tailed spectra rather than a few dominant directions (Martin & Mahoney, 2021), so they compress poorly by plain truncation. But the change that fine-tuning makes is often very low rank (Aghajanyan et al., 2021, could fine-tune RoBERTa to 90% of full performance on one task with only 200 parameters), which is the bet LoRA makes.
Power iteration
The opening experiment was an algorithm. Power iteration finds the top eigenvector of a matrix by multiplying a random vector by it over and over, normalizing each time so nothing overflows,
Why does it work, and how fast? Take symmetric with eigenvalues ordered and write the start as . Normalization only rescales, so points along
Every term but the first shrinks by at least per step, so the tangent of the angle between and is at most times its starting value. In plain words, each multiplication amplifies the top direction more than any other, and the error shrinks geometrically at a rate set by the gap between the two largest eigenvalues. The eigenvalue estimate converges even faster. The Rayleigh quotient is a weighted average of eigenvalues with weights proportional to , so its error is of order , the square of the vector's error. This is a general feature of Rayleigh quotients for symmetric matrices, a first-order error in the vector gives only a second-order error in the eigenvalue.
Three ways power iteration fails are worth knowing. If (eigenvalues and , say) the direction never settles. If the start has exactly, it converges to the wrong eigenvector, although a random start makes this a probability-zero event and rounding error rescues it anyway. And if the gap is small, it is slow. The number of steps to gain a factor of is , about , so a gap of 1% needs about a hundred steps per factor of .
The same loop gives the spectral norm of any matrix , by running it on without ever forming that product, alternating and , with . Spectral normalization runs a single step of this per training step and keeps between steps, since the weights change little, and the σReparam fix of §5.7 is built on the same estimate. And since a Hessian-vector product costs about as much as a gradient (§0.3), power iteration with Hessian-vector products finds the sharpness of a network with billions of parameters without ever forming its Hessian.
To get the top eigenvectors at once, multiply a block of vectors and re-orthonormalize them with a QR factorization each step, which keeps them from all collapsing onto . This is orthogonal iteration (or subspace iteration), and it converges at the rate . A final Rayleigh-Ritz step, an eigendecomposition of the small matrix , rotates the block into the best individual eigenvector estimates. Production solvers refine the same ideas. Lanczos methods (scipy.sparse.linalg.eigsh) reuse every vector the iteration produces, and randomized SVD (Halko, Martinsson & Tropp, 2011, implemented as torch.svd_lowrank) uses one random block multiplication plus a few power steps to get the top singular vectors of a huge matrix.
Power iteration and orthogonal iteration
For a symmetric positive semidefinite matrix A (a covariance, say), implement
power_iteration(A, iters, rng)returning(lam, v), the top eigenvalue (as a Rayleigh quotient) and a unit eigenvector, starting fromrng.normal(size=n);top_k_eigh(A, k, iters, rng)returning(lams, V)withlamsof shape(k,)in descending order andVof shape(n, k)with orthonormal columns, by orthogonal iteration with a QR step every iteration and a Rayleigh-Ritz step at the end.
Do not call np.linalg.eig, eigh, or svd on A itself. (You may use np.linalg.eigh on the small matrix in the Rayleigh-Ritz step.)
Condition numbers
The condition number of an invertible matrix is the ratio of its largest to its smallest stretch,
and it is infinite for a singular matrix. For a symmetric positive definite matrix it is , the same that set the speed of gradient descent in §0.6. It has a second meaning, just as important, which is how much a matrix amplifies errors.
Solve , but with the right-hand side slightly wrong, (from measurement noise, or just rounding). The solution moves by , so . Meanwhile , so . Multiplying the two inequalities,
In plain words, a relative error in the data can come back times larger in the answer. The bound is tight, reached when lies along the top left singular vector and along the bottom one. A practical rule follows. You lose about significant digits. Float64 carries about 16 digits, so a matrix with leaves you four. Float32 carries about 7 and bfloat16 under 3 (§0.9), so a solve with in bfloat16 returns noise.
This is why you should never solve least squares by forming (the "normal equations") when accuracy matters. The singular values of are , so , and squaring the condition number doubles the digits lost. np.linalg.lstsq works with directly through the SVD. Ridge regularization helps for the same reason, , which a modest can bring down by orders of magnitude.
The error grows with and stays below the bound , where is the float64 rounding error. At the Hilbert matrix has , every digit is gone, and the "solution" is 10% wrong even though nothing went wrong in the code. In the polynomial fit, the normal equations lose seven orders of magnitude of accuracy that lstsq keeps.
Conditioning shows up throughout training. Badly scaled input features make a linear model's Hessian ill-conditioned, which is why standardizing features speeds up gradient descent. Adam's per-parameter scaling is a crude diagonal attempt to reduce the condition number. And Jordan, who introduced Muon, observed that the updates SGD with momentum and Adam produce for Transformer weight matrices have very high condition numbers, dominated by a few directions, which Muon fixes by setting every singular value of the update to 1 (§8.6).
Projections and least squares
Projecting a vector onto a line is the most basic linear-algebra operation in machine learning. For a unit vector , the closest point to on the line through is , and what remains, , is perpendicular to . For a subspace with an orthonormal basis given by the columns of , add up the pieces, .
If the subspace is spanned by the columns of a general matrix of full column rank, find the closest point to by requiring the residual to be perpendicular to every column, . That gives and
In plain words, projecting twice is the same as projecting once, and the projection is symmetric. Its eigenvalues are therefore only 0 and 1 (from , any eigenvalue satisfies ), with 1 on the subspace and 0 on its orthogonal complement, and its trace is the dimension . Look again at the equation for . It is the least-squares normal equation. So least squares is a projection, of the targets onto the column space of the features, and the fitted values are .
The SVD gives the general version. The pseudoinverse , where inverts the nonzero singular values and leaves the zeros, returns the minimum-norm least-squares solution even when is rank deficient, and is the projection onto its column space.
The last two lines remove a single direction from a vector, which is a real technique. Removing a "gender direction" from word embeddings was an early debiasing method (Bolukbasi et al., 2016), and projecting one learned direction out of a model's internal activations is how researchers delete a concept the network represents, the idea behind activation steering. Every PCA plot is a projection onto two directions, and the output of an attention head always lies in the span of its value vectors.
Whitening
Whitening transforms data so that its features are uncorrelated with unit variance, its covariance becoming . Center the data (rows are examples) to , and let be its sample covariance. In this subsection is a whitening matrix, applied to each example as , so the whitened data are with covariance . Any with whitens. Two choices are standard,
Both work, since for instance . In plain words, PCA whitening rotates the data onto its principal axes and rescales each axis to unit variance. ZCA whitening does the same and then rotates back, so the features keep their original orientation.
In fact every whitening matrix is one of these times a rotation. If and both whiten, then satisfies , using , which is the whitening condition for rearranged. So the choice among whitenings is a choice of rotation, and ZCA is special. It is the whitening that moves the data the least.
∂ ZCA is the whitening closest to the original data
For a whitening matrix , the mean squared distance between whitened and original data is
so minimizing it means maximizing . Every whitening matrix is for an orthogonal , so . Write . Then , because . Equality holds for , which is ZCA. Kessy, Lewin & Strimmer (2018) compare this and four other natural whitenings in detail. ∎
Two practical notes. Divide by rather than , because directions with nearly zero variance are mostly noise, and whitening would blow that noise up to unit size. And whitening is everywhere once you look for it. BatchNorm and LayerNorm (§0.7) are whitening with a diagonal , rescaling each feature without decorrelating them. The Mahalanobis distance of §0.4 is the ordinary distance after ZCA whitening. Whitening sentence embeddings before comparing them with cosine similarity is a cheap fix for their anisotropy (Su et al., 2021), as §1.9 shows. And Muon's update is a whitened gradient. If the gradient is (thin SVD, full rank), then .
PCA and ZCA whitening
Implement whiten(X, method="zca", eps=0.0) for data X of shape (N, d), returning (Z, W, mu) where mu is the mean (shape (d,)), W is the (d, d) whitening matrix, and Z = (X - mu) @ W.T. Use the covariance with divisor and the eigenvalues . For method="pca", W is with the eigenvalues in descending order, so the first output coordinate is the direction of largest variance. For method="zca", W is .
PCA is the same decomposition again
Principal component analysis, which §1.6 uses to draw embedding spaces, is the spectral theorem applied to and the SVD applied to , and the two agree. If , then . So the principal directions are the right singular vectors of the centered data, and the variance along direction is . By the Rayleigh quotient, the top direction is the unit vector that maximizes the variance of the projected data. By Eckart-Young, projecting onto the top directions gives the best rank- approximation of the data. Maximum variance and minimum reconstruction error are the same choice. The latent semantic analysis of §1.4 is the truncated SVD of a word co-occurrence matrix.
Where this shows up in modern models
Gradients through a recurrence
Backpropagating through steps of a recurrent network multiplies the gradient by Jacobians, each (§0.8). If the activation's slope is at most , submultiplicativity bounds the whole product by , so gradients must vanish when . In the long run, (Gelfand's formula), so the spectral radius decides whether a linear recurrence eventually explodes. But for matrices with skewed eigenvectors the short run can look very different. The matrix below has both eigenvalues equal to 0.5, yet it more than triples a vector in one step, and the norms of its powers stay above 1 for the first four steps before they decay.
The last line is the idea behind orthogonal initialization (Saxe et al., 2014). An orthogonal matrix has every singular value equal to 1, so its powers neither shrink nor grow any vector, and gradients pass through many linear steps unchanged. §3.3 carries out the full analysis for trained RNNs.
Attention
The attention scores of one head are , where . The matrix that defines how tokens are compared has rank at most , so each head compares tokens along only directions, and multi-head attention (§4.5) is a sum of low-rank bilinear forms instead of one full-rank one. The attention matrix itself is row-stochastic (every row is a softmax, so it is nonnegative and sums to 1). Its rows sum to 1, so and 1 is an eigenvalue, and no eigenvalue is larger in absolute value. Repeated averaging pulls every token's vector toward the same mixture, and Dong, Cordonnier & Loukas (2021) proved that a stack of pure attention layers, without residual connections or MLPs, converges to a rank-one output doubly exponentially fast in depth. The residual stream of §5.1 is part of what prevents it.
One more rank fact limits every language model. The logits for contexts over a vocabulary of tokens are , with hidden states and output embeddings , so the logit matrix has rank at most even though it is . Yang et al. (2018) called this the softmax bottleneck and argued that natural language's true log-probability matrix has much higher rank than .
LoRA
LoRA (Hu et al., 2021) freezes a pretrained weight and learns an update with and , so the update has rank at most and costs parameters. For a projection with that is 65,536 instead of 16.8 million. Eckart-Young tells you exactly what you give up. If full fine-tuning would have made the update , the best LoRA could hope for leaves an error of . In the LoRA paper, ranks from 1 to 8 performed about equally well when adapting GPT-3 175B's query and value projections on the two tasks where they compared ranks, which suggests those updates have a few dominant directions. §14.5 measures the spectra of real fine-tuning updates.
Muon
Muon (§8.6) replaces the momentum matrix by , all singular values set to 1. The norms of this section explain why that is a principled step. Among all updates with spectral norm at most 1, the one that decreases a linearized loss the most maximizes . Expanding gives , since a matrix of spectral norm at most 1 cannot give for unit vectors. The bound is reached at . So is steepest descent when step size is measured in the spectral norm, and the nuclear norm is the spectral norm's dual. Muon computes it with a few matrix multiplications (Newton-Schulz iterations) instead of an SVD, because matrix multiplications are what GPUs do fastest.
Compressing a layer without changing its outputs
Truncating the SVD of a weight matrix minimizes the error in the weights. What you care about is the error in the layer's outputs on real inputs, and when the inputs are far from isotropic the two goals differ. Directions the inputs rarely use can be cut freely, and directions they use heavily must be kept. Whitening the inputs turns the second problem into the first, which is the core of activation-aware compression methods such as SVD-LLM (Wang et al., 2024). The last exercise derives it.
Activation-aware low-rank compression
A linear layer computes for weights and calibration inputs (full column rank). Implement activation_aware_lowrank(W, X, r) returning of rank at most that minimizes the output error .
Derive it first. With (Cholesky), show that for any , and then that the answer is , where is the truncated SVD.
In PyTorch
Everything above has a direct equivalent in torch.linalg, which runs on GPUs and supports batches of matrices (a leading batch dimension is decomposed matrix by matrix).
Which decomposition, when
| decomposition | NumPy / PyTorch | needs | cost for | use it for |
|---|---|---|---|---|
| Cholesky | cholesky | symmetric PD | testing PD, solving with covariances, sampling Gaussians | |
| symmetric eigen | eigh, eigvalsh | symmetric | about with vectors | covariances, Hessians, PCA, whitening |
| general eigen | eig | square (may be complex) | about | stability of recurrences, spectral radius |
| QR | qr | any | orthonormal bases, projections, orthogonal iteration | |
| SVD | svd, svdvals | any | about with vectors | norms, rank, low-rank approximation, pseudoinverse |
| iterative (power, Lanczos, randomized) | eigsh, svd_lowrank | only products | a few dozen products | top few eigen or singular pairs of huge matrices |
The costs are the standard flop counts for dense matrices from Golub and Van Loan's Matrix Computations, rounded. What matters is the order. Cholesky is the cheapest by far, and an SVD with vectors is an order of magnitude more expensive, which is why you should never compute a full SVD when you only need a norm estimate.
Read more
- Gilbert Strang (2019). Linear Algebra and Learning from Data. The linear algebra of deep learning from one of its best teachers, with the SVD at the center.
- Trefethen & Bau (1997). Numerical Linear Algebra. The classic on how SVD, QR, eigensolvers, and conditioning work in floating point, in short lectures.
- Eckart & Young (1936). The approximation of one matrix by another of lower rank. The original low-rank approximation theorem, three pages long.
- Halko, Martinsson & Tropp (2011). Finding structure with randomness: Probabilistic algorithms for constructing approximate matrix decompositions. Randomized SVD and why a few power steps make it accurate.
- Kessy, Lewin & Strimmer (2018). Optimal whitening and decorrelation. PCA, ZCA, Cholesky, and correlation-based whitening compared, and which is optimal for what.
- Hu et al. (2021). LoRA: Low-Rank Adaptation of Large Language Models. The low-rank update, with an analysis of the rank and subspaces of the learned updates.
- Dong, Cordonnier & Loukas (2021). Attention is Not All You Need: Pure Attention Loses Rank Doubly Exponentially with Depth. Why stacked attention collapses without residual connections.
- Yang, Dai, Salakhutdinov & Cohen (2018). Breaking the Softmax Bottleneck: A High-Rank RNN Language Model. The rank limit of the softmax output layer.