Module contents
Lesson 17 of 25Core 100 min

Low-rank approximation and the Eckart-Young theorem

Images, ratings, network weights and asset returns often contain less information than their dimensions suggest. Prove that truncated SVD is the best rank-k approximation, choose a rank based on energy or noise, and apply effective-rank measures to compression, denoising, total least squares and real model weights.

After this lesson you can

  • Compute the truncated SVD and its exact spectral and Frobenius errors.
  • Prove the Eckart-Young theorem in spectral norm and state it for unitarily invariant norms.
  • Choose the approximation rank with energy criteria and the optimal Gavish–Donoho threshold.
  • Compute and interpret the numerical rank, stable rank and effective rank of a matrix.
  • Solve a total least squares problem using SVD and compare it with ordinary least squares.

Before you start

Motivation: far less information than the size suggests

A grayscale photograph with 1000×10001000 \times 1000 pixels is a matrix with a million numbers. A matrix of user ratings for movies has millions of entries. A dense layer in a mid-sized transformer, W∈R4096×4096\mat{W} \in \R^{4096\times 4096}, stores nearly seventeen million parameters. Daily returns for 500 stocks over ten years form a matrix of size 2500×5002500 \times 500.

In every case, the matrix contains much less information than its size suggests. Neighboring pixels are similar. User preferences depend on a few factors such as genre, era and tone. Stocks move together with the market and their sector. Formally, the matrix is close to a low-rank matrix. A rank-kk matrix takes k(m+n)k(m + n) numbers to store instead of mnmn:

A⏟m×n≈B⏟m×k C⊤⏟k×n.\underbrace{\mat{A}}_{m\times n} \approx \underbrace{\mat{B}}_{m\times k}\,\underbrace{\mat{C}\T}_{k\times n}.

For m=n=4096m = n = 4096 and k=64k = 64, that is 3.1 %3.1\,\% of the numbers. This lesson answers three questions. What is the best rank-kk matrix, and what error does it incur? The Eckart-Young theorem says it is the truncated SVD, with error determined by the singular values. How do you choose kk in noisy data? How do you measure how close a full-rank matrix is to low rank?

The answers appear throughout the curriculum. Principal component analysis approximates centered data by a low-rank matrix. LoRA adapts a language model using low-rank updates ΔW=BA\Delta\mat{W} = \mat{B}\mat{A}. Statistical factor models for portfolios are truncated SVDs of the returns matrix. At the end, you will measure the spectra of GPT-2 weights and see which aspects of neural networks can be described by low rank.

Intuition: an image is a sum of layers

Recall from the SVD lesson that any matrix A∈Rm×n\mat{A} \in \R^{m\times n} of rank rr is a sum of rr rank-one layers:

A=∑i=1rσi uivi⊤,σ1≥σ2≥⋯≥σr>0,\mat{A} = \sum_{i=1}^{r} \sigma_i\,\vb{u}_i\vb{v}_i\T, \qquad \sigma_1 \ge \sigma_2 \ge \dots \ge \sigma_r > 0,

The ui\vb{u}_i are orthonormal in Rm\R^m, and the vi\vb{v}_i are orthonormal in Rn\R^n. Each layer uivi⊤\vb{u}_i\vb{v}_i\T has Frobenius norm 11, so σi\sigma_i measures its weight. The simplest approximation to A\mat{A} keeps the kk heaviest layers. Try this with an image.

InteractiveImage compression with truncated SVD
Vary kk and compare the image, error and spectrum. The landscape is recognizable at k=10k = 10 using 16% of the numbers. Try the textures next. The horizontal stripes have rank 1, the checkerboard has rank 2, and the smooth diagonal wave has rank 3. The sharp diagonal stripes need 12 layers and the disk needs 28. Noise does not compress well. Beyond σ1\sigma_1, its spectrum falls slowly with no steps. You can also upload an image, which is processed in your browser.

The rest of the lesson turns these observations into theorems:

  1. Relative error is determined by the spectral tail. The ∥A−Ak∥F/∥A∥F\norm{\mat{A} - \mat{A}_k}_F / \norm{\mat{A}}_F readout is exactly the square root of the fraction of ∑iσi2\sum_i \sigma_i^2 in the shaded region.
  2. Rank depends on orientation. A separable function f(x)g(y)f(x)g(y) has rank 1, and a sum of kk separable functions has rank at most ≤k\le k. The wave sin⁡(a(x+y))=sin⁡(ax)cos⁡(ay)+cos⁡(ax)sin⁡(ay)\sin(a(x + y)) = \sin(ax)\cos(ay) + \cos(ax)\sin(ay) is a sum of two products plus the constant, giving rank 3. Sharp diagonal stripes contain many harmonics, and each harmonic contributes two layers.
  3. Spectral decay makes compression possible. For the landscape, σi\sigma_i fall by several orders of magnitude. The noise spectrum barely falls.

The next figure constructs the truncated SVD one layer at a time.

InteractiveLayer by layer
Press play. Each step adds one layer σkukvk⊤\sigma_k\vb{u}_k\vb{v}_k\T, the product of a vertical profile uk\vb{u}_k (left strip) and a horizontal one vk⊤\vb{v}_k\T (top strip). Compare the thumbnails. Layers 1 through 8 show large-scale structure. Layers 41 through 48 oscillate rapidly and carry little weight.

The first layers draw the large-scale structure: average brightness, horizon, house and sun. Each layer multiplies a vertical by a horizontal profile, producing axis-aligned bands and crossings. This explains why the diagonal roof edges take so many layers. The later layers alternate sign nearly pixel by pixel, capturing texture and sensor noise. This anticipates the section on choosing kk. If the signal lies in early layers and noise is spread across all layers, truncation also filters the data.

Truncated SVD and its exact error

The set {B:rank⁡B≤k}\{\mat{B} : \rank\mat{B} \le k\} is nonconvex. For example, averaging two rank-1 matrices typically gives rank 2. Yet the problem has an explicit solution for the norms of interest. Start by calculating the error of the natural candidate.

Proof

The difference is A−Ak=∑i=k+1pσiuivi⊤=U diag⁡(0,…,0,σk+1,…,σp) V⊤\mat{A} - \mat{A}_k = \sum_{i=k+1}^{p}\sigma_i\vb{u}_i\vb{v}_i\T = \mat{U}\,\diag(0, \dots, 0, \sigma_{k+1}, \dots, \sigma_p)\,\mat{V}\T, already in SVD form. Its singular values are σk+1,…,σp\sigma_{k+1}, \dots, \sigma_p and kk zeros. The spectral norm is the largest singular value, σk+1\sigma_{k+1}. The Frobenius norm is invariant under orthogonal multiplication on either side, ∥UDV⊤∥F=∥D∥F\norm{\mat{U}\mat{D}\mat{V}\T}_F = \norm{\mat{D}}_F, so it equals ∑i>kσi2\sqrt{\sum_{i>k}\sigma_i^2}. The Schatten norms are defined as the ℓq\ell_q norm of the singular-value vector.

