"""Analysis + figures for the reproduction of arXiv:2602.02431. Reads the raw sweep CSVs in results/ and writes * aggregated CSVs (mean +- sem over seeds, thresholds, log-d fits) * interactive plotly figures (figures/*.html, plotly loaded from CDN) """ from __future__ import annotations import argparse import json import math import os import numpy as np import pandas as pd import plotly.graph_objects as go from scipy.interpolate import PchipInterpolator RES = "results" FIG = "figures" PALETTE = ["#3b1c62", "#5b2c8d", "#8b2fa0", "#b52d7f", "#d4426a", "#e8663c", "#f39325", "#f7c325"] def _c(i, n): return PALETTE[int(round(i * (len(PALETTE) - 1) / max(n - 1, 1)))] def agg(df, xcol="delta"): g = df.groupby(["d", xcol])["sq_overlap"] out = g.agg(["mean", "std", "count"]).reset_index() out["sem"] = out["std"] / np.sqrt(out["count"].clip(lower=1)) return out def threshold(x, y, target, smooth=True): """Smallest x at which the (monotonised) curve y(x) reaches `target`.""" x = np.asarray(x, float) y = np.asarray(y, float) if smooth and len(y) >= 5: k = np.array([0.25, 0.5, 0.25]) y = np.convolve(np.pad(y, 1, mode="edge"), k, mode="valid") ymon = np.maximum.accumulate(y) if ymon[-1] < target or ymon[0] > target: return np.nan f = PchipInterpolator(x, ymon - target) lo = np.searchsorted(ymon, target) a, b = x[max(lo - 1, 0)], x[min(lo, len(x) - 1)] if a == b: return float(a) xs = np.linspace(a, b, 4001) vals = f(xs) idx = np.argmin(np.abs(vals)) return float(xs[idx]) def linfit(x, y): x, y = np.asarray(x, float), np.asarray(y, float) m = np.isfinite(x) & np.isfinite(y) x, y = x[m], y[m] if len(x) < 2: return dict(slope=np.nan, intercept=np.nan, r2=np.nan, n=len(x)) b, a = np.polyfit(x, y, 1) yhat = a + b * x ss_res = float(((y - yhat) ** 2).sum()) ss_tot = float(((y - y.mean()) ** 2).sum()) return dict(slope=float(b), intercept=float(a), r2=float(1 - ss_res / ss_tot) if ss_tot > 0 else np.nan, n=int(len(x))) def write_fig(fig, name): os.makedirs(FIG, exist_ok=True) path = os.path.join(FIG, name + ".html") fig.write_html(path, include_plotlyjs="cdn", full_html=True) print("wrote", path) return path def overlap_fig(a, title, ytitle="Squared overlap ⟨θ*, θ̂⟩²", xtitle="δ = n/d", logx=False): dims = sorted(a["d"].unique()) fig = go.Figure() for i, d in enumerate(dims): s = a[a["d"] == d].sort_values(a.columns[1]) x = s[s.columns[1]] fig.add_trace(go.Scatter( x=x, y=s["mean"], mode="lines+markers", name=f"d={d}", line=dict(color=_c(i, len(dims)), width=2), marker=dict(size=6), error_y=dict(type="data", array=s["sem"], visible=True, thickness=1, width=0, color=_c(i, len(dims))))) fig.update_layout(title=title, xaxis_title=xtitle, yaxis_title=ytitle, template="plotly_white", height=460, legend=dict(orientation="v", x=1.02, y=1)) if logx: fig.update_xaxes(type="log") return fig def thresholds_fig(rows, title, ytitle="Threshold δ = n/d"): fig = go.Figure() tgts = sorted({r["target"] for r in rows}) for i, t in enumerate(tgts): sub = [r for r in rows if r["target"] == t and np.isfinite(r["value"])] if not sub: continue x = [r["logd"] for r in sub] y = [r["value"] for r in sub] f = linfit(x, y) col = _c(i, len(tgts)) fig.add_trace(go.Scatter(x=x, y=y, mode="markers", marker=dict(size=9, color=col), name=f"overlap={t} (R²={f['r2']:.3f})")) xs = np.linspace(min(x), max(x), 10) fig.add_trace(go.Scatter(x=xs, y=f["intercept"] + f["slope"] * xs, mode="lines", line=dict(color=col, width=2), showlegend=False)) fig.update_layout(title=title, xaxis_title="log d", yaxis_title=ytitle, template="plotly_white", height=460) return fig def main(): ap = argparse.ArgumentParser() ap.add_argument("--targets", default="0.1,0.2,0.3,0.4,0.5") args = ap.parse_args() targets = [float(v) for v in args.targets.split(",")] os.makedirs(FIG, exist_ok=True) summary = {} # ---------------- spherical sweeps (Claims 1, 2, 5) --------------------- thr_rows = [] for act, label in (("quad", "quadratic σ(z)=z²"), ("trunc", "truncated σ(z)=min(z²,M), M=8")): path = f"{RES}/sweep_{act}.csv" if not os.path.exists(path): continue df = pd.read_csv(path) a = agg(df) a.to_csv(f"{RES}/agg_{act}.csv", index=False) write_fig(overlap_fig(a, f"Full-batch spherical GD, {label}"), f"overlap_{act}") for d in sorted(a["d"].unique()): s = a[a["d"] == d].sort_values("delta") for t in targets: thr_rows.append(dict(method="full-batch", act=act, d=int(d), logd=math.log(d), target=t, value=threshold(s["delta"], s["mean"], t))) # bimodality diagnostic: fraction of seeds that reach non-trivial overlap fr = (df.assign(ok=(df["sq_overlap"] > 0.25).astype(float)) .groupby(["d", "delta"])["ok"].mean().reset_index()) fr.to_csv(f"{RES}/success_frac_{act}.csv", index=False) # ---------------- one-pass SGD baseline (Claim 5) ---------------------- for act in ("trunc", "quad"): p = f"{RES}/sweep_online_{act}.csv" if not os.path.exists(p): continue df = pd.read_csv(p) # the Arous et al. lower bound holds for *any* step size eta <~ 1/d, so the # fair baseline is the envelope over the eta = c/d grid at each (d, n). a = (df.groupby(["d", "delta"])["sq_overlap"].max().reset_index() .rename(columns={"sq_overlap": "mean"})) a["sem"] = 0.0 a.to_csv(f"{RES}/agg_online_{act}.csv", index=False) write_fig(overlap_fig( a, f"One-pass (online) spherical SGD, {act} σ — best η over c/d grid"), f"overlap_online_{act}") for d in sorted(a["d"].unique()): s = a[a["d"] == d].sort_values("delta") for t in targets: thr_rows.append(dict(method="one-pass-sgd", act=act, d=int(d), logd=math.log(d), target=t, value=threshold(s["delta"], s["mean"], t))) if thr_rows: tdf = pd.DataFrame(thr_rows) tdf.to_csv(f"{RES}/thresholds.csv", index=False) fits = [] for (meth, act), g in tdf.groupby(["method", "act"]): for t in targets: sub = g[g["target"] == t] f = linfit(sub["logd"], sub["value"]) f.update(method=meth, act=act, target=t) fits.append(f) rows = [r for _, r in g.iterrows()] write_fig( thresholds_fig([dict(target=r["target"], logd=r["logd"], value=r["value"]) for r in rows], f"Sample-complexity threshold vs log d — {meth}, {act}"), f"threshold_{meth.replace('-', '_')}_{act}") pd.DataFrame(fits).to_csv(f"{RES}/threshold_fits.csv", index=False) summary["threshold_fits"] = fits # Claim 5: side-by-side separation figure combos = [("full-batch", "trunc", "full-batch GD, truncated σ", PALETTE[1]), ("full-batch", "quad", "full-batch GD, quadratic σ", PALETTE[3]), ("one-pass-sgd", "trunc", "one-pass SGD, truncated σ", PALETTE[5]), ("one-pass-sgd", "quad", "one-pass SGD, quadratic σ", PALETTE[6])] for tg in (0.3, 0.5): fig = go.Figure() for meth, act, lab, col in combos: sub = tdf[(tdf["method"] == meth) & (tdf["act"] == act) & (tdf["target"] == tg)].sort_values("logd") if sub.empty or not np.isfinite(sub["value"]).any(): continue f = linfit(sub["logd"], sub["value"]) fig.add_trace(go.Scatter(x=sub["logd"], y=sub["value"], mode="markers", marker=dict(size=10, color=col), name=f"{lab} — slope {f['slope']:.2f}, R²={f['r2']:.3f}")) xs = np.linspace(sub["logd"].min(), sub["logd"].max(), 10) fig.add_trace(go.Scatter(x=xs, y=f["intercept"] + f["slope"] * xs, mode="lines", line=dict(color=col, width=2), showlegend=False)) fig.update_layout( title=f"Sample complexity δ = n/d for squared overlap {tg}: " "full-batch vs one-pass", xaxis_title="log d", yaxis_title="threshold δ = n/d", template="plotly_white", height=470, legend=dict(orientation="h", yanchor="bottom", y=-0.42)) write_fig(fig, f"separation_target{str(tg).replace('.', '')}") # ---- direct test of the n ≍ d log d scaling (Theorem 3.1 vs 3.2) -------- scal = [] for act in ("quad", "trunc"): p = f"{RES}/agg_{act}.csv" if not os.path.exists(p): continue a = pd.read_csv(p) for d in sorted(a["d"].unique()): s = a[a["d"] == d].sort_values("delta") f = PchipInterpolator(s["delta"].values, s["mean"].values) for mode, dl in ([("fixed δ=4", 4.0), ("fixed δ=8", 8.0), ("δ=1.2·log d", 1.2 * math.log(d))]): if s["delta"].min() <= dl <= s["delta"].max(): scal.append(dict(act=act, d=int(d), logd=math.log(d), mode=mode, delta=round(dl, 3), mean=float(f(dl)))) if scal: sdf = pd.DataFrame(scal) sdf.to_csv(f"{RES}/scaling_collapse.csv", index=False) fig = go.Figure() styles = {("quad", "fixed δ=4"): (PALETTE[5], "solid"), ("quad", "fixed δ=8"): (PALETTE[6], "solid"), ("quad", "δ=1.2·log d"): (PALETTE[1], "dash"), ("trunc", "fixed δ=4"): (PALETTE[3], "dot"), ("trunc", "fixed δ=8"): (PALETTE[0], "dot")} for (act, mode), g in sdf.groupby(["act", "mode"]): if (act, mode) not in styles: continue col, dash = styles[(act, mode)] g = g.sort_values("logd") fig.add_trace(go.Scatter(x=g["logd"], y=g["mean"], mode="lines+markers", name=f"{act}, {mode}", line=dict(color=col, width=2, dash=dash))) fig.update_layout( title="Overlap along n ∝ d (fixed δ) vs n ∝ d log d — quadratic vs truncated σ", xaxis_title="log d", yaxis_title="Squared overlap ⟨θ*, θ̂⟩²", template="plotly_white", height=470, legend=dict(orientation="h", yanchor="bottom", y=-0.38)) write_fig(fig, "scaling_collapse") summary["scaling_collapse"] = scal with open(f"{RES}/analysis_summary.json", "w") as f: json.dump(summary, f, indent=2, default=float) print(json.dumps(summary.get("threshold_fits", []), indent=2, default=float)[:4000]) if __name__ == "__main__": main()