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 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, , stores nearly seventeen million parameters. Daily returns for 500 stocks over ten years form a matrix of size .
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- matrix takes numbers to store instead of :
For and , that is of the numbers. This lesson answers three questions. What is the best rank- 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 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 . 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 of rank is a sum of rank-one layers:
The are orthonormal in , and the are orthonormal in . Each layer has Frobenius norm , so measures its weight. The simplest approximation to keeps the heaviest layers. Try this with an image.
The rest of the lesson turns these observations into theorems:
- Relative error is determined by the spectral tail. The readout is exactly the square root of the fraction of in the shaded region.
- Rank depends on orientation. A separable function has rank 1, and a sum of separable functions has rank at most . The wave is a sum of two products plus the constant, giving rank 3. Sharp diagonal stripes contain many harmonics, and each harmonic contributes two layers.
- Spectral decay makes compression possible. For the landscape, fall by several orders of magnitude. The noise spectrum barely falls.
The next figure constructs the truncated SVD one layer at a time.
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 . 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 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 , already in SVD form. Its singular values are and zeros. The spectral norm is the largest singular value, . The Frobenius norm is invariant under orthogonal multiplication on either side, , so it equals . The Schatten norms are defined as the norm of the singular-value vector.
∎Two practical consequences:
- Relative error and energy. Since , the squared relative error is the fraction of discarded energy, . 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 values equal to , while .
Counting parameters and operations
Storing as takes numbers, or if you store the separately as in the first figure. The factorization saves storage if and only if
which for a square matrix becomes . The same holds for applying the matrix: takes multiplications instead of . A dense layer of size thus becomes two linear layers with no activation between them, sized and . 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- 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 with . By rank–nullity, . Let , of dimension . Since , the two subspaces of intersect in a nonzero vector: there exists with .
Write with . Since and , with the orthonormal,
Therefore , and the preceding proposition shows that attains the bound.
∎Step 2: Weyl’s inequality for singular values
Proof
Let and be the truncated SVDs of and , with . Their sum has rank . Apply step 1 to with , then use the triangle inequality and the preceding error formula:
∎With we obtain . Singular values are stable. A perturbation with spectral norm moves each by at most , 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
The second step gives more than the Frobenius bound. The singular-value vector of dominates that of , namely , entry by entry. Von Neumann’s 1937 theorem characterizes unitarily invariant norms ( for orthogonal ) as symmetric gauge functions of singular values. These functions are monotone in the absolute value of each entry. Thus in all such norms. This is Mirsky’s extension.
Is the best approximation unique?
Uniqueness depends on the norm.
- In Frobenius norm, is the unique minimizer if and only if . If , changing the basis within the repeated singular subspace gives other equally good solutions.
- In spectral norm, it is never unique under and . For and , every with satisfies . In general, with leaves error . The spectral norm depends on the worst direction and allows freedom in the others.
Variational formulation: maximizing
For , another view of the theorem connects it to optimization. Every rank-one matrix is with . Expanding the square gives
With and fixed, the minimum occurs at and equals . Minimizing the error means maximizing over two spheres. The maximum is and occurs at . For matrices, and are represented by two angles, so the entire landscape fits on a map.
The map shows an additional fact about this objective. It has a unique maximum up to the signs of and , a saddle at and no spurious local maxima. In general, the critical points of on the spheres are the singular pairs , and if only the leading pair is a local maximum. This is why gradient descent often works when factorizing despite the nonconvex objective. Lesson 25 explores this dynamic when training networks.
Choosing : energy, the elbow and noise
The theorem tells you what to do for a given . The choice of depends on what you want the approximation to achieve.
Energy criterion. Take the smallest such that , with = 0.9, 0.95 or 0.99. This guarantees a relative Frobenius error of . Use this criterion for compression when you want to preserve all of .
Spectral elbow. Plot or against 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
and you aim to recover from . For a pure-noise matrix of size with , the singular values of concentrate in the interval as dimensions grow, according to the Marchenko-Pastur law. A signal component , with unit vectors and , separates from the bulk only if (the BBP transition). It then appears displaced outwards at with . 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 is above the bulk edge, . 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.
What to look for in the figure:
- Two error curves with different shapes. The error relative to the data, , always falls with 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 . With the defaults (, ), it retains 4 layers. The oracle, which sees , 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 and , the BBP formula puts the fifth peak at , just below threshold , so asymptotically either choice costs almost the same. The threshold is optimal asymptotically, over large matrices, and on average. In a matrix of size , it is somewhat conservative, yet it stays near the minimum.
- The energy criterion performs poorly with noise. With , the noise energy is more than twice the signal energy (). Retaining 90% of 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 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 is the number of above . Numerical rank therefore gives the number of dimensions you cannot remove without moving the matrix by more than . The default tolerance of np.linalg.matrix_rank is , on the scale of the SVD’s own rounding error. When data have measurement noise at level , a sensible tolerance is of order instead of machine epsilon.
Numerical rank depends on a threshold and changes in discrete jumps. Two continuous measures complement it:
- The stable rank, . It satisfies , is robust to small perturbations and appears in randomized SVD and random matrix bounds. It is dominated by , so one large singular value can pull it toward 1.
- The effective rank of Roy and Vetterli (2007), with . It is the exponential of the entropy of the normalized singular values. It equals if 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 instead of in the entropy, or the participation ratio . Check a paper’s definition before comparing reported values.
Why are so many large matrices approximately low rank?
Udell and Townsend (2019) offer an explanation. Suppose each row has a latent variable (a user’s preferences), and each column has one (a movie’s attributes). Suppose for piecewise analytic . 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 . The proof combines a Taylor expansion of 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 . It assumes is exact and assigns all the error to . 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 . The perturbed augmented matrix , with , has a nonzero vector in its null space and hence rank . This is an Eckart-Young problem. The smallest Frobenius-norm perturbation reducing the rank of to is . The null space of is the line spanned by , the last right singular vector of . Normalize its last component to to obtain
which exists if and is unique if also . A sufficient condition for both is .
Closed form. Since is an eigenvector of with eigenvalue , write in blocks and set . The first block row gives
Compare this with the OLS normal equations, , and ridge regression, . TLS acts like ridge with negative . Subtracting the term reverses shrinkage. Noise in inflates 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 , each row a point minus the centroid. The TLS line passes through the centroid with direction and normal , the right singular vectors of . The sum of squared perpendicular distances is exactly and is minimal among lines by Eckart-Young with applied to . The line is also the first principal component.
If with independent of variance , the OLS slope converges to instead of . It is attenuated toward zero, more so as noise in grows. TLS is consistent under isotropic noise, . Otherwise, first rescale the variables to equalize noise variances: divide by , fit, and undo the scaling. Without that information, TLS can overshoot, as the figure shows with .
Implementation from scratch
Start with a matrix from a latent-variable model like Udell and Townsend’s: with . Its numerical rank is high, yet its spectrum decays quickly.
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- approximation without taking the SVD of . Subspace iteration alternates multiplying a block of vectors by and , reorthonormalizing the vectors. It converges to the subspace of the leading singular vectors at rate . Then only the SVD of the small matrix is needed. This is the basis of the randomized SVD used by libraries for large matrices.
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- matrices make poor competitors. Use projections of onto subspaces of dimension () and small perturbations of the optimal subspace.
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 between 3 and 0.8 (in units of ), plus noise. Compare four ways to choose .
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 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.
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 , and returns the smallest integer k, from 0 to the number of values, such that the sum of the first k 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)tls_line(points). Given an array of shape (N, 2) with points , return the slope a and intercept b of the total least squares line , 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()Standard library implementations
In practice, choose the appropriate library routine.
| Task | Tool | Notes |
|---|---|---|
| Full or reduced SVD of a dense matrix | np.linalg.svd(A, full_matrices=False), scipy.linalg.svd | LAPACK (gesdd by default). |
| Singular values only | np.linalg.svd(A, compute_uv=False), scipy.linalg.svdvals | Faster and more accurate than forming |
| A few of a large or sparse matrix | scipy.sparse.linalg.svds(A, k) | Lanczos or LOBPCG methods |
| Fast rank- approximation | sklearn.utils.extmath.randomized_svd, sklearn.decomposition.TruncatedSVD, torch.svd_lowrank | Subspace iteration with random initialization |
| Numerical rank | np.linalg.matrix_rank(A, tol=...) | Default: |
| Total least squares | scipy.odr (orthogonal distance regression) or the SVD of | scipy.odr accepts separate weights for each variable |
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, ), the attention output (attn.proj, ), and the two MLP layers ( and ). The first run downloads the model, around 500 MB, to the Hugging Face cache. In transformers, these layers are Conv1D and store weights as , with .
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}")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 . 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 . The second accounts for the data. If layer inputs have second-moment matrix , the relevant error is . Apply Eckart-Young to to get the minimum at rank , namely . To estimate without external data, the cell samples text from the model itself.
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}")npm run lab and open the connection link.The recorded baseline perplexity is around 24. With , which still uses 83% of the numbers, the SVD of 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 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
Step 1 of 5. Which subspace associated with do you use, and what do you know about its dimension?
More than one answer may be correct.
Summary
- Two ideas in the proof. A dimensional argument gives the spectral-norm result. Weyl’s inequality, , extends it to all singular values and therefore to Frobenius and every unitarily invariant norm.
- Choose based on the goal. Use captured energy for compression. To recover a signal from noise, use a noise-aware threshold such as Gavish–Donoho ( 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 , another application of Eckart-Young. Stable and effective rank are continuous measures that answer different questions.
- Total least squares applies Eckart-Young to . 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.