∎

Two practical consequences:

  • Relative error and energy. Since ∥A∥F2=∑iσi2\norm{\mat{A}}_F^2 = \sum_i\sigma_i^2, the squared relative error is the fraction of discarded energy, ∥A−Ak∥F2/∥A∥F2=1−∑i≤kσi2/∑iσi2\norm{\mat{A} - \mat{A}_k}_F^2/\norm{\mat{A}}_F^2 = 1 - \sum_{i\le k}\sigma_i^2 / \sum_i\sigma_i^2. This is the fraction shown in the first figure.
  • The two norms can yield very different errors. The spectral norm counts the first discarded singular value. The Frobenius norm includes all of them. With a flat spectrum of pp values equal to σ\sigma, ∥A−Ak∥2=σ\norm{\mat{A} - \mat{A}_k}_2 = \sigma while ∥A−Ak∥F=σp−k\norm{\mat{A} - \mat{A}_k}_F = \sigma\sqrt{p - k}.

Counting parameters and operations

Storing Ak\mat{A}_k as (UkΣk) Vk⊤(\mat{U}_k\mat{\Sigma}_k)\,\mat{V}_k\T takes k(m+n)k(m + n) numbers, or k(m+n+1)k(m + n + 1) if you store the σi\sigma_i separately as in the first figure. The factorization saves storage if and only if

k(m+n)<mn  ⟺  k<mnm+n,k(m + n) \lt mn \iff k \lt \frac{mn}{m + n},

which for a square matrix becomes k<n/2k \lt n/2. The same holds for applying the matrix: Akx=Uk(Σk(Vk⊤x))\mat{A}_k\vb{x} = \mat{U}_k(\mat{\Sigma}_k(\mat{V}_k\T\vb{x})) takes k(m+n)k(m + n) multiplications instead of mnmn. A dense layer y=Wx\vb{y} = \mat{W}\vb{x} of size dout×dind_{\text{out}}\times d_{\text{in}} thus becomes two linear layers with no activation between them, sized din→kd_{\text{in}} \to k and k→doutk \to d_{\text{out}}. This is the bottleneck also used by linear autoencoders. Splitting a large operator into two smaller ones is also the idea behind depthwise separable convolutions in vision.

The Eckart-Young-Mirsky theorem

The truncated SVD is optimal among all rank-kk approximations.

This is the Eckart-Young theorem, or Eckart-Young-Mirsky in its general form. The proof has three steps: the spectral norm via a dimensional argument, a Weyl inequality for singular values derived from that step, and the Frobenius norm as a corollary.

Step 1: spectral norm via dimension

Proof

Let B\mat{B} with rank⁡B≤k\rank\mat{B} \le k. By rank–nullity, dim⁡null⁡(B)=n−rank⁡B≥n−k\dim\nullsp(\mat{B}) = n - \rank\mat{B} \ge n - k. Let Vk+1=span⁡{v1,…,vk+1}\mathcal{V}_{k+1} = \spn\{\vb{v}_1, \dots, \vb{v}_{k+1}\}, of dimension k+1k + 1. Since (n−k)+(k+1)=n+1>n(n - k) + (k + 1) = n + 1 \gt n, the two subspaces of Rn\R^n intersect in a nonzero vector: there exists x∈null⁡(B)∩Vk+1\vb{x} \in \nullsp(\mat{B}) \cap \mathcal{V}_{k+1} with ∥x∥2=1\norm{\vb{x}}_2 = 1.

Write x=∑i=1k+1civi\vb{x} = \sum_{i=1}^{k+1} c_i\vb{v}_i with ∑ici2=1\sum_i c_i^2 = 1. Since Bx=0\mat{B}\vb{x} = \vb{0} and Avi=σiui\mat{A}\vb{v}_i = \sigma_i\vb{u}_i, with the ui\vb{u}_i orthonormal,

∥(A−B)x∥22=∥Ax∥22=∥∑i=1k+1ciσiui∥22=∑i=1k+1ci2σi2≥σk+12∑i=1k+1ci2=σk+12.\norm{(\mat{A} - \mat{B})\vb{x}}_2^2 = \norm{\mat{A}\vb{x}}_2^2 = \Big\lVert\sum_{i=1}^{k+1} c_i\sigma_i\vb{u}_i\Big\rVert_2^2 = \sum_{i=1}^{k+1} c_i^2\sigma_i^2 \ge \sigma_{k+1}^2\sum_{i=1}^{k+1} c_i^2 = \sigma_{k+1}^2.

Therefore ∥A−B∥2≥∥(A−B)x∥2≥σk+1\norm{\mat{A} - \mat{B}}_2 \ge \norm{(\mat{A} - \mat{B})\vb{x}}_2 \ge \sigma_{k+1}, and the preceding proposition shows that Ak\mat{A}_k attains the bound.

∎

Step 2: Weyl’s inequality for singular values

Proof

Let Xi−1\mat{X}_{i-1} and Yj−1\mat{Y}_{j-1} be the truncated SVDs of X\mat{X} and Y\mat{Y}, with X0=0\mat{X}_0 = \mat{0}. Their sum Xi−1+Yj−1\mat{X}_{i-1} + \mat{Y}_{j-1} has rank ≤i+j−2\le i + j - 2. Apply step 1 to X+Y\mat{X} + \mat{Y} with k=i+j−2k = i + j - 2, then use the triangle inequality and the preceding error formula:

σi+j−1(X+Y)≤∥(X+Y)−(Xi−1+Yj−1)∥2≤∥X−Xi−1∥2+∥Y−Yj−1∥2=σi(X)+σj(Y).\sigma_{i+j-1}(\mat{X} + \mat{Y}) \le \norm{(\mat{X} + \mat{Y}) - (\mat{X}_{i-1} + \mat{Y}_{j-1})}_2 \le \norm{\mat{X} - \mat{X}_{i-1}}_2 + \norm{\mat{Y} - \mat{Y}_{j-1}}_2 = \sigma_i(\mat{X}) + \sigma_j(\mat{Y}).∎

With j=1j = 1 we obtain σi(X+Y)≤σi(X)+∥Y∥2\sigma_i(\mat{X} + \mat{Y}) \le \sigma_i(\mat{X}) + \norm{\mat{Y}}_2. Singular values are stable. A perturbation with spectral norm ε\eps moves each σi\sigma_i by at most ε\eps, by applying the inequality in both directions. This stability gives meaning to numerical rank in the next section.

Step 3: Frobenius norm and all unitarily invariant norms

σi+k(A)≤σi(A−B)+σk+1(B)\sigma_{i+k}(\mat{A}) \le \sigma_i(\mat{A} - \mat{B}) + \sigma_{k+1}(\mat{B})
Apply Weyl to A = (A − B) + B with j = k + 1.
1/5

