Skip to content

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.

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 log⁡L=a+blog⁡N\log L = a + b \log N 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-rr approximation as balanced factors BCBC; and lstsq(A, b), least squares by QR using qr_householder from qr.py.

Learning objectives

  • Read A=UΣV⊤A = U\Sigma V^\top geometrically and relate singular values to the eigenvalues of A⊤AA^\top A 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.
SymbolMeaningType / shape
AAthe matrix, mm rows and nn columnsfloat64[m, n]
k=min⁡(m,n)k = \min(m, n)number of singular valuesint
UUleft singular vectors, orthonormal columns (U⊤U=IU^\top U = I)float64[m, k]
σ1≥⋯≥σk≥0\sigma_1 \ge \dots \ge \sigma_k \ge 0singular values; Σ=diag⁡(σ)\Sigma = \operatorname{diag}(\sigma)float64[k]
VVright singular vectors, orthonormal columns; the contract returns V⊤V^\topfloat64[n, k]
ui,viu_i, v_icolumn ii of UU and of VVvectors
∥x∥\lVert x \rVertEuclidean length x⊤x\sqrt{x^\top x}scalar
∥A∥2=max⁡∥x∥=1∥Ax∥\lVert A \rVert_2 = \max_{\lVert x \rVert = 1} \lVert Ax \rVertspectral normscalar
∥A∥F=∑ijAij2\lVert A \rVert_F = \sqrt{\sum_{ij} A_{ij}^2}Frobenius normscalar
ArA_rthe truncated SVD ∑i≤rσiuivi⊤\sum_{i \le r} \sigma_i u_i v_i^\topfloat64[m, n]
wi,wjw_i, w_jtwo columns of the working matrix WWvectors
α,β,γ\alpha, \beta, \gammawi⊤wiw_i^\top w_i, wj⊤wjw_j^\top w_j, wi⊤wjw_i^\top w_jscalars
ζ,t,c,s\zeta, t, c, srotation parameters: t=tan⁡θt = \tan\theta, c=cos⁡θc = \cos\theta, s=sin⁡θs = \sin\thetascalars
ε\varepsilonfloat64 machine epsilon, 2−52≈2.2×10−162^{-52} \approx 2.2 \times 10^{-16}
κ(A)=σ1/σk\kappa(A) = \sigma_1 / \sigma_kcondition numberscalar
Q,RQ, Rthe QR factors from the previous sectionsfloat64[m, k], float64[k, n]

Every real m×nm \times n matrix factors as

A=UΣV⊤=∑i=1kσi uivi⊤,A = U \Sigma V^\top = \sum_{i=1}^{k} \sigma_i\, u_i v_i^\top ,

with orthonormal columns in UU and VV and non-negative σi\sigma_i in descending order. Read it right to left on a vector xx: V⊤xV^\top x takes the coordinates of xx along the directions viv_i, Σ\Sigma stretches coordinate ii by σi\sigma_i, and UU sends the result out along the directions uiu_i. So Avi=σiuiA v_i = \sigma_i u_i: rotate, stretch along the axes, rotate again. The unit sphere goes to an ellipsoid whose semi-axes are σiui\sigma_i u_i. This is the reduced SVD (UU is m×km \times k); the full one pads UU to a square matrix, which nothing in this book needs.

Each pair (ui,vi)(u_i, v_i) can be negated together without changing AA, since (−ui)σi(−vi)⊤=uiσivi⊤(-u_i)\sigma_i(-v_i)^\top = u_i \sigma_i v_i^\top. 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 V⊤V^\top 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.

