""" Core library for reproducing the linear-regression theory of "Why Self-Training Helps and Hurts: Denoising vs. Signal Forgetting" (arXiv 2602.14029). Implements: * Algorithm 1 (iterative self-training / self-distillation, ridgeless & ridge) * Theorem 3.2 single-spike deterministic risk recursion (B*_t, V*_t) * Theorem 3.6 multi-spike deterministic risk recursion * iGCV estimator (eq. 11-12) and the survival / suppression factors Notation matches the paper: y = x'beta + eps, x ~ N(0, Sigma), eps ~ N(0, sigma^2) [noise only at t=0] rho = p / n, tau = rho - 1 (ridgeless effective regularization) Prediction risk R(bhat) = (bhat - beta)' Sigma (bhat - beta) """ import numpy as np # --------------------------------------------------------------------------- # Estimators & Algorithm 1 # --------------------------------------------------------------------------- def ridgeless_fit(X, Y): """Minimum-norm least squares (X'X)^+ X'Y. In the overparameterized regime (n < p, which is our entire setting) the min-norm interpolator has the closed form X'(XX')^-1 Y, requiring only an n x n solve -- far faster than SVD-based lstsq. Falls back to lstsq if the Gram matrix is singular or n >= p. """ n, p = X.shape if n < p: G = X @ X.T # n x n try: z = np.linalg.solve(G, Y) return X.T @ z except np.linalg.LinAlgError: pass beta, *_ = np.linalg.lstsq(X, Y, rcond=None) return beta def project_rowspace(X, V): """Apply P = X^+ X (orthogonal projection onto row space of X) to columns of V. P V = X'(XX')^-1 X V when n < p. V may be 1-D or 2-D.""" n, p = X.shape if n < p: G = X @ X.T return X.T @ np.linalg.solve(G, X @ V) # underparameterized: P = I return V def ridge_fit(X, Y, lam): """Ridge: (X'X + n*lam I)^-1 X'Y.""" n, p = X.shape if lam == 0.0: return ridgeless_fit(X, Y) A = X.T @ X + n * lam * np.eye(p) return np.linalg.solve(A, X.T @ Y) class SpikedCov: """Structured spiked covariance Sigma = sum_j (s_j-1) u_j u_j' + I. Provides O(n p) sampling and O(p) quadratic forms (no dense p x p matmul). U columns are the orthonormal spike directions; `spikes` their strengths.""" def __init__(self, p, spikes, U): self.p = p self.spikes = np.asarray(spikes, float) self.U = U # (p, k) self.a = np.sqrt(self.spikes) - 1.0 # sqrt-eigval offset def sample(self, m, rng): Z = rng.standard_normal((m, self.p)) return Z + (Z @ self.U) * self.a @ self.U.T # X ~ N(0, Sigma) def quad(self, d): # d' Sigma d Ud = self.U.T @ d return float(d @ d + ((self.spikes - 1.0) * Ud) @ Ud) class DiagCov: """Diagonal covariance Sigma = diag(v). O(n p) sampling.""" def __init__(self, v): self.v = np.asarray(v, float) self.sq = np.sqrt(self.v) self.p = len(self.v) def sample(self, m, rng): return rng.standard_normal((m, self.p)) * self.sq def quad(self, d): return float((d * self.v) @ d) def iterative_self_train(Sigma_sqrt, beta, n, sigma, T, lam=0.0, rng=None, return_betas=False, cov=None): """ Run Algorithm 1 for T iterations (t = 0 .. T). t=0 : fit on noisy data (Y0 = X0 beta + eps). t>=1: fresh X_t, noiseless pseudo-labels Y_t = X_t bhat_{t-1}, refit. Sigma_sqrt : (p,p) symmetric square-root of the feature covariance Sigma. Returns array of prediction risks R_t, shape (T+1,). Optionally the betas. """ if rng is None: rng = np.random.default_rng() p = beta.shape[0] if cov is not None: gen_X = lambda m: cov.sample(m, rng) def risk(bhat): return cov.quad(bhat - beta) else: Sigma = Sigma_sqrt @ Sigma_sqrt # Sigma_sqrt is symmetric gen_X = lambda m: rng.standard_normal((m, p)) @ Sigma_sqrt def risk(bhat): d = bhat - beta return float(d @ (Sigma @ d)) # t = 0 : noisy fit X0 = gen_X(n) eps = sigma * rng.standard_normal(n) Y0 = X0 @ beta + eps bhat = ridge_fit(X0, Y0, lam) if lam > 0 else ridgeless_fit(X0, Y0) risks = [risk(bhat)] betas = [bhat.copy()] for t in range(1, T + 1): Xt = gen_X(n) Yt = Xt @ bhat # noiseless pseudo-labels bhat = ridge_fit(Xt, Yt, lam) if lam > 0 else ridgeless_fit(Xt, Yt) risks.append(risk(bhat)) betas.append(bhat.copy()) risks = np.array(risks) return (risks, betas) if return_betas else risks def simulate_risk(Sigma_sqrt, beta, n, sigma, T, lam=0.0, trials=10, seed=0, cov=None): """Monte-Carlo prediction risk R_t averaged over `trials`.""" rng = np.random.default_rng(seed) acc = np.zeros(T + 1) sq = np.zeros(T + 1) for _ in range(trials): r = iterative_self_train(Sigma_sqrt, beta, n, sigma, T, lam=lam, rng=rng, cov=cov) acc += r sq += r ** 2 mean = acc / trials std = np.sqrt(np.maximum(sq / trials - mean ** 2, 0.0)) return mean, std # --------------------------------------------------------------------------- # Theorem 3.2 -- single-spike deterministic recursion # --------------------------------------------------------------------------- def spiked_theory(s, rho, r2, sigma2, T): """ Deterministic risk R*_t = B*_t + V*_t for the single-spike model (Thm 3.2). Sigma = (s-1) u1 u1' + I, beta = r u1 with r^2 = r2. tau = rho - 1. Returns dict with arrays B, V, R (length T+1) and 'survival' factor. """ tau = rho - 1.0 kappa = s / (s + tau) # contraction / survival factor survival = kappa ** (np.arange(T + 1) + 1) # (s/(s+tau))^{t+1} B = r2 * s * (1.0 - survival) ** 2 # eq (4) V = np.zeros(T + 1) V[0] = sigma2 / tau + (tau * s / (s + tau) ** 2) * r2 for t in range(1, T + 1): # eq (5): V_t = V_{t-1}/(1+tau) + tau r^2 s^{2t+1}/(s+tau)^{2(t+1)} V[t] = V[t - 1] / (1.0 + tau) + tau * r2 * s ** (2 * t + 1) / (s + tau) ** (2 * (t + 1)) return {"B": B, "V": V, "R": B + V, "tau": tau, "kappa": kappa, "survival": survival} def multi_spike_theory(spikes, r2s, rho, sigma2, T): """ Multi-spike deterministic recursion (Thm 3.6). spikes : list of spike strengths s_1..s_k (each > 1) r2s : list of signal powers r_j^2 along each spike direction. Returns dict with B, V, R arrays and per-direction survival factors. """ spikes = np.asarray(spikes, float) r2s = np.asarray(r2s, float) tau = rho - 1.0 tt = np.arange(T + 1) # eq (6): B_t = sum_j r_j^2 s_j (1 - (s_j/(s_j+tau))^{t+1})^2 B = np.zeros(T + 1) survivals = {} for j, (s, rj2) in enumerate(zip(spikes, r2s)): surv = (s / (s + tau)) ** (tt + 1) survivals[j] = surv B += rj2 * s * (1.0 - surv) ** 2 # eq (7): V recursion V = np.zeros(T + 1) V[0] = sigma2 / tau + np.sum(tau * r2s * spikes / (spikes + tau) ** 2) for t in range(1, T + 1): inject = np.sum(tau * r2s * spikes ** (2 * t + 1) / (spikes + tau) ** (2 * (t + 1))) V[t] = V[t - 1] / (1.0 + tau) + inject return {"B": B, "V": V, "R": B + V, "tau": tau, "survivals": survivals, "kappas": spikes / (spikes + tau)} def general_diag_theory(eigs, beta, rho, sigma2, T, lam=0.0): """ General deterministic-equivalent recursion (Section 4, Thm 4.2 / eq 10) for a diagonal feature covariance Sigma = diag(eigs), identical across iterations, with aspect ratio rho = p/n_t fixed (so tau_t = tau constant). Returns the deterministic prediction risk R*_t decomposed into systematic + stochastic. Because Sigma is diagonal and constant, Q_t = Q = diag(q_i), q_i=lam_i/(lam_i+tau), and every trace reduces to a 1-D sum over eigenvalues. """ eigs = np.asarray(eigs, float) beta = np.asarray(beta, float) p = len(eigs) # solve fixed point (8): 1/rho = (1/p) sum_i lam_i/(lam_i+tau) + lam/tau def fp(tau): return (np.mean(eigs / (eigs + tau)) + lam / tau) - 1.0 / rho lo, hi = 1e-8, 1e8 for _ in range(200): mid = np.sqrt(lo * hi) if fp(mid) > 0: # decreasing in tau lo = mid else: hi = mid tau = np.sqrt(lo * hi) q = eigs / (eigs + tau) # Q diagonal L = lam / tau + (tau / p) * np.sum(eigs / (eigs + tau) ** 2) # deterministic effective noise D^2_t D = np.zeros(T + 1) D[0] = (sigma2 + tau ** 2 * np.sum(beta ** 2 * eigs / (eigs + tau) ** 2)) / L for t in range(1, T + 1): term1 = tau ** 2 * np.sum(beta ** 2 * q ** (2 * t + 1) / (eigs + tau)) term2 = 0.0 for h in range(t): trace = np.sum(q ** (2 * (t - h)) / (eigs + tau) ** 2) term2 += (D[h] / p) * trace D[t] = (term1 + tau ** 2 * term2) / L # deterministic risk R*_t (eq 10) B = np.zeros(T + 1) # systematic V = np.zeros(T + 1) # stochastic for t in range(T + 1): B[t] = np.sum(eigs * (q ** (t + 1) - 1.0) ** 2 * beta ** 2) acc = 0.0 for h in range(t + 1): trace = np.sum(q ** (2 * (t - h)) * eigs ** 2 / (eigs + tau) ** 2) acc += (D[h] / p) * trace V[t] = acc return {"B": B, "V": V, "R": B + V, "tau": tau, "D": D} def build_spiked_covariance(p, spikes, dirs=None): """ Sigma = sum_j (s_j - 1) u_j u_j' + I_p. Returns (Sigma_sqrt, U) with U the spike eigenvectors (columns). dirs: optional (p,k) orthonormal directions; default = first k canonical basis vectors. """ spikes = np.asarray(spikes, float) k = len(spikes) if dirs is None: U = np.zeros((p, k)) for j in range(k): U[j, j] = 1.0 else: U = dirs # eigen-decomposition is trivial: Sigma_sqrt = I + sum_j (sqrt(s_j)-1) u_j u_j' Sigma_sqrt = np.eye(p) for j in range(k): uj = U[:, j] Sigma_sqrt += (np.sqrt(spikes[j]) - 1.0) * np.outer(uj, uj) return Sigma_sqrt, U # --------------------------------------------------------------------------- # iGCV estimator (Section 4.2, eq. 11-12) # --------------------------------------------------------------------------- def igcv_trajectory(Sigma_sqrt, beta, n, sigma, T, lam=0.0, rng=None, cov=None): """ One trial: returns (true_risk[t], igcv_est[t]) for t=0..T. iGCV (eq 12) estimates R(bhat_t) + sigma^2 using ONLY the initial noisy dataset D0 and the cumulative projection A_t = P_t...P_1. We report igcv_est - sigma^2 as the estimate of R(bhat_t). """ if rng is None: rng = np.random.default_rng() p = beta.shape[0] if cov is not None: gen_X = lambda m: cov.sample(m, rng) risk = lambda bhat: cov.quad(bhat - beta) else: Sigma = Sigma_sqrt @ Sigma_sqrt gen_X = lambda m: rng.standard_normal((m, p)) @ Sigma_sqrt def risk(bhat): d = bhat - beta return float(d @ (Sigma @ d)) # Initial ridge fit on the noisy data D0. lam>0 keeps the GCV correction # well-conditioned (the interpolating ridgeless fit has zero residuals, so # the leave-one-out correction 1 - tr(H)/n0 degenerates; the paper uses the # ridge / pseudoinverse-continuity profile, Hastie et al. 2022; Patil 2021). # The self-training iterations t>=1 are always ridgeless row-space projections. lam0 = lam if lam > 0 else 1e-3 X0 = gen_X(n) eps = sigma * rng.standard_normal(n) Y0 = X0 @ beta + eps bhat0 = ridge_fit(X0, Y0, lam0) # smoother H = X0 (X0'X0/n + lam0 I)^-1 X0' / n0 (n0 x n0); X0 @ C = H G = X0.T @ X0 / n Ginv = np.linalg.inv(G + lam0 * np.eye(p)) C = Ginv @ X0.T / n # p x n0 H = X0 @ C # n0 x n0 denom = 1.0 - np.trace(H) / n resid0 = Y0 - X0 @ bhat0 # y_i - x_i' bhat0 (nonzero for lam0>0) # Trajectory: bhat_t = P_t ... P_1 bhat0 = A_t bhat0. A_bhat0 = bhat0.copy() A_C = C.copy() true_risk, igcv = [], [] for t in range(0, T + 1): if t >= 1: Xt = gen_X(n) A_C = project_rowspace(Xt, A_C) # P_t A_{t-1} C A_bhat0 = project_rowspace(Xt, A_bhat0) # P_t A_{t-1} bhat0 true_risk.append(risk(A_bhat0)) # leverage multiplier M_t (eq 11) and corrected residual iGCV (eq 12) Mt = (np.trace(X0 @ A_C) / n) / denom corr = (Y0 - X0 @ A_bhat0) + resid0 * Mt igcv.append(float(np.mean(corr ** 2)) - sigma ** 2) return np.array(true_risk), np.array(igcv)