The second step gives more than the Frobenius bound. The singular-value vector of A−B\mat{A} - \mat{B} dominates that of A−Ak\mat{A} - \mat{A}_k, namely (σk+1,…,σp,0,…,0)(\sigma_{k+1}, \dots, \sigma_p, 0, \dots, 0), entry by entry. Von Neumann’s 1937 theorem characterizes unitarily invariant norms (∥QAR∥=∥A∥\norm{\mat{Q}\mat{A}\mat{R}} = \norm{\mat{A}} for orthogonal Q,R\mat{Q}, \mat{R}) as symmetric gauge functions of singular values. These functions are monotone in the absolute value of each entry. Thus ∥A−B∥≥∥A−Ak∥\norm{\mat{A} - \mat{B}} \ge \norm{\mat{A} - \mat{A}_k} in all such norms. This is Mirsky’s extension.

Is the best approximation unique?

Uniqueness depends on the norm.

  • In Frobenius norm, Ak\mat{A}_k is the unique minimizer if and only if σk>σk+1\sigma_k \gt \sigma_{k+1}. If σk=σk+1\sigma_k = \sigma_{k+1}, changing the basis within the repeated singular subspace gives other equally good solutions.
  • In spectral norm, it is never unique under k≥1k \ge 1 and σk+1>0\sigma_{k+1} \gt 0. For A=diag⁡(3,1)\mat{A} = \diag(3, 1) and k=1k = 1, every B=diag⁡(3+t,0)\mat{B} = \diag(3 + t, 0) with ∣t∣≤1\abs{t} \le 1 satisfies ∥A−B∥2=max⁡(∣t∣,1)=1=σ2\norm{\mat{A} - \mat{B}}_2 = \max(\abs{t}, 1) = 1 = \sigma_2. In general, B=∑i≤k(σi+ti)uivi⊤\mat{B} = \sum_{i\le k}(\sigma_i + t_i)\vb{u}_i\vb{v}_i\T with ∣ti∣≤σk+1\abs{t_i} \le \sigma_{k+1} leaves error max⁡(max⁡i∣ti∣,σk+1)=σk+1\max(\max_i\abs{t_i}, \sigma_{k+1}) = \sigma_{k+1}. The spectral norm depends on the worst direction and allows freedom in the others.

Variational formulation: maximizing u⊤Av\vb{u}\T\mat{A}\vb{v}

For k=1k = 1, another view of the theorem connects it to optimization. Every rank-one matrix is s uv⊤s\,\vb{u}\vb{v}\T with ∥u∥=∥v∥=1\norm{\vb{u}} = \norm{\vb{v}} = 1. Expanding the square gives

∥A−suv⊤∥F2=∥A∥F2−2s u⊤Av+s2,\norm{\mat{A} - s\vb{u}\vb{v}\T}_F^2 = \norm{\mat{A}}_F^2 - 2s\,\vb{u}\T\mat{A}\vb{v} + s^2,

With u\vb{u} and v\vb{v} fixed, the minimum occurs at s=u⊤Avs = \vb{u}\T\mat{A}\vb{v} and equals ∥A∥F2−(u⊤Av)2\norm{\mat{A}}_F^2 - (\vb{u}\T\mat{A}\vb{v})^2. Minimizing the error means maximizing (u⊤Av)2(\vb{u}\T\mat{A}\vb{v})^2 over two spheres. The maximum is σ12\sigma_1^2 and occurs at (u1,v1)(\vb{u}_1, \vb{v}_1). For 2×22\times 2 matrices, u\vb{u} and v\vb{v} are represented by two angles, so the entire landscape fits on a map.

InteractiveThe landscape of rank-one approximations
In the left panel, v\vb{v} lies on the unit circle, its image Av\mat{A}\vb{v} lies on the ellipse, and the projection of Av\mat{A}\vb{v} onto the line along u\vb{u} has signed length u⊤Av\vb{u}\T\mat{A}\vb{v}. The map shows captured energy as a function of the two angles. Run gradient ascent from several initial points. It reaches the same maximum. Turn on the singular vectors to see the maximum and the saddle.

The map shows an additional fact about this objective. It has a unique maximum up to the signs of u\vb{u} and v\vb{v}, a saddle at (u2,v2)(\vb{u}_2, \vb{v}_2) and no spurious local maxima. In general, the critical points of (u,v)↦u⊤Av(\vb{u}, \vb{v}) \mapsto \vb{u}\T\mat{A}\vb{v} on the spheres are the singular pairs (±ui,±vi)(\pm\vb{u}_i, \pm\vb{v}_i), and if σ1>σ2\sigma_1 \gt \sigma_2 only the leading pair is a local maximum. This is why gradient descent often works when factorizing A≈BC⊤\mat{A} \approx \mat{B}\mat{C}\T despite the nonconvex objective. Lesson 25 explores this dynamic when training networks.

Choosing kk: energy, the elbow and noise

The theorem tells you what to do for a given kk. The choice of kk depends on what you want the approximation to achieve.

Energy criterion. Take the smallest kk such that ∑i≤kσi2≥e∑iσi2\sum_{i\le k}\sigma_i^2 \ge e\sum_i\sigma_i^2, with ee = 0.9, 0.95 or 0.99. This guarantees a relative Frobenius error of ≤1−e\le \sqrt{1 - e}. Use this criterion for compression when you want to preserve all of A\mat{A}.

Spectral elbow. Plot σi\sigma_i or log⁡σi\log\sigma_i against ii in a scree plot and look for the point where the curve changes from steep to nearly flat. It is a visual heuristic and can be hard to reproduce.

Signal plus noise. A different setting matters for machine learning. The data are

X=S+σZ,rank⁡S=r pequen˜o,Zij∼iidN(0,1),\mat{X} = \mat{S} + \sigma\mat{Z}, \qquad \rank\mat{S} = r \text{ pequeño}, \qquad Z_{ij} \iid \Normal(0, 1),

and you aim to recover S\mat{S} from X\mat{X}. For a pure-noise matrix of size m×nm\times n with β=m/n≤1\beta = m/n \le 1, the singular values of σZ\sigma\mat{Z} concentrate in the interval σn [1−β, 1+β]\sigma\sqrt{n}\,[1 - \sqrt{\beta},\, 1 + \sqrt{\beta}] as dimensions grow, according to the Marchenko-Pastur law. A signal component θn ab⊤\theta\sqrt{n}\,\vb{a}\vb{b}\T, with unit vectors a\vb{a} and b\vb{b}, separates from the bulk only if θ>β1/4σ\theta \gt \beta^{1/4}\sigma (the BBP transition). It then appears displaced outwards at σn (1+ρ2)(β+ρ2)/ρ\sigma\sqrt{n}\,\sqrt{(1 + \rho^2)(\beta + \rho^2)}/\rho with ρ=θ/σ\rho = \theta/\sigma. The random matrices lesson covers both results. Here we use their consequence.

