Frontier: random matrices and matrix concentration
When dimension grows with the amount of data, scalar probability is insufficient: random-matrix spectra matter. Study matrix Bernstein and covariance estimation error, extreme singular values, the semicircle and Marchenko–Pastur laws, and the BBP transition in spiked models. These tools underpin current research on double descent, high-dimensional PCA and trained-network weight spectra.
After this lesson you can
- Apply matrix Bernstein to bound ‖Σ̂ - Σ‖ and determine the required sample size.
- Bound extreme singular values of Gaussian matrices using ε-nets.
- Derive the semicircle law by the method of moments and recognize the Marchenko–Pastur law.
- Explain the BBP transition and its consequences for PCA when d/n is not negligible.
- Critically read papers using random matrices to analyze neural networks.
Before you start
- 04Sub-Gaussian random variablesSub-exponential random variablesBernstein's inequalityEpsilon-net argumentConcentration of the normCovariance matrixMultivariate Gaussian distributionConvergence in distributionWeak law of large numbers
- 02Spectral theoremSingular value decompositionOperator normTrace and determinant via eigenvaluesTrace
Motivation: pure noise that looks like structure
Take observations of independent variables, all with mean 0 and variance 1. The true covariance matrix is : all 200 eigenvalues are 1 and no direction is special. Now compute sample covariance and run PCA. The largest eigenvalue is near and the smallest near ; condition number, which should be 1, is around 30 (and tends to 34 as and grow in that ratio); the first 20 components, 10% of the total, ‘explain’ about 24% of variance. An unwary analyst might see low-rank structure with smooth spectral decay. It is noise.
This does not contradict the law of large numbers. Each entry of converges to its counterpart in with error of order . Scale is the problem: there are entries, and the error’s operator norm, which moves eigenvalues, accumulates fluctuations coherently. With fixed, error does not tend to 0 but , which for is . Earlier scalar probability answered ‘how far does an average depart from its mean?’; this lesson asks ‘how far does a random matrix spectrum depart from the spectrum of its mean?’ at three levels:
- Nonasymptotic bounds (matrix concentration): matrix Bernstein and extreme singular values provide bounds for each and , determining covariance sample requirements.
- Limit laws (random matrix theory): when with , the whole eigenvalue distribution converges to a deterministic law: Wigner’s semicircle for symmetric matrices and Marchenko-Pastur for covariances.
- Phase transitions: a low-rank signal buried in noise is spectrally visible only above an exact threshold. Below it, PCA is blind even with infinite proportional data.
This language appears throughout current research: regression error double descent, high-dimensional PCA, deep-network initialization and spectra of trained-network weights. The end examines real GPT-2 data.
Matrix concentration: Bernstein’s inequality
Start nonasymptotically. Let be a sum of independent centered symmetric random matrices . Bound , its largest singular value. A first attempt uses : for each fixed , is a scalar sum to which Bernstein applies, and an ε-net of the sphere controls the maximum. This works but the net has points and union costs factor . A better tool works directly with matrices and pays only .
This is the matrix Bernstein inequality. Compare scalar Bernstein: the same expression with replaced by the norm of the sum of matrix second moments, and a leading factor. This dimensional price cannot generally be removed: if are diagonal with independent entries, is diagonal and the maximum absolute value of independent scalar sums. The maximal inequality bounds that maximum by times each sum’s scale, and independent variables (e.g. Gaussian) attain . Remarkably the noncommutative case is no worse than diagonal.
Proof
It suffices to bound ; applying it to gives the lower tail, and their union gives . The Chernoff method proof has four pieces.
1. Matrix Laplace transform. For , , since is positive definite and its largest eigenvalue is at most their sum. Markov gives
2. Cumulant subadditivity (Lieb). In the scalar case . For matrices if they do not commute, so factorization fails. Lieb’s deep theorem (1973) substitutes: for fixed symmetric , function is concave on positive-definite matrices. Jensen applied to gives ; applying it summand by summand (conditioning on the independent others),
3. Each summand’s generating function. Let , an increasing function. Since eigenvalues of are , apply scalar inequality eigenvalue by eigenvalue:
where is Loewner order ( if is positive semidefinite). Using in the series gives for . Taking expectations using and :
The logarithm is monotone in Loewner order, so .
4. Finish. is also monotone, so
because an matrix with eigenvalues has exponential trace . This leaves . With , , so and exponent . The expectation bound uses the same pieces without passing through the tail: by Jensen , divide by and optimize , giving . For apply this to block-diagonal matrix with blocks and , whose largest eigenvalue is and which has the same and : hence .
∎Samples needed to estimate covariance
The central application is sample covariance. If are independent copies of centered vector with , then is exactly a sum as in the theorem.
This is covariance estimation error in its cleanest form; the final guided exercise proves it in three lines using matrix Bernstein. The reading matters. Write . Since , is at least effective rank , equal to if and much smaller if variance is concentrated in a few directions. For relative error it suffices that
For isotropic data in and , theorem constants require about million samples: the leading term is . Effective-rank-10 covariance needs many fewer independently of except logarithmically: why PCA works in enormous dimensions when signal has low rank.
Is necessary? It depends. If with uniform in (coordinate sampling), , , and is diagonal with entries , where counts occurrences of coordinate . Error is the maximum of binomial deviations, and this maximum does have . For Gaussian or sphere-uniform data the bound is pessimistic by that factor: the next section gives the exact answer without the logarithm. The lab measures it.
Extreme singular values of Gaussian matrices
Let , have independent entries. Its singular values control what matters: and are the largest and smallest eigenvalues of isotropic sample covariance . Since for every unit , one expects in every direction. The correction is exactly .
This is the extreme singular values result. Its ingredients: expectations and from Slepian and Gordon Gaussian comparison inequalities (Davidson and Szarek, 2001), and immediate concentration around them: and are 1-Lipschitz in Frobenius norm (Weyl inequalities, ), so Gaussian concentration for Lipschitz functions gives tails .
Gordon’s inequalities are not proved here, but an ε-net yields the correct order and exemplifies random matrix norm bounds.
Proof
(Upper bound with nonoptimal constant.) Let and be -nets of spheres and , with and , existing by lesson 22’s volume argument.
Step 1: control norm on the net. Let unit vectors satisfy , with , at distance from them. Then
so .
Step 2: each net point is Gaussian. For fixed unit , , because .
Step 3: union. . With the right side is , and since ,
with probability at least .
∎The net gives order with a constant 4 times worse than the true one; Gordon gives constant 1. For the net argument also works (lower-bound at every net point and use the upper bound to cover the sphere). Arbitrary independent isotropic sub-Gaussian rows admit a version with constants: , where is the rows’ sub-Gaussian norm (Vershynin, High-Dimensional Probability, theorem 4.6.1).
Divide by and square for the desired consequence. With and probability , all eigenvalues of lie in
For Gaussian data covariance error is , without Bernstein’s . Extremes are exactly the first histogram’s edges. Marchenko-Pastur describes what lies between.
import numpy as np
rng = np.random.default_rng(0)
print(" n d s_min √n−√d s_max √n+√d cota de la red 4.2(√n+√d)")
for n, d in [(100, 10), (400, 100), (800, 200), (1000, 50), (300, 300)]:
G = rng.standard_normal((n, d))
s = np.linalg.svd(G, compute_uv=False)
print(f"{n:5d} {d:5d} {s.min():6.2f} {np.sqrt(n) - np.sqrt(d):6.2f} {s.max():6.2f} {np.sqrt(n) + np.sqrt(d):6.2f} {4.2 * (np.sqrt(n) + np.sqrt(d)):7.1f}")
# las fluctuaciones alrededor de √n + √d son O(1), no O(√n): 20 réplicas con n = 400, d = 100
smax = [np.linalg.svd(rng.standard_normal((400, 100)), compute_uv=False)[0] for _ in range(20)]
print(f"\ns_max en 20 réplicas: media {np.mean(smax):.3f}, desviación típica {np.std(smax):.3f} (√n + √d = 30)")In the last, square row, nearly vanishes, as predicts. A square Gaussian matrix is invertible but ill-conditioned; its smallest singular value is of order (Edelman, 1988). Across replicates stays slightly below with small fluctuations: a theoretical surprise discussed at the edge.
Wigner’s semicircle law
Move from bounds to limit laws. The simplest object is a symmetric matrix with independent entries.
Why ? Because : the mean of is 1, so eigenvalues are order 1. With they would all tend to 0; unnormalized they spread as . This is the commonest scaling mistake here.
Wigner’s semicircle law says that the eigenvalue histogram of one large matrix is deterministic: it does not fluctuate with the sample. It depends on the entry law only through variance.
Moment method: Dyck paths
The classical proof counts. Since , spectral distribution moments are traces of powers, and traces are index sums:
Each term is a closed walk of steps in the complete graph on ; its expectation depends only on how often each edge is traversed. Three observations decide everything:
- Every edge must be traversed at least twice. If edge appears once, factor is independent of the rest and has mean 0: the term vanishes.
- There are at most distinct edges and, since the walk is connected, at most distinct vertices. The number of walks with vertices is , so after division by only exactly vertices survive. In particular, if is odd nothing survives: odd moments tend to 0.
- Survivors are trees traversed twice. A connected graph with edges and vertices is a tree, and a closed walk crossing each tree edge exactly twice is a depth-first traversal: down once, up once. Each contributes .
Encode the traversal by recording going down and going up: this gives steps , starting and ending at 0 and never below 0. This is a Dyck path; the number of Dyck paths of length is Catalan number . Each shape admits vertex labelings, so
The first are . To see they are semicircle moments, with , , a beta integral. The guided exercise counts case by hand.
Two standard steps turn expected-moment convergence into the theorem. First variance: similar counting shows (supporting path pairs must share an edge, costing two vertices), so Chebyshev and Borel-Cantelli make moments converge almost surely. Second, the compactly supported semicircle is determined by its moments, so moment convergence implies weak convergence. If entries only have finite variance rather than all moments, truncate and control error using Hoffman-Wielandt (Anderson, Guionnet and Zeitouni, chapter 2).
Universality and its limits
Counting used only and : this is universality. It has precise limits:
- Infinite variance. For power tails , , the correct normalization is , not , and the limit is another heavy-tailed law (Lévy matrices, Ben Arous and Guionnet, 2008), related to stable laws. This appears in the heavy-tail option.
- The edge needs more than density. The largest eigenvalue converges to 2 iff entries have a finite fourth moment (Bai and Yin, 1988). With finite variance but infinite fourth moment, the histogram converges to semicircle while a few eigenvalues escape to infinity.
- Dependence. If entries are no longer independent (covariance matrices, matrix products, network Jacobians), shape changes. The next law is the first example.
The Stieltjes transform (idea)
The moment method is elementary but rigid. The flexible tool is the Stieltjes transform of measure ,
which for the spectral distribution is the resolvent’s normalized trace . Density is recovered by inversion: . The semicircle has a one-line derivation. By the Schur complement formula, the first resolvent diagonal entry is
where is the first column without its first entry and is without its first row and column. is negligible, and is independent of with variance- entries, so the quadratic form concentrates at (lesson 22’s norm concentration, now for quadratic forms). Averaging diagonal entries gives , i.e.
and the imaginary part on the real axis is : the semicircle without counting paths. This self-consistency technique generalizes to covariances, multilayer models and most current research calculations.
Marchenko-Pastur law
Return to the motivating sample covariance. Now has rows with independent entries of mean 0 and variance , and is .
This is the Marchenko-Pastur law. The continuous-density interval and eigenvalues inside are called the spectral bulk; anything above needs explanation. The atom is linear algebra: with , has rank and zero eigenvalues. Edges are those of the extreme-singular-value theorem, and recovers the classical regime: support shrinks toward 1 with width .
The first two moments can be calculated by hand and explain the first figure’s spread. With and Gaussian data, , and
Eigenvalue variance around mean 1 is . With this is standard deviation around a true value with no spread. No method inspecting individual eigenvalues can ignore it.
The Marchenko-Pastur Stieltjes transform follows from the same self-consistency argument and satisfies, with ,
The discriminant is , and the correct root’s imaginary part at real gives exactly . The lab checks this numerically by solving at with small .
A consequence: the double-descent peak
Marchenko-Pastur’s first inverse moment is for , and explodes as because lower edge reaches 0. This directly affects regression. With , noise variance and isotropic Gaussian rows, least squares satisfies by inverse-Wishart expectation, tending to
Estimation error diverges at interpolation threshold even for a correct model and moderate noise. For infinitely many solutions exist, and the minimum-norm interpolator has risk , which falls again: double descent in its simplest form (Hastie, Montanari, Rosset and Tibshirani, 2022). The final section simulates the full curve.
Spiked models and the BBP transition
So far pure noise. Now add signal: with
Variance in direction is ; in others it is 1. This is Johnstone’s (2001) spiked covariance model, and PCA asks whether the largest eigenvalue of reveals the spike and its eigenvector points to . In fixed dimension, yes for any given enough . With the answer is a phase transition.
This is the BBP phase transition. Baik, Ben Arous and Péché proved it for complex data via largest-eigenvalue fluctuations; Baik and Silverstein (2006) gave real-data limits, and Paul (2007) the eigenvector limit. Below threshold the spike is spectrally invisible: the largest eigenvalue behaves as without signal and the top eigenvector is nearly orthogonal to .
Where the threshold comes from
The cleanest mechanism is the additive Wigner analogue, fully derived with the Stieltjes transform. Let with Wigner , and fixed unit vector . A number outside (hence for large outside the spectrum of ) is an eigenvalue of iff
by the rank-one perturbation determinant lemma. As before, the quadratic form concentrates on normalized trace: for . And decreases on , with and . Equation has a solution outside the bulk iff , then . If , the perturbation cannot produce an outlier: is bounded by its edge value, whose finiteness sets the threshold.
For covariance the same argument with Marchenko-Pastur’s transform gives threshold . An elegant check: function attains its minimum exactly at , where it equals , the edge. Increasing branch is the isolated eigenvalue; the decreasing branch corresponds to nothing, since an eigenvalue cannot move away from bulk as signal weakens.
Three practical consequences:
- Detecting a spike requires . A direction with 50% more variance () in needs more than samples for PCA to see it, many more to see it well.
- Seeing is not accurate estimation. Just above threshold overlap is small: with and it is , an angle of about to truth. The eigenvalue is biased upward: it estimates , not . Inverting this formula underlies covariance shrinkage (Donoho, Gavish and Johnstone, 2018), linked to covariance cleaning and random-matrix cleaning in finance.
- Choosing how many components to keep has a principled answer: those sufficiently above Marchenko-Pastur’s edge, the idea of PCA rank selection against noise.
Edge fluctuations and finite-size validity
The previous laws are asymptotic. How far does the largest eigenvalue move at finite size? Much less than the CLT suggests. For a GOE matrix (Gaussian, variance 1 off-diagonal and 2 on it),
the Tracy-Widom distribution (1996), non-Gaussian, asymmetric, with mean and standard deviation . For sample covariance, Johnstone (2001) proved an analogue with centering and scale . The 99% quantile of is , yielding a principled signal test: for and , , , an eigenvalue above is significant at 1%. Universality extends here: the same fluctuations hold for non-Gaussian sufficiently light-tailed entries (Soshnikov, 1999; Tao and Vu, 2010; Erdős and Yau).
Two scales coexist and are easily confused. The edge fluctuates as ; an isolated eigenvalue above BBP fluctuates as , Gaussian. Near threshold, with of order , they mix: the BBP figure’s region where simulations depart from the limit curve.
The next cell calculates the GOE largest-eigenvalue law without building a dense matrix. Dumitriu and Edelman (2002) proved GOE has the same eigenvalues as a tridiagonal matrix with diagonal and subdiagonal ; its largest eigenvalue is found by bisection using Sturm sequences, vectorized across thousands of replicates.
import numpy as np
rng = np.random.default_rng(1)
def lmax_goe(n, reps):
"""Mayor autovalor de reps matrices GOE n×n, vía el modelo tridiagonal de Dumitriu y Edelman."""
a = rng.normal(0, np.sqrt(2), size=(reps, n)) # diagonal
b2 = rng.chisquare(np.arange(n - 1, 0, -1), size=(reps, n - 1)) # subdiagonal al cuadrado
lo = np.full(reps, 1.0 * np.sqrt(n)) # λmax ≈ 2√n: el intervalo [√n, 3√n] lo contiene
hi = np.full(reps, 3.0 * np.sqrt(n))
for _ in range(32): # bisección: ¿hay n autovalores por debajo de x?
x = (lo + hi) / 2
q = a[:, 0] - x # pivotes de T − xI (recurrencia de Sturm)
negativos = (q < 0).astype(int)
for i in range(1, n):
q = a[:, i] - x - b2[:, i - 1] / np.where(q == 0, 1e-300, q)
negativos += q < 0
todos = negativos == n
hi = np.where(todos, x, hi)
lo = np.where(todos, lo, x)
return (lo + hi) / 2
for n in [25, 100, 400]:
s = n ** (2 / 3) * (lmax_goe(n, 1000) / np.sqrt(n) - 2)
print(f"n = {n:4d}: n^(2/3)(λmax − 2) tiene media {s.mean():+.3f} y desviación típica {s.std():.3f}"
f" (Tracy-Widom: −1.21 y 1.27)")
print("\nEscala del borde para n = 400: n^(−2/3) =", round(400 ** (-2 / 3), 4), " frente a n^(−1/2) =", 400 ** -0.5)Mean approaches from below, and standard deviation lies between and , of order even for small sizes (1000 replicates give sampling error about 0.03). Practically, pure-noise largest eigenvalue is below the asymptotic edge on average by about units; one a few hundredths above the edge with in the hundreds proves nothing.
Current research: double descent and weight spectra
Double descent in linear regression
The Marchenko-Pastur formula predicts the minimum-norm interpolator’s entire risk curve. The cell simulates it: data, variable , signal and noise .
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(2)
n, sigma2, reps = 100, 1.0, 12
ds = np.array([10, 30, 50, 70, 85, 92, 97, 103, 110, 130, 160, 200, 300, 400])
def teoria(g):
return sigma2 * g / (1 - g) if g < 1 else (1 - 1 / g) + sigma2 / (g - 1)
riesgo = []
for d in ds:
beta = rng.standard_normal(d)
beta /= np.linalg.norm(beta)
err = []
for _ in range(reps):
X = rng.standard_normal((n, d))
y = X @ beta + np.sqrt(sigma2) * rng.standard_normal(n)
b = np.linalg.lstsq(X, y, rcond=None)[0] # norma mínima si d > n
err.append(np.sum((b - beta) ** 2))
riesgo.append(np.median(err))
print(f"d = {d:3d} γ = {d / n:4.2f} ‖β̂ − β‖² mediana {riesgo[-1]:7.2f} límite {teoria(d / n):7.2f}")
gs = np.linspace(0.05, 4, 400)
plt.semilogy(gs, [teoria(g) for g in gs], color="gray", label="límite (Marchenko-Pastur)")
plt.semilogy(ds / n, riesgo, "o", label="simulación, n = 100")
plt.axvline(1, ls=":", color="k"); plt.xlabel("γ = d/n"); plt.ylabel("error de estimación")
plt.legend(); plt.show()The peak at is not classical overfitting: it is the smallest eigenvalue of , pushed toward 0 by edge and amplifying noise by . Any regularization moving eigenvalues from zero (ridge, early stopping) smooths the peak. Hastie and coauthors extend this to nonisotropic covariances and nonlinear random features, where the same Stieltjes machinery predicts two-layer network double descent; see learning theory.
Weight spectra of trained networks
Martin and Mahoney (2021) proposed reading training from each weight matrix’s spectrum. For (), examine spectral density of : at independent-entry initialization it is Marchenko-Pastur with . Training appears as deviations from that null law, classified into phases: random, eigenvalue ‘bleeding’ outside bulk, bulk plus spikes, bulk decay, heavy tail and rank collapse. Their thesis is that large well-trained networks have tails resembling power law , an implicit self-regularization, and exponent correlates with model quality without test data.
The interactive uses precalculated spectra: a small digit perceptron in three variants at five training times, and four GPT-2 small MLP matrices. Each is fitted to Marchenko-Pastur (scale via median, robust to spikes), with 99% Tracy-Widom threshold marked, estimated using Hill on the top 10%, and above all compared with a null model: the same matrix with shuffled entries, preserving each weight’s marginal law while destroying correlations.
These data are useful precisely because their conclusions are modest:
- Learning a simple task is low rank. With 10 classes, perceptron matrix has 10 eigenvalues above threshold from epoch 3 (9 with He initialization), and the rest remains Marchenko-Pastur at slightly smaller scale. Training is a low-rank perturbation of initialization, the ‘bulk plus spikes’ phase.
- Memorization costs rank. With shuffled labels the network reaches 100% training accuracy (without generalizing) with about 60 directions outside bulk in the same layer.
- GPT-2 is different. In the interactive’s four MLP matrices, 83 to 111 of 768 eigenvalues exceed threshold, the largest exceeds ten times the fitted edge, and rank versus eigenvalue is almost straight: a genuine heavy tail. The shuffled null returns nearly perfect Marchenko-Pastur with edge (at most one eigenvalue touches threshold), so the tail resides in joint weight structure, not individual weight law.
- A tail estimator cannot know what it measures. Hill on the top 10% gives between 1.7 and 2.5 for the real-label, reduced-initialization perceptron, ‘very heavy tail’ values (smaller than GPT-2’s 3.4 to 4.2), because it mixes ten spikes with the bulk edge. Without the null and the spectrum the number misleads. Power-law fitting with few points is delicate (Clauset, Shalizi and Newman, 2009), and Martin and Mahoney carefully choose the tail start before fitting.
With that caution, this is a serious research program: weight spectra diagnose training without test data (reliability module), Jacobian spectra help choose dynamical-isometry initializations, and Hessian spectra illuminate optimization. Each asks what noise explains and what it does not.
Lab: spectral laws from scratch
Four NumPy experiments using only eigvalsh. First, semicircle universality, with moments versus Catalan numbers.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
def wigner(n, ley):
if ley == "gaussiana":
X = rng.standard_normal((n, n))
elif ley == "rademacher":
X = rng.choice([-1.0, 1.0], size=(n, n))
else: # uniforme en [−√3, √3]: varianza 1
X = rng.uniform(-np.sqrt(3), np.sqrt(3), size=(n, n))
X = np.triu(X) + np.triu(X, 1).T # simétrica: manda el triángulo superior
return X / np.sqrt(n)
def semicirculo(x):
return np.sqrt(np.clip(4 - x ** 2, 0, None)) / (2 * np.pi)
n = 300
xs = np.linspace(-2.3, 2.3, 400)
fig, ax = plt.subplots(figsize=(7, 3.2))
for ley in ["gaussiana", "rademacher", "uniforme"]:
lam = np.linalg.eigvalsh(wigner(n, ley))
mom = [np.mean(lam ** (2 * k)) for k in (1, 2, 3, 4)]
print(f"{ley:10s} λmax = {lam.max():.3f} momentos pares 2, 4, 6, 8: " + " ".join(f"{m:6.3f}" for m in mom))
ax.hist(lam, bins=40, density=True, histtype="step", lw=1.5, label=ley)
print("Catalan: " + " ".join(f"{c:6d}" for c in (1, 2, 5, 14)))
ax.plot(xs, semicirculo(xs), "k", lw=2, label="semicírculo")
ax.legend(fontsize=8); plt.show()Second, Marchenko-Pastur: hand-derived density, histogram comparison, first two moments and numerical Stieltjes inversion.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(1)
def mp_densidad(x, g, s2=1.0):
lm, lp = s2 * (1 - np.sqrt(g)) ** 2, s2 * (1 + np.sqrt(g)) ** 2
x = np.asarray(x, dtype=float)
dentro = (x > lm) & (x < lp)
out = np.zeros_like(x)
out[dentro] = np.sqrt((lp - x[dentro]) * (x[dentro] - lm)) / (2 * np.pi * g * s2 * x[dentro])
return out
def mp_stieltjes(z, g):
"""Raíz de γ z s² + (z − 1 + γ) s + 1 = 0 con Im s > 0 (la transformada de una medida)."""
a, b = g * z, z - 1 + g
raiz = np.sqrt(b * b - 4 * a + 0j)
s1, s2 = (-b + raiz) / (2 * a), (-b - raiz) / (2 * a)
return np.where(s1.imag > 0, s1, s2)
n, d = 800, 400
g = d / n
X = rng.standard_normal((n, d))
lam = np.linalg.eigvalsh(X.T @ X / n)
print(f"γ = {g}: autovalores en [{lam.min():.3f}, {lam.max():.3f}]; bordes teóricos "
f"[{(1 - np.sqrt(g)) ** 2:.3f}, {(1 + np.sqrt(g)) ** 2:.3f}]")
print(f"media {lam.mean():.4f} (teoría 1); varianza {lam.var():.4f} (teoría (d + 1)/n = {(d + 1) / n:.4f})")
xs = np.linspace(0.01, 3.2, 600)
inversion = mp_stieltjes(xs + 1e-9j, g).imag / np.pi
print("máx |densidad por inversión − fórmula cerrada| =", f"{np.max(np.abs(inversion - mp_densidad(xs, g))):.1e}")
# la transformada empírica, (1/d) tr(Σ̂ − z)^(-1), ya está cerca de la teórica a distancia η = 0.05 del eje
z = xs + 0.05j
emp = np.mean(1 / (lam[None, :] - z[:, None]), axis=1)
print("máx |s_emp − s_MP| a altura 0.05:", f"{np.max(np.abs(emp - mp_stieltjes(z, g))):.3f}")
plt.hist(lam, bins=50, density=True, alpha=0.5, label="autovalores de Σ̂")
plt.plot(xs, mp_densidad(xs, g), "k", label="Marchenko-Pastur")
plt.plot(xs, emp.imag / np.pi, "--", label="Im s_emp(x + 0.05i)/π")
plt.legend(); plt.show()Inversion reproduces the closed formula with error introduced by height near edges; the empirical transform at height smooths the histogram, as used in practice with finite spectra.
Third, the BBP threshold from scratch, with the same noise for every as in the figure.
import numpy as np
rng = np.random.default_rng(3)
n, d = 600, 300
g = d / n
Z = rng.standard_normal((n, d))
S0 = Z.T @ Z / n
print(f"γ = {g}, umbral √γ = {np.sqrt(g):.3f}, borde (1 + √γ)² = {(1 + np.sqrt(g)) ** 2:.3f}\n")
print(" β λ1 simulado λ1 límite solapamiento límite")
for beta in [0.2, 0.4, 0.6, 0.7, 0.8, 1.0, 1.5, 2.0, 3.0]:
c = np.sqrt(1 + beta) # x = Z Σ^(1/2) con Σ = I + β e1 e1ᵀ: reescalar la coordenada 1
S = S0.copy(); S[0, :] *= c; S[:, 0] *= c
w, V = np.linalg.eigh(S)
arriba = beta > np.sqrt(g)
lam_lim = (1 + beta) * (1 + g / beta) if arriba else (1 + np.sqrt(g)) ** 2
ov_lim = (1 - g / beta ** 2) / (1 + g / beta) if arriba else 0.0
print(f"{beta:5.2f} {w[-1]:9.3f} {lam_lim:9.3f} {V[0, -1] ** 2:9.3f} {ov_lim:9.3f}")Fourth, matrix Bernstein versus reality. Both laws have exactly and , so the bound is identical; true error differs. To see factor vary , fixing and increasing dimension.
import numpy as np
rng = np.random.default_rng(4)
gam = 1 / 16 # n = 16 d en todas las filas
def error_esfera(n, d): # x uniforme en la esfera de radio √d
G = rng.standard_normal((n, d))
X = np.sqrt(d) * G / np.linalg.norm(G, axis=1, keepdims=True)
return np.max(np.abs(np.linalg.eigvalsh(X.T @ X / n - np.eye(d))))
def error_coordenadas(n, d): # x = √d e_J: Σ̂ es diagonal con entradas d·N_j/n
cuentas = np.bincount(rng.integers(0, d, size=n), minlength=d)
return np.max(np.abs(d * cuentas / n - 1))
print(" d n cota de Bernstein esfera 2√γ + γ coordenadas")
for d in [8, 32, 128, 512, 2048]:
n = int(d / gam)
L = v = d / n # m = d y ‖Σ‖ = 1
cota = np.sqrt(2 * v * np.log(2 * d)) + L * np.log(2 * d) / 3
e_esf = np.mean([error_esfera(n, d) for _ in range(4)]) if d <= 128 else float("nan")
e_coo = np.mean([error_coordenadas(n, d) for _ in range(20)])
print(f"{d:6d} {n:6d} {cota:12.3f} {e_esf:7.3f} {2 * np.sqrt(gam) + gam:7.3f} {e_coo:9.3f}")The bound holds for both laws and grows with due to . Sphere error does not grow with it: it stabilizes at extreme-singular-value prediction , approaching from below (, , ). Coordinate-sampling error does grow with at the bound’s rate: it is the maximum of binomial fluctuations, and for the maximum of variables is inevitable. Matrix Bernstein is optimal for its class’s worst case, not every distribution.
Library version: GPT-2 spectra
For pretrained models use transformers to load weights and standard linear algebra for the rest. GPT-2 small stores linear layers as Conv1D with shape (input, output): MLP layers are and . The cell analyzes all 24 MLP matrices with the interactive’s protocol. CPU runtime is under a minute, mostly importing transformers and loading the model (eigenvalues of 48 matrices take seconds); the first run downloads about 500 MB of weights.
import numpy as np
import torch
from transformers import GPT2LMHeadModel
torch.set_num_threads(4)
modelo = GPT2LMHeadModel.from_pretrained("gpt2")
pesos = {k: v.detach().double().numpy() for k, v in modelo.state_dict().items()
if k.endswith(("mlp.c_fc.weight", "mlp.c_proj.weight"))}
del modelo
def mediana_mp(g, K=20000):
lm, lp = (1 - np.sqrt(g)) ** 2, (1 + np.sqrt(g)) ** 2
x = np.linspace(lm, lp, K)
dens = np.sqrt(np.clip((lp - x) * (x - lm), 0, None)) / (2 * np.pi * g * x)
cdf = np.cumsum(dens); cdf /= cdf[-1]
return x[np.searchsorted(cdf, 0.5)]
def analiza(W):
A = W if W.shape[0] >= W.shape[1] else W.T # N × M con N ≥ M
N, M = A.shape
g = M / N
lam = np.sort(np.linalg.eigvalsh(A.T @ A / N))[::-1]
s2 = np.median(lam) / mediana_mp(g) # escala del bulk, robusta a espigas
a = np.sqrt(N - 1) + np.sqrt(M)
umbral = s2 * (a * a / N + 2.02 * a * (1 / np.sqrt(N - 1) + 1 / np.sqrt(M)) ** (1 / 3) / N)
k = int(0.1 * M)
hill = 1 + k / np.sum(np.log(lam[:k] / lam[k]))
return (lam > umbral).sum(), lam[0] / (s2 * (1 + np.sqrt(g)) ** 2), hill
rng = np.random.default_rng(0)
print("matriz fuera λmax/borde α Hill | nulo: fuera α Hill")
for nombre, W in pesos.items():
fuera, ratio, hill = analiza(W)
fuera0, _, hill0 = analiza(rng.permutation(W.ravel()).reshape(W.shape))
corto = nombre.removeprefix("transformer.").removesuffix(".weight") # p. ej. h.0.mlp.c_fc (bloques desde 0)
print(f"{corto:16s} {fuera:5d} {ratio:9.1f} {hill:6.2f} | {fuera0:9d} {hill0:6.2f}")npm run lab and open the connection link.Read output as in the interactive: out-of-bulk eigenvalue count and tail exponent are descriptions meaningful against the null. All c_fc and almost all c_proj have 80 to 112 outliers (fewer in h.0, h.1 and h.11.mlp.c_proj, with 48, 41 and 72); largest is 8 to 39 times the edge, and most nulls have none or almost none. But in early-block c_proj the shuffled null retains up to 17 above threshold and falls from 10 to 6.5. These matrices have a few enormous individual weights (in h.1.mlp.c_proj to h.3.mlp.c_proj, over 150 standard deviations from the mean, with kurtosis of hundreds): a heavy-tailed marginal law explaining part of the spectral tail without weight correlations. Separating both sources is exactly the null model’s purpose. Martin’s weightwatcher library automates analysis with more careful power-law fitting (Kolmogorov-Smirnov tail-start selection, as in Clauset et al.); useful, but do the transparent version first.
Common mistakes
Exercises
Step 1 of 4. Which walks can contribute a nonzero term?
Step 1 of 4. How do you write as a sum of independent centered matrices?
mp_density(x, gamma, sigma2), the Marchenko-Pastur density with ratio and variance (zero outside support; x may be an array), and fit_mp(eigs), estimating (gamma, sigma2) from observed sample-covariance eigenvalues by moments. Use mean and second moment .import numpy as np
def mp_density(x, gamma, sigma2=1.0):
"""Densidad de Marchenko-Pastur (parte continua) en los puntos x."""
x = np.asarray(x, dtype=float)
return np.zeros_like(x)
def fit_mp(eigs):
"""Estima (gamma, sigma2) por momentos a partir de los autovalores."""
eigs = np.asarray(eigs, dtype=float)
return 0.0, 0.0Summary
- Matrix Bernstein bounds independent matrix sums using matrix variance and dimension factor ; for covariance it gives samples with effective rank .
- For Gaussian matrices , with Gaussian tails: covariance error is without a logarithm. ε-nets give the order; Gordon gives the constant.
- Semicircle: by the moment method, Wigner even moments approach Catalan numbers because only tree walks (Dyck paths) survive. The limit depends only on entry variance.
- Marchenko-Pastur: isotropic-noise sample covariance has eigenvalue variance around 1, edges ; inverse moment explains the double-descent peak.
- BBP: spike is PCA-visible iff ; then the eigenvalue is biased, , and overlap is .
- At finite size the edge fluctuates as (Tracy-Widom), an isolated eigenvalue as . Network weight spectra require a null: the perceptron learns low rank; GPT-2 has a genuine heavy tail.