File size: 10,136 Bytes
3e68a65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""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  # true latent dimension used throughout the paper's experiments


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))


# ---------------------------------------------------------------- sampling

def dirichlet_latent(n, r, rng):
    return rng.dirichlet(np.ones(r), size=n)  # rows on the simplex


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":
        # Paper item (b) says "E_ij + 1 ~ Laplace(0,1)", but Laplace(0,1) is already
        # mean-zero, so the +1 shift would violate the paper's own mean-zero
        # requirement; we read it as E_ij ~ Laplace(0,1) (variance 2).
        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))  # infinite 4th moment: violates A7
    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()  # eigs of P via Gram
    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  # r x r, same non-zero spectrum as P
    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  # orthonormal columns
    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


# ---------------------------------------------------------------- spectral

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)))


# ---------------------------------------------------------------- alignment

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)  # Xhat^circ per Eq. (def:Xcirc)
        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])  # d x d subgradient wrt W
            W = W - step * g
            U, _, Vt = np.linalg.svd(W)  # polar retraction to O_d
            W = U @ Vt
            step *= 0.985
    return best


# ---------------------------------------------------------------- output

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:  # keep computing even if a push fails
            print(f"[push] FAILED ({e}); will retry later", flush=True)


def log(msg):
    print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)