The result is due to Gavish and Donoho (2014), stated here without proof. Notice that λ⋆(β)\lambda^\star(\beta) is above the bulk edge, 1+β1 + \sqrt{\beta}. A weak component that barely clears the bulk has singular vectors so contaminated by noise that including it adds more error than it removes. Keeping components that rise out of the Marchenko-Pastur bulk is also the basis of covariance matrix cleaning in portfolio models.

InteractiveSeparating signal from noise
A 60×12060\times 120 matrix contains a rank-rr signal plus noise. Above, the noise bulk of the singular-value spectrum follows the Marchenko-Pastur curve. Signal peaks appear in orange beyond the red threshold. Triangles mark the true strengths θi\theta_i. Below, the error relative to the signal is U-shaped, while the error relative to the data falls throughout. Raise σ\sigma and try the buttons. With high noise, the energy criterion retains dozens of noise layers.

What to look for in the figure:

  • Two error curves with different shapes. The error relative to the data, ∥X^k−X∥F\norm{\hat{\mat{X}}_k - \mat{X}}_F, always falls with kk because more layers improve the fit. The error relative to the signal falls while added layers contain signal, then rises when they contain noise. This is the bias–variance trade-off in miniature.
  • The threshold is at or near the bottom of the U, without knowing S\mat{S}. With the defaults (r=5r = 5, σ=1\sigma = 1), it retains 4 layers. The oracle, which sees S\mat{S}, retains 5. The error differs by two percentage points (59% versus 57%). The fifth component is real, but so close to the bulk that its estimated singular vectors are unreliable. Resample the noise several times. Including it usually helps very slightly, and sometimes hurts. This is a borderline case. With θ5=1.45\theta_5 = 1.45 and β=1/2\beta = 1/2, the BBP formula puts the fifth peak at 1.96n σ1.96\sqrt{n}\,\sigma, just below threshold λ⋆(1/2)n σ≈1.98n σ\lambda^\star(1/2)\sqrt{n}\,\sigma \approx 1.98\sqrt{n}\,\sigma, so asymptotically either choice costs almost the same. The threshold is optimal asymptotically, over large matrices, and on average. In a matrix of size 60×12060\times 120, it is somewhat conservative, yet it stays near the minimum.
  • The energy criterion performs poorly with noise. With σ=1\sigma = 1, the noise energy ≈σ2mn=7200\approx \sigma^2 mn = 7200 is more than twice the signal energy (≈2980\approx 2980). Retaining 90% of ∥X∥F2\norm{\mat{X}}_F^2 requires dozens of layers.

Numerical rank, stable rank and effective rank

In floating-point arithmetic, matrices from data or computations rarely have exactly zero singular values. The algebraic rank is almost always min⁡(m,n)\min(m, n) and is uninformative. We need measures that tolerate small perturbations. The Eckart-Young theorem gives the first one directly.

The second equality follows from Eckart-Young in spectral norm. The smallest rank achievable within distance ≤ε\le \eps is the number of σi\sigma_i above ε\eps. Numerical rank therefore gives the number of dimensions you cannot remove without moving the matrix by more than ε\eps. The default tolerance of np.linalg.matrix_rank is ε=σ1max⁡(m,n) εmaˊq\eps = \sigma_1 \max(m, n)\,\eps_{\text{máq}}, on the scale of the SVD’s own rounding error. When data have measurement noise at level δ\delta, a sensible tolerance is of order δ\delta instead of machine epsilon.

Numerical rank depends on a threshold and changes in discrete jumps. Two continuous measures complement it:

  • The stable rank, sr⁡(A)=∥A∥F2/∥A∥22=∑iσi2/σ12\operatorname{sr}(\mat{A}) = \norm{\mat{A}}_F^2/\norm{\mat{A}}_2^2 = \sum_i\sigma_i^2/\sigma_1^2. It satisfies 1≤sr⁡(A)≤rank⁡A1 \le \operatorname{sr}(\mat{A}) \le \rank\mat{A}, is robust to small perturbations and appears in randomized SVD and random matrix bounds. It is dominated by σ1\sigma_1, so one large singular value can pull it toward 1.
  • The effective rank of Roy and Vetterli (2007), erank⁡(A)=exp⁡(−∑ipilog⁡pi)\operatorname{erank}(\mat{A}) = \exp\big(-\sum_i p_i\log p_i\big) with pi=σi/∑jσjp_i = \sigma_i/\sum_j\sigma_j. It is the exponential of the entropy of the normalized singular values. It equals rr if rr singular values are equal and the rest are zero, and lies between 1 and the rank. It measures how many directions share the spectral mass.

The three measures answer different questions. Numerical rank asks which dimensions survive a given perturbation level, stable rank compares the dominant direction with the total, and effective rank measures how broadly the spectrum is distributed. The literature includes variants using σi2\sigma_i^2 instead of σi\sigma_i in the entropy, or the participation ratio (∑σi2)2/∑σi4(\sum\sigma_i^2)^2/\sum\sigma_i^4. Check a paper’s definition before comparing reported values.

InteractiveFive ways to count rank
Singular values σ1≥⋯≥σ40\sigma_1 \ge \dots \ge \sigma_{40} (log scale)
  • above tolerance
  • below tolerance
  • tolerance ε
110⁻³10⁻⁶10⁻⁹10⁻¹²110203040
Five measures on the same axis (0 to 40)
0510203040algebraic ranknumerical rank (ε = 10⁻³·σ₁)k for 90% of energystable rankeffective rank
Spectrum
0.25
0
10⁻³
algebraic rank40
numerical rank (ε = 10⁻³·σ₁)28
k for 90% of energy5
stable rank2.54
effective rank10.90
The stable rank (2.5) is dominated by σ1\sigma_1. The effective rank (10.9) measures how many directions share the mass ∑iσi\sum_i \sigma_i.
For the same spectrum, the five measures range from 2.5 to 40. Select Rank 5 + noise and add a noise floor η\eta. The slightest noise drives the algebraic rank from 5 to 40, while the continuous measures barely change. Move the tolerance to see numerical rank pass through every possible value when the spectrum decays without steps.

Why are so many large matrices approximately low rank?

Udell and Townsend (2019) offer an explanation. Suppose each row ii has a latent variable αi\vb{\alpha}_i (a user’s preferences), and each column has one βj\vb{\beta}_j (a movie’s attributes). Suppose Aij=g(αi,βj)A_{ij} = g(\vb{\alpha}_i, \vb{\beta}_j) for piecewise analytic gg. These matrices typically have full rank, yet the authors prove that every entry can be approximated within a fixed absolute error by a matrix of rank O(log⁡(m+n))\bigO(\log(m + n)). The proof combines a Taylor expansion of gg with the Johnson-Lindenstrauss lemma. Approximate low rank can arise when a few smoothly interacting factors generate many observations. The first code cell shows the spectral decay of such a matrix.

