AI from scratch · Linear algebra 3 · Stage 3: classic ML and judging models

Singular value decomposition: rotate, stretch, rotate

Linear algebra 2 found the arrows a matrix only stretches, but only some matrices have enough of them, and only symmetric ones keep them at right angles. The singular value decomposition (SVD) works for every matrix, any shape: each one is a rotation, then a stretch along the axes, then another rotation. Ordering the stretches from biggest to smallest turns out to be one of the most useful ideas in machine learning: compression, PCA, recommendations, solving equations that have no exact answer, and fine-tuning big models cheaply all come from it.

1. Every matrix turns a circle into an ellipse

Drag the blue and yellow arrows: they're where the matrix sends the steps \(\hat\imath\) and \(\hat\jmath\) (chapter 1). The gray circle of unit arrows becomes a tilted ellipse, always. Its longest radius is the most the matrix stretches anything, its shortest the least. The green and pink arrows are the two unit arrows that land exactly on the ellipse's axes. Now press Play: the same matrix as three simple moves.

Predict first: drag the yellow arrow onto the same line as the blue one. What happens to the ellipse, and to \(\sigma_2\)?

It flattens into a line segment and \(\sigma_2\) drops to 0: both columns point the same way, so every output lands on that one line. The matrix squashes the plane, its determinant is 0, and it can't be undone (linear algebra 1's singular matrix). "Singular" values got their name from exactly this.

\[ A = U\,\Sigma\,V^\top \qquad \Sigma = \begin{bmatrix} \sigma_1 & 0 \\ 0 & \sigma_2 \end{bmatrix}, \quad \sigma_1 \ge \sigma_2 \ge 0 \]

Read it right to left, like a sequence of moves: \(V^\top\) rotates the plane so the two directions that will become the ellipse's axes (the columns of \(V\), the right singular vectors) lie along x and y; \(\Sigma\) stretches x by \(\sigma_1\) and y by \(\sigma_2\), the singular values; \(U\) rotates the result into place, its columns pointing along the ellipse's axes. (When the matrix flips the plane over, one stretch is shown negative.) In more dimensions it's the same: an \(m \times n\) matrix rotates, stretches along up to \(\min(m, n)\) axes, and rotates again.

Every matrix, whatever it does, is a rotation, a stretch along two perpendicular axes, and another rotation: the circle always becomes an ellipse.

Why is it always an ellipse?
  1. The squared length of an output is \(\lVert Ax \rVert^2 = (Ax)\cdot(Ax) = x^\top A^\top A\, x\). So everything about lengths lives in the matrix \(A^\top A\).
  2. \(A^\top A\) is symmetric, so (linear algebra 2) it has two perpendicular unit eigenvectors \(v_1, v_2\), with eigenvalues \(\lambda_1 \ge \lambda_2\). They can't be negative: each is a squared length, \(\lVert A v_i \rVert^2 = v_i^\top A^\top A v_i = \lambda_i\).
  3. So \(A v_1\) has length \(\sqrt{\lambda_1}\), call it \(\sigma_1\), and \(A v_2\) has length \(\sigma_2 = \sqrt{\lambda_2}\).
  4. And the two outputs are perpendicular too: \((A v_1)\cdot(A v_2) = v_1^\top A^\top A v_2 = \lambda_2\, v_1 \cdot v_2 = 0\). Call their directions \(u_1, u_2\).
  5. Any unit arrow is \(x = \cos t\, v_1 + \sin t\, v_2\), so \(A x = \cos t\, \sigma_1 u_1 + \sin t\, \sigma_2 u_2\): exactly the points of an ellipse with half-axes \(\sigma_1\) and \(\sigma_2\) along \(u_1\) and \(u_2\).

That's the whole proof, and it's also a way to compute the SVD: eigenvectors of \(A^\top A\) give \(V\), the square roots of its eigenvalues give \(\Sigma\), and \(u_i = A v_i / \sigma_i\) gives \(U\).

Where it breaks: when the SVD isn't unique

The singular values themselves are always unique. Only the axes can be ambiguous, and only in these cases.

A pure rotation by 30°: what are its singular values? Give the larger one.