Multiply out A⊤A=VΣ⊤U⊤UΣV⊤=VΣ2V⊤A^\top A = V \Sigma^\top U^\top U \Sigma V^\top = V \Sigma^2 V^\top: the viv_i are eigenvectors of the symmetric matrix A⊤AA^\top A with eigenvalues σi2\sigma_i^2 (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 xx with coordinates c=V⊤xc = V^\top x, ∥Ax∥2=∑iσi2ci2≤σ12\lVert Ax \rVert^2 = \sum_i \sigma_i^2 c_i^2 \le \sigma_1^2, with equality at x=v1x = v_1: the spectral norm is ∥A∥2=σ1\lVert A \rVert_2 = \sigma_1, the most AA can stretch a unit vector. Orthogonal factors do not change the sum of squares of entries, so the Frobenius norm is ∥A∥F=∑iσi2\lVert A \rVert_F = \sqrt{\sum_i \sigma_i^2}.

That connection suggests a shortcut: form A⊤AA^\top A and call an eigensolver. It would compute the SVD, but badly. Squaring the singular values squares the condition number, and a σi\sigma_i below ε σ1≈10−8σ1\sqrt{\varepsilon}\,\sigma_1 \approx 10^{-8}\sigma_1 drowns in the rounding of σ12\sigma_1^2. Jacobi works on AA itself.

Work on a tall matrix (m≥nm \ge n; for a wide one, decompose A⊤A^\top and swap UU and VV at the end, since nn orthogonal columns can only exist in Rm\mathbb{R}^m when m≥nm \ge n). Start with W=AW = A and V=IV = I, and keep the invariant W=AVW = AV with VV orthogonal. If all columns of WW were mutually orthogonal, their lengths would be the singular values and their directions the uiu_i: W=UΣW = U\Sigma, so A=UΣV⊤A = U \Sigma V^\top.

To make columns ii and jj orthogonal, rotate them in their plane:

wi←c wi−s wj,wj←s wi+c wj,w_i \leftarrow c\, w_i - s\, w_j, \qquad w_j \leftarrow s\, w_i + c\, w_j ,

and apply the same rotation to columns ii and jj of VV, so W=AVW = AV still holds; the rotation is orthogonal, so VV stays orthogonal. The new inner product is cs(α−β)+(c2−s2)γcs(\alpha - \beta) + (c^2 - s^2)\gamma. Setting it to zero with t=s/ct = s/c gives t2+2ζt−1=0t^2 + 2\zeta t - 1 = 0, ζ=(β−α)/(2γ)\zeta = (\beta - \alpha) / (2\gamma). Take the smaller root,

t=sign⁡(ζ)∣ζ∣+1+ζ2,c=11+t2,s=c t,t = \frac{\operatorname{sign}(\zeta)}{\lvert \zeta \rvert + \sqrt{1 + \zeta^2}}, \qquad c = \frac{1}{\sqrt{1 + t^2}}, \qquad s = c\,t ,

with sign⁡(0)=+1\operatorname{sign}(0) = +1. It is the rotation by at most 45°45°, the one that converges. A sweep visits every pair i<ji < j 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 30×1230 \times 12 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 ∣γ∣>mεαβ\lvert \gamma \rvert > m \varepsilon \sqrt{\alpha \beta}, that is, when the cosine of the angle between the columns exceeds mεm\varepsilon. A fixed threshold such as ∣γ∣>10−15\lvert\gamma\rvert > 10^{-15} skips every rotation on a matrix scaled by 10−1210^{-12} (all inner products are about 10−2410^{-24}) and returns garbage; on a matrix scaled by 101210^{12} it never stops. Stop after the first sweep that rotates nothing (the contract caps sweeps at 64). Finally, σj=∥wj∥\sigma_j = \lVert w_j \rVert, sorted descending (stably), uj=wj/σju_j = w_j / \sigma_j, and the sign rule.

The last step divides by σj\sigma_j, which fails when AA is rank deficient. If AA has rank ρ<k\rho < k, then k−ρk - \rho singular values are zero and their columns wjw_j are (numerically) zero: wj/σjw_j / \sigma_j is 0/00/0. The contract treats σj≤mεσ1\sigma_j \le m \varepsilon \sigma_1 as zero and fills uju_j with a unit vector orthogonal to the uu‘s already chosen: take the first standard basis vector eie_i that has more than half its length left after projecting out the previous columns (e←e−U(U⊤e)e \leftarrow e - U(U^\top e), 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.

Now the payoff. The truncated SVD Ar=∑i≤rσiuivi⊤A_r = \sum_{i \le r} \sigma_i u_i v_i^\top has rank rr, and A−Ar=∑i>rσiuivi⊤A - A_r = \sum_{i > r} \sigma_i u_i v_i^\top is itself an SVD, so

∥A−Ar∥2=σr+1,∥A−Ar∥F=∑i>rσi2.\lVert A - A_r \rVert_2 = \sigma_{r+1}, \qquad \lVert A - A_r \rVert_F = \sqrt{\textstyle\sum_{i > r} \sigma_i^2} .

The Eckart-Young theorem says no matrix of rank at most rr 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 ArA_r as two factors BB (m×rm \times r) and CC (r×nr \times n) with BC=ArBC = A_r. Many splits multiply to the same product; the contract uses the balanced one,

B=UrΣr1/2,C=Σr1/2Vr⊤,B = U_r \Sigma_r^{1/2}, \qquad C = \Sigma_r^{1/2} V_r^\top ,

so B⊤B=CC⊤=ΣrB^\top B = C C^\top = \Sigma_r and both factors carry the same scale. PiSSA initializes LoRA this way because gradient descent on BCBC updates each factor in proportion to the other’s size; a split such as (UrΣr,Vr⊤)(U_r\Sigma_r, V_r^\top) trains one factor much faster than the other.

The last tool solves systems with more equations than unknowns. For a tall AA with independent columns, Ax=bAx = b usually has no solution; least squares picks xx minimizing ∥Ax−b∥\lVert Ax - b \rVert. The minimizer makes the residual r=b−Axr = b - Ax orthogonal to every column of AA: A⊤r=0A^\top r = 0, the normal equations A⊤Ax=A⊤bA^\top A x = A^\top b. Solving them as written is the classic mistake. κ(A⊤A)=κ(A)2\kappa(A^\top A) = \kappa(A)^2, so a polynomial fit with κ(A)≈3.5×106\kappa(A) \approx 3.5 \times 10^6 (degree 9 at 40 points of [0,1][0, 1]) recovers its coefficients only to about 10−310^{-3}.

QR avoids the square. With A=QRA = QR, QQ 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 xx:

∥Ax−b∥2=∥Rx−Q⊤b∥2+∥(I−QQ⊤)b∥2.\lVert Ax - b \rVert^2 = \lVert Rx - Q^\top b \rVert^2 + \lVert (I - QQ^\top) b \rVert^2 .

So xx solves the triangular system Rx=Q⊤bR x = Q^\top b, by back substitution from the last row up: xi=(zi−∑j>iRijxj)/Riix_i = (z_i - \sum_{j > i} R_{ij} x_j) / R_{ii} with z=Q⊤bz = Q^\top b. The error now grows like κ(A)ε\kappa(A)\varepsilon: 5×10−105 \times 10^{-10} for the same fit. If some ∣Rii∣\lvert R_{ii} \rvert is tiny (≤max⁡(m,n) εmax⁡j∣Rjj∣\le \max(m, n)\,\varepsilon \max_j \lvert R_{jj} \rvert), 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 AA.

Take

A=(3045).A = \begin{pmatrix} 3 & 0 \\ 4 & 5 \end{pmatrix}.

Jacobi. There is one pair, (0,1)(0, 1). The table follows the rotation quantity by quantity:

QuantityValue
α=∥w0∥2\alpha = \lVert w_0 \rVert^2, β=∥w1∥2\beta = \lVert w_1 \rVert^2, γ=w0⊤w1\gamma = w_0^\top w_19+16=259 + 16 = 25, 0+25=250 + 25 = 25, 0+20=200 + 20 = 20
ζ=(β−α)/(2γ)\zeta = (\beta - \alpha)/(2\gamma)00, so t=1t = 1, c=s=1/2c = s = 1/\sqrt{2} (a 45°45° rotation)
new w0=c w0−s w1w_0 = c\,w_0 - s\,w_1(3−0, 4−5)/2=(3,−1)/2(3 - 0,\ 4 - 5)/\sqrt{2} = (3, -1)/\sqrt{2}, length 5\sqrt{5}
new w1=s w0+c w1w_1 = s\,w_0 + c\,w_1(3+0, 4+5)/2=(3,9)/2(3 + 0,\ 4 + 5)/\sqrt{2} = (3, 9)/\sqrt{2}, length 45=35\sqrt{45} = 3\sqrt{5}
new VV columnsv0=(1,−1)/2v_0 = (1, -1)/\sqrt{2}, v1=(1,1)/2v_1 = (1, 1)/\sqrt{2}
second sweepw0⊤w1=(9−9)/2=0w_0^\top w_1 = (9 - 9)/2 = 0: nothing to rotate, stop

Sorting puts σ1=35≈6.708\sigma_1 = 3\sqrt{5} \approx 6.708 first, then σ2=5≈2.236\sigma_2 = \sqrt{5} \approx 2.236. Check: σ12+σ22=50=9+16+25=∥A∥F2\sigma_1^2 + \sigma_2^2 = 50 = 9 + 16 + 25 = \lVert A \rVert_F^2, and σ1σ2=15=∣det⁡A∣\sigma_1\sigma_2 = 15 = \lvert \det A \rvert. Dividing each ww by its length:

U=110(133−1),Σ=(35005),V⊤=12(111−1).U = \frac{1}{\sqrt{10}}\begin{pmatrix} 1 & 3 \\ 3 & -1 \end{pmatrix}, \quad \Sigma = \begin{pmatrix} 3\sqrt{5} & 0 \\ 0 & \sqrt{5} \end{pmatrix}, \quad V^\top = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix}.

The sign rule holds already: each row of V⊤V^\top has its largest entries tied, and the first is positive.

Rank 1. A1=σ1u1v1⊤=35⋅120(1133)=(1.51.54.54.5)A_1 = \sigma_1 u_1 v_1^\top = 3\sqrt{5} \cdot \frac{1}{\sqrt{20}} \begin{pmatrix} 1 & 1 \\ 3 & 3 \end{pmatrix} = \begin{pmatrix} 1.5 & 1.5 \\ 4.5 & 4.5 \end{pmatrix}. The error A−A1=(1.5−1.5−0.50.5)=σ2u2v2⊤A - A_1 = \begin{pmatrix} 1.5 & -1.5 \\ -0.5 & 0.5 \end{pmatrix} = \sigma_2 u_2 v_2^\top has spectral and Frobenius norm 2.25+2.25+0.25+0.25=5=σ2\sqrt{2.25 + 2.25 + 0.25 + 0.25} = \sqrt{5} = \sigma_2, as Eckart-Young says. The balanced factors are B=451/4(1,3)⊤/10B = 45^{1/4}(1, 3)^\top/\sqrt{10} and C=451/4(1,1)/2C = 45^{1/4}(1, 1)/\sqrt{2}.

Least squares. Fit a line x0+x1tx_0 + x_1 t through (0,1)(0, 1), (1,2)(1, 2), (2,2)(2, 2): A=(101112)A = \begin{pmatrix} 1 & 0 \\ 1 & 1 \\ 1 & 2 \end{pmatrix}, b=(1,2,2)b = (1, 2, 2). By hand, the residual condition A⊤(b−Ax)=0A^\top(b - Ax) = 0 reads 3x0+3x1=53x_0 + 3x_1 = 5 and 3x0+5x1=63x_0 + 5x_1 = 6, so x1=1/2x_1 = 1/2 and x0=7/6x_0 = 7/6. Check: the residual b−Ax=(1−7/6, 2−5/3, 2−13/6)=(−1/6,1/3,−1/6)b - Ax = (1 - 7/6,\ 2 - 5/3,\ 2 - 13/6) = (-1/6, 1/3, -1/6) sums to 0 (orthogonal to the first column) and 0⋅(−1/6)+1⋅(1/3)+2⋅(−1/6)=00 \cdot (-1/6) + 1 \cdot (1/3) + 2 \cdot (-1/6) = 0 (orthogonal to the second). Writing out the normal equations is fine for a 2×22 \times 2 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.

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 AA unchanged, since a LoRA initializer keeps the weight it decomposes. svd rejects 1-D and non-finite inputs, low_rank requires 1≤r≤min⁡(m,n)1 \le r \le \min(m, n), and lstsq raises on dependent columns, a wide system, or a wrong-length bb.

The design follows from the principles in order. The SVD must be accurate for small singular values, which rules out an eigensolver on A⊤AA^\top A; working on AA directly with orthogonal rotations keeps every operation norm-preserving. If W=AVW = AV with VV orthogonal and WW‘s columns mutually orthogonal, then W=UΣW = U\Sigma 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 γ\gamma solves t2+2ζt−1=0t^2 + 2\zeta t - 1 = 0; the smaller root keeps ∣θ∣≤45°\lvert\theta\rvert \le 45°, which is what makes sweeps converge (in the worked example ζ=0\zeta = 0, t=1t = 1, a 45°45° rotation). “Orthogonal enough” must be scale-free, so the test compares ∣γ∣\lvert\gamma\rvert with mεαβm\varepsilon\sqrt{\alpha\beta}: a cosine, not an absolute size.

The algorithm needs m≥nm \ge n, so a wide matrix is decomposed as A⊤A^\top with UU and VV 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 σ1\sigma_1 cannot be normalized and gets a deterministic orthonormal completion. Signs are fixed last, on VV, so the result is unique and comparable with LAPACK. low_rank is then the truncated SVD split as Σ\sqrt{\Sigma} into each side, and lstsq is QR followed by back substitution on Rx=Q⊤bRx = Q^\top b, with a relative rank check before dividing.

The Jacobi kernel works on a copy of a tall matrix and accumulates VV:

EPS = 2.0**-52
MAX_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 = True

The rotation itself applies the same (c,s)(c, s) to WW and to VV so the invariant holds. Both new columns are combinations of both old ones, so VV‘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: converged

Reading off the factors takes lengths, a stable descending sort, and normalization or completion. The worked example ends with 5\sqrt 5 in column 0 and 353\sqrt 5 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 eie_i 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 VV and UU 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 unchanged

low_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_r

lstsq 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 x

The full solution is svd.py.

A sweep visits n(n−1)/2n(n-1)/2 pairs at O(m)O(m) each, so it costs O(mn2)O(mn^2), with a handful of sweeps in practice; memory is O(mn+n2)O(mn + n^2). lstsq is one QR, O(mn2)O(mn^2), plus O(n2)O(n^2) back substitution.

Eigen-decomposing A⊤AA^\top A squares κ\kappa and loses every singular value below about 10−8σ110^{-8}\sigma_1. 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 κ(A)\kappa(A) instead of κ(A)2\kappa(A)^2: 5×10−105 \times 10^{-10} instead of 10−310^{-3} on the degree-9 fit. Two tradeoffs are accepted: lstsq refuses rank-deficient AA 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.

A correct solution passes a set of checks that mirror the theory. The hand example must reproduce UU, Σ\Sigma, V⊤V^\top to 10−1410^{-14}, pinning the rotation, the order, and the sign rule; A1A_1, the balanced factors, and the error 5\sqrt{5}; and the line fit x=(7/6,1/2)x = (7/6, 1/2). Random tall, wide, square, and 1×n1 \times n matrices must match np.linalg.svd entry by entry after the same sign rule, since the decomposition is the unique one. Scaling by 10±1210^{\pm 12} must scale the result exactly, svd(c A) being cc times svd(A), because the rotation test is relative. Rank-deficient and zero matrices, common among co-occurrence matrices, must give orthonormal UU and no NaN.

For low_rank, the spectral and Frobenius errors for r=1,2,4,6r = 1, 2, 4, 6 must match Eckart-Young, which is the optimality word vectors and PiSSA rely on; the factors must satisfy B⊤B=CC⊤=ΣrB^\top B = C C^\top = \Sigma_r; and r=0r = 0, r<0r < 0, and r>min⁡(m,n)r > \min(m, n) must raise. For lstsq, one and three right-hand sides must match np.linalg.lstsq; the residual must satisfy A⊤(b−Ax)=0A^\top (b - Ax) = 0; the degree-9 polynomial fit (κ≈3.5×106\kappa \approx 3.5 \times 10^6) must recover its coefficients to 10−610^{-6}, as the capstone’s scaling-law fit needs; and dependent columns, a wide system, and a wrong-length bb must raise. Throughout, AA must be unchanged, and 1-D and NaN inputs must raise.

The mistakes that break these checks:

PitfallSymptomHow the solution avoids it
solving the normal equations A⊤Ax=A⊤bA^\top A x = A^\top bfine on easy fits, three correct digits on a degree-9 polynomial fitfactors with qr_householder and solves Rx=Q⊤bRx = Q^\top b
leaving singular values in sweep orderlow_rank keeps the wrong directions; the error is not σr+1\sigma_{r+1}sorts with np.argsort(-S, kind="stable")
the rotation with the wrong sign (s=−cts = -ct)the columns never become orthogonal; 64 sweeps of noises = c * t with tt the root of t2+2ζt−1=0t^2 + 2\zeta t - 1 = 0
stopping after one sweepthe columns are far from orthogonal: singular values of a random 30×1230 \times 12 matrix off by 0.2 to 0.8repeats sweeps until one rotates nothing
the unbalanced split (UrΣr,Vr⊤)(U_r\Sigma_r, V_r^\top)same product, factors at different scalesmultiplies sqrt(S[:r]) into both factors
dividing a zero column by its zero lengthNaN in UU for rank-deficient matricescalls _complete when S[j] is below the floor
no sign rulefactors disagree with LAPACK’s on some columns; downstream tests that fix a seed see flipped vectorsmakes the largest ∣entry∣\lvert\text{entry}\rvert of each VV column positive
an absolute threshold ∣γ∣>10−15\lvert\gamma\rvert > 10^{-15}tiny-scaled matrices are returned unrotatedcompares with tol * sqrt(alpha * beta)
decomposing a wide matrix without transposingshapes come out wrongdecomposes M.T and swaps the roles of UU and VV
back substitution from the top rowwrong xx whenever RR is not diagonalloops range(n - 1, -1, -1)
no rank check in lstsqdivision by a zero diagonal entry of RR: infraises when diag.min() is below the relative floor
rotating the caller’s array in placethe decomposed weight is now UΣU\Sigmarotates 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.

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-rr latent; and the scaling-law fit in the TinyStories capstone is lstsq on log⁡\log loss against log⁡\log parameters. In this book, Error analysis, condition numbers, and tolerance budgets reads condition numbers σ1/σk\sigma_1/\sigma_k from svd, and later optimization material on the Muon optimizer checks its Newton-Schulz approximation of UV⊤UV^\top against this SVD. The next section, Inner products, projections, cosine similarity, and top-k, returns to the geometry of projections.

  • 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 rr triples of a huge sparse matrix from a few matrix products with random vectors.
  • numpy.linalg.lstsq (LAPACK dgelsd): the minimum-norm solution for rank-deficient AA, via the SVD.
  • PEFT’s PiSSA initializer (peft/tuners/lora/layer.py, pissa_init): the same balanced split on GPU, then the residual W−BCW - BC 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).
  • Singular value decomposition: A=UΣV⊤A = U\Sigma V^\top with orthonormal UU, VV and non-negative descending σi\sigma_i.
  • Spectral norm: ∥A∥2=σ1\lVert A \rVert_2 = \sigma_1, the largest stretch of a unit vector.
  • Frobenius norm: ∥A∥F=∑iσi2\lVert A \rVert_F = \sqrt{\sum_i \sigma_i^2}, 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 i<ji < j.
  • Eckart-Young theorem: the truncated SVD ArA_r is the closest rank-rr matrix in spectral and Frobenius norm.
  • Balanced split: B=UrΣr1/2B = U_r\Sigma_r^{1/2}, C=Σr1/2Vr⊤C = \Sigma_r^{1/2}V_r^\top, so both factors carry the same scale.
  • Normal equations: A⊤Ax=A⊤bA^\top A x = A^\top b, the least-squares optimality condition, which squares the condition number if solved directly.
  • Every real matrix is A=UΣV⊤A = U \Sigma V^\top: rotate, stretch along the axes by the singular values, rotate again. The singular values are the square roots of the eigenvalues of A⊤AA^\top A, and the largest is the most AA 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 10−1210^{-12} is never rotated.
  • Keeping the rr largest singular triples gives the closest rank-rr matrix, and the spectral error is exactly the first dropped singular value (Eckart-Young); splitting σ\sqrt{\sigma} into each factor makes them start at the same scale.
  • Least squares by QR solves Rx=Q⊤bRx = Q^\top b with error growing like κ(A)\kappa(A); the normal equations square it.
  • Sorting, a sign rule, and a deterministic completion for zero singular values make the decomposition unique and reproducible.
  1. Why is the rotation test ∣γ∣≤mεαβ\lvert\gamma\rvert \le m\varepsilon\sqrt{\alpha\beta} and not ∣γ∣≤10−15\lvert\gamma\rvert \le 10^{-15}?

    Answer

    γ/αβ\gamma/\sqrt{\alpha\beta} is the cosine of the angle between the columns, which does not change when AA is scaled. An absolute threshold depends on the scale: at 10−1210^{-12} every γ\gamma is about 10−2410^{-24} and nothing is rotated; at 101210^{12} nothing ever passes.

  2. 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 rr largest, so low_rank taking the first rr columns is only correct after a descending sort. The worked example ends with 5\sqrt 5 in column 0 and 353\sqrt 5 in column 1, which sorting swaps.

  3. Why are VV‘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 for V[:, j] would mix a new column into the second formula. The W update avoids this by building both columns in one column_stack.

  4. Why split Σr\sqrt{\Sigma_r} into each factor of low_rank?

    Answer

    Any split B=UrDB = U_r D, C=D−1ΣrVr⊤C = D^{-1}\Sigma_r V_r^\top multiplies to ArA_r, but the gradient of a product with respect to one factor scales with the other. The balanced split gives B⊤B=CC⊤=ΣrB^\top B = CC^\top = \Sigma_r, so both factors train at the same rate (PiSSA’s choice).

  5. Why does lstsq compare the smallest ∣Rii∣\lvert R_{ii}\rvert with max⁡(m,n)εmax⁡∣Rjj∣\max(m, n)\varepsilon\max\lvert R_{jj}\rvert 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 AA.