Total least squares

Ordinary least squares (OLS) solves min⁡x∥Ax−b∥2\min_{\vb{x}}\norm{\mat{A}\vb{x} - \vb{b}}_2. It assumes A\mat{A} is exact and assigns all the error to b\vb{b}. When fitting a line, this means measuring residuals vertically. Both variables can have error: the position and velocity of a robot estimated by sensors, two prices measured with microstructure noise, or the calibration of one instrument against another. These are errors-in-variables models.

The constraint says [A+ΔA    b+Δb][x−1]=0[\mat{A} + \Delta\mat{A}\;\; \vb{b} + \Delta\vb{b}]\begin{bmatrix}\vb{x}\\ -1\end{bmatrix} = \vb{0}. The perturbed augmented matrix C+ΔC\mat{C} + \Delta\mat{C}, with C=[A    b]∈Rm×(n+1)\mat{C} = [\mat{A}\;\; \vb{b}] \in \R^{m\times(n+1)}, has a nonzero vector in its null space and hence rank ≤n\le n. This is an Eckart-Young problem. The smallest Frobenius-norm perturbation reducing the rank of C\mat{C} to nn is ΔC=−σn+1un+1vn+1⊤\Delta\mat{C} = -\sigma_{n+1}\vb{u}_{n+1}\vb{v}_{n+1}\T. The null space of C+ΔC\mat{C} + \Delta\mat{C} is the line spanned by vn+1\vb{v}_{n+1}, the last right singular vector of C\mat{C}. Normalize its last component to −1-1 to obtain

xTLS=−1vn+1, n+1[v1, n+1⋮vn, n+1],\vb{x}_{\text{TLS}} = -\frac{1}{v_{n+1,\,n+1}}\begin{bmatrix} v_{1,\,n+1} \\ \vdots \\ v_{n,\,n+1}\end{bmatrix},

which exists if vn+1, n+1≠0v_{n+1,\,n+1} \ne 0 and is unique if also σn(C)>σn+1(C)\sigma_n(\mat{C}) \gt \sigma_{n+1}(\mat{C}). A sufficient condition for both is σn(A)>σn+1(C)\sigma_n(\mat{A}) \gt \sigma_{n+1}(\mat{C}).

Closed form. Since vn+1\vb{v}_{n+1} is an eigenvector of C⊤C\mat{C}\T\mat{C} with eigenvalue σn+12\sigma_{n+1}^2, write C⊤C\mat{C}\T\mat{C} in blocks and set vn+1∝(x,−1)\vb{v}_{n+1} \propto (\vb{x}, -1). The first block row gives

A⊤Ax−A⊤b=σn+12x  ⟺  xTLS=(A⊤A−σn+12I)−1A⊤b.\mat{A}\T\mat{A}\vb{x} - \mat{A}\T\vb{b} = \sigma_{n+1}^2\vb{x} \iff \vb{x}_{\text{TLS}} = (\mat{A}\T\mat{A} - \sigma_{n+1}^2\mat{I})\inv\mat{A}\T\vb{b}.

Compare this with the OLS normal equations, (A⊤A)x=A⊤b(\mat{A}\T\mat{A})\vb{x} = \mat{A}\T\vb{b}, and ridge regression, (A⊤A+λI)x=A⊤b(\mat{A}\T\mat{A} + \lambda\mat{I})\vb{x} = \mat{A}\T\vb{b}. TLS acts like ridge with negative λ\lambda. Subtracting the term reverses shrinkage. Noise in A\mat{A} inflates A⊤A\mat{A}\T\mat{A} and shrinks the OLS solution, and TLS corrects that bias at the cost of worse conditioning.

Fitting a line

In the plane, take the centered data D∈RN×2\mat{D} \in \R^{N\times 2}, each row a point minus the centroid. The TLS line passes through the centroid with direction v1\vb{v}_1 and normal v2\vb{v}_2, the right singular vectors of D\mat{D}. The sum of squared perpendicular distances is exactly σ22\sigma_2^2 and is minimal among lines by Eckart-Young with k=1k = 1 applied to D\mat{D}. The line is also the first principal component.

InteractiveVertical and perpendicular residuals
The points come from a line of slope 0.8 with noise in xx and yy. You can drag the points. Orange shows OLS with its vertical residuals. Magenta shows TLS with its perpendicular residuals. Increase σx\sigma_x. The OLS line flattens due to regression dilution, while TLS stays near the true line when σx=σy\sigma_x = \sigma_y. Then lower σx\sigma_x below σy\sigma_y and watch TLS overshoot.

If x=x∗+δx = x^\ast + \delta with independent δ\delta of variance σx2\sigma_x^2, the OLS slope converges to a Var⁡(x∗)/(Var⁡(x∗)+σx2)a\,\Var(x^\ast)/(\Var(x^\ast) + \sigma_x^2) instead of aa. It is attenuated toward zero, more so as noise in xx grows. TLS is consistent under isotropic noise, σx=σy\sigma_x = \sigma_y. Otherwise, first rescale the variables to equalize noise variances: divide yy by σy/σx\sigma_y/\sigma_x, fit, and undo the scaling. Without that information, TLS can overshoot, as the figure shows with σx<σy\sigma_x \lt \sigma_y.

Implementation from scratch

Start with a matrix from a latent-variable model like Udell and Townsend’s: Aij=1/(1+αi⊤βj)A_{ij} = 1/(1 + \vb{\alpha}_i\T\vb{\beta}_j) with αi,βj∈[0,1]3\vb{\alpha}_i, \vb{\beta}_j \in [0, 1]^3. Its numerical rank is high, yet its spectrum decays quickly.

[ ]A latent-variable matrix: full rank with spectral decayBrowser
import numpy as np

rng = np.random.default_rng(0)
m, n = 300, 200
alpha = rng.uniform(0, 1, (m, 3))   # variable latente de cada fila
beta = rng.uniform(0, 1, (n, 3))    # variable latente de cada columna
A = 1.0 / (1.0 + alpha @ beta.T)    # A_ij = g(alpha_i, beta_j), analítica

s = np.linalg.svd(A, compute_uv=False)
print("rango numérico (tolerancia de NumPy):", np.linalg.matrix_rank(A))
for k in [1, 2, 5, 10, 20]:
    print(f"sigma_{k + 1} / sigma_1 = {s[k] / s[0]:.1e}")

Next, compute a rank-kk approximation without taking the SVD of A\mat{A}. Subspace iteration alternates multiplying a block of vectors by A\mat{A} and A⊤\mat{A}\T, reorthonormalizing the kk vectors. It converges to the subspace of the leading kk singular vectors at rate (σk+1/σk)2t(\sigma_{k+1}/\sigma_k)^{2t}. Then only the SVD of the small matrix Q⊤A∈Rk×n\mat{Q}\T\mat{A} \in \R^{k\times n} is needed. This is the basis of the randomized SVD used by libraries for large matrices.

