| """Core routines for reproducing arXiv:2601.06014 (Taing & Levin, ICML 2026): |
| "On the Effect of Misspecifying the Embedding Dimension in Low-rank Network Models". |
| |
| Model: A = P + E with P = rho * X X^T, X in R^{n x r}. |
| ASE: Xhat_{1:d} = Uhat_{1:d} |Shat|^{1/2}_{1:d}, eigenpairs sorted by |eigenvalue| desc. |
| |
| Backend: torch CUDA eigh when available (float64), else numpy. |
| """ |
| import csv |
| import json |
| import math |
| import os |
| import time |
| import zlib |
|
|
| import numpy as np |
|
|
| try: |
| import torch |
|
|
| HAS_TORCH = True |
| HAS_CUDA = torch.cuda.is_available() |
| except Exception: |
| HAS_TORCH = False |
| HAS_CUDA = False |
|
|
| R_TRUE = 5 |
|
|
|
|
| def seed_for(*parts): |
| """Stable 32-bit seed from string parts.""" |
| return zlib.crc32("|".join(str(p) for p in parts).encode()) & 0xFFFFFFFF |
|
|
|
|
| def rng_for(*parts): |
| return np.random.default_rng(seed_for(*parts)) |
|
|
|
|
| |
|
|
| def dirichlet_latent(n, r, rng): |
| return rng.dirichlet(np.ones(r), size=n) |
|
|
|
|
| def sym_noise(n, dist, rng, sigma=1.0): |
| """Symmetric mean-zero noise matrix. dist in {normal, laplace, exp, poisson, t2.5}. |
| sigma scales the base distribution (base variances: normal 1, laplace 2, exp 1, |
| poisson 1, t2.5 = 5).""" |
| if dist == "normal": |
| M = rng.standard_normal((n, n)) |
| elif dist == "laplace": |
| |
| |
| |
| M = rng.laplace(0.0, 1.0, size=(n, n)) |
| elif dist == "exp": |
| M = rng.exponential(1.0, size=(n, n)) - 1.0 |
| elif dist == "poisson": |
| M = rng.poisson(1.0, size=(n, n)).astype(np.float64) - 1.0 |
| elif dist == "t2.5": |
| M = rng.standard_t(2.5, size=(n, n)) |
| else: |
| raise ValueError(dist) |
| if sigma != 1.0: |
| M *= sigma |
| U = np.triu(M, 1) |
| return U + U.T + np.diag(np.diag(M)) |
|
|
|
|
| def weighted_rdpg(n, r, dist, rng, rho=1.0, sigma=1.0): |
| """Returns (A, Xs, lam_pop) with Xs = sqrt(rho)*X the estimand and lam_pop the |
| non-zero eigenvalues of P (descending), computed exactly via the r x r Gram trick.""" |
| X = dirichlet_latent(n, r, rng) |
| Xs = math.sqrt(rho) * X |
| P = Xs @ Xs.T |
| A = P + sym_noise(n, dist, rng, sigma=sigma) |
| lam_pop = np.linalg.eigvalsh(Xs.T @ Xs)[::-1].copy() |
| return A, Xs, lam_pop |
|
|
|
|
| def binary_dirichlet_rdpg(n, r, rng, rho=1.0): |
| """Sparse binary RDPG with Dirichlet latents. A_ij ~ Bern(rho x_i^T x_j), diag 0.""" |
| X = dirichlet_latent(n, r, rng) |
| Xs = math.sqrt(rho) * X |
| P = Xs @ Xs.T |
| U = rng.random((n, n)) |
| A = (np.triu(U, 1) < np.triu(P, 1)).astype(np.float64) |
| A = A + A.T |
| lam_pop = np.linalg.eigvalsh(Xs.T @ Xs)[::-1].copy() |
| return A, Xs, lam_pop |
|
|
|
|
| def sbm_binary(n, r, rng, p_in=0.9, p_out=0.1): |
| """SBM per paper Section 4.2: pi ~ Dir(1_r), z ~ Cat(pi), B = 0.1 + 0.8 I. |
| Latent truth X = U_{1:r} S^{1/2}_{1:r} from P = Z B Z^T (exact via r x r trick).""" |
| B = np.full((r, r), p_out) + (p_in - p_out) * np.eye(r) |
| while True: |
| pi = rng.dirichlet(np.ones(r)) |
| z = rng.choice(r, size=n, p=pi) |
| counts = np.bincount(z, minlength=r) |
| if counts.min() >= 1: |
| break |
| C = np.diag(np.sqrt(counts.astype(np.float64))) |
| K = C @ B @ C |
| lam, Q = np.linalg.eigh(K) |
| lam = lam[::-1].copy() |
| Q = Q[:, ::-1].copy() |
| Z = np.zeros((n, r)) |
| Z[np.arange(n), z] = 1.0 |
| U = Z @ np.diag(1.0 / np.sqrt(counts)) @ Q |
| X = U @ np.diag(np.sqrt(np.maximum(lam, 0.0))) |
| P = X @ X.T |
| Urand = rng.random((n, n)) |
| A = (np.triu(Urand, 1) < np.triu(P, 1)).astype(np.float64) |
| A = A + A.T |
| return A, X, lam |
|
|
|
|
| |
|
|
| def full_eigh(A): |
| """Full symmetric eigendecomposition, float64. Returns (w, V) ascending, numpy.""" |
| t0 = time.time() |
| if HAS_CUDA: |
| T = torch.from_numpy(np.ascontiguousarray(A)).cuda() |
| w, V = torch.linalg.eigh(T) |
| w = w.cpu().numpy() |
| V = V.cpu().numpy() |
| del T |
| torch.cuda.empty_cache() |
| else: |
| w, V = np.linalg.eigh(A) |
| return w, V, time.time() - t0 |
|
|
|
|
| def spectral_norm_sym(E): |
| """||E|| for symmetric E (largest |eigenvalue|).""" |
| if HAS_CUDA: |
| T = torch.from_numpy(np.ascontiguousarray(E)).cuda() |
| w = torch.linalg.eigvalsh(T) |
| out = float(torch.max(torch.abs(w)).cpu()) |
| del T |
| torch.cuda.empty_cache() |
| return out |
| w = np.linalg.eigvalsh(E) |
| return float(np.max(np.abs(w))) |
|
|
|
|
| def ase_decompose(A, r=R_TRUE, max_dim=45): |
| """One eigh, reused across embedding dimensions. |
| |
| Returns dict with: |
| order : indices of eigenpairs sorted by |eigenvalue| descending |
| w : all eigenvalues (ascending, as returned by eigh) |
| V : all eigenvectors |
| abs_w_desc : |eigenvalues| descending |
| max_abs_trail_full : max_{alpha>r} max_j |u_hat_{j,alpha}| (ALL trailing pairs) |
| max_abs_trail_win : same but only over trailing pairs r+1..max_dim (used in ASE) |
| eigh_s : eigh wall seconds |
| """ |
| w, V, eigh_s = full_eigh(A) |
| order = np.argsort(-np.abs(w), kind="stable") |
| abs_w_desc = np.abs(w)[order] |
| trail = order[r:] |
| max_abs_trail_full = float(np.max(np.abs(V[:, trail]))) if trail.size else float("nan") |
| win = order[r:max_dim] |
| max_abs_trail_win = float(np.max(np.abs(V[:, win]))) if win.size else float("nan") |
| return dict(order=order, w=w, V=V, abs_w_desc=abs_w_desc, |
| max_abs_trail_full=max_abs_trail_full, |
| max_abs_trail_win=max_abs_trail_win, eigh_s=eigh_s) |
|
|
|
|
| def ase_embed(dec, d): |
| """d-dimensional ASE from a decomposition.""" |
| idx = dec["order"][:d] |
| return dec["V"][:, idx] * np.sqrt(np.abs(dec["w"][idx]))[None, :] |
|
|
|
|
| def trailing_block_2inf(dec, r, d): |
| """||Xhat_{r+1:d}||_{2,inf}: max row norm of the extra-dimension block (d>r).""" |
| if d <= r: |
| return 0.0 |
| idx = dec["order"][r:d] |
| blk = dec["V"][:, idx] * np.sqrt(np.abs(dec["w"][idx]))[None, :] |
| return float(np.max(np.linalg.norm(blk, axis=1))) |
|
|
|
|
| |
|
|
| def pad_cols(M, d): |
| n, c = M.shape |
| if c >= d: |
| return M[:, :d] |
| return np.hstack([M, np.zeros((n, d - c))]) |
|
|
|
|
| def procrustes(Xhat, Xtrue): |
| """W = argmin_W ||Xhat W - Xtrue||_F over O_d (Eq. 18 in the paper).""" |
| M = Xhat.T @ Xtrue |
| U, s, Vt = np.linalg.svd(M) |
| W = U @ Vt |
| return W, s |
|
|
|
|
| def errors_at_dim(dec, Xs, d, r=R_TRUE): |
| """Paper's evaluation: pad, Frobenius-Procrustes align, report norms. |
| |
| Returns (err2inf, errF, trail2inf, min_frob_sq) where min_frob_sq is the exact |
| closed-form min over W of ||Xhat W - Xtrue||_F^2 (from the Procrustes SVD).""" |
| Xhat = ase_embed(dec, d) |
| if d >= r: |
| Xt = pad_cols(Xs, d) |
| Xh = Xhat |
| else: |
| Xh = pad_cols(Xhat, r) |
| Xt = Xs |
| W, s = procrustes(Xh, Xt) |
| D = Xh @ W - Xt |
| err2inf = float(np.max(np.linalg.norm(D, axis=1))) |
| errF = float(np.linalg.norm(D)) |
| min_frob_sq = float((Xh * Xh).sum() + (Xt * Xt).sum() - 2.0 * s.sum()) |
| return err2inf, errF, trailing_block_2inf(dec, r, d), min_frob_sq |
|
|
|
|
| def min_2inf_over_W(Xh, Xt, iters=300, seed=0): |
| """Approximately minimize ||Xh W - Xt||_{2,inf} over orthogonal W (subgradient |
| descent + polar retraction, multi-start). Returns achieved value (upper bound on |
| the true min).""" |
| rng = np.random.default_rng(seed) |
| d = Xh.shape[1] |
| W0, _ = procrustes(Xh, Xt) |
| best = np.inf |
| for start in range(3): |
| W = W0.copy() |
| if start > 0: |
| Q, _ = np.linalg.qr(W0 + 0.05 * rng.standard_normal((d, d))) |
| W = Q |
| step = 0.1 |
| for it in range(iters): |
| D = Xh @ W - Xt |
| rown = np.linalg.norm(D, axis=1) |
| i = int(np.argmax(rown)) |
| best = min(best, float(rown[i])) |
| if rown[i] < 1e-15: |
| break |
| g = np.outer(Xh[i], D[i] / rown[i]) |
| W = W - step * g |
| U, _, Vt = np.linalg.svd(W) |
| W = U @ Vt |
| step *= 0.985 |
| return best |
|
|
|
|
| |
|
|
| class ResultSink: |
| """Appends rows to a local CSV and periodically pushes it to a HF dataset repo.""" |
|
|
| def __init__(self, fname, fieldnames, repo_id="visv-Bro/rdpg-misspec-results"): |
| self.fname = fname |
| self.fieldnames = fieldnames |
| self.repo_id = repo_id |
| self.rows_since_push = 0 |
| new = not os.path.exists(fname) |
| self.fh = open(fname, "a", newline="") |
| self.writer = csv.DictWriter(self.fh, fieldnames=fieldnames) |
| if new: |
| self.writer.writeheader() |
| self.fh.flush() |
|
|
| def add(self, **row): |
| self.writer.writerow(row) |
| self.fh.flush() |
| self.rows_since_push += 1 |
|
|
| def push(self, force=False): |
| if os.environ.get("NO_PUSH", "0") == "1": |
| return |
| if self.rows_since_push == 0 and not force: |
| return |
| try: |
| from huggingface_hub import HfApi |
|
|
| HfApi().upload_file( |
| path_or_fileobj=self.fname, |
| path_in_repo=os.path.basename(self.fname), |
| repo_id=self.repo_id, |
| repo_type="dataset", |
| ) |
| print(f"[push] {self.fname} -> {self.repo_id} ok", flush=True) |
| self.rows_since_push = 0 |
| except Exception as e: |
| print(f"[push] FAILED ({e}); will retry later", flush=True) |
|
|
|
|
| def log(msg): |
| print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True) |
|
|