Rotations don't stretch anything: the circle stays a circle, so \(\sigma_1 = \sigma_2 = 1\). That's also why its determinant is 1 (the area doesn't change).

2. Singular values and eigenvalues

For a symmetric matrix (a covariance, a Hessian), the two ideas meet: singular values are the eigenvalues' sizes, and \(U\) and \(V\) are the eigenvectors. For other matrices they differ, and the SVD still exists when eigenvectors don't (a shear has only one eigen-direction, but its circle still becomes an ellipse). The link that always holds: \(A^\top A\) is symmetric, its eigenvalues are \(\sigma_i^2\), and its eigenvectors are \(V\). The ratio \(\sigma_1/\sigma_2\) is the condition number (Calculus 3's \(\kappa\), now for any matrix; linear algebra 1's "nearly flat" matrices have a big one): how stretched the ellipse is, and how much rounding errors get magnified when you solve with this matrix.

Eigenvalues tell you what happens if you apply a matrix over and over; singular values tell you the most and least it can stretch anything in one go.

Where it breaks: eigenvalues that hide a stretch

The shear \(\begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}\) has eigenvalues 1 and 1: judged by them, nothing grows. Its singular values are 1.618 and 0.618: some arrows grow by 62% in one step. Both are right about different questions. Applied 100 times, the shear moves a point by about 100 (it grows linearly, not exponentially), while a matrix with an eigenvalue of 1.1 would blow it up by \(1.1^{100} \approx 13{,}800\).

In a neural network a gradient passes through one weight matrix per layer, and each is different. What sets how much it can grow or shrink at each step is that layer's singular values, which is why stage 4's "making nets train" talks about keeping them near 1 (careful initialization, normalization).

Estimate: float32 numbers carry about 7 significant digits. You solve a system whose matrix has condition number \(10^6\). Roughly how many digits of the answer can you trust?

About \(7 - 6 = 1\). Each power of ten in the condition number can cost one digit of accuracy. That's the practical meaning of a thin ellipse: small errors along its short axis get stretched by \(\sigma_1/\sigma_2\) when you undo the matrix.

3. Keep the big stretches: compression

Written as a sum, the SVD is a stack of simple layers, each a column times a row, weighted by its singular value:

\[ A = \sigma_1 u_1 v_1^\top + \sigma_2 u_2 v_2^\top + \dots \]

Each layer \(u_i v_i^\top\) is a rank-1 matrix (every row a multiple of the same row). Keep only the \(k\) biggest and you have the best possible rank-\(k\) approximation of \(A\): no other choice of \(k\) layers comes closer (the Eckart–Young theorem). A grayscale photo is a matrix of brightnesses, so here is Grace Hopper, the computing pioneer, in 1984 (U.S. Navy photo, public domain), rebuilt from her first few layers:

A matrix is a stack of layers, biggest first; dropping the small ones loses the least.

Why do the biggest layers win?
  1. Measure a matrix's size by its energy: the sum of its squared entries (the squared length of all the numbers as one long vector).
  2. Rotations don't change lengths, so they don't change energy. \(A = U\Sigma V^\top\) and \(\Sigma\) have the same energy: \(\sigma_1^2 + \sigma_2^2 + \dots\)
  3. The same goes for any group of layers: they're built from perpendicular \(u_i\) and perpendicular \(v_i\), so their energies just add, like the sides of a right triangle.
  4. The error of keeping the first \(k\) layers is the layers you dropped, so its energy is \(\sigma_{k+1}^2 + \sigma_{k+2}^2 + \dots\) Keeping the biggest makes that as small as it can be among the SVD's own layers.

That no other rank-\(k\) matrix, built from any layers at all, does better is the Eckart–Young theorem; its proof takes another page, but steps 2 to 4 are the intuition. It's also why the share of \(\sum \sigma_i^2\) you keep is the honest measure of "how much of the picture is left".

Where it breaks: what low rank is bad at

A rank-10 version of a 300 × 256 image stores 10 columns of \(U\) (300 numbers each), 10 rows of \(V^\top\) (256 each), and 10 singular values. How many numbers is that?

\(10 \times (300 + 256 + 1) = 3{,}000 + 2{,}560 + 10 = 5{,}570\), against 76,800 pixels in the original: about 7%, and already recognizable.

4. PCA, done with the SVD

Linear algebra 2 found principal components as eigenvectors of the covariance matrix \(X^\top X/(n-1)\) of centered data. The SVD of the centered data itself gives the same directions without ever forming \(X^\top X\) (which squares the condition number, and loses precision): the rows of \(V^\top\) are the components, and \(\sigma_i^2/(n-1)\) are the variances along them. This is how scikit-learn's PCA does it.

Why does forming \(X^\top X\) lose precision?

The singular values of \(X^\top X\) are \(\sigma_i^2\) (its eigenvalues, from the "Why always an ellipse" box), so its condition number is \((\sigma_1/\sigma_{\min})^2\): the square of \(X\)'s. Data with condition number \(10^5\) becomes \(10^{10}\), and in float64's 16 digits that leaves about 6 trustworthy digits instead of 11. The SVD works on \(X\) directly and never pays that price.

Where it breaks: big variance isn't the same as useful

5. Hidden tastes: a tiny recommender

