""" rmt_diffusion.py ================ Core library for reproducing the LINEAR-THEORY claims of: "A Random Matrix Theory Perspective on the Consistency of Diffusion Models" Binxu Wang, Jacob A. Zavatone-Veth, Cengiz Pehlevan (ICML 2026, arXiv:2602.02908) The paper's central claims about linear diffusion models reduce to random-matrix / linear-algebra statements about the empirical covariance of a finite dataset. This module implements: * solve_kappa -- the self-consistent renormalized-noise map kappa(lambda) (Eq. 4) * denoiser_matrix -- the optimal linear denoiser Sigma_hat (Sigma_hat + s^2 I)^-1 (Eq. 2) * deterministic-equivalence predictions for the denoiser EXPECTATION (Result 4.1) and VARIANCE (Result 4.2), plus the sampling-map overshrinkage (Result 5.1) * Monte-Carlo estimators over dataset realizations to VALIDATE those predictions Everything runs on CPU in minutes. We work in the eigenbasis of the population covariance Sigma = diag(eigs) (WLOG) and set the population mean mu = 0, exactly the simplification the paper adopts (mu_hat = mu) to isolate finite-sample covariance effects. """ from __future__ import annotations import numpy as np # np.trapz was renamed to np.trapezoid in NumPy 2.0 (and removed later); support both. _trapz = getattr(np, "trapezoid", None) or np.trapz # -------------------------------------------------------------------------------------- # Population covariance # -------------------------------------------------------------------------------------- def power_law_spectrum(d: int, alpha: float = 1.0, floor: float = 1e-3, normalize: bool = True) -> np.ndarray: """Population eigenvalues lambda_k = k^{-alpha}, k = 1..d. Natural-image covariances have an approximately power-law spectrum (Ruderman 1994), which is the regime the paper studies. `floor` keeps the smallest eigenvalues from underflowing; `normalize` sets the top eigenvalue to 1. """ k = np.arange(1, d + 1, dtype=float) eigs = k ** (-alpha) + floor if normalize: eigs = eigs / eigs[0] return eigs # descending def sample_empirical_cov(eigs: np.ndarray, n: int, rng: np.random.Generator) -> np.ndarray: """Draw n samples x_i ~ N(0, diag(eigs)) and return the empirical covariance Sigma_hat = (1/n) sum_i x_i x_i^T (a d x d Wishart-type matrix).""" d = eigs.shape[0] z = rng.standard_normal((n, d)) x = z * np.sqrt(eigs)[None, :] # rows ~ N(0, diag(eigs)) return (x.T @ x) / n # -------------------------------------------------------------------------------------- # Renormalized noise scale kappa(lambda) (Silverstein / Marchenko-Pastur; Eq. 4) # -------------------------------------------------------------------------------------- def _normalized_trace_resolvent(eigs: np.ndarray, kappa: float) -> float: """ (1/d) * sum_k lambda_k / (lambda_k + kappa) = tr[Sigma (Sigma + kappa I)^-1]. """ return float(np.mean(eigs / (eigs + kappa))) def solve_kappa(lam: float, eigs: np.ndarray, gamma: float, tol: float = 1e-12, max_iter: int = 200) -> float: """Solve the self-consistent equation (Eq. 4): kappa - lam = gamma * kappa * tr[Sigma (Sigma + kappa I)^-1] for the unique kappa > 0, by bisection. gamma = d / n is the aspect ratio. Returns kappa >= lam (finite data renormalize the noise scale UP). """ if lam <= 0: return 0.0 def h(kappa: float) -> float: return kappa - lam - gamma * kappa * _normalized_trace_resolvent(eigs, kappa) lo = lam # h(lam) = -gamma*lam*g(lam) <= 0 hi = lam + max(lam, 1.0) # expand upper bracket until h(hi) > 0 it = 0 while h(hi) < 0 and it < 100: hi *= 2.0 it += 1 for _ in range(max_iter): mid = 0.5 * (lo + hi) hm = h(mid) if abs(hm) < tol or (hi - lo) < tol * max(1.0, mid): return mid if hm < 0: lo = mid else: hi = mid return 0.5 * (lo + hi) # -------------------------------------------------------------------------------------- # Degrees-of-freedom functions (Eq. 5, UNNORMALIZED trace Tr) # -------------------------------------------------------------------------------------- def df1(eigs: np.ndarray, lam: float) -> float: return float(np.sum(eigs / (eigs + lam))) def df2(eigs: np.ndarray, lam: float) -> float: return float(np.sum(eigs ** 2 / (eigs + lam) ** 2)) # -------------------------------------------------------------------------------------- # Linear denoiser (Eq. 2, mu = 0): D*(x; s) = Sigma_hat (Sigma_hat + s^2 I)^-1 x # -------------------------------------------------------------------------------------- def denoiser_matrix(Sigma: np.ndarray, sigma2: float) -> np.ndarray: """Return the linear-denoiser matrix M = C (C + sigma2 I)^-1 for covariance C.""" d = Sigma.shape[0] return Sigma @ np.linalg.solve(Sigma + sigma2 * np.eye(d), np.eye(d)) def population_denoiser_diag(eigs: np.ndarray, ridge: float) -> np.ndarray: """Diagonal (in population eigenbasis) of the population denoiser with ridge penalty: lambda_k / (lambda_k + ridge). With ridge = kappa(sigma2) this is Result 4.1.""" return eigs / (eigs + ridge) # -------------------------------------------------------------------------------------- # Deterministic-equivalence predictions # -------------------------------------------------------------------------------------- def predict_shrinkage_along_pc(eigs: np.ndarray, sigma2: float, gamma: float): """Result 4.1 / Fig 2C: expected shrinkage of the empirical denoiser along population PC u_k is lambda_k/(lambda_k + kappa(sigma2)) (renormalized), which OVER-shrinks relative to the naive population value lambda_k/(lambda_k + sigma2).""" kappa = solve_kappa(sigma2, eigs, gamma) renorm = eigs / (eigs + kappa) # DE prediction (what finite data give) naive = eigs / (eigs + sigma2) # infinite-data population denoiser return kappa, renorm, naive def predict_denoiser_variance_along_pc(eigs: np.ndarray, sigma2: float, n: int, x_vec: np.ndarray): """Result 4.2: Var over dataset realizations of u_k^T D*_hat(x; sigma) , per PC k. Var ~ [ kappa^2 / (n - df2(kappa)) ] * chi(lambda_k, kappa) * calD(x, kappa) with chi(lambda, kappa) = lambda/(lambda+kappa)^2 (anisotropy; bell-shaped, peak at lambda = kappa, peak value 1/(4 kappa)) and calD(x,kappa) = sum_k lambda_k x_k^2/(lambda_k+kappa)^2 (inhomogeneity). Returns (kappa, per-k variance prediction, chi, peak_value). """ d = eigs.shape[0] gamma = d / n kappa = solve_kappa(sigma2, eigs, gamma) chi = eigs / (eigs + kappa) ** 2 # anisotropy per PC inhom = float(np.sum(eigs * x_vec ** 2 / (eigs + kappa) ** 2)) # calD(x, kappa) prefactor = kappa ** 2 / (n - df2(eigs, kappa)) var_pred = prefactor * chi * inhom peak_value = 1.0 / (4.0 * kappa) # max of chi at lambda = kappa return kappa, var_pred, chi, inhom, peak_value def predict_sqrt_cov_scaling(eigs: np.ndarray, n: int): """Result 5.1 / Fig 4A: the sampling map contains Sigma_hat^{1/2}. Its expected scaling along population eigenmode u_k, E[u_k^T Sigma_hat^{1/2} u_k], OVER-shrinks relative to the ideal sqrt(lambda_k), most severely for low eigenmodes and small n. A convenient deterministic-equivalence-style prediction (Balakrishnan integral of the kappa map) for the per-mode scaling is: s_k ~ (2/pi) * integral_0^inf lambda_k / (lambda_k + kappa(u^2)) du which we evaluate numerically. Returns (ideal sqrt(lambda_k), predicted s_k).""" ideal = np.sqrt(eigs) gamma = eigs.shape[0] / n # integrate over u on a log-spaced grid; integrand decays like lambda_k/u^2 for large u u = np.concatenate([np.linspace(1e-4, 5.0, 4000), np.linspace(5.0, 200.0, 4000)]) kap = np.array([solve_kappa(uu ** 2, eigs, gamma) for uu in u]) pred = np.empty_like(eigs) for k, lk in enumerate(eigs): integrand = lk / (lk + kap) pred[k] = (2.0 / np.pi) * _trapz(integrand, u) return ideal, pred # -------------------------------------------------------------------------------------- # Monte-Carlo estimators (ground truth to validate the DE predictions above) # -------------------------------------------------------------------------------------- def mc_trace_resolvent(eigs: np.ndarray, lam: float, n: int, R: int, rng: np.random.Generator) -> float: """MC estimate of (1/d) Tr[Sigma_hat (Sigma_hat + lam I)^-1], averaged over R draws. Validates the deterministic equivalence ~ (1/d) Tr[Sigma (Sigma + kappa(lam) I)^-1].""" d = eigs.shape[0] vals = np.empty(R) I = np.eye(d) for r in range(R): C = sample_empirical_cov(eigs, n, rng) M = C @ np.linalg.solve(C + lam * I, I) vals[r] = np.trace(M) / d return float(vals.mean()) def mc_denoiser_stats(eigs: np.ndarray, sigma2: float, n: int, R: int, x_vec: np.ndarray, rng: np.random.Generator): """Monte-Carlo mean and variance, over R dataset realizations, of the per-PC denoiser response u_k^T D*_hat(x; sigma) (with population PCs = coordinate axes here). Returns (mean_k, var_k) arrays of length d.""" d = eigs.shape[0] I = np.eye(d) resp = np.empty((R, d)) for r in range(R): C = sample_empirical_cov(eigs, n, rng) M = C @ np.linalg.solve(C + sigma2 * I, I) # denoiser matrix resp[r] = M @ x_vec # response vector; u_k^T (.) = coord k return resp.mean(axis=0), resp.var(axis=0, ddof=1) def mc_sqrt_cov_scaling(eigs: np.ndarray, n: int, R: int, rng: np.random.Generator) -> np.ndarray: """MC estimate of E[u_k^T Sigma_hat^{1/2} u_k] per population eigenmode k.""" d = eigs.shape[0] acc = np.zeros(d) for r in range(R): C = sample_empirical_cov(eigs, n, rng) w, V = np.linalg.eigh(C) w = np.clip(w, 0.0, None) C_half = (V * np.sqrt(w)) @ V.T acc += np.diag(C_half) # u_k = e_k in population eigenbasis return acc / R def sqrt_cov(C: np.ndarray) -> np.ndarray: """Symmetric PSD square root of C (the linear generative / sampling map).""" w, V = np.linalg.eigh(C) w = np.clip(w, 0.0, None) return (V * np.sqrt(w)) @ V.T def mc_sqrtmap_variance(eigs: np.ndarray, n: int, R: int, rng: np.random.Generator) -> np.ndarray: """Result 5.2: per-mode VARIANCE, across dataset realizations, of the sampling-map diagonal u_k^T Sigma_hat^{1/2} u_k. For a linear/Gaussian score model the probability-flow ODE integrates in closed form to the map x = Sigma_hat^{1/2} z, so this is the variance of the FULL generative trajectory (not a one-step denoise). Returns the per-mode variance (length d).""" d = eigs.shape[0] vals = np.empty((R, d)) for r in range(R): C = sample_empirical_cov(eigs, n, rng) vals[r] = np.diag(sqrt_cov(C)) return vals.var(axis=0, ddof=1) def predict_sqrtmap_variance(eigs: np.ndarray, n: int) -> np.ndarray: """Leading-order deterministic-equivalence prediction for Result 5.2. With u_k = e_k, u_k^T Sigma_hat u_k = (1/n) sum_i (z_ik^2) lambda_k has variance 2 lambda_k^2 / n exactly; the delta method through g(t)=sqrt(t) (g'=1/(2 sqrt(lambda_k))) gives Var[u_k^T Sigma_hat^{1/2} u_k] ~ lambda_k / (2 n) i.e. anisotropic (proportional to lambda_k) and decaying as 1/n. The residual vs MC is the finite-sample coupling of off-diagonal Sigma_hat entries into the matrix sqrt.""" return eigs / (2.0 * n) def mc_split_consistency(eigs: np.ndarray, n: int, n_seeds: int, rng: np.random.Generator): """Fig 1 (linear model): two NON-OVERLAPPING data splits A, B (n samples each, disjoint) each define a linear diffusion sampler x = Sigma_hat^{1/2} z. Generate samples from the SAME seeds z under both splits and measure cross-split agreement: * mean cosine similarity cos(x_A, x_B) -> 1 as n grows * mean relative squared deviation ||x_A-x_B||^2 / (||x_A|| ||x_B||) The deviation is set by the sampling-map variance (Result 5.2), so it decays ~ 1/n: finite datasets that never share a sample still generate the same picture from a seed, and they agree better with more data. Returns (mean_cosine, mean_rel_sq_deviation).""" d = eigs.shape[0] HA = sqrt_cov(sample_empirical_cov(eigs, n, rng)) # split A sampler HB = sqrt_cov(sample_empirical_cov(eigs, n, rng)) # split B sampler (disjoint draw) Z = rng.standard_normal((n_seeds, d)) XA = Z @ HA.T XB = Z @ HB.T nA = np.linalg.norm(XA, axis=1) nB = np.linalg.norm(XB, axis=1) cos = np.sum(XA * XB, axis=1) / (nA * nB) rel_sq = np.sum((XA - XB) ** 2, axis=1) / (nA * nB) return float(cos.mean()), float(rel_sq.mean()) def mc_total_denoiser_variance(eigs: np.ndarray, sigma2: float, n: int, R: int, rng: np.random.Generator) -> float: """Global scaling (Fig 3D): total variance of the denoiser matrix entries across realizations, Sum_{ij} Var[M_ij], which the theory predicts decays ~ 1/n at large n.""" d = eigs.shape[0] I = np.eye(d) mats = np.empty((R, d, d)) for r in range(R): C = sample_empirical_cov(eigs, n, rng) mats[r] = C @ np.linalg.solve(C + sigma2 * I, I) return float(mats.var(axis=0, ddof=1).sum()) # -------------------------------------------------------------------------------------- # Small self-test # -------------------------------------------------------------------------------------- if __name__ == "__main__": rng = np.random.default_rng(0) eigs = power_law_spectrum(50, alpha=1.0) lam = 0.1 gamma = 50 / 500 k = solve_kappa(lam, eigs, gamma) print(f"kappa({lam}) = {k:.5f} (>= lam: {k >= lam})") de = _normalized_trace_resolvent(eigs, k) mc = mc_trace_resolvent(eigs, lam, n=500, R=200, rng=rng) print(f"trace resolvent DE={de:.5f} MC={mc:.5f} rel.err={abs(de-mc)/mc:.3%}")