[ ]Rank k by subspace iteration and its exact errorBrowser
def rank_k(A, k, iters=30, seed=0):
    """Factores (U_k, s_k, Vt_k) de la mejor aproximación de rango k, por iteración de subespacios."""
    rng = np.random.default_rng(seed)
    Q, _ = np.linalg.qr(A @ rng.standard_normal((A.shape[1], k)))
    for _ in range(iters):
        Z, _ = np.linalg.qr(A.T @ Q)     # base del espacio de filas
        Q, _ = np.linalg.qr(A @ Z)       # base del espacio de columnas
    Ub, sb, Vbt = np.linalg.svd(Q.T @ A, full_matrices=False)   # SVD de una matriz k x n
    return Q @ Ub, sb, Vbt

for k in [1, 3, 5]:
    U, sk, Vt = rank_k(A, k)
    Ak = (U * sk) @ Vt
    print(f"k={k}:  ||A-A_k||_2 = {np.linalg.norm(A - Ak, 2):.6f}  (sigma_k+1 = {s[k]:.6f})   "
          f"||A-A_k||_F = {np.linalg.norm(A - Ak):.6f}  (cola = {np.sqrt(np.sum(s[k:]**2)):.6f})")

The two columns agree to six decimal places, as the error formula predicts. Next, compare Eckart-Young with thousands of alternatives. Random rank-kk matrices make poor competitors. Use projections of A\mat{A} onto subspaces of dimension kk (QQ⊤A\mat{Q}\mat{Q}\T\mat{A}) and small perturbations of the optimal subspace.

[ ]Eckart-Young against 3000 alternativesBrowser
m2, n2, k = 12, 8, 2
peor = np.inf
for t in range(3000):
    M = rng.standard_normal((m2, n2))
    U, S, Vt = np.linalg.svd(M)
    cota_2, cota_F = S[k], np.sqrt(np.sum(S[k:]**2))
    tipo = t % 3
    if tipo == 0:      # rango k cualquiera
        B = rng.standard_normal((m2, k)) @ rng.standard_normal((k, n2))
    elif tipo == 1:    # proyección sobre un subespacio aleatorio de dimensión k
        Q, _ = np.linalg.qr(rng.standard_normal((m2, k)))
        B = Q @ Q.T @ M
    else:              # proyección sobre un subespacio casi óptimo
        Q, _ = np.linalg.qr(U[:, :k] + 0.05 * rng.standard_normal((m2, k)))
        B = Q @ Q.T @ M
    peor = min(peor, np.linalg.norm(M - B, 2) / cota_2, np.linalg.norm(M - B) / cota_F)
print(f"menor cociente error / cota de Eckart-Young: {peor:.6f}  (nunca baja de 1)")

Finally, denoise a rank-10 signal with strengths θi\theta_i between 3 and 0.8 (in units of n σ\sqrt{n}\,\sigma), plus noise. Compare four ways to choose kk.

[ ]Denoising: Gavish–Donoho versus the energy criterionBrowser
m, n, r = 200, 400, 10
b = m / n
theta = np.linspace(3.0, 0.8, r)
Uq, _ = np.linalg.qr(rng.standard_normal((m, r)))
Vq, _ = np.linalg.qr(rng.standard_normal((n, r)))
S_true = np.sqrt(n) * (Uq * theta) @ Vq.T
sigma = 1.0
X = S_true + sigma * rng.standard_normal((m, n))

U, s, Vt = np.linalg.svd(X, full_matrices=False)
lam = np.sqrt(2 * (b + 1) + 8 * b / (b + 1 + np.sqrt(b * b + 14 * b + 1)))
omega = 0.56 * b**3 - 0.95 * b**2 + 1.82 * b + 1.43

def error(k):
    return np.linalg.norm((U[:, :k] * s[:k]) @ Vt[:k] - S_true) / np.linalg.norm(S_true)

errores = [error(k) for k in range(40)]
energia = np.cumsum(s**2) / np.sum(s**2)
criterios = {
    "Gavish-Donoho, sigma conocido": int(np.sum(s > lam * np.sqrt(n) * sigma)),
    "Gavish-Donoho, sigma estimado": int(np.sum(s > omega * np.median(s))),
    "90 % de energía": int(np.searchsorted(energia, 0.9) + 1),
    "rango verdadero": r,
    "oráculo (mejor k)": int(np.argmin(errores)),
}
print(f"error relativo de no hacer nada (X frente a S): {np.linalg.norm(X - S_true) / np.linalg.norm(S_true):.3f}")
for nombre, k in criterios.items():
    print(f"{nombre:32s} k = {k:3d}   error relativo = {error(k):.3f}")

The Gavish–Donoho threshold, with σ\sigma either known or estimated by the median, matches the oracle and reduces relative error from 2.2 to 0.63. Keeping the true rank of 10 gives a worse estimate. The three weakest components fall below the threshold and their singular vectors are almost entirely noise. The energy criterion retains more than a hundred layers and barely improves on the raw data.

CodeTruncated SVD and choosing k
Implement truncated_svd(A, k), which returns the best rank-k approximation of A with the same shape. Return a zero matrix when k = 0 and A itself when k is at least min(A.shape). Then implement choose_rank(singular_values, energy). It takes singular values in descending order and a fraction energy in [0,1][0, 1], and returns the smallest integer k, from 0 to the number of values, such that the sum of the first k σi2\sigma_i^2 is at least energy times the total. You may use np.linalg.svd.
import numpy as np

def truncated_svd(A, k):
  # tu código
  return A

def choose_rank(singular_values, energy):
  # tu código
  return len(singular_values)
Shift+Enter to run
CodeThe total least squares line
Implement tls_line(points). Given an array of shape (N, 2) with points (xi,yi)(x_i, y_i), return the slope a and intercept b of the total least squares line y=ax+by = ax + b, which minimizes the sum of squared perpendicular distances. Use the SVD of the centered data. Assume that the line is nonvertical.
import numpy as np

def tls_line(points):
  # tu código: de momento, mínimos cuadrados ordinarios
  x, y = points[:, 0], points[:, 1]
  a = np.sum((x - x.mean()) * (y - y.mean())) / np.sum((x - x.mean())**2)
  return a, y.mean() - a * x.mean()
Shift+Enter to run

Standard library implementations

In practice, choose the appropriate library routine.

