icml26332-fullbatch-results / scripts /spectral_audit.py
vimarsh's picture
Add reproduction scripts
1f48ccf verified
Raw
History Blame Contribute Delete
6.2 kB
"""Numerical audit of the spectral statements behind Theorems 3.1 and 3.2.
(A) Spectrum of A* = (2/n) sum_i y_i x_i x_i^T.
Truncated sigma (paper eq. 3.13): |lam1 - 6| + |lam2 - 2| <= C(e^{-M/3} + M sqrt(d/n)).
Quadratic sigma (proof of Thm 3.1): lam_max is driven by the heaviest sample,
lam1 ~ 2 log(n) / delta -> diverges with d at fixed delta, killing the BBP spike.
(B) Uniform-in-theta BBP transition for A(theta) = (2/n) sum_i y_i phi(<x_i,theta>^2) x_i x_i^T,
the key technical ingredient of Theorem 3.2.
(C) Uniform indicator-mass bound (Lemma "indicatorbound"):
(1/n) sum_i 1{<x_i,theta>^2 > M} <= C (e^{-M/2} + sqrt(d/n) log(n/d)) for all theta.
Checked on random directions and on adversarially chosen directions.
"""
from __future__ import annotations
import argparse
import csv
import json
import math
import os
import sys
import time
import torch
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import sim
from sweep_spherical import a_star_chunked, top2
def A_theta(data, theta, act, M):
z = data.X @ theta
w = data.y * sim.phi(z * z, act, M)
n = data.X.shape[0]
return (2.0 / n) * (data.X.T @ (w[:, None] * data.X))
def adversarial_theta(data, M, iters=200, lr=0.5):
"""Maximise the empirical mass of {<x_i,theta>^2 > M} by smoothed ascent."""
d = data.X.shape[1]
theta = data.X[data.y.argmax()].clone()
theta = theta / theta.norm()
theta.requires_grad_(True)
opt = torch.optim.Adam([theta], lr=lr)
tau = 0.5
for _ in range(iters):
opt.zero_grad()
z = data.X @ (theta / theta.norm())
loss = -torch.sigmoid((z * z - M) / tau).mean()
loss.backward()
opt.step()
with torch.no_grad():
theta = theta / theta.norm()
return theta.detach()
def main():
p = argparse.ArgumentParser()
p.add_argument("--dims", default="128,256,512,1024,2048")
p.add_argument("--deltas", default="2,4,8,16,32,64,128")
p.add_argument("--Ms", default="2,4,8,16,32")
p.add_argument("--seeds", type=int, default=5)
p.add_argument("--n-theta", type=int, default=8, help="random thetas for part (B)")
p.add_argument("--out-prefix", required=True)
args = p.parse_args()
dev = "cuda" if torch.cuda.is_available() else "cpu"
dims = [int(v) for v in args.dims.split(",")]
deltas = [float(v) for v in args.deltas.split(",")]
Ms = [float(v) for v in args.Ms.split(",")]
rows_a, rows_b, rows_c = [], [], []
t0 = time.time()
# ---- (A) spectrum of A* -------------------------------------------------
for act in ("quad", "trunc"):
for d in dims:
for delta in deltas:
n = int(round(delta * d))
for M in (Ms if act == "trunc" else [8.0]):
for s in range(args.seeds):
data = sim.make_data(d, n, 31 * d + 7 * s + int(delta), act, M,
dev, torch.float32)
A = a_star_chunked(data.X, data.y).double()
l1, l2, v1 = top2(A)
ov = float((v1 @ data.theta_star.double()) ** 2)
rows_a.append(dict(
act=act, d=d, delta=delta, n=n, M=M, seed=s,
lam1=round(l1, 6), lam2=round(l2, 6), gap=round(l1 - l2, 6),
sq_overlap_v1=round(ov, 6), sin2=round(1 - ov, 8),
logn_over_delta=round(2 * math.log(n) / delta, 4)))
del data, A
torch.cuda.empty_cache() if dev == "cuda" else None
print(f"[{time.time()-t0:6.1f}s] (A) {act} d={d} done", flush=True)
# ---- (B) uniform-in-theta BBP + (C) indicator mass ----------------------
g = torch.Generator(device=dev).manual_seed(11)
for act in ("quad", "trunc"):
for d in (256, 1024):
for delta in (4.0, 16.0, 64.0):
n = int(round(delta * d))
for M in ([8.0] if act == "quad" else [4.0, 8.0, 16.0]):
data = sim.make_data(d, n, 77 * d + int(delta), act, M, dev, torch.float32)
thetas = {}
for k in range(args.n_theta):
v = torch.randn(d, generator=g, device=dev, dtype=torch.float32)
thetas[f"random{k}"] = v / v.norm()
thetas["theta_star"] = data.theta_star
thetas["adversarial"] = adversarial_theta(data, M)
for name, th in thetas.items():
A = A_theta(data, th, act, M).double()
l1, l2, v1 = top2(A)
ov = float((v1 @ data.theta_star.double()) ** 2)
rows_b.append(dict(act=act, d=d, delta=delta, n=n, M=M,
theta=name, lam1=round(l1, 6),
lam2=round(l2, 6), gap=round(l1 - l2, 6),
sq_overlap_v1=round(ov, 6)))
z = data.X @ th
mass = float((z * z > M).to(torch.float64).mean())
bound = math.exp(-M / 2) + math.sqrt(d / n) * math.log(n / d)
rows_c.append(dict(act=act, d=d, delta=delta, n=n, M=M,
theta=name, mass=round(mass, 8),
bound_base=round(bound, 8),
ratio=round(mass / bound, 6)))
del A
del data
torch.cuda.empty_cache() if dev == "cuda" else None
print(f"[{time.time()-t0:6.1f}s] (B/C) {act} d={d} done", flush=True)
for rows, name in ((rows_a, "spectrum"), (rows_b, "uniform_bbp"), (rows_c, "indicator")):
path = f"{args.out_prefix}_{name}.csv"
with open(path, "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
w.writeheader()
w.writerows(rows)
print("wrote", path, len(rows), "rows")
if __name__ == "__main__":
main()