Eight people rated ten films, 1 to 5 stars, but 30% of the ratings are missing. The table is made up from two hidden tastes (how much each film is an action film or a love story, how much each person likes each), plus noise. Nobody tells the SVD that; it finds two big singular values and much smaller ones after them. To guess the missing ratings: fill them with each film's average, take the rank-2 version, put its guesses into the gaps, and repeat. This is the idea behind the Netflix Prize-era recommenders, and still behind many today.

The directions the SVD finds are mixtures you name afterwards ("taste 1 is mostly action against romance"). Real recommenders add regularization and learn from millions of ratings, but the shape of the answer is this one: a person is a short vector of tastes, a film is a short vector of qualities, and a rating is roughly their dot product.

If a few hidden factors explain a table, the table is close to low rank, and its biggest layers are those factors.

Why do two tastes make rank 2?

Put each person's two tastes in a row of \(P\) (8 × 2) and each film's two qualities in a row of \(Q\) (10 × 2). If every rating is a person's tastes dotted with a film's qualities, the whole table is \(R = P Q^\top\). Every column of \(R\) is then a mix of \(P\)'s two columns, so \(R\) has rank at most 2, and its SVD has only two nonzero singular values. Noise adds small ones on top. Reading the singular values backwards tells you how many hidden factors there are.

Where it breaks

6. Solving the unsolvable: the pseudo-inverse

Linear algebra 1 solved square, invertible systems, and noted that libraries' np.linalg.lstsq works from \(X\) itself rather than \(X^\top X\). This is how: invert each stretch, \(\sigma_i \to 1/\sigma_i\), and skip the ones that are zero (or tiny). That's the pseudo-inverse \(A^+ = V\,\Sigma^+\,U^\top\). It exists for every matrix; for an overdetermined system it gives the least-squares answer, and when columns repeat (linear algebra 1's twin column) it still gives one sensible answer, the smallest weights that fit.

Turn the problem so the matrix is just stretches, divide by each stretch you can, and leave the rest alone.

Why does the pseudo-inverse give least squares?
  1. We want \(w\) making \(\lVert X w - y \rVert\) as small as possible, with \(X = U\Sigma V^\top\).
  2. Rotating doesn't change lengths, so rotate everything by \(U^\top\): the error is \(\lVert \Sigma V^\top w - U^\top y \rVert\).
  3. Name the rotated unknowns \(z = V^\top w\) and the rotated targets \(c = U^\top y\). The problem falls apart into one tiny equation per axis: \(\sigma_i z_i \approx c_i\).
  4. Where \(\sigma_i \ne 0\), solve it exactly: \(z_i = c_i / \sigma_i\). Rows with no \(\sigma\) at all (more equations than unknowns) can't be matched by any \(w\): their \(c_i\) is the error left over, the least squares residual.
  5. Where \(\sigma_i = 0\), any \(z_i\) fits equally well; choosing 0 gives the shortest \(w\). Rotate back, \(w = V z\), and that's \(w = V \Sigma^+ U^\top y\).
Where it breaks: tiny stretches

A singular value that should be 0 but came out as \(10^{-12}\) (rounding) or 0.001 (noise) gets divided into: \(c_i / \sigma_i\) is huge, and the weights explode. NumPy's pinv treats values below a cutoff as zero (its rcond). Ridge regression (chapter 11) does it smoothly: it replaces \(1/\sigma_i\) with \(\sigma_i / (\sigma_i^2 + \lambda)\), which is close to \(1/\sigma_i\) for big stretches and close to 0 for tiny ones. Regularization is, seen this way, a gentle pseudo-inverse.

7. Why big models fine-tune with low rank

A large language model's layer can be a 4,096 × 4,096 matrix: 16.8 million weights. Fine-tuning it for a new task changes those weights by some \(\Delta W\), and experiments found that useful changes are close to low-rank: a few directions matter. LoRA (stage 6) trains the change directly as a product \(\Delta W = B A\) with \(B\) of shape 4,096 × \(r\) and \(A\) of shape \(r\) × 4,096, for a small rank \(r\) like 8. That's the SVD's lesson used in reverse: if only a few layers matter, learn only those.

Where it breaks: when the change isn't low-rank

LoRA bets that the fine-tuning change needs only \(r\) directions per layer. Small adjustments (a tone, a format, a narrow task) fit that bet. Teaching a model a lot that's new (a language it barely saw) needs a change of higher rank, and a small \(r\) then trains fine but stops improving early. People raise \(r\), or fine-tune fully, when LoRA's validation loss stalls above full fine-tuning's.

With \(r = 8\): what percent of the 16.8 million weights does LoRA train for that layer? (Two decimal places.)

\(2 \times 4096 \times 8 = 65{,}536\) trainable numbers, against \(4096^2 = 16{,}777{,}216\): 0.39%.

8. What to carry forward

All lessons: AI from scratch. Gilbert Strang's MIT 18.065 lectures (free on OCW) build machine learning around this decomposition.

Last updated