TaskToolNotes
Full or reduced SVD of a dense matrixnp.linalg.svd(A, full_matrices=False), scipy.linalg.svdLAPACK (gesdd by default). O(mnmin⁡(m,n))\bigO(mn\min(m, n))
Singular values onlynp.linalg.svd(A, compute_uv=False), scipy.linalg.svdvalsFaster and more accurate than forming A⊤A\mat{A}\T\mat{A}
A few σi\sigma_i of a large or sparse matrixscipy.sparse.linalg.svds(A, k)Lanczos or LOBPCG methods
Fast rank-kk approximationsklearn.utils.extmath.randomized_svd, sklearn.decomposition.TruncatedSVD, torch.svd_lowrankSubspace iteration with random initialization
Numerical ranknp.linalg.matrix_rank(A, tol=...)Default: ε=σ1max⁡(m,n) εmaˊq\eps = \sigma_1\max(m, n)\,\eps_{\text{máq}}
Total least squaresscipy.odr (orthogonal distance regression) or the SVD of [A    b][\mat{A}\;\; \vb{b}]scipy.odr accepts separate weights for each variable
[ ]The libraries give the same resultsBrowser
from scipy.sparse.linalg import svds
from sklearn.utils.extmath import randomized_svd

k = 5
U_r, s_r, Vt_r = randomized_svd(A, n_components=k, n_iter=7, random_state=0)
U_s, s_s, Vt_s = svds(A, k=k)                    # devuelve los sigma en orden creciente
s_full = np.linalg.svd(A, compute_uv=False)

print("NumPy        :", np.round(s_full[:k], 8))
print("randomized   :", np.round(s_r, 8))
print("svds         :", np.round(s_s[::-1], 8))
Ak = (U_r * s_r) @ Vt_r
print("error de la aproximación aleatorizada:", np.linalg.norm(A - Ak), " cota:", np.sqrt(np.sum(s_full[k:]**2)))

Effective rank in a real model

Are the weights of a pretrained network low rank? The next cell loads GPT-2 small (124 million parameters) on the GPU and measures four weight matrices in each of three blocks: the joint query, key and value projection (c_attn, 768×2304768\times 2304), the attention output (attn.proj, 768×768768\times 768), and the two MLP layers (768×3072768\times 3072 and 3072×7683072\times 768). The first run downloads the model, around 500 MB, to the Hugging Face cache. In transformers, these layers are Conv1D and store weights as (din,dout)(d_{\text{in}}, d_{\text{out}}), with y=xW\vb{y} = \vb{x}\mat{W}.

[ ]Spectrum of GPT-2 weightsLocal GPU
import time, copy
import torch
from transformers import GPT2LMHeadModel, GPT2TokenizerFast

torch.manual_seed(0)
dev = "cuda" if torch.cuda.is_available() else "cpu"
tok = GPT2TokenizerFast.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2").to(dev).eval()

def stable_rank(s):
    return float((s**2).sum() / s[0]**2)

def effective_rank(s):
    p = s / s.sum()
    p = p[p > 0]
    return float(torch.exp(-(p * p.log()).sum()))

def energy_rank(s, e=0.9):
    c = torch.cumsum(s**2, 0) / (s**2).sum()
    return int((c < e).sum()) + 1

