9.5 SVD, Eckart-Young low rank, and least squares
Sooner or later you start treating text as numbers you can factor. word2vec skip-gram with negative sampling, and the PPMI-SVD baseline in AI Engineering counts which words appear near which others in a matrix with tens of thousands of rows and asks for 64 numbers per word that keep most of its structure. That is the best rank-64 approximation of the matrix, and the singular value decomposition is the only tool that gives it with a proof of optimality.
Concepts from other sections (12)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- LoRA adapter: a low-rank update stored separately from the base model. Read more: 20.3.4 Portability and load triage in AI Engineering
- Eigenvector / eigenvalue: a non-zero and scalar with . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- Sign rule: flipping signs so that , which makes the factorization unique. Read more: 9.3 Orthogonality, Householder QR, and orthogonal initialization
- PiSSA: initializing the adapter at the top- singular part of and freezing the residual. Read more: 12.6 LoRA: low-rank adaptation with PiSSA initialization and merging in AI Engineering
- Orthonormal: a set of unit-length vectors that are pairwise orthogonal. Read more: 9.3 Orthogonality, Householder QR, and orthogonal initialization
- machine epsilon: , the gap between 1 and the next float64. Read more: 7.1 Derivatives and Finite Differences
- Condition number: how much the exact answer of a problem moves relative to a change in its input. Read more: 15.3 Error analysis, condition numbers, and tolerance budgets
- Inner product: . Read more: 9.6 Inner products, projections, cosine similarity, and top-k
- LoRA: a frozen Linear plus a trainable low-rank update . Read more: 12.6 LoRA: low-rank adaptation with PiSSA initialization and merging in AI Engineering
- relative accuracy: the number of correct significant digits, which subtraction of nearly equal numbers destroys. Read more: 7.3 Activation Functions and Their Derivatives
- PPMI: , a finite, sparse, non-negative matrix suitable for SVD. Read more: 17.3 Mutual information, PMI, and PPMI
- Divide and conquer / divide-and-conquer: an algorithm design that splits a problem into independent subproblems, solves them recursively, and combines their results; unlike dynamic programming the subproblems do not overlap, and the gain comes from better asymptotics, as in merge sort. Read more: Chapter 13: Recursion and divide-and-conquer in Programming and Algorithms
The same decomposition comes back three more times. LoRA: low-rank adaptation with PiSSA initialization and merging starts a LoRA adapter on the top singular directions of a weight matrix, Multi-head latent attention compresses attention’s keys and values into a low-rank latent, and the TinyStories capstone fits a scaling law to a handful of runs by least squares. The pieces are already in place: orthogonal matrices and QR from Orthogonality, Householder QR, and orthogonal initialization, and eigenvalues from Eigenvalues, power iteration, and the spectral radius. This section puts them together. The first half of the linear algebra problem set, part a is useful practice beforehand.
The solution is svd.py, with contract svd.pyi. It provides svd(A), the reduced SVD by one-sided Jacobi rotations with singular values descending and a fixed sign rule; low_rank(A, r), the best rank- approximation as balanced factors ; and lstsq(A, b), least squares by QR using qr_householder from qr.py.
Learning objectives
- Read geometrically and relate singular values to the eigenvalues of and to the spectral and Frobenius norms.
- Compute an SVD by one-sided Jacobi rotations, by hand for a 2 by 2 matrix, with a scale-free convergence test.
- State the Eckart-Young theorem, compute the error of a truncated SVD, and explain the balanced split used by PiSSA.
- Solve least squares by QR and explain why the normal equations lose accuracy.
Notation
Section titled “Notation”| Symbol | Meaning | Type / shape |
|---|---|---|
| the matrix, rows and columns | float64[m, n] | |
| number of singular values | int | |
| left singular vectors, orthonormal columns () | float64[m, k] | |
| singular values; | float64[k] | |
| right singular vectors, orthonormal columns; the contract returns | float64[n, k] | |
| column of and of | vectors | |
| Euclidean length | scalar | |
| spectral norm | scalar | |
| Frobenius norm | scalar | |
| the truncated SVD | float64[m, n] | |
| two columns of the working matrix | vectors | |
| , , | scalars | |
| rotation parameters: , , | scalars | |
| float64 machine epsilon, | ||
| condition number | scalar | |
| the QR factors from the previous sections | float64[m, k], float64[k, n] |
What the SVD says
Section titled “What the SVD says”Every real matrix factors as
with orthonormal columns in and and non-negative in descending order. Read it right to left on a vector : takes the coordinates of along the directions , stretches coordinate by , and sends the result out along the directions . So : rotate, stretch along the axes, rotate again. The unit sphere goes to an ellipsoid whose semi-axes are . This is the reduced SVD ( is ); the full one pads to a square matrix, which nothing in this book needs.
Each pair can be negated together without changing , since . When the singular values are distinct this is the only freedom, so the contract fixes it with a sign rule: the entry of largest absolute value in each row of is positive (the first such entry on ties). With it, the solution’s factors and LAPACK’s (after the same rule) agree entry by entry.
Singular values, eigenvalues, and norms
Section titled “Singular values, eigenvalues, and norms”Multiply out : the are eigenvectors of the symmetric matrix with eigenvalues (problem 8 of the linear algebra problem set, part b proves it). So everything the previous section said about eigenvalues applies, with two differences: singular values exist for every matrix, square or not, and they are never negative or complex.
Two norms come straight from them. For a unit with coordinates , , with equality at : the spectral norm is , the most can stretch a unit vector. Orthogonal factors do not change the sum of squares of entries, so the Frobenius norm is .
That connection suggests a shortcut: form and call an eigensolver. It would compute the SVD, but badly. Squaring the singular values squares the condition number, and a below drowns in the rounding of . Jacobi works on itself.
One-sided Jacobi
Section titled “One-sided Jacobi”Work on a tall matrix (; for a wide one, decompose and swap and at the end, since orthogonal columns can only exist in when ). Start with and , and keep the invariant with orthogonal. If all columns of were mutually orthogonal, their lengths would be the singular values and their directions the : , so .
To make columns and orthogonal, rotate them in their plane:
and apply the same rotation to columns and of , so still holds; the rotation is orthogonal, so stays orthogonal. The new inner product is . Setting it to zero with gives , . Take the smaller root,
with . It is the rotation by at most , the one that converges. A sweep visits every pair once. A rotation for one pair can spoil an earlier pair a little, but the off-diagonal mass shrinks every sweep and, near the end, quadratically; random matrices finish in 7 or 8 sweeps, the last one only confirming that nothing needs rotating.
When is a pair “orthogonal enough”? The test must be relative: rotate only when , that is, when the cosine of the angle between the columns exceeds . A fixed threshold such as skips every rotation on a matrix scaled by (all inner products are about ) and returns garbage; on a matrix scaled by it never stops. Stop after the first sweep that rotates nothing (the contract caps sweeps at 64). Finally, , sorted descending (stably), , and the sign rule.
Rank deficiency
Section titled “Rank deficiency”The last step divides by , which fails when is rank deficient. If has rank , then singular values are zero and their columns are (numerically) zero: is . The contract treats as zero and fills with a unit vector orthogonal to the ‘s already chosen: take the first standard basis vector that has more than half its length left after projecting out the previous columns (, done twice for accuracy), and normalize it. Any such completion is a valid SVD, because it multiplies a zero singular value; the contract fixes this one so the result is deterministic.
Eckart-Young and the balanced split
Section titled “Eckart-Young and the balanced split”Now the payoff. The truncated SVD has rank , and is itself an SVD, so
The Eckart-Young theorem says no matrix of rank at most does better in either norm: the truncated SVD is the best low-rank approximation. That is why it is the right way to compress a co-occurrence matrix or initialize a low-rank adapter.
low_rank returns as two factors () and () with . Many splits multiply to the same product; the contract uses the balanced one,
so and both factors carry the same scale. PiSSA initializes LoRA this way because gradient descent on updates each factor in proportion to the other’s size; a split such as trains one factor much faster than the other.
Least squares by QR
Section titled “Least squares by QR”The last tool solves systems with more equations than unknowns. For a tall with independent columns, usually has no solution; least squares picks minimizing . The minimizer makes the residual orthogonal to every column of : , the normal equations . Solving them as written is the classic mistake. , so a polynomial fit with (degree 9 at 40 points of ) recovers its coefficients only to about .
QR avoids the square. With , has orthonormal columns, so the residual splits into a part inside the column space and a part orthogonal to it, and only the first depends on :
So solves the triangular system , by back substitution from the last row up: with . The error now grows like : for the same fit. If some is tiny (), the columns are dependent, the minimizer is not unique, and the contract raises instead of dividing by almost zero. The test is relative to the largest pivot so it does not depend on the units of .
Working it by hand
Section titled “Working it by hand”Take
Jacobi. There is one pair, . The table follows the rotation quantity by quantity:
| Quantity | Value |
|---|---|
| , , | , , |
| , so , (a rotation) | |
| new | , length |
| new | , length |
| new columns | , |
| second sweep | : nothing to rotate, stop |
Sorting puts first, then . Check: , and . Dividing each by its length:
The sign rule holds already: each row of has its largest entries tied, and the first is positive.
Rank 1. . The error has spectral and Frobenius norm , as Eckart-Young says. The balanced factors are and .
Least squares. Fit a line through , , : , . By hand, the residual condition reads and , so and . Check: the residual sums to 0 (orthogonal to the first column) and (orthogonal to the second). Writing out the normal equations is fine for a system on paper with exact fractions; the solution still goes through QR, because in floating point the square of the condition number is what hurts.
Designing the API
Section titled “Designing the API”def svd(A: ArrayLike) -> tuple[NDArray, NDArray, NDArray]: """Reduced SVD by one-sided Jacobi: U [m, k], S [k] descending, Vt [k, n], A == U @ diag(S) @ Vt, the largest |entry| of each Vt row positive."""
def low_rank(A: ArrayLike, r: int) -> tuple[NDArray, NDArray]: """B = U_r sqrt(S_r) [m, r], C = sqrt(S_r) Vt_r [r, n]: B @ C is the best rank-r approximation."""
def lstsq(A: ArrayLike, b: ArrayLike) -> NDArray: """argmin ||A x - b|| for a tall, full-column-rank A, by QR and back substitution."""All three leave unchanged, since a LoRA initializer keeps the weight it decomposes. svd rejects 1-D and non-finite inputs, low_rank requires , and lstsq raises on dependent columns, a wide system, or a wrong-length .
Building it step by step
Section titled “Building it step by step”The design follows from the principles in order. The SVD must be accurate for small singular values, which rules out an eigensolver on ; working on directly with orthogonal rotations keeps every operation norm-preserving. If with orthogonal and ‘s columns mutually orthogonal, then and the SVD is read off, so the algorithm keeps that invariant and drives the column inner products to zero, one pair at a time. For a pair, the rotation that zeroes solves ; the smaller root keeps , which is what makes sweeps converge (in the worked example , , a rotation). “Orthogonal enough” must be scale-free, so the test compares with : a cosine, not an absolute size.
The algorithm needs , so a wide matrix is decomposed as with and swapped. Column lengths come out in sweep order, but Eckart-Young needs descending order, so sort stably for determinism. A column whose length is negligible relative to cannot be normalized and gets a deterministic orthonormal completion. Signs are fixed last, on , so the result is unique and comparable with LAPACK. low_rank is then the truncated SVD split as into each side, and lstsq is QR followed by back substitution on , with a relative rank check before dividing.
The Jacobi kernel works on a copy of a tall matrix and accumulates :
EPS = 2.0**-52MAX_SWEEPS = 64
def _jacobi_tall(T): W = np.array(T, dtype=np.float64) # a copy; its columns become U * S rows, cols = W.shape V = np.eye(cols) # invariant: W == T @ V, V orthogonal tol = rows * EPS for _ in range(MAX_SWEEPS): rotated = False for i in range(cols - 1): for j in range(i + 1, cols): wi, wj = W[:, i], W[:, j] alpha = float(wi @ wi) beta = float(wj @ wj) gamma = float(wi @ wj) if alpha == 0.0 or beta == 0.0: continue # a zero column is orthogonal to everything if abs(gamma) <= tol * math.sqrt(alpha * beta): continue # relative test: the cosine is below m * eps rotated = TrueThe rotation itself applies the same to and to so the invariant holds. Both new columns are combinations of both old ones, so ‘s columns are copied before being overwritten; the W update avoids the problem by building both columns in one column_stack:
zeta = (beta - alpha) / (2.0 * gamma) sign = 1.0 if zeta >= 0.0 else -1.0 # sign(0) = +1 t = sign / (abs(zeta) + math.sqrt(1.0 + zeta * zeta)) # smaller root, no cancellation c = 1.0 / math.sqrt(1.0 + t * t) s = c * t W[:, [i, j]] = np.column_stack((c * wi - s * wj, s * wi + c * wj)) vi, vj = V[:, i].copy(), V[:, j].copy() # copies: both new columns use the old ones V[:, i] = c * vi - s * vj V[:, j] = s * vi + c * vj if not rotated: break # a sweep with no rotation: convergedReading off the factors takes lengths, a stable descending sort, and normalization or completion. The worked example ends with in column 0 and in column 1, which the sort swaps:
S = np.sqrt(np.einsum("ij,ij->j", W, W)) # column lengths order = np.argsort(-S, kind="stable") S, W, V = S[order], W[:, order], V[:, order] U = np.zeros((rows, cols)) floor = rows * EPS * (S[0] if cols else 0.0) for j in range(cols): if S[j] > floor and S[j] > 0.0: U[:, j] = W[:, j] / S[j] else: U[:, j] = _complete(U[:, :j], rows) # zero singular value: any orthonormal u works return U, S, V_complete takes the first with more than half its length left after projecting out the previous columns twice (one projection loses orthogonality to rounding; two is enough):
def _complete(Uprev, rows): for i in range(rows): e = np.zeros(rows) e[i] = 1.0 for _ in range(2): # twice is enough (Kahan, Parlett) e -= Uprev @ (Uprev.T @ e) norm = math.sqrt(float(e @ e)) if norm > 0.5: return e / norm raise AssertionError("unreachable: fewer than rows orthonormal columns")The public svd validates, handles empty and wide shapes, and applies the sign rule to and together:
def svd(A): M = np.asarray(A, dtype=np.float64) # a view; _jacobi_tall copies if M.ndim != 2: raise ValueError(f"svd: A must be 2-D, got shape {M.shape}") if not np.isfinite(M).all(): raise ValueError("svd: A has a NaN or infinite entry") m, n = M.shape k = min(m, n) if k == 0: return np.zeros((m, 0)), np.zeros(0), np.zeros((0, n)) if m >= n: U, S, V = _jacobi_tall(M) else: # A^T = U' S V'^T, so A = V' S U'^T: the roles swap. Ut, S, Vt_ = _jacobi_tall(M.T) U, V = Vt_, Ut big = np.argmax(np.abs(V), axis=0) # first largest |entry| per column of V d = np.where(V[big, np.arange(k)] < 0.0, -1.0, 1.0) return U * d, S, (V * d).T # flip u_i and v_i together: A unchangedlow_rank is three lines once svd exists:
def low_rank(A, r): U, S, Vt = svd(A) k = S.shape[0] if not 1 <= r <= k: raise ValueError(f"low_rank: need 1 <= r <= min(m, n) = {k}, got r = {r}") root = np.sqrt(S[:r]) return U[:, :r] * root, root[:, None] * Vt[:r] # B^T B = C C^T = Sigma_rlstsq factors with QR, checks the rank relative to the largest pivot, and back-substitutes. Indexing x[i] on the first axis lets one loop handle b of shape [m] or [m, k]:
Q, R = qr_householder(M) diag = np.abs(np.diag(R)) if n == 0: return np.zeros((0,) + y.shape[1:]) if diag.min() <= max(m, n) * EPS * diag.max(): raise ValueError("lstsq: A is rank deficient (a diagonal entry of R is ~0)") z = Q.T @ y # the coordinates of b's projection onto range(A) x = np.zeros((n,) + y.shape[1:]) for i in range(n - 1, -1, -1): # back substitution, last row first x[i] = (z[i] - R[i, i + 1 :] @ x[i + 1 :]) / R[i, i] return xThe full solution is svd.py.
Why this design
Section titled “Why this design”A sweep visits pairs at each, so it costs , with a handful of sweeps in practice; memory is . lstsq is one QR, , plus back substitution.
Eigen-decomposing squares and loses every singular value below about . Golub-Kahan bidiagonalization, what LAPACK does, is faster for large matrices but much longer to write, and its relative accuracy for tiny singular values is weaker than Jacobi’s; for the sizes this book decomposes, Jacobi’s simplicity and accuracy win. QR rather than the normal equations makes the least-squares error scale with instead of : instead of on the degree-9 fit. Two tradeoffs are accepted: lstsq refuses rank-deficient rather than returning the minimum-norm solution (that needs the SVD and is what numpy.linalg.lstsq does), and the sweep cap of 64 is a safety stop, never reached on well-formed input.
What can go wrong
Section titled “What can go wrong”A correct solution passes a set of checks that mirror the theory. The hand example must reproduce , , to , pinning the rotation, the order, and the sign rule; , the balanced factors, and the error ; and the line fit . Random tall, wide, square, and matrices must match np.linalg.svd entry by entry after the same sign rule, since the decomposition is the unique one. Scaling by must scale the result exactly, svd(c A) being times svd(A), because the rotation test is relative. Rank-deficient and zero matrices, common among co-occurrence matrices, must give orthonormal and no NaN.
For low_rank, the spectral and Frobenius errors for must match Eckart-Young, which is the optimality word vectors and PiSSA rely on; the factors must satisfy ; and , , and must raise. For lstsq, one and three right-hand sides must match np.linalg.lstsq; the residual must satisfy ; the degree-9 polynomial fit () must recover its coefficients to , as the capstone’s scaling-law fit needs; and dependent columns, a wide system, and a wrong-length must raise. Throughout, must be unchanged, and 1-D and NaN inputs must raise.
The mistakes that break these checks:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| solving the normal equations | fine on easy fits, three correct digits on a degree-9 polynomial fit | factors with qr_householder and solves |
| leaving singular values in sweep order | low_rank keeps the wrong directions; the error is not | sorts with np.argsort(-S, kind="stable") |
| the rotation with the wrong sign () | the columns never become orthogonal; 64 sweeps of noise | s = c * t with the root of |
| stopping after one sweep | the columns are far from orthogonal: singular values of a random matrix off by 0.2 to 0.8 | repeats sweeps until one rotates nothing |
| the unbalanced split | same product, factors at different scales | multiplies sqrt(S[:r]) into both factors |
| dividing a zero column by its zero length | NaN in for rank-deficient matrices | calls _complete when S[j] is below the floor |
| no sign rule | factors disagree with LAPACK’s on some columns; downstream tests that fix a seed see flipped vectors | makes the largest of each column positive |
| an absolute threshold | tiny-scaled matrices are returned unrotated | compares with tol * sqrt(alpha * beta) |
| decomposing a wide matrix without transposing | shapes come out wrong | decomposes M.T and swaps the roles of and |
| back substitution from the top row | wrong whenever is not diagonal | loops range(n - 1, -1, -1) |
no rank check in lstsq | division by a zero diagonal entry of : inf | raises when diag.min() is below the relative floor |
| rotating the caller’s array in place | the decomposed weight is now | rotates np.array(T), a copy |
Warning: The normal equations are the classic trap because they work on every easy example you try by hand. The damage only shows on ill-conditioned fits, exactly the ones (like polynomial or scaling-law fits) where you most need the digits.
Where this leads
Section titled “Where this leads”In AI Engineering, ppmi_svd_embeddings in word2vec skip-gram with negative sampling, and the PPMI-SVD baseline keeps the top singular directions of the PPMI matrix as word vectors; LoRA: low-rank adaptation with PiSSA initialization and merging initializes LoRA with low_rank(W, r) and trains the residual; mha_to_mla in Multi-head latent attention compresses the key and value projections to a rank- latent; and the scaling-law fit in the TinyStories capstone is lstsq on loss against parameters. In this book, Error analysis, condition numbers, and tolerance budgets reads condition numbers from svd, and later optimization material on the Muon optimizer checks its Newton-Schulz approximation of against this SVD. The next section, Inner products, projections, cosine similarity, and top-k, returns to the geometry of projections.
Further reading
Section titled “Further reading”- LAPACK
dgesvj(Drmac and Veselic;SRC/dgesvj.f,dgejsv.f): preconditioning by QR with column pivoting, de Rijk’s pivoting, and blocked rotations, giving Jacobi’s high relative accuracy at near-LAPACK speed. - LAPACK
dgesdd, what NumPy calls (numpy/linalg/_linalg.py,SRC/dgesdd.f): Householder bidiagonalization, then divide and conquer on the bidiagonal matrix; much faster for large matrices. - Randomized SVD (Halko, Martinsson, Tropp 2011;
sklearn.utils.extmath.randomized_svd): the top triples of a huge sparse matrix from a few matrix products with random vectors. numpy.linalg.lstsq(LAPACKdgelsd): the minimum-norm solution for rank-deficient , via the SVD.- PEFT’s PiSSA initializer (
peft/tuners/lora/layer.py,pissa_init): the same balanced split on GPU, then the residual frozen as the base weight. - Trefethen and Bau, Numerical Linear Algebra, lectures 4, 5, 11, 31; Demmel and Veselic, “Jacobi’s method is more accurate than QR” (1992); Eckart and Young, “The approximation of one matrix by another of lower rank” (1936); Meng, Wang, and Zhang, “PiSSA” (2024).
Key terms
Section titled “Key terms”- Singular value decomposition: with orthonormal , and non-negative descending .
- Spectral norm: , the largest stretch of a unit vector.
- Frobenius norm: , the square root of the sum of squared entries.
- One-sided Jacobi: an SVD algorithm that rotates pairs of columns until all are mutually orthogonal.
- Sweep: one pass of Jacobi rotations over every column pair .
- Eckart-Young theorem: the truncated SVD is the closest rank- matrix in spectral and Frobenius norm.
- Balanced split: , , so both factors carry the same scale.
- Normal equations: , the least-squares optimality condition, which squares the condition number if solved directly.
Summary
Section titled “Summary”- Every real matrix is : rotate, stretch along the axes by the singular values, rotate again. The singular values are the square roots of the eigenvalues of , and the largest is the most can stretch a unit vector.
- One-sided Jacobi rotates pairs of columns until all are orthogonal; the test for “orthogonal enough” must be relative to the column lengths, or a matrix scaled by is never rotated.
- Keeping the largest singular triples gives the closest rank- matrix, and the spectral error is exactly the first dropped singular value (Eckart-Young); splitting into each factor makes them start at the same scale.
- Least squares by QR solves with error growing like ; the normal equations square it.
- Sorting, a sign rule, and a deterministic completion for zero singular values make the decomposition unique and reproducible.
Review questions
Section titled “Review questions”-
Why is the rotation test and not ?
Answer
is the cosine of the angle between the columns, which does not change when is scaled. An absolute threshold depends on the scale: at every is about and nothing is rotated; at nothing ever passes.
-
Why does the solution sort the singular values after the sweeps instead of trusting their order?
Answer
Jacobi leaves the lengths in whatever column they ended up in. Eckart-Young keeps the largest, so
low_ranktaking the first columns is only correct after a descending sort. The worked example ends with in column 0 and in column 1, which sorting swaps. -
Why are ‘s columns copied before being overwritten in the rotation?
Answer
Both new columns are combinations of both old ones. Updating
V[:, i]first and then reading it forV[:, j]would mix a new column into the second formula. TheWupdate avoids this by building both columns in onecolumn_stack. -
Why split into each factor of
low_rank?Answer
Any split , multiplies to , but the gradient of a product with respect to one factor scales with the other. The balanced split gives , so both factors train at the same rate (PiSSA’s choice).
-
Why does
lstsqcompare the smallest with before solving?Answer
A near-zero pivot means the columns are dependent and the minimizer is not unique; dividing by it gives huge or infinite coefficients. The test is relative to the largest pivot so it does not depend on the units of .