print(f"{'bloque':>6} {'matriz':>10} {'forma':>12} {'r. estable':>10} {'r. efectivo':>11} {'k (90 %)':>9}")
with torch.no_grad():
    for l in [0, 5, 11]:
        blk = model.transformer.h[l]
        for name, W in [("c_attn", blk.attn.c_attn.weight), ("attn.proj", blk.attn.c_proj.weight),
                        ("mlp.fc", blk.mlp.c_fc.weight), ("mlp.proj", blk.mlp.c_proj.weight)]:
            s = torch.linalg.svdvals(W.float())
            print(f"{l:>6} {name:>10} {str(tuple(W.shape)):>12} {stable_rank(s):10.1f} {effective_rank(s):11.1f} {energy_rank(s):9d}")
    G = torch.randn(768, 3072, device=dev) / 768**0.5
    s = torch.linalg.svdvals(G)
    print(f"{'ref.':>6} {'gaussiana':>10} {'(768, 3072)':>12} {stable_rank(s):10.1f} {effective_rank(s):11.1f} {energy_rank(s):9d}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Stable rank is small, between a few and a little over one hundred, versus around 340 for a Gaussian matrix of size 768×3072768\times 3072. Each layer has a few very large singular values. Yet effective rank in the MLP layers is around 700 of 768. In attention layers it varies more by block, from around 350 to 690. Capturing 90% of an MLP layer’s energy needs around 500 directions. These are of the same order as the Gaussian reference matrix, around 740 and 585, even though it has no structure. The pretrained weights have a few dominant directions on top of a broad, full spectrum. LoRA exploits low rank in the weight change when adapting the model to a task.

To see how much this matters, the next cell truncates the two MLP layers in all twelve blocks and measures perplexity on a test paragraph. It compares two variants. The first applies Eckart-Young to W\mat{W}. The second accounts for the data. If layer inputs x\vb{x} have second-moment matrix C=E[xx⊤]≻0\mat{C} = \E[\vb{x}\vb{x}\T] \succ 0, the relevant error is E∥x⊤(W−W^)∥2=∥C1/2(W−W^)∥F2\E\norm{\vb{x}\T(\mat{W} - \hat{\mat{W}})}^2 = \norm{\mat{C}^{1/2}(\mat{W} - \hat{\mat{W}})}_F^2. Apply Eckart-Young to C1/2W\mat{C}^{1/2}\mat{W} to get the minimum at rank kk, namely W^=C−1/2[C1/2W]k\hat{\mat{W}} = \mat{C}^{-1/2}[\mat{C}^{1/2}\mat{W}]_k. To estimate C\mat{C} without external data, the cell samples text from the model itself.

[ ]Compressing the GPT-2 MLP: SVD of W versus a data-aware SVDLocal GPU
text = ("The kitchen was quiet in the early morning, and the only sound came from the kettle on the stove. "
        "She opened the window to let in the cool air, then measured flour, sugar and a pinch of salt into a large bowl. "
        "Her grandmother had taught her that good bread needs patience more than skill: the dough must rest, rise and rest again. "
        "While it rested, she walked to the market, where farmers were unloading boxes of apples, pears and fresh vegetables. "
        "A man at the corner sold coffee from a small cart, and a group of students waited in line, talking about their exams. "
        "When she came back, the dough had doubled in size. She shaped it into two loaves, covered them with a towel "
        "and turned on the oven. By noon the whole house smelled of warm bread, and her neighbours knocked on the door to ask "
        "whether there was a loaf to spare. She laughed, cut the first one into thick slices and put the kettle on again.")
ids = tok(text, return_tensors="pt").input_ids.to(dev)

@torch.no_grad()
def perplexity(m):
    return float(torch.exp(m(ids, labels=ids).loss))

# calibración: 16 secuencias de 256 tokens muestreadas del propio modelo
with torch.no_grad():
    start = torch.full((16, 1), tok.bos_token_id, device=dev)
    calib = model.generate(start, attention_mask=torch.ones_like(start), do_sample=True, top_k=50,
                           max_new_tokens=255, pad_token_id=tok.eos_token_id)

cov = {}
def make_hook(key):
    def hook(mod, inp, out):
        x = inp[0].reshape(-1, inp[0].shape[-1]).float()
        cov[key] = cov.get(key, 0) + x.T @ x
    return hook

handles = []
for i, blk in enumerate(model.transformer.h):
    handles.append(blk.mlp.c_fc.register_forward_hook(make_hook((i, "fc"))))
    handles.append(blk.mlp.c_proj.register_forward_hook(make_hook((i, "proj"))))
with torch.no_grad():
    model(calib)
for h in handles:
    h.remove()

@torch.no_grad()
def factors(W, C=None):
    """SVD de W, o de C^(1/2) W si se da la matriz de segundos momentos C de las entradas."""
    if C is None:
        U, S, Vh = torch.linalg.svd(W, full_matrices=False)
        return U, S, Vh, None
    lam, Q = torch.linalg.eigh(C)
    lam = lam.clamp_min(lam.max() * 1e-6)          # regulariza direcciones casi sin datos
    R = (Q * lam.sqrt()) @ Q.T
    R_inv = (Q / lam.sqrt()) @ Q.T
    U, S, Vh = torch.linalg.svd(R @ W, full_matrices=False)
    return U, S, Vh, R_inv

fac = {}
for i, blk in enumerate(model.transformer.h):
    for name, lin in [("fc", blk.mlp.c_fc), ("proj", blk.mlp.c_proj)]:
        fac[(i, name, "W")] = factors(lin.weight.float())
        fac[(i, name, "datos")] = factors(lin.weight.float(), cov[(i, name)])

@torch.no_grad()
def compressed(k, mode):
    m = copy.deepcopy(model)
    for i, blk in enumerate(m.transformer.h):
        for name, lin in [("fc", blk.mlp.c_fc), ("proj", blk.mlp.c_proj)]:
            U, S, Vh, R_inv = fac[(i, name, mode)]
            Wk = (U[:, :k] * S[:k]) @ Vh[:k]
            lin.weight.copy_(Wk if R_inv is None else R_inv @ Wk)
    return m

print(f"modelo original: perplejidad {perplexity(model):.1f}")
for k in [768, 512, 384, 256]:
    frac = k * (768 + 3072) / (768 * 3072)
    print(f"k = {k:3d}  números {frac:6.1%}   SVD de W: {perplexity(compressed(k, 'W')):8.1f}"
          f"   SVD con los datos: {perplexity(compressed(k, 'datos')):8.1f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The recorded baseline perplexity is around 24. With k=512k = 512, which still uses 83% of the numbers, the SVD of W\mat{W} raises perplexity above 400. The data-aware variant stays between 30 and 40, more than ten times lower. The exact value depends on the calibration sample. At k=256k = 256 both degrade substantially. Three lessons follow. Low rank in the weights alone does not compress GPT-2 effectively. The error norm matters more than the algorithm because Eckart-Young optimizes the norm you specify. Aggressive compression calls for a fine-tuning pass, as shown in the inference module’s lesson on structured pruning.

Common mistakes

Exercises

ProofEckart-Young in spectral norm
Prove: If A∈Rm×n\mat{A} \in \R^{m\times n} has SVD A=∑iσiuivi⊤\mat{A} = \sum_i \sigma_i\vb{u}_i\vb{v}_i\T and rank⁡B≤k<min⁡(m,n)\rank\mat{B} \le k \lt \min(m, n), then ∥A−B∥2≥σk+1\norm{\mat{A} - \mat{B}}_2 \ge \sigma_{k+1}.
0
Let B\mat{B} be any m×nm\times n matrix of rank at most kk. Make no other assumptions about it.

Step 1 of 5. Which subspace associated with B\mat{B} do you use, and what do you know about its dimension?

NumericRelative rank-one error
A matrix has singular values 55, 33 and 11. What is the relative Frobenius error ∥A−A1∥F/∥A∥F\norm{\mat{A} - \mat{A}_1}_F / \norm{\mat{A}}_F of its best rank-1 approximation?
NumericStable rank
Calculate the stable rank ∥A∥F2/∥A∥22\norm{\mat{A}}_F^2/\norm{\mat{A}}_2^2 of a matrix with singular values 44, 22, 22 and 11.
QuizLoRA in a large layer
What fraction of the parameters of a 4096×40964096\times 4096 matrix does a rank-64 factorization BC⊤\mat{B}\mat{C}\T require?
QuizHow many optimal approximations are there?
Let A=diag⁡(3,1)\mat{A} = \diag(3, 1). Which of these rank-1 matrices are best rank-1 approximations of A\mat{A} in spectral norm?

More than one answer may be correct.

NumericA concrete threshold
A square 1000×10001000\times 1000 matrix is a low-rank signal plus independent Gaussian noise with standard deviation σ=0.1\sigma = 0.1 in each entry. What singular value must a component exceed to be kept by the optimal Gavish–Donoho threshold?
QuizCenter before truncating?
A matrix X\mat{X} contains 10 00010\,000 customers and 5050 strictly positive features such as amounts and frequencies. You compute its SVD without centering. What is most likely?
QuizWhen should you use total least squares?
You fit y=ax+by = ax + b to measurements in which xx and yy have independent noise, with known σy=3σx\sigma_y = 3\sigma_x. What should you do?

Summary

Key idea
The truncated SVD Ak=∑i≤kσiuivi⊤\mat{A}_k = \sum_{i\le k}\sigma_i\vb{u}_i\vb{v}_i\T is the best rank-kk matrix in every unitarily invariant norm. The discarded singular values give the error: σk+1\sigma_{k+1} in spectral norm and ∑i>kσi2\sqrt{\sum_{i>k}\sigma_i^2} in Frobenius norm.
  • Two ideas in the proof. A dimensional argument gives the spectral-norm result. Weyl’s inequality, σi+j−1(X+Y)≤σi(X)+σj(Y)\sigma_{i+j-1}(\mat{X} + \mat{Y}) \le \sigma_i(\mat{X}) + \sigma_j(\mat{Y}), extends it to all singular values and therefore to Frobenius and every unitarily invariant norm.
  • Choose kk based on the goal. Use captured energy for compression. To recover a signal from noise, use a noise-aware threshold such as Gavish–Donoho (43n σ\tfrac{4}{\sqrt{3}}\sqrt{n}\,\sigma for square matrices). The error relative to the signal is U-shaped.
  • Measure rank without exact zeros. Numerical rank is the smallest rank within spectral distance ≤ε\le \eps, another application of Eckart-Young. Stable and effective rank are continuous measures that answer different questions.
  • Total least squares applies Eckart-Young to [A    b][\mat{A}\;\; \vb{b}]. The solution comes from the last singular vector. It corrects OLS attenuation with noisy explanatory variables and requires isotropic noise or appropriate rescaling.
  • Measure the spectra of real networks. GPT-2’s pretrained weights have broad spectra. Truncating blindly can destroy performance. The norm in which you measure error, with or without the data, determines whether compression works.