vimarsh commited on
Commit
1f48ccf
·
verified ·
1 Parent(s): 0d2bc4a

Add reproduction scripts

Browse files
scripts/__pycache__/analyze.cpython-313.pyc ADDED
Binary file (18.1 kB). View file
 
scripts/__pycache__/sim.cpython-310.pyc ADDED
Binary file (9.38 kB). View file
 
scripts/__pycache__/sweep_spherical.cpython-310.pyc ADDED
Binary file (5.34 kB). View file
 
scripts/analyze.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analysis + figures for the reproduction of arXiv:2602.02431.
2
+
3
+ Reads the raw sweep CSVs in results/ and writes
4
+ * aggregated CSVs (mean +- sem over seeds, thresholds, log-d fits)
5
+ * interactive plotly figures (figures/*.html, plotly loaded from CDN)
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import math
13
+ import os
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+ import plotly.graph_objects as go
18
+ from scipy.interpolate import PchipInterpolator
19
+
20
+ RES = "results"
21
+ FIG = "figures"
22
+ PALETTE = ["#3b1c62", "#5b2c8d", "#8b2fa0", "#b52d7f", "#d4426a", "#e8663c",
23
+ "#f39325", "#f7c325"]
24
+
25
+
26
+ def _c(i, n):
27
+ return PALETTE[int(round(i * (len(PALETTE) - 1) / max(n - 1, 1)))]
28
+
29
+
30
+ def agg(df, xcol="delta"):
31
+ g = df.groupby(["d", xcol])["sq_overlap"]
32
+ out = g.agg(["mean", "std", "count"]).reset_index()
33
+ out["sem"] = out["std"] / np.sqrt(out["count"].clip(lower=1))
34
+ return out
35
+
36
+
37
+ def threshold(x, y, target, smooth=True):
38
+ """Smallest x at which the (monotonised) curve y(x) reaches `target`."""
39
+ x = np.asarray(x, float)
40
+ y = np.asarray(y, float)
41
+ if smooth and len(y) >= 5:
42
+ k = np.array([0.25, 0.5, 0.25])
43
+ y = np.convolve(np.pad(y, 1, mode="edge"), k, mode="valid")
44
+ ymon = np.maximum.accumulate(y)
45
+ if ymon[-1] < target or ymon[0] > target:
46
+ return np.nan
47
+ f = PchipInterpolator(x, ymon - target)
48
+ lo = np.searchsorted(ymon, target)
49
+ a, b = x[max(lo - 1, 0)], x[min(lo, len(x) - 1)]
50
+ if a == b:
51
+ return float(a)
52
+ xs = np.linspace(a, b, 4001)
53
+ vals = f(xs)
54
+ idx = np.argmin(np.abs(vals))
55
+ return float(xs[idx])
56
+
57
+
58
+ def linfit(x, y):
59
+ x, y = np.asarray(x, float), np.asarray(y, float)
60
+ m = np.isfinite(x) & np.isfinite(y)
61
+ x, y = x[m], y[m]
62
+ if len(x) < 2:
63
+ return dict(slope=np.nan, intercept=np.nan, r2=np.nan, n=len(x))
64
+ b, a = np.polyfit(x, y, 1)
65
+ yhat = a + b * x
66
+ ss_res = float(((y - yhat) ** 2).sum())
67
+ ss_tot = float(((y - y.mean()) ** 2).sum())
68
+ return dict(slope=float(b), intercept=float(a),
69
+ r2=float(1 - ss_res / ss_tot) if ss_tot > 0 else np.nan, n=int(len(x)))
70
+
71
+
72
+ def write_fig(fig, name):
73
+ os.makedirs(FIG, exist_ok=True)
74
+ path = os.path.join(FIG, name + ".html")
75
+ fig.write_html(path, include_plotlyjs="cdn", full_html=True)
76
+ print("wrote", path)
77
+ return path
78
+
79
+
80
+ def overlap_fig(a, title, ytitle="Squared overlap ⟨θ*, θ̂⟩²", xtitle="δ = n/d",
81
+ logx=False):
82
+ dims = sorted(a["d"].unique())
83
+ fig = go.Figure()
84
+ for i, d in enumerate(dims):
85
+ s = a[a["d"] == d].sort_values(a.columns[1])
86
+ x = s[s.columns[1]]
87
+ fig.add_trace(go.Scatter(
88
+ x=x, y=s["mean"], mode="lines+markers", name=f"d={d}",
89
+ line=dict(color=_c(i, len(dims)), width=2),
90
+ marker=dict(size=6),
91
+ error_y=dict(type="data", array=s["sem"], visible=True, thickness=1,
92
+ width=0, color=_c(i, len(dims)))))
93
+ fig.update_layout(title=title, xaxis_title=xtitle, yaxis_title=ytitle,
94
+ template="plotly_white", height=460,
95
+ legend=dict(orientation="v", x=1.02, y=1))
96
+ if logx:
97
+ fig.update_xaxes(type="log")
98
+ return fig
99
+
100
+
101
+ def thresholds_fig(rows, title, ytitle="Threshold δ = n/d"):
102
+ fig = go.Figure()
103
+ tgts = sorted({r["target"] for r in rows})
104
+ for i, t in enumerate(tgts):
105
+ sub = [r for r in rows if r["target"] == t and np.isfinite(r["value"])]
106
+ if not sub:
107
+ continue
108
+ x = [r["logd"] for r in sub]
109
+ y = [r["value"] for r in sub]
110
+ f = linfit(x, y)
111
+ col = _c(i, len(tgts))
112
+ fig.add_trace(go.Scatter(x=x, y=y, mode="markers", marker=dict(size=9, color=col),
113
+ name=f"overlap={t} (R²={f['r2']:.3f})"))
114
+ xs = np.linspace(min(x), max(x), 10)
115
+ fig.add_trace(go.Scatter(x=xs, y=f["intercept"] + f["slope"] * xs, mode="lines",
116
+ line=dict(color=col, width=2), showlegend=False))
117
+ fig.update_layout(title=title, xaxis_title="log d", yaxis_title=ytitle,
118
+ template="plotly_white", height=460)
119
+ return fig
120
+
121
+
122
+ def main():
123
+ ap = argparse.ArgumentParser()
124
+ ap.add_argument("--targets", default="0.1,0.2,0.3,0.4,0.5")
125
+ args = ap.parse_args()
126
+ targets = [float(v) for v in args.targets.split(",")]
127
+ os.makedirs(FIG, exist_ok=True)
128
+ summary = {}
129
+
130
+ # ---------------- spherical sweeps (Claims 1, 2, 5) ---------------------
131
+ thr_rows = []
132
+ for act, label in (("quad", "quadratic σ(z)=z²"),
133
+ ("trunc", "truncated σ(z)=min(z²,M), M=8")):
134
+ path = f"{RES}/sweep_{act}.csv"
135
+ if not os.path.exists(path):
136
+ continue
137
+ df = pd.read_csv(path)
138
+ a = agg(df)
139
+ a.to_csv(f"{RES}/agg_{act}.csv", index=False)
140
+ write_fig(overlap_fig(a, f"Full-batch spherical GD, {label}"), f"overlap_{act}")
141
+ for d in sorted(a["d"].unique()):
142
+ s = a[a["d"] == d].sort_values("delta")
143
+ for t in targets:
144
+ thr_rows.append(dict(method="full-batch", act=act, d=int(d),
145
+ logd=math.log(d), target=t,
146
+ value=threshold(s["delta"], s["mean"], t)))
147
+ # bimodality diagnostic: fraction of seeds that reach non-trivial overlap
148
+ fr = (df.assign(ok=(df["sq_overlap"] > 0.25).astype(float))
149
+ .groupby(["d", "delta"])["ok"].mean().reset_index())
150
+ fr.to_csv(f"{RES}/success_frac_{act}.csv", index=False)
151
+
152
+ # ---------------- one-pass SGD baseline (Claim 5) ----------------------
153
+ for act in ("trunc", "quad"):
154
+ p = f"{RES}/sweep_online_{act}.csv"
155
+ if not os.path.exists(p):
156
+ continue
157
+ df = pd.read_csv(p)
158
+ # the Arous et al. lower bound holds for *any* step size eta <~ 1/d, so the
159
+ # fair baseline is the envelope over the eta = c/d grid at each (d, n).
160
+ a = (df.groupby(["d", "delta"])["sq_overlap"].max().reset_index()
161
+ .rename(columns={"sq_overlap": "mean"}))
162
+ a["sem"] = 0.0
163
+ a.to_csv(f"{RES}/agg_online_{act}.csv", index=False)
164
+ write_fig(overlap_fig(
165
+ a, f"One-pass (online) spherical SGD, {act} σ — best η over c/d grid"),
166
+ f"overlap_online_{act}")
167
+ for d in sorted(a["d"].unique()):
168
+ s = a[a["d"] == d].sort_values("delta")
169
+ for t in targets:
170
+ thr_rows.append(dict(method="one-pass-sgd", act=act, d=int(d),
171
+ logd=math.log(d), target=t,
172
+ value=threshold(s["delta"], s["mean"], t)))
173
+
174
+ if thr_rows:
175
+ tdf = pd.DataFrame(thr_rows)
176
+ tdf.to_csv(f"{RES}/thresholds.csv", index=False)
177
+ fits = []
178
+ for (meth, act), g in tdf.groupby(["method", "act"]):
179
+ for t in targets:
180
+ sub = g[g["target"] == t]
181
+ f = linfit(sub["logd"], sub["value"])
182
+ f.update(method=meth, act=act, target=t)
183
+ fits.append(f)
184
+ rows = [r for _, r in g.iterrows()]
185
+ write_fig(
186
+ thresholds_fig([dict(target=r["target"], logd=r["logd"], value=r["value"])
187
+ for r in rows],
188
+ f"Sample-complexity threshold vs log d — {meth}, {act}"),
189
+ f"threshold_{meth.replace('-', '_')}_{act}")
190
+ pd.DataFrame(fits).to_csv(f"{RES}/threshold_fits.csv", index=False)
191
+ summary["threshold_fits"] = fits
192
+
193
+ # Claim 5: side-by-side separation figure
194
+ combos = [("full-batch", "trunc", "full-batch GD, truncated σ", PALETTE[1]),
195
+ ("full-batch", "quad", "full-batch GD, quadratic σ", PALETTE[3]),
196
+ ("one-pass-sgd", "trunc", "one-pass SGD, truncated σ", PALETTE[5]),
197
+ ("one-pass-sgd", "quad", "one-pass SGD, quadratic σ", PALETTE[6])]
198
+ for tg in (0.3, 0.5):
199
+ fig = go.Figure()
200
+ for meth, act, lab, col in combos:
201
+ sub = tdf[(tdf["method"] == meth) & (tdf["act"] == act)
202
+ & (tdf["target"] == tg)].sort_values("logd")
203
+ if sub.empty or not np.isfinite(sub["value"]).any():
204
+ continue
205
+ f = linfit(sub["logd"], sub["value"])
206
+ fig.add_trace(go.Scatter(x=sub["logd"], y=sub["value"], mode="markers",
207
+ marker=dict(size=10, color=col),
208
+ name=f"{lab} — slope {f['slope']:.2f}, R²={f['r2']:.3f}"))
209
+ xs = np.linspace(sub["logd"].min(), sub["logd"].max(), 10)
210
+ fig.add_trace(go.Scatter(x=xs, y=f["intercept"] + f["slope"] * xs,
211
+ mode="lines", line=dict(color=col, width=2),
212
+ showlegend=False))
213
+ fig.update_layout(
214
+ title=f"Sample complexity δ = n/d for squared overlap {tg}: "
215
+ "full-batch vs one-pass",
216
+ xaxis_title="log d", yaxis_title="threshold δ = n/d",
217
+ template="plotly_white", height=470,
218
+ legend=dict(orientation="h", yanchor="bottom", y=-0.42))
219
+ write_fig(fig, f"separation_target{str(tg).replace('.', '')}")
220
+
221
+ # ---- direct test of the n ≍ d log d scaling (Theorem 3.1 vs 3.2) --------
222
+ scal = []
223
+ for act in ("quad", "trunc"):
224
+ p = f"{RES}/agg_{act}.csv"
225
+ if not os.path.exists(p):
226
+ continue
227
+ a = pd.read_csv(p)
228
+ for d in sorted(a["d"].unique()):
229
+ s = a[a["d"] == d].sort_values("delta")
230
+ f = PchipInterpolator(s["delta"].values, s["mean"].values)
231
+ for mode, dl in ([("fixed δ=4", 4.0), ("fixed δ=8", 8.0),
232
+ ("δ=1.2·log d", 1.2 * math.log(d))]):
233
+ if s["delta"].min() <= dl <= s["delta"].max():
234
+ scal.append(dict(act=act, d=int(d), logd=math.log(d), mode=mode,
235
+ delta=round(dl, 3), mean=float(f(dl))))
236
+ if scal:
237
+ sdf = pd.DataFrame(scal)
238
+ sdf.to_csv(f"{RES}/scaling_collapse.csv", index=False)
239
+ fig = go.Figure()
240
+ styles = {("quad", "fixed δ=4"): (PALETTE[5], "solid"),
241
+ ("quad", "fixed δ=8"): (PALETTE[6], "solid"),
242
+ ("quad", "δ=1.2·log d"): (PALETTE[1], "dash"),
243
+ ("trunc", "fixed δ=4"): (PALETTE[3], "dot"),
244
+ ("trunc", "fixed δ=8"): (PALETTE[0], "dot")}
245
+ for (act, mode), g in sdf.groupby(["act", "mode"]):
246
+ if (act, mode) not in styles:
247
+ continue
248
+ col, dash = styles[(act, mode)]
249
+ g = g.sort_values("logd")
250
+ fig.add_trace(go.Scatter(x=g["logd"], y=g["mean"], mode="lines+markers",
251
+ name=f"{act}, {mode}",
252
+ line=dict(color=col, width=2, dash=dash)))
253
+ fig.update_layout(
254
+ title="Overlap along n ∝ d (fixed δ) vs n ∝ d log d — quadratic vs truncated σ",
255
+ xaxis_title="log d", yaxis_title="Squared overlap ⟨θ*, θ̂⟩²",
256
+ template="plotly_white", height=470,
257
+ legend=dict(orientation="h", yanchor="bottom", y=-0.38))
258
+ write_fig(fig, "scaling_collapse")
259
+ summary["scaling_collapse"] = scal
260
+
261
+ with open(f"{RES}/analysis_summary.json", "w") as f:
262
+ json.dump(summary, f, indent=2, default=float)
263
+ print(json.dumps(summary.get("threshold_fits", []), indent=2, default=float)[:4000])
264
+
265
+
266
+ if __name__ == "__main__":
267
+ main()
scripts/analyze_audit.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Figures for the numerical audits of the spectral statements (Claims 1 and 2)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import os
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ import plotly.graph_objects as go
12
+
13
+ from analyze import PALETTE, _c, write_fig, linfit
14
+
15
+ RES = "results"
16
+
17
+
18
+ def main():
19
+ out = {}
20
+ a = pd.read_csv(f"{RES}/audit_spectrum.csv")
21
+ dims = sorted(a["d"].unique())
22
+
23
+ # --- lambda1(A*): diverges for quadratic, converges to 6 for truncated -----
24
+ fig = go.Figure()
25
+ for i, d in enumerate(dims):
26
+ q = a[(a["act"] == "quad") & (a["d"] == d)].groupby("delta")["lam1"].mean().reset_index()
27
+ t = a[(a["act"] == "trunc") & (a["M"] == 8.0) & (a["d"] == d)] \
28
+ .groupby("delta")["lam1"].mean().reset_index()
29
+ fig.add_trace(go.Scatter(x=q["delta"], y=q["lam1"], mode="lines+markers",
30
+ name=f"quad d={d}", line=dict(color=_c(i, len(dims)), dash="dash")))
31
+ fig.add_trace(go.Scatter(x=t["delta"], y=t["lam1"], mode="lines+markers",
32
+ name=f"trunc d={d}", line=dict(color=_c(i, len(dims)))))
33
+ fig.add_hline(y=6, line_dash="dot", line_color="#111",
34
+ annotation_text="population λ₁ = 6")
35
+ fig.update_layout(title="λ₁(A*) vs δ = n/d — quadratic (dashed) vs truncated M=8 (solid)",
36
+ xaxis_title="δ = n/d", yaxis_title="λ₁(A*)", xaxis_type="log",
37
+ yaxis_type="log", template="plotly_white", height=470)
38
+ write_fig(fig, "audit_lam1")
39
+
40
+ # --- the eq. (3.13) error: |lam1-6| + |lam2-2| vs the claimed rate ---------
41
+ t = a[(a["act"] == "trunc")].copy()
42
+ t["err"] = (t["lam1"] - 6).abs() + (t["lam2"] - 2).abs()
43
+ t["rate"] = np.exp(-t["M"] / 3) + t["M"] * np.sqrt(t["d"] / t["n"])
44
+ g = t.groupby(["M", "delta", "d"])[["err", "rate"]].mean().reset_index()
45
+ g["C"] = g["err"] / g["rate"]
46
+ g.to_csv(f"{RES}/audit_eq313.csv", index=False)
47
+ fig = go.Figure()
48
+ Ms = sorted(g["M"].unique())
49
+ for i, M in enumerate(Ms):
50
+ s = g[g["M"] == M]
51
+ fig.add_trace(go.Scatter(x=s["rate"], y=s["err"], mode="markers",
52
+ marker=dict(size=9, color=_c(i, len(Ms))), name=f"M={M:g}"))
53
+ lim = [float(g["rate"].min()) * 0.8, float(g["rate"].max()) * 1.2]
54
+ for C, dash in ((1.0, "dot"), (0.5, "dash")):
55
+ fig.add_trace(go.Scatter(x=lim, y=[C * lim[0], C * lim[1]], mode="lines",
56
+ line=dict(color="#444", dash=dash), name=f"C = {C}"))
57
+ fig.update_layout(
58
+ title="Eq. (3.13) audit: |λ₁−6| + |λ₂−2| vs C(e^(−M/3) + M√(d/n))",
59
+ xaxis_title="e^(−M/3) + M√(d/n)", yaxis_title="|λ₁−6| + |λ₂−2|",
60
+ xaxis_type="log", yaxis_type="log", template="plotly_white", height=470)
61
+ write_fig(fig, "audit_eq313")
62
+ out["eq313_max_C"] = float(g["C"].max())
63
+ out["eq313_max_C_largedelta"] = float(g[g["delta"] >= 16]["C"].max())
64
+
65
+ # --- uniform-in-theta BBP --------------------------------------------------
66
+ b = pd.read_csv(f"{RES}/audit_uniform_bbp.csv")
67
+ bt = b[(b["act"] == "trunc") & (b["M"] == 8.0)].copy()
68
+ bt["kind"] = np.where(bt["theta"].str.startswith("random"), "random θ", bt["theta"])
69
+ fig = go.Figure()
70
+ kinds = ["random θ", "theta_star", "adversarial"]
71
+ cols = {"random θ": PALETTE[1], "theta_star": PALETTE[4], "adversarial": PALETTE[6]}
72
+ for k in kinds:
73
+ s = bt[bt["kind"] == k]
74
+ for j, col in enumerate(("lam1", "lam2")):
75
+ fig.add_trace(go.Scatter(
76
+ x=s["delta"], y=s[col], mode="markers",
77
+ marker=dict(size=11, color=cols[k], symbol="circle" if j == 0 else "x"),
78
+ name=f"{k} — λ{j+1}", legendgroup=k, showlegend=True))
79
+ fig.add_hline(y=6, line_dash="dot", line_color="#111")
80
+ fig.add_hline(y=2, line_dash="dot", line_color="#111")
81
+ fig.update_layout(
82
+ title="Uniform-in-θ BBP transition of A(θ): λ₁ (circles) and λ₂ (crosses), truncated M=8",
83
+ xaxis_title="δ = n/d", yaxis_title="eigenvalue of A(θ)", xaxis_type="log",
84
+ template="plotly_white", height=470)
85
+ write_fig(fig, "audit_uniform_bbp")
86
+ s64 = bt[bt["delta"] == 64.0]
87
+ out["bbp_delta64"] = dict(lam1_min=float(s64["lam1"].min()), lam1_max=float(s64["lam1"].max()),
88
+ lam2_min=float(s64["lam2"].min()), lam2_max=float(s64["lam2"].max()),
89
+ ov_min=float(s64["sq_overlap_v1"].min()),
90
+ ov_max=float(s64["sq_overlap_v1"].max()))
91
+
92
+ # --- indicator mass -------------------------------------------------------
93
+ c = pd.read_csv(f"{RES}/audit_indicator.csv")
94
+ ct = c[c["act"] == "trunc"].copy()
95
+ ct["kind"] = np.where(ct["theta"].str.startswith("random"), "random θ", ct["theta"])
96
+ fig = go.Figure()
97
+ for i, k in enumerate(["random θ", "theta_star", "adversarial"]):
98
+ s = ct[ct["kind"] == k]
99
+ fig.add_trace(go.Box(x=s["M"], y=s["ratio"], name=k,
100
+ marker_color=[PALETTE[1], PALETTE[4], PALETTE[6]][i]))
101
+ fig.add_hline(y=1.0, line_dash="dot", line_color="#111",
102
+ annotation_text="bound with C = 1")
103
+ fig.update_layout(
104
+ title="Uniform indicator-mass bound: measured mass ÷ (e^(−M/2) + √(d/n)·log(n/d))",
105
+ xaxis_title="M", yaxis_title="ratio", template="plotly_white", height=440,
106
+ boxmode="group")
107
+ write_fig(fig, "audit_indicator")
108
+ out["indicator_max_ratio"] = float(ct["ratio"].max())
109
+ out["indicator_max_ratio_adv"] = float(ct[ct["kind"] == "adversarial"]["ratio"].max())
110
+
111
+ # --- Theorem 3.2 deficit bound --------------------------------------------
112
+ th = pd.read_csv(f"{RES}/thm32_bound.csv")
113
+ gg = th.groupby(["M", "delta"])[["deficit", "rate", "C_implied"]].mean().reset_index()
114
+ fig = go.Figure()
115
+ Ms = sorted(gg["M"].unique())
116
+ for i, M in enumerate(Ms):
117
+ s = gg[gg["M"] == M]
118
+ fig.add_trace(go.Scatter(x=s["rate"], y=s["deficit"], mode="markers+lines",
119
+ marker=dict(size=10, color=_c(i, len(Ms))),
120
+ line=dict(color=_c(i, len(Ms))), name=f"M={M:g}"))
121
+ lim = [float(gg["rate"].min()) * 0.9, float(gg["rate"].max()) * 1.1]
122
+ fig.add_trace(go.Scatter(x=lim, y=lim, mode="lines", line=dict(color="#444", dash="dot"),
123
+ name="C = 1"))
124
+ fig.update_layout(
125
+ title="Theorem 3.2 audit: realised deficit 1 − |⟨θ_∞,θ*⟩| vs e^(−M/2) + (d/n)^(1/5), d=512",
126
+ xaxis_title="e^(−M/2) + (d/n)^(1/5)", yaxis_title="1 − |⟨θ_∞, θ*⟩|",
127
+ xaxis_type="log", yaxis_type="log", template="plotly_white", height=470)
128
+ write_fig(fig, "audit_thm32")
129
+ out["thm32_max_C_Mge4"] = float(th[th["M"] >= 4]["C_implied"].max())
130
+ out["thm32_max_C_all"] = float(th["C_implied"].max())
131
+
132
+ # --- smooth vs hard truncation robustness ---------------------------------
133
+ p = f"{RES}/sweep_smooth.csv"
134
+ if os.path.exists(p):
135
+ sm = pd.read_csv(p).groupby(["d", "delta"])["sq_overlap"].mean().reset_index()
136
+ hd = pd.read_csv(f"{RES}/sweep_trunc.csv").groupby(["d", "delta"])["sq_overlap"] \
137
+ .mean().reset_index()
138
+ dims2 = sorted(sm["d"].unique())
139
+ fig = go.Figure()
140
+ for i, d in enumerate(dims2):
141
+ s = sm[sm["d"] == d].sort_values("delta")
142
+ h = hd[hd["d"] == d].sort_values("delta")
143
+ fig.add_trace(go.Scatter(x=s["delta"], y=s["sq_overlap"], mode="lines+markers",
144
+ name=f"smooth d={d}", line=dict(color=_c(i, len(dims2)))))
145
+ fig.add_trace(go.Scatter(x=h["delta"], y=h["sq_overlap"], mode="lines",
146
+ name=f"hard d={d}",
147
+ line=dict(color=_c(i, len(dims2)), dash="dot")))
148
+ fig.update_layout(
149
+ title="Robustness: C^∞ truncation (eq. 3.10, solid) vs hard truncation (eq. 4.3, dotted)",
150
+ xaxis_title="δ = n/d", yaxis_title="squared overlap",
151
+ template="plotly_white", height=470)
152
+ write_fig(fig, "audit_smooth_vs_hard")
153
+ mrg = sm.merge(hd, on=["d", "delta"], suffixes=("_smooth", "_hard"))
154
+ mrg["absdiff"] = (mrg["sq_overlap_smooth"] - mrg["sq_overlap_hard"]).abs()
155
+ mrg.to_csv(f"{RES}/smooth_vs_hard.csv", index=False)
156
+ out["smooth_vs_hard_maxdiff_delta_ge_4"] = float(mrg[mrg["delta"] >= 4]["absdiff"].max())
157
+ out["smooth_vs_hard_meandiff_delta_ge_4"] = float(mrg[mrg["delta"] >= 4]["absdiff"].mean())
158
+
159
+ with open(f"{RES}/audit_summary.json", "w") as f:
160
+ json.dump(out, f, indent=2, default=float)
161
+ print(json.dumps(out, indent=2, default=float))
162
+
163
+
164
+ if __name__ == "__main__":
165
+ main()
scripts/analyze_gd.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analysis + figures for the squared-loss GD trajectories (Claims 3 and 4).
2
+
3
+ Theorem 4.1: ||theta_t - theta*||^2 <= C (1 - eta alpha)^{t - tbar}, tbar <= C log d / eta.
4
+ Section 4: phase 1 = angle reduction + norm growth (O(log d / eta) steps),
5
+ phase 2 = geometric refinement.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import glob
11
+ import json
12
+ import math
13
+ import os
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+ import plotly.graph_objects as go
18
+
19
+ from analyze import PALETTE, _c, linfit, write_fig, thresholds_fig
20
+
21
+ RES = "results"
22
+
23
+
24
+ def load(prefix):
25
+ t = pd.read_csv(f"{RES}/{prefix}_traj.csv")
26
+ s = pd.read_csv(f"{RES}/{prefix}_summary.csv")
27
+ return t, s
28
+
29
+
30
+ def mean_traj(t):
31
+ return (t.groupby(["d", "step"])[["sq_overlap", "norm", "dist2", "loss"]]
32
+ .mean().reset_index())
33
+
34
+
35
+ def first_cross(steps, vals, target, above=True):
36
+ steps, vals = np.asarray(steps), np.asarray(vals)
37
+ m = vals >= target if above else vals <= target
38
+ return float(steps[np.argmax(m)]) if m.any() else np.nan
39
+
40
+
41
+ def traj_fig(mt, ycol, title, ytitle, logy=False, hline=None):
42
+ dims = sorted(mt["d"].unique())
43
+ fig = go.Figure()
44
+ for i, d in enumerate(dims):
45
+ s = mt[mt["d"] == d]
46
+ fig.add_trace(go.Scatter(x=s["step"], y=s[ycol], mode="lines", name=f"d={d}",
47
+ line=dict(color=_c(i, len(dims)), width=2)))
48
+ if hline is not None:
49
+ fig.add_hline(y=hline, line_dash="dot", line_color="#888")
50
+ fig.update_layout(title=title, xaxis_title="GD step t", yaxis_title=ytitle,
51
+ template="plotly_white", height=460)
52
+ if logy:
53
+ fig.update_yaxes(type="log")
54
+ return fig
55
+
56
+
57
+ def phase_table(t, eta, targets=(0.9,)):
58
+ rows = []
59
+ for (d, seed), g in t.groupby(["d", "seed"]):
60
+ g = g.sort_values("step")
61
+ st, ov, nr, d2 = (g["step"].values, g["sq_overlap"].values,
62
+ g["norm"].values, g["dist2"].values)
63
+ t_angle = first_cross(st, ov, 0.9)
64
+ t_norm = first_cross(st, nr, 0.25)
65
+ tbar = np.nanmax([t_angle, t_norm])
66
+ rate = np.nan
67
+ if np.isfinite(tbar):
68
+ m = (st >= tbar) & (d2 > 1e-11) & (d2 < 1e2)
69
+ if m.sum() >= 5:
70
+ b, a = np.polyfit(st[m], np.log(d2[m]), 1)
71
+ rate = float(b)
72
+ rows.append(dict(d=int(d), seed=int(seed), t_angle=t_angle, t_norm=t_norm,
73
+ tbar=tbar, log_rate_per_step=rate,
74
+ rho=math.exp(rate) if np.isfinite(rate) else np.nan,
75
+ alpha_implied=(1 - math.exp(rate)) / eta
76
+ if np.isfinite(rate) else np.nan,
77
+ t_star_angle_pred=3 * math.log(d) / math.log(1 + 1.99 * eta)))
78
+ return pd.DataFrame(rows)
79
+
80
+
81
+ def main():
82
+ out = {}
83
+ targets = [0.1, 0.2, 0.3, 0.4, 0.5]
84
+
85
+ # ------------------------------------------------ main run: r0 = d^-2 ----
86
+ t, s = load("gd_trunc_r2")
87
+ eta = float(s["eta"].iloc[0])
88
+ mt = mean_traj(t)
89
+ mt.to_csv(f"{RES}/agg_gd_trunc_r2.csv", index=False)
90
+ write_fig(traj_fig(mt, "sq_overlap",
91
+ "Squared-loss full-batch GD — overlap vs steps (truncated σ, M=8, δ=10)",
92
+ "Squared overlap ⟨θ*, θ̂⟩²"), "gd_overlap")
93
+ write_fig(traj_fig(mt, "norm",
94
+ "Squared-loss full-batch GD — ‖θ_t‖ vs steps (truncated σ, M=8, δ=10)",
95
+ "‖θ_t‖", hline=1.0), "gd_norm")
96
+ write_fig(traj_fig(mt, "dist2",
97
+ "Strong recovery: ‖θ_t − θ*‖² vs steps (truncated σ, M=8, δ=10)",
98
+ "‖θ_t − θ*‖²", logy=True), "gd_dist2")
99
+
100
+ thr = []
101
+ for d in sorted(mt["d"].unique()):
102
+ g = mt[mt["d"] == d].sort_values("step")
103
+ for tg in targets:
104
+ thr.append(dict(target=tg, d=int(d), logd=math.log(d),
105
+ value=first_cross(g["step"], g["sq_overlap"], tg)))
106
+ tdf = pd.DataFrame(thr)
107
+ tdf.to_csv(f"{RES}/gd_time_thresholds.csv", index=False)
108
+ write_fig(thresholds_fig(thr, "Iteration complexity vs log d — full-batch GD, squared loss",
109
+ ytitle="GD steps T to reach target overlap"), "gd_T_vs_logd")
110
+ out["T_vs_logd_fits"] = [
111
+ dict(target=tg, **linfit(tdf[tdf["target"] == tg]["logd"],
112
+ tdf[tdf["target"] == tg]["value"]))
113
+ for tg in targets]
114
+
115
+ ph = phase_table(t, eta)
116
+ ph.to_csv(f"{RES}/gd_phases.csv", index=False)
117
+ phm = ph.groupby("d").median(numeric_only=True).reset_index()
118
+ phm["logd"] = np.log(phm["d"])
119
+ out["eta"] = eta
120
+ out["phases_median"] = phm.to_dict("records")
121
+ out["tbar_vs_logd"] = linfit(phm["logd"], phm["tbar"])
122
+ out["alpha_implied"] = dict(median=float(phm["alpha_implied"].median()),
123
+ min=float(phm["alpha_implied"].min()),
124
+ max=float(phm["alpha_implied"].max()))
125
+ out["final"] = s.groupby("d")[["final_dist2", "final_sq_overlap", "final_norm",
126
+ "final_loss"]].median().reset_index().to_dict("records")
127
+
128
+ # phase figure: two-phase decomposition for one dimension
129
+ dsel = 1024 if 1024 in set(mt["d"]) else sorted(mt["d"])[-1]
130
+ g = mt[mt["d"] == dsel].sort_values("step")
131
+ fig = go.Figure()
132
+ fig.add_trace(go.Scatter(x=g["step"], y=g["norm"], name="‖θ_t‖",
133
+ line=dict(color=PALETTE[1], width=2)))
134
+ fig.add_trace(go.Scatter(x=g["step"], y=g["sq_overlap"], name="⟨θ*, θ̂⟩²",
135
+ line=dict(color=PALETTE[5], width=2)))
136
+ fig.add_trace(go.Scatter(x=g["step"], y=g["dist2"], name="‖θ_t − θ*‖²",
137
+ line=dict(color=PALETTE[3], width=2, dash="dot"),
138
+ yaxis="y2"))
139
+ tb = float(phm[phm["d"] == dsel]["tbar"].iloc[0])
140
+ fig.add_vline(x=tb, line_dash="dash", line_color="#444",
141
+ annotation_text=f"t̄ ≈ {tb:.0f}", annotation_position="top")
142
+ fig.update_layout(
143
+ title=f"Two-phase trajectory (d={dsel}): angle reduction + norm growth, then geometric refinement",
144
+ xaxis_title="GD step t", yaxis_title="overlap² / ‖θ_t‖",
145
+ yaxis2=dict(title="‖θ_t − θ*‖²", overlaying="y", side="right", type="log"),
146
+ template="plotly_white", height=470)
147
+ write_fig(fig, "gd_two_phase")
148
+
149
+ # ------------------------------------------------ r0 = d^-15 (Theorem) --
150
+ if os.path.exists(f"{RES}/gd_trunc_r15_traj.csv"):
151
+ t15, s15 = load("gd_trunc_r15")
152
+ mt15 = mean_traj(t15)
153
+ mt15.to_csv(f"{RES}/agg_gd_trunc_r15.csv", index=False)
154
+ write_fig(traj_fig(mt15, "norm",
155
+ "Theorem 4.1 initialisation r₀ = d⁻¹⁵ — norm growth",
156
+ "‖θ_t‖", logy=True), "gd_norm_r15")
157
+ thr15 = []
158
+ for d in sorted(mt15["d"].unique()):
159
+ g = mt15[mt15["d"] == d].sort_values("step")
160
+ for tg in targets:
161
+ thr15.append(dict(target=tg, d=int(d), logd=math.log(d),
162
+ value=first_cross(g["step"], g["sq_overlap"], tg)))
163
+ write_fig(thresholds_fig(thr15, "Iteration complexity vs log d — r₀ = d⁻¹⁵",
164
+ ytitle="GD steps T to reach target overlap"),
165
+ "gd_T_vs_logd_r15")
166
+ pd.DataFrame(thr15).to_csv(f"{RES}/gd_time_thresholds_r15.csv", index=False)
167
+ out["r15_T_vs_logd_fits"] = [
168
+ dict(target=tg, **linfit([r["logd"] for r in thr15 if r["target"] == tg],
169
+ [r["value"] for r in thr15 if r["target"] == tg]))
170
+ for tg in targets]
171
+ ph15 = phase_table(t15, float(s15["eta"].iloc[0]))
172
+ ph15.to_csv(f"{RES}/gd_phases_r15.csv", index=False)
173
+ out["r15_phases_median"] = (ph15.groupby("d").median(numeric_only=True)
174
+ .reset_index().to_dict("records"))
175
+ out["r15_final"] = s15.groupby("d")[["final_dist2", "final_sq_overlap"]] \
176
+ .median().reset_index().to_dict("records")
177
+
178
+ # ------------------------------------------------ eta scaling (Claim 4) --
179
+ eta_rows = []
180
+ for path in sorted(glob.glob(f"{RES}/gd_trunc_eta*_summary.csv")) + \
181
+ [f"{RES}/gd_trunc_r2_summary.csv"]:
182
+ pre = path.replace("_summary.csv", "").split("/")[-1]
183
+ tt, ss = load(pre)
184
+ e = float(ss["eta"].iloc[0])
185
+ p = phase_table(tt, e).groupby("d").median(numeric_only=True).reset_index()
186
+ for r in p.itertuples():
187
+ eta_rows.append(dict(eta=e, d=int(r.d), tbar=r.tbar,
188
+ tbar_times_eta=r.tbar * e,
189
+ alpha_implied=r.alpha_implied))
190
+ if eta_rows:
191
+ edf = pd.DataFrame(eta_rows)
192
+ edf.to_csv(f"{RES}/gd_eta_scaling.csv", index=False)
193
+ fig = go.Figure()
194
+ for i, d in enumerate(sorted(edf["d"].unique())):
195
+ s2 = edf[edf["d"] == d].sort_values("eta")
196
+ fig.add_trace(go.Scatter(x=1 / s2["eta"], y=s2["tbar"], mode="lines+markers",
197
+ name=f"d={d}", line=dict(color=_c(i, edf["d"].nunique()))))
198
+ fig.update_layout(title="Phase-1 length t̄ scales as 1/η (fixed d, δ=10)",
199
+ xaxis_title="1/η", yaxis_title="t̄ (steps)",
200
+ template="plotly_white", height=440)
201
+ write_fig(fig, "gd_tbar_vs_eta")
202
+ out["eta_scaling"] = edf.to_dict("records")
203
+
204
+ # ------------------------------------------------ control: quadratic ----
205
+ if os.path.exists(f"{RES}/gd_quad_r2_summary.csv"):
206
+ _, sq = load("gd_quad_r2")
207
+ out["control_quad_final"] = (sq.groupby("d")[["final_dist2", "final_sq_overlap",
208
+ "final_norm", "final_loss"]]
209
+ .median().reset_index().to_dict("records"))
210
+ cmp_rows = []
211
+ for act, dfx in (("trunc", s), ("quad", sq)):
212
+ for r in (dfx.groupby("d")[["final_dist2"]].median().reset_index()).itertuples():
213
+ cmp_rows.append(dict(act=act, d=int(r.d), final_dist2=float(r.final_dist2)))
214
+ cdf = pd.DataFrame(cmp_rows)
215
+ fig = go.Figure()
216
+ for i, act in enumerate(["trunc", "quad"]):
217
+ s2 = cdf[cdf["act"] == act].sort_values("d")
218
+ fig.add_trace(go.Bar(x=[str(int(v)) for v in s2["d"]], y=s2["final_dist2"],
219
+ name={"trunc": "truncated σ (Thm 4.1)",
220
+ "quad": "untruncated σ(z)=z² (control)"}[act],
221
+ marker_color=PALETTE[1 if act == "trunc" else 5]))
222
+ fig.update_layout(title="Strong recovery control: final ‖θ_T − θ*‖² at δ=10, T=6000",
223
+ xaxis_title="d", yaxis_title="‖θ_T − θ*‖²", yaxis_type="log",
224
+ template="plotly_white", height=440, barmode="group")
225
+ write_fig(fig, "gd_control_quad")
226
+ cdf.to_csv(f"{RES}/gd_control_quad.csv", index=False)
227
+
228
+ with open(f"{RES}/gd_analysis_summary.json", "w") as f:
229
+ json.dump(out, f, indent=2, default=float)
230
+ print(json.dumps({k: v for k, v in out.items()
231
+ if k in ("eta", "T_vs_logd_fits", "tbar_vs_logd", "alpha_implied",
232
+ "phases_median", "final")}, indent=2, default=float))
233
+
234
+
235
+ if __name__ == "__main__":
236
+ main()
scripts/make_poster_figs.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render poster PNGs (3200x2000, aspect 1.6) from the reproduction CSVs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import os
7
+
8
+ import matplotlib
9
+ matplotlib.use("Agg")
10
+ import matplotlib.pyplot as plt
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ from analyze import linfit
15
+
16
+ RES, OUT = "results", "images"
17
+ os.makedirs(OUT, exist_ok=True)
18
+
19
+ ACC = "#1f4e79"
20
+ ACC2 = "#c2410c"
21
+ GOLD = "#b45309"
22
+ GREY = "#6b7280"
23
+ CMAP = plt.get_cmap("plasma")
24
+
25
+ plt.rcParams.update({
26
+ "font.size": 26, "axes.labelsize": 30, "axes.titlesize": 32,
27
+ "legend.fontsize": 24, "xtick.labelsize": 25, "ytick.labelsize": 25,
28
+ "axes.linewidth": 2.2, "lines.linewidth": 4.0, "grid.alpha": 0.28,
29
+ "figure.dpi": 200, "savefig.bbox": "tight", "savefig.pad_inches": 0.25,
30
+ })
31
+ FS = (16, 10)
32
+ FS_WIDE = (17.6, 8.0)
33
+
34
+
35
+ def _dcolors(dims):
36
+ return {d: CMAP(0.06 + 0.82 * i / max(len(dims) - 1, 1)) for i, d in enumerate(dims)}
37
+
38
+
39
+ def fig_overlap(act, title, fname, annotate=None):
40
+ a = pd.read_csv(f"{RES}/agg_{act}.csv")
41
+ dims = sorted(a["d"].unique())
42
+ cols = _dcolors(dims)
43
+ fig, ax = plt.subplots(figsize=FS)
44
+ for d in dims:
45
+ s = a[a["d"] == d].sort_values("delta")
46
+ ax.plot(s["delta"], s["mean"], "-o", ms=8, color=cols[d], label=f"d={d}")
47
+ ax.set_xlabel(r"$\delta = n/d$")
48
+ ax.set_ylabel(r"squared overlap $\langle\theta^\star,\hat\theta\rangle^2$")
49
+ ax.set_title(title, pad=14)
50
+ ax.grid(True, ls=":")
51
+ ax.legend(ncol=2, frameon=False, loc="lower right")
52
+ if annotate:
53
+ ax.annotate(annotate, xy=(0.03, 0.95), xycoords="axes fraction", va="top",
54
+ fontsize=26, color=ACC2, weight="bold")
55
+ fig.savefig(f"{OUT}/{fname}", dpi=200)
56
+ plt.close(fig)
57
+
58
+
59
+ def fig_separation():
60
+ t = pd.read_csv(f"{RES}/thresholds.csv")
61
+ fig, ax = plt.subplots(figsize=(16, 10.6))
62
+ combos = [("one-pass-sgd", "trunc", "one-pass SGD, truncated", ACC2, "o"),
63
+ ("full-batch", "quad", "full-batch GD, quadratic", GOLD, "s"),
64
+ ("full-batch", "trunc", "full-batch GD, truncated", ACC, "D")]
65
+ for meth, act, lab, col, mk in combos:
66
+ s = t[(t["method"] == meth) & (t["act"] == act) & (t["target"] == 0.3)].sort_values("logd")
67
+ s = s[np.isfinite(s["value"])]
68
+ f = linfit(s["logd"], s["value"])
69
+ ax.plot(s["logd"], s["value"], mk, ms=16, color=col,
70
+ label=f"{lab} — slope {f['slope']:.2f}")
71
+ xs = np.linspace(s["logd"].min(), s["logd"].max(), 10)
72
+ ax.plot(xs, f["intercept"] + f["slope"] * xs, "-", color=col, lw=3.5, alpha=0.8)
73
+ ax.set_xlabel(r"$\log d$")
74
+ ax.set_ylabel(r"threshold $\delta = n/d$ for overlap$^2 = 0.3$")
75
+ ax.set_title("Sample complexity: full-batch removes the $\\log d$ factor", pad=14)
76
+ ax.grid(True, ls=":")
77
+ ax.legend(frameon=False, loc="upper left")
78
+ fig.savefig(f"{OUT}/pf_separation.png", dpi=200)
79
+ plt.close(fig)
80
+
81
+
82
+ def fig_strong():
83
+ a = pd.read_csv(f"{RES}/agg_gd_trunc_r2.csv")
84
+ dims = sorted(a["d"].unique())
85
+ cols = _dcolors(dims)
86
+ fig, ax = plt.subplots(figsize=FS_WIDE)
87
+ for d in dims:
88
+ s = a[a["d"] == d].sort_values("step")
89
+ ax.semilogy(s["step"], np.maximum(s["dist2"], 1e-13), color=cols[d], label=f"d={d}")
90
+ ax.set_xlabel("GD step $t$")
91
+ ax.set_ylabel(r"$\|\theta_t-\theta^\star\|^2$")
92
+ ax.set_title(r"Strong recovery: geometric convergence after the search phase", pad=14)
93
+ ax.grid(True, ls=":", which="both")
94
+ ax.legend(ncol=2, frameon=False, loc="upper right")
95
+ fig.savefig(f"{OUT}/pf_strong.png", dpi=200)
96
+ plt.close(fig)
97
+
98
+
99
+ def fig_two_phase():
100
+ a = pd.read_csv(f"{RES}/agg_gd_trunc_r2.csv")
101
+ ph = pd.read_csv(f"{RES}/gd_phases.csv").groupby("d").median(numeric_only=True)
102
+ d = 1024 if 1024 in set(a["d"]) else sorted(a["d"])[-1]
103
+ s = a[a["d"] == d].sort_values("step")
104
+ tb = float(ph.loc[d, "tbar"])
105
+ fig, ax = plt.subplots(figsize=FS_WIDE)
106
+ ax.plot(s["step"], s["norm"], color=ACC, label=r"$\|\theta_t\|$")
107
+ ax.plot(s["step"], s["sq_overlap"], color=ACC2, label=r"overlap$^2$")
108
+ ax.axvline(tb, color="#374151", ls="--", lw=3)
109
+ ax.axvspan(0, tb, color=GOLD, alpha=0.09)
110
+ ax.text(tb * 0.5, 0.55, "Phase 1\nangle ↓, norm ↑", ha="center", fontsize=26, color=GOLD)
111
+ ax.text(tb * 1.35, 0.30, "Phase 2\ngeometric", ha="left", fontsize=26, color=ACC)
112
+ ax2 = ax.twinx()
113
+ ax2.semilogy(s["step"], np.maximum(s["dist2"], 1e-13), color=GREY, ls=":", lw=3.5,
114
+ label=r"$\|\theta_t-\theta^\star\|^2$")
115
+ ax2.set_ylabel(r"$\|\theta_t-\theta^\star\|^2$", color=GREY)
116
+ ax.set_xlim(0, min(float(s["step"].max()), tb * 2.6))
117
+ ax.set_xlabel("GD step $t$")
118
+ ax.set_ylabel(r"$\|\theta_t\|$ / overlap$^2$")
119
+ ax.set_title(f"Two-phase trajectory (d={d}, $\\bar t\\approx${tb:.0f})", pad=14)
120
+ ax.grid(True, ls=":")
121
+ ax.legend(frameon=False, loc="center right")
122
+ fig.savefig(f"{OUT}/pf_two_phase.png", dpi=200)
123
+ plt.close(fig)
124
+
125
+
126
+ def fig_time():
127
+ t = pd.read_csv(f"{RES}/gd_time_thresholds.csv")
128
+ ph = pd.read_csv(f"{RES}/gd_phases.csv").groupby("d").median(numeric_only=True).reset_index()
129
+ fig, ax = plt.subplots(figsize=FS)
130
+ tg = sorted(t["target"].unique())
131
+ for i, g in enumerate(tg):
132
+ s = t[t["target"] == g].sort_values("logd")
133
+ f = linfit(s["logd"], s["value"])
134
+ c = CMAP(0.08 + 0.75 * i / max(len(tg) - 1, 1))
135
+ ax.plot(s["logd"], s["value"], "o", ms=14, color=c,
136
+ label=f"overlap$^2$={g} ($R^2$={f['r2']:.2f})")
137
+ xs = np.linspace(s["logd"].min(), s["logd"].max(), 10)
138
+ ax.plot(xs, f["intercept"] + f["slope"] * xs, "-", color=c, lw=3, alpha=0.85)
139
+ f = linfit(np.log(ph["d"]), ph["tbar"])
140
+ ax.plot(np.log(ph["d"]), ph["tbar"], "k^--", ms=15, lw=3,
141
+ label=f"$\\bar t$ (phase 1 end), $R^2$={f['r2']:.2f}")
142
+ ax.set_xlabel(r"$\log d$")
143
+ ax.set_ylabel("GD steps")
144
+ ax.set_title(r"Iteration complexity grows like $\log d$", pad=14)
145
+ ax.grid(True, ls=":")
146
+ ax.legend(frameon=False, loc="upper left", ncol=2)
147
+ fig.savefig(f"{OUT}/pf_time.png", dpi=200)
148
+ plt.close(fig)
149
+
150
+
151
+ def fig_spectrum():
152
+ a = pd.read_csv(f"{RES}/audit_spectrum.csv")
153
+ fig, ax = plt.subplots(figsize=FS)
154
+ q = a[(a["act"] == "quad")].groupby(["d", "delta"])[["lam1", "lam2"]].mean().reset_index()
155
+ tr = a[(a["act"] == "trunc") & (a["M"] == 8.0)].groupby(["d", "delta"])[["lam1", "lam2"]] \
156
+ .mean().reset_index()
157
+ dims = sorted(set(q["d"]) & set(tr["d"]))
158
+ cols = _dcolors(dims)
159
+ for d in dims:
160
+ s = q[q["d"] == d].sort_values("delta")
161
+ ax.plot(s["delta"], s["lam1"], "--o", ms=9, color=cols[d], alpha=0.85)
162
+ s = tr[tr["d"] == d].sort_values("delta")
163
+ ax.plot(s["delta"], s["lam1"], "-D", ms=9, color=cols[d])
164
+ ax.axhline(6, color="#111", ls=":", lw=3)
165
+ ax.text(a["delta"].max() * 0.55, 6.4, r"population $\lambda_1=6$", fontsize=25)
166
+ ax.set_xscale("log")
167
+ ax.set_yscale("log")
168
+ ax.set_xlabel(r"$\delta = n/d$")
169
+ ax.set_ylabel(r"$\lambda_1(A^\star)$")
170
+ ax.set_title(r"BBP spike survives only under truncation (solid) — quadratic (dashed) diverges",
171
+ pad=14, fontsize=27)
172
+ ax.grid(True, ls=":", which="both")
173
+ hd = [plt.Line2D([], [], color="k", ls="-", marker="D", label="truncated $\\sigma$"),
174
+ plt.Line2D([], [], color="k", ls="--", marker="o", label="quadratic $\\sigma$")]
175
+ hd += [plt.Line2D([], [], color=cols[d], lw=5, label=f"d={d}") for d in dims]
176
+ ax.legend(handles=hd, frameon=False, ncol=2, loc="upper right")
177
+ fig.savefig(f"{OUT}/pf_spectrum.png", dpi=200)
178
+ plt.close(fig)
179
+
180
+
181
+ def fig_scorecard():
182
+ rows = [
183
+ ("1", "Quadratic σ: no full-batch gain (Thm 3.1)", "SUPPORTED",
184
+ "δ* ∝ log d, slope 0.65–0.95, R² 0.97–0.99"),
185
+ ("2", "Truncated σ: weak recovery at n ≳ d (Thm 3.2)", "SUPPORTED",
186
+ "curves collapse: spread 0.020 vs 0.126"),
187
+ ("3", "Strong recovery, T ≳ log d (Thm 4.1)", "SUPPORTED",
188
+ "‖θ_T−θ*‖² → 1e-13 at r₀ = d⁻¹⁵"),
189
+ ("4", "Two-phase trajectory (Sec. 4)", "SUPPORTED",
190
+ "t̄ ∝ log d (R² 0.97) and ∝ 1/η; α ≈ 2.7"),
191
+ ("5", "Matches the n ≳ d lower bound (Thm 3.2)", "SUPPORTED",
192
+ "slope 0.04 vs 1.52 for one-pass SGD"),
193
+ ]
194
+ fig, ax = plt.subplots(figsize=FS)
195
+ ax.axis("off")
196
+ ax.set_xlim(0, 1)
197
+ ax.set_ylim(0, 1)
198
+ y = 0.90
199
+ ax.text(0.02, 0.985, "Verdict by claim", fontsize=34, weight="bold", color=ACC, va="top")
200
+ for num, name, verdict, ev in rows:
201
+ ax.add_patch(plt.Rectangle((0.015, y - 0.145), 0.97, 0.14, facecolor="#f6f7f9",
202
+ edgecolor="#d7dbe0", lw=2))
203
+ ax.add_patch(plt.Rectangle((0.015, y - 0.145), 0.012, 0.14, facecolor=ACC, lw=0))
204
+ ax.text(0.045, y - 0.035, f"Claim {num} · {name}", fontsize=27, weight="bold", va="top")
205
+ ax.text(0.045, y - 0.098, ev, fontsize=24, color="#334155", va="top")
206
+ ax.text(0.965, y - 0.062, verdict, fontsize=26, weight="bold", color="#166534",
207
+ ha="right", va="center")
208
+ y -= 0.165
209
+ ax.text(0.02, 0.055, "5/5 claims reproduced · 2× RTX 4000 Ada · ~5.6 GPU-hours · $0 cloud spend",
210
+ fontsize=25, color=GREY, va="center")
211
+ fig.savefig(f"{OUT}/pf_scorecard.png", dpi=200)
212
+ plt.close(fig)
213
+
214
+
215
+ if __name__ == "__main__":
216
+ fig_overlap("quad", r"Quadratic $\sigma(z)=z^2$: threshold drifts right with $d$",
217
+ "pf_quad.png")
218
+ fig_overlap("trunc", r"Truncated $\sigma(z)=\min(z^2,8)$: curves collapse",
219
+ "pf_trunc.png")
220
+ fig_separation()
221
+ fig_strong()
222
+ fig_two_phase()
223
+ fig_time()
224
+ try:
225
+ fig_spectrum()
226
+ except FileNotFoundError:
227
+ print("skip spectrum (audit not finished)")
228
+ fig_scorecard()
229
+ print("wrote", sorted(os.listdir(OUT)))
scripts/sim.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core simulation library for reproducing arXiv:2602.02431 (ICML 2026 #26332).
2
+
3
+ Single-index model: x_i ~ N(0, I_d), y_i = sigma(<x_i, theta*>), ||theta*|| = 1.
4
+
5
+ Activations
6
+ -----------
7
+ * ``quad`` sigma(z) = z^2 (paper Sec. 3.1)
8
+ * ``trunc`` sigma(z) = min(z^2, M) (paper eq. 4.3, hard truncation)
9
+ * ``smooth`` sigma(z) = int_0^{z^2} phi(u) du (paper eq. 3.10, smooth truncation)
10
+
11
+ Algorithms
12
+ ----------
13
+ * ``spherical_flow`` full-batch spherical GD on the correlation loss
14
+ L(theta) = -(1/n) sum_i y_i sigma(<x_i, theta>)
15
+ theta <- normalize(theta + eta (I - theta theta^T) A(theta) theta)
16
+ with A(theta) = (2/n) sum_i y_i phi(<x_i,theta>^2) x_i x_i^T.
17
+ * ``online_sgd`` one-pass spherical SGD on the same loss (each sample used once).
18
+ * ``squared_gd`` full-batch Euclidean GD on the squared loss (paper Sec. 4).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import math
24
+ from dataclasses import dataclass
25
+
26
+ import torch
27
+
28
+
29
+ # --------------------------------------------------------------------------- #
30
+ # activations
31
+ # --------------------------------------------------------------------------- #
32
+ def _bump(u: torch.Tensor) -> torch.Tensor:
33
+ """gamma(u) = exp(-1/u) for u > 0, else 0."""
34
+ out = torch.zeros_like(u)
35
+ pos = u > 0
36
+ out[pos] = torch.exp(-1.0 / u[pos])
37
+ return out
38
+
39
+
40
+ def phi_smooth(u: torch.Tensor, M: float) -> torch.Tensor:
41
+ """C^inf cutoff: phi = 1 for |u| <= M, 0 for |u| >= 2M (paper Sec. 3.2)."""
42
+ t = (u.abs() - M) / M
43
+ g0, g1 = _bump(t), _bump(1.0 - t)
44
+ S = torch.where(g0 + g1 > 0, g0 / (g0 + g1 + 1e-300), torch.zeros_like(t))
45
+ return (1.0 - S).clamp_(0.0, 1.0)
46
+
47
+
48
+ _SMOOTH_TABLE: dict[tuple[float, str, str], tuple[torch.Tensor, torch.Tensor]] = {}
49
+
50
+
51
+ def _smooth_sigma_table(M: float, device, dtype, npts: int = 200_001):
52
+ key = (M, str(device), str(dtype))
53
+ if key not in _SMOOTH_TABLE:
54
+ u = torch.linspace(0.0, 2.0 * M, npts, device=device, dtype=dtype)
55
+ f = phi_smooth(u, M)
56
+ du = u[1] - u[0]
57
+ cum = torch.cumsum((f[1:] + f[:-1]) * 0.5 * du, dim=0)
58
+ cum = torch.cat([torch.zeros(1, device=device, dtype=dtype), cum])
59
+ _SMOOTH_TABLE[key] = (u, cum)
60
+ return _SMOOTH_TABLE[key]
61
+
62
+
63
+ def sigma(z: torch.Tensor, act: str, M: float) -> torch.Tensor:
64
+ if act == "quad":
65
+ return z * z
66
+ if act == "trunc":
67
+ return torch.clamp(z * z, max=M)
68
+ if act == "smooth":
69
+ u, cum = _smooth_sigma_table(M, z.device, z.dtype)
70
+ w = torch.clamp(z * z, max=2.0 * M)
71
+ idx = torch.clamp(
72
+ torch.searchsorted(u, w.reshape(-1).contiguous()), 1, u.numel() - 1
73
+ )
74
+ u0, u1 = u[idx - 1], u[idx]
75
+ c0, c1 = cum[idx - 1], cum[idx]
76
+ frac = (w.reshape(-1) - u0) / (u1 - u0)
77
+ return (c0 + frac * (c1 - c0)).reshape(z.shape)
78
+ raise ValueError(act)
79
+
80
+
81
+ def phi(w: torch.Tensor, act: str, M: float) -> torch.Tensor:
82
+ """phi(u) with sigma'(z) = 2 z phi(z^2); argument ``w`` is z^2."""
83
+ if act == "quad":
84
+ return torch.ones_like(w)
85
+ if act == "trunc":
86
+ return (w < M).to(w.dtype)
87
+ if act == "smooth":
88
+ return phi_smooth(w, M)
89
+ raise ValueError(act)
90
+
91
+
92
+ def sigma_prime(z: torch.Tensor, act: str, M: float) -> torch.Tensor:
93
+ return 2.0 * z * phi(z * z, act, M)
94
+
95
+
96
+ # --------------------------------------------------------------------------- #
97
+ # data
98
+ # --------------------------------------------------------------------------- #
99
+ @dataclass
100
+ class Data:
101
+ X: torch.Tensor
102
+ y: torch.Tensor
103
+ theta_star: torch.Tensor
104
+
105
+
106
+ def make_data(d: int, n: int, seed: int, act: str, M: float, device, dtype) -> Data:
107
+ g = torch.Generator(device=device).manual_seed(seed)
108
+ theta_star = torch.randn(d, generator=g, device=device, dtype=dtype)
109
+ theta_star /= theta_star.norm()
110
+ X = torch.randn(n, d, generator=g, device=device, dtype=dtype)
111
+ y = sigma(X @ theta_star, act, M)
112
+ return Data(X, y, theta_star)
113
+
114
+
115
+ def rand_sphere(d: int, seed: int, device, dtype) -> torch.Tensor:
116
+ g = torch.Generator(device=device).manual_seed(seed)
117
+ v = torch.randn(d, generator=g, device=device, dtype=dtype)
118
+ return v / v.norm()
119
+
120
+
121
+ # --------------------------------------------------------------------------- #
122
+ # full-batch spherical gradient descent on the correlation loss
123
+ # --------------------------------------------------------------------------- #
124
+ def a_star(data: Data) -> torch.Tensor:
125
+ """A* = (2/n) sum_i y_i x_i x_i^T (paper eq. 3.3)."""
126
+ n = data.X.shape[0]
127
+ return (2.0 / n) * (data.X.T @ (data.y[:, None] * data.X))
128
+
129
+
130
+ def _Atheta_matvec(data: Data, theta: torch.Tensor, act: str, M: float) -> torch.Tensor:
131
+ """A(theta) @ theta without forming A(theta) (paper eq. 3.11)."""
132
+ z = data.X @ theta
133
+ w = data.y * phi(z * z, act, M) * z
134
+ return (2.0 / data.X.shape[0]) * (data.X.T @ w)
135
+
136
+
137
+ def spherical_flow(
138
+ data: Data,
139
+ theta0: torch.Tensor,
140
+ act: str,
141
+ M: float,
142
+ eta: float = 0.1,
143
+ T: int = 1000,
144
+ tol: float = 1e-12,
145
+ check_every: int = 50,
146
+ use_matrix: bool | None = None,
147
+ record_every: int = 0,
148
+ ):
149
+ """Full-batch spherical GD on the correlation loss (paper eq. 3.4 / 3.12).
150
+
151
+ Returns ``(theta, steps_run, trace)`` where ``trace`` is a list of
152
+ ``(step, squared_overlap)`` when ``record_every > 0``.
153
+ """
154
+ if use_matrix is None:
155
+ use_matrix = act == "quad"
156
+ A = a_star(data) if use_matrix else None
157
+ theta = theta0.clone()
158
+ ts = data.theta_star
159
+ trace = []
160
+ prev_ray = None
161
+ prev_ov = None
162
+ steps = T
163
+ for t in range(T):
164
+ Ath = (A @ theta) if use_matrix else _Atheta_matvec(data, theta, act, M)
165
+ ray = theta @ Ath
166
+ grad = Ath - ray * theta # (I - theta theta^T) A(theta) theta
167
+ theta = theta + eta * grad
168
+ theta = theta / theta.norm()
169
+ if record_every and (t % record_every == 0 or t == T - 1):
170
+ trace.append((t + 1, float((theta @ ts) ** 2)))
171
+ if (t + 1) % check_every == 0:
172
+ # converged: Rayleigh quotient (= -loss) and overlap both stationary
173
+ ray, ov = float(ray), float((theta @ ts) ** 2)
174
+ if (
175
+ prev_ray is not None
176
+ and abs(ray - prev_ray) <= tol * max(abs(ray), 1e-30)
177
+ and abs(ov - prev_ov) <= tol
178
+ ):
179
+ steps = t + 1
180
+ break
181
+ prev_ray, prev_ov = ray, ov
182
+ return theta, steps, trace
183
+
184
+
185
+ # --------------------------------------------------------------------------- #
186
+ # one-pass (online) spherical SGD on the correlation loss
187
+ # --------------------------------------------------------------------------- #
188
+ def online_sgd(
189
+ d: int,
190
+ n: int,
191
+ seeds: int,
192
+ act: str,
193
+ M: float,
194
+ eta: float,
195
+ seed0: int,
196
+ device,
197
+ dtype,
198
+ checkpoints: list[int],
199
+ chunk: int = 2048,
200
+ ):
201
+ """One-pass spherical SGD, vectorised over ``seeds`` independent replicas.
202
+
203
+ theta <- normalize(theta + eta (I - theta theta^T) y_t sigma'(<x_t,theta>) x_t)
204
+
205
+ Returns dict ``{n_used: mean squared overlap}`` measured at ``checkpoints``.
206
+ """
207
+ g = torch.Generator(device=device).manual_seed(seed0)
208
+ ts = torch.randn(seeds, d, generator=g, device=device, dtype=dtype)
209
+ ts /= ts.norm(dim=1, keepdim=True)
210
+ th = torch.randn(seeds, d, generator=g, device=device, dtype=dtype)
211
+ th /= th.norm(dim=1, keepdim=True)
212
+
213
+ out: dict[int, float] = {}
214
+ cps = sorted(checkpoints)
215
+ ci = 0
216
+ done = 0
217
+ while done < n:
218
+ m = min(chunk, n - done)
219
+ Xc = torch.randn(seeds, m, d, generator=g, device=device, dtype=dtype)
220
+ for j in range(m):
221
+ x = Xc[:, j, :] # (S, d)
222
+ zstar = (x * ts).sum(1)
223
+ y = sigma(zstar, act, M)
224
+ z = (x * th).sum(1)
225
+ coef = y * sigma_prime(z, act, M) # (S,)
226
+ gvec = coef[:, None] * x
227
+ gvec = gvec - (gvec * th).sum(1, keepdim=True) * th
228
+ th = th + eta * gvec
229
+ th = th / th.norm(dim=1, keepdim=True)
230
+ done += 1
231
+ while ci < len(cps) and done == cps[ci]:
232
+ out[done] = float(((th * ts).sum(1) ** 2).mean())
233
+ ci += 1
234
+ del Xc
235
+ return out
236
+
237
+
238
+ # --------------------------------------------------------------------------- #
239
+ # full-batch Euclidean GD on the squared loss (paper Sec. 4)
240
+ # --------------------------------------------------------------------------- #
241
+ def squared_gd(
242
+ data: Data,
243
+ theta0: torch.Tensor,
244
+ act: str,
245
+ M: float,
246
+ eta: float,
247
+ T: int,
248
+ record_every: int = 1,
249
+ stop_err: float | None = None,
250
+ ):
251
+ """theta_{t+1} = theta_t - eta * (1/n) sum_i (sigma(<x_i,th>) - y_i) sigma'(<x_i,th>) x_i.
252
+
253
+ Returns a dict of trajectory arrays (step, sq_overlap, norm, dist2, loss).
254
+ """
255
+ X, y, ts = data.X, data.y, data.theta_star
256
+ n = X.shape[0]
257
+ theta = theta0.clone()
258
+ rec = {"step": [], "sq_overlap": [], "norm": [], "dist2": [], "loss": []}
259
+
260
+ def _record(t):
261
+ nr = float(theta.norm())
262
+ ov = float((theta @ ts) ** 2) / max(nr * nr, 1e-300)
263
+ d2 = min(
264
+ float(((theta - ts) ** 2).sum()), float(((theta + ts) ** 2).sum())
265
+ )
266
+ z = X @ theta
267
+ loss = float((0.5 / n) * ((sigma(z, act, M) - y) ** 2).sum())
268
+ rec["step"].append(t)
269
+ rec["sq_overlap"].append(ov)
270
+ rec["norm"].append(nr)
271
+ rec["dist2"].append(d2)
272
+ rec["loss"].append(loss)
273
+ return d2
274
+
275
+ _record(0)
276
+ for t in range(1, T + 1):
277
+ z = X @ theta
278
+ resid = (sigma(z, act, M) - y) * sigma_prime(z, act, M)
279
+ grad = (X.T @ resid) / n
280
+ theta = theta - eta * grad
281
+ if record_every and (t % record_every == 0 or t == T):
282
+ d2 = _record(t)
283
+ if stop_err is not None and d2 < stop_err:
284
+ break
285
+ return rec
286
+
287
+
288
+ # --------------------------------------------------------------------------- #
289
+ # helpers
290
+ # --------------------------------------------------------------------------- #
291
+ def top2_eig(A: torch.Tensor):
292
+ """Top-two eigenvalues and top eigenvector of a symmetric matrix."""
293
+ A = 0.5 * (A + A.T)
294
+ evals, evecs = torch.linalg.eigh(A.double())
295
+ return float(evals[-1]), float(evals[-2]), evecs[:, -1].to(A.dtype)
296
+
297
+
298
+ def log2_steps(d: int, mult: float = 1000.0) -> int:
299
+ return int(mult * math.log(d) ** 2)
scripts/smoke.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Smoke test + timing benchmark for sim.py."""
2
+ import math
3
+ import sys
4
+ import time
5
+
6
+ import torch
7
+
8
+ sys.path.insert(0, __file__.rsplit("/", 1)[0])
9
+ import sim
10
+
11
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
12
+ print("device:", dev, torch.cuda.get_device_name(0) if dev == "cuda" else "")
13
+
14
+ # --- activation sanity ------------------------------------------------------
15
+ z = torch.linspace(-6, 6, 13, device=dev, dtype=torch.float64)
16
+ for act in ("quad", "trunc", "smooth"):
17
+ s = sim.sigma(z, act, 8.0)
18
+ print(f"{act:7s} sigma:", [round(float(v), 3) for v in s])
19
+ # numeric derivative check
20
+ eps = 1e-6
21
+ for act in ("quad", "trunc", "smooth"):
22
+ zz = torch.tensor([0.5, 1.5, 2.5, 3.5], device=dev, dtype=torch.float64)
23
+ num = (sim.sigma(zz + eps, act, 8.0) - sim.sigma(zz - eps, act, 8.0)) / (2 * eps)
24
+ ana = sim.sigma_prime(zz, act, 8.0)
25
+ print(f"{act:7s} d/dz max err:", float((num - ana).abs().max()))
26
+
27
+ # --- E[2 y x x^T] spectrum sanity (population lambda1=6, lambda2=2 for quad) --
28
+ for act in ("quad", "trunc", "smooth"):
29
+ d, n = 64, 64 * 400
30
+ data = sim.make_data(d, n, 0, act, 8.0, dev, torch.float64)
31
+ A = sim.a_star(data)
32
+ l1, l2, v1 = sim.top2_eig(A)
33
+ ov = float((v1 @ data.theta_star) ** 2)
34
+ print(f"{act:7s} n/d=400: lam1={l1:.3f} lam2={l2:.3f} ov^2={ov:.4f}")
35
+
36
+ # --- flow smoke -------------------------------------------------------------
37
+ for act in ("quad", "trunc"):
38
+ d, n = 256, 256 * 8
39
+ data = sim.make_data(d, n, 1, act, 8.0, dev, torch.float32)
40
+ th0 = sim.rand_sphere(d, 1234, dev, torch.float32)
41
+ t0 = time.time()
42
+ th, steps, _ = sim.spherical_flow(data, th0, act, 8.0, eta=0.1, T=20000)
43
+ ov = float((th @ data.theta_star) ** 2)
44
+ l1, l2, v1 = sim.top2_eig(sim.a_star(data))
45
+ print(
46
+ f"{act:7s} flow d={d} delta=8: ov^2={ov:.4f} steps={steps} "
47
+ f"({time.time()-t0:.1f}s) v1(A*) ov^2={float((v1@data.theta_star)**2):.4f}"
48
+ )
49
+
50
+ # --- squared-loss GD smoke --------------------------------------------------
51
+ d, n = 256, 2560
52
+ data = sim.make_data(d, n, 2, "trunc", 8.0, dev, torch.float64)
53
+ th0 = sim.rand_sphere(d, 7, dev, torch.float64) * d ** -2.0
54
+ t0 = time.time()
55
+ rec = sim.squared_gd(data, th0, "trunc", 8.0, eta=0.1 / 64, T=4000, record_every=20)
56
+ print(
57
+ f"squared GD d={d} delta=10: final ov^2={rec['sq_overlap'][-1]:.5f} "
58
+ f"norm={rec['norm'][-1]:.4f} dist2={rec['dist2'][-1]:.3e} ({time.time()-t0:.1f}s)"
59
+ )
60
+
61
+ # --- timing benchmark -------------------------------------------------------
62
+ for d in (1024, 4096):
63
+ n = 11 * d
64
+ t0 = time.time()
65
+ data = sim.make_data(d, n, 3, "trunc", 8.0, dev, torch.float32)
66
+ torch.cuda.synchronize() if dev == "cuda" else None
67
+ t_gen = time.time() - t0
68
+ th0 = sim.rand_sphere(d, 5, dev, torch.float32)
69
+ t0 = time.time()
70
+ sim.spherical_flow(data, th0, "trunc", 8.0, T=200, check_every=10 ** 9)
71
+ torch.cuda.synchronize() if dev == "cuda" else None
72
+ t_flow = time.time() - t0
73
+ t0 = time.time()
74
+ A = sim.a_star(data)
75
+ torch.cuda.synchronize() if dev == "cuda" else None
76
+ t_A = time.time() - t0
77
+ t0 = time.time()
78
+ sim.spherical_flow(data, th0, "quad", 8.0, T=2000, check_every=10 ** 9)
79
+ torch.cuda.synchronize() if dev == "cuda" else None
80
+ t_mat = time.time() - t0
81
+ print(
82
+ f"d={d} n={n}: gen={t_gen:.2f}s trunc-flow 200 steps={t_flow:.2f}s "
83
+ f"form A*={t_A:.2f}s matrix-flow 2000 steps={t_mat:.2f}s"
84
+ )
85
+ del data
86
+ torch.cuda.empty_cache() if dev == "cuda" else None
87
+ print("T=1000 log^2 d:", {d: sim.log2_steps(d) for d in (64, 1024, 4096, 8192)})
scripts/spectral_audit.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Numerical audit of the spectral statements behind Theorems 3.1 and 3.2.
2
+
3
+ (A) Spectrum of A* = (2/n) sum_i y_i x_i x_i^T.
4
+ Truncated sigma (paper eq. 3.13): |lam1 - 6| + |lam2 - 2| <= C(e^{-M/3} + M sqrt(d/n)).
5
+ Quadratic sigma (proof of Thm 3.1): lam_max is driven by the heaviest sample,
6
+ lam1 ~ 2 log(n) / delta -> diverges with d at fixed delta, killing the BBP spike.
7
+
8
+ (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,
9
+ the key technical ingredient of Theorem 3.2.
10
+
11
+ (C) Uniform indicator-mass bound (Lemma "indicatorbound"):
12
+ (1/n) sum_i 1{<x_i,theta>^2 > M} <= C (e^{-M/2} + sqrt(d/n) log(n/d)) for all theta.
13
+ Checked on random directions and on adversarially chosen directions.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import csv
20
+ import json
21
+ import math
22
+ import os
23
+ import sys
24
+ import time
25
+
26
+ import torch
27
+
28
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
29
+ import sim
30
+ from sweep_spherical import a_star_chunked, top2
31
+
32
+
33
+ def A_theta(data, theta, act, M):
34
+ z = data.X @ theta
35
+ w = data.y * sim.phi(z * z, act, M)
36
+ n = data.X.shape[0]
37
+ return (2.0 / n) * (data.X.T @ (w[:, None] * data.X))
38
+
39
+
40
+ def adversarial_theta(data, M, iters=200, lr=0.5):
41
+ """Maximise the empirical mass of {<x_i,theta>^2 > M} by smoothed ascent."""
42
+ d = data.X.shape[1]
43
+ theta = data.X[data.y.argmax()].clone()
44
+ theta = theta / theta.norm()
45
+ theta.requires_grad_(True)
46
+ opt = torch.optim.Adam([theta], lr=lr)
47
+ tau = 0.5
48
+ for _ in range(iters):
49
+ opt.zero_grad()
50
+ z = data.X @ (theta / theta.norm())
51
+ loss = -torch.sigmoid((z * z - M) / tau).mean()
52
+ loss.backward()
53
+ opt.step()
54
+ with torch.no_grad():
55
+ theta = theta / theta.norm()
56
+ return theta.detach()
57
+
58
+
59
+ def main():
60
+ p = argparse.ArgumentParser()
61
+ p.add_argument("--dims", default="128,256,512,1024,2048")
62
+ p.add_argument("--deltas", default="2,4,8,16,32,64,128")
63
+ p.add_argument("--Ms", default="2,4,8,16,32")
64
+ p.add_argument("--seeds", type=int, default=5)
65
+ p.add_argument("--n-theta", type=int, default=8, help="random thetas for part (B)")
66
+ p.add_argument("--out-prefix", required=True)
67
+ args = p.parse_args()
68
+
69
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
70
+ dims = [int(v) for v in args.dims.split(",")]
71
+ deltas = [float(v) for v in args.deltas.split(",")]
72
+ Ms = [float(v) for v in args.Ms.split(",")]
73
+ rows_a, rows_b, rows_c = [], [], []
74
+ t0 = time.time()
75
+
76
+ # ---- (A) spectrum of A* -------------------------------------------------
77
+ for act in ("quad", "trunc"):
78
+ for d in dims:
79
+ for delta in deltas:
80
+ n = int(round(delta * d))
81
+ for M in (Ms if act == "trunc" else [8.0]):
82
+ for s in range(args.seeds):
83
+ data = sim.make_data(d, n, 31 * d + 7 * s + int(delta), act, M,
84
+ dev, torch.float32)
85
+ A = a_star_chunked(data.X, data.y).double()
86
+ l1, l2, v1 = top2(A)
87
+ ov = float((v1 @ data.theta_star.double()) ** 2)
88
+ rows_a.append(dict(
89
+ act=act, d=d, delta=delta, n=n, M=M, seed=s,
90
+ lam1=round(l1, 6), lam2=round(l2, 6), gap=round(l1 - l2, 6),
91
+ sq_overlap_v1=round(ov, 6), sin2=round(1 - ov, 8),
92
+ logn_over_delta=round(2 * math.log(n) / delta, 4)))
93
+ del data, A
94
+ torch.cuda.empty_cache() if dev == "cuda" else None
95
+ print(f"[{time.time()-t0:6.1f}s] (A) {act} d={d} done", flush=True)
96
+
97
+ # ---- (B) uniform-in-theta BBP + (C) indicator mass ----------------------
98
+ g = torch.Generator(device=dev).manual_seed(11)
99
+ for act in ("quad", "trunc"):
100
+ for d in (256, 1024):
101
+ for delta in (4.0, 16.0, 64.0):
102
+ n = int(round(delta * d))
103
+ for M in ([8.0] if act == "quad" else [4.0, 8.0, 16.0]):
104
+ data = sim.make_data(d, n, 77 * d + int(delta), act, M, dev, torch.float32)
105
+ thetas = {}
106
+ for k in range(args.n_theta):
107
+ v = torch.randn(d, generator=g, device=dev, dtype=torch.float32)
108
+ thetas[f"random{k}"] = v / v.norm()
109
+ thetas["theta_star"] = data.theta_star
110
+ thetas["adversarial"] = adversarial_theta(data, M)
111
+ for name, th in thetas.items():
112
+ A = A_theta(data, th, act, M).double()
113
+ l1, l2, v1 = top2(A)
114
+ ov = float((v1 @ data.theta_star.double()) ** 2)
115
+ rows_b.append(dict(act=act, d=d, delta=delta, n=n, M=M,
116
+ theta=name, lam1=round(l1, 6),
117
+ lam2=round(l2, 6), gap=round(l1 - l2, 6),
118
+ sq_overlap_v1=round(ov, 6)))
119
+ z = data.X @ th
120
+ mass = float((z * z > M).to(torch.float64).mean())
121
+ bound = math.exp(-M / 2) + math.sqrt(d / n) * math.log(n / d)
122
+ rows_c.append(dict(act=act, d=d, delta=delta, n=n, M=M,
123
+ theta=name, mass=round(mass, 8),
124
+ bound_base=round(bound, 8),
125
+ ratio=round(mass / bound, 6)))
126
+ del A
127
+ del data
128
+ torch.cuda.empty_cache() if dev == "cuda" else None
129
+ print(f"[{time.time()-t0:6.1f}s] (B/C) {act} d={d} done", flush=True)
130
+
131
+ for rows, name in ((rows_a, "spectrum"), (rows_b, "uniform_bbp"), (rows_c, "indicator")):
132
+ path = f"{args.out_prefix}_{name}.csv"
133
+ with open(path, "w", newline="") as f:
134
+ w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
135
+ w.writeheader()
136
+ w.writerows(rows)
137
+ print("wrote", path, len(rows), "rows")
138
+
139
+
140
+ if __name__ == "__main__":
141
+ main()
scripts/sweep_online_sgd.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One-pass (online) spherical SGD baseline on the correlation loss.
2
+
3
+ Ben Arous et al. (2021), Thm 1.4: for information exponent 2 activations, one-pass
4
+ SGD with the largest stable step size eta ~ 1/d needs n >~ d log d samples for weak
5
+ recovery. This is the baseline that Claims 2/5 of arXiv:2602.02431 separate from.
6
+
7
+ Each replica sees every sample exactly once, so a single run of length n_max also
8
+ gives the overlap for every smaller n -> the whole delta-curve comes from one pass.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import csv
15
+ import math
16
+ import os
17
+ import sys
18
+ import time
19
+
20
+ import torch
21
+
22
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23
+ import sim
24
+
25
+
26
+ def main():
27
+ p = argparse.ArgumentParser()
28
+ p.add_argument("--act", default="trunc", choices=["quad", "trunc", "smooth"])
29
+ p.add_argument("--dims", default="64,128,256,512,1024,2048,4096,8192")
30
+ p.add_argument("--seeds", type=int, default=32)
31
+ p.add_argument("--M", type=float, default=8.0)
32
+ p.add_argument("--eta-cs", default="0.025,0.05,0.1,0.2",
33
+ help="grid of step sizes eta = c/d (the c values)")
34
+ p.add_argument("--delta-max-mult", type=float, default=6.0,
35
+ help="delta_max = mult * log(d)")
36
+ p.add_argument("--n-checkpoints", type=int, default=60)
37
+ p.add_argument("--out", required=True)
38
+ args = p.parse_args()
39
+
40
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
41
+ dims = [int(v) for v in args.dims.split(",")]
42
+ rows = []
43
+ t_start = time.time()
44
+ for d in dims:
45
+ dmax = args.delta_max_mult * math.log(d)
46
+ deltas = [round(dmax * (i + 1) / args.n_checkpoints, 4) for i in range(args.n_checkpoints)]
47
+ cps = sorted({max(1, int(round(dl * d))) for dl in deltas})
48
+ n_max = cps[-1]
49
+ chunk = max(128, min(2048, (1 << 23) // (d * args.seeds)))
50
+ for c in [float(v) for v in args.eta_cs.split(",")]:
51
+ eta = c / d
52
+ t0 = time.time()
53
+ out = sim.online_sgd(
54
+ d, n_max, args.seeds, args.act, args.M, eta, 4242 + d, dev,
55
+ torch.float32, cps, chunk=chunk,
56
+ )
57
+ for n_used, ov in out.items():
58
+ rows.append(dict(act=args.act, d=d, n=n_used, delta=round(n_used / d, 4),
59
+ eta_c=c, eta=eta, seeds=args.seeds,
60
+ sq_overlap=round(ov, 6)))
61
+ print(f"[{time.time()-t_start:7.1f}s] d={d:5d} n_max={n_max} eta={eta:.3g} "
62
+ f"(c={c}) final ov2={out[cps[-1]]:.4f} ({time.time()-t0:.1f}s)", flush=True)
63
+
64
+ with open(args.out, "w", newline="") as f:
65
+ w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
66
+ w.writeheader()
67
+ w.writerows(rows)
68
+ print(f"wrote {args.out} ({len(rows)} rows, {time.time()-t_start:.1f}s)")
69
+
70
+
71
+ if __name__ == "__main__":
72
+ main()
scripts/sweep_spherical.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Full-batch spherical GD on the correlation loss: overlap vs delta = n/d.
2
+
3
+ Reproduces Figures 1a/1b of arXiv:2602.02431 (paper #26332).
4
+ quad -> Theorem 3.1 (Claim 1): threshold delta grows with log d
5
+ trunc -> Theorem 3.2 (Claims 2/5): threshold delta is d-independent
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import csv
12
+ import math
13
+ import os
14
+ import sys
15
+ import time
16
+
17
+ import torch
18
+
19
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
20
+ import sim
21
+
22
+
23
+ def a_star_chunked(X, y, chunk=16384):
24
+ n, d = X.shape
25
+ A = torch.zeros(d, d, device=X.device, dtype=X.dtype)
26
+ for i in range(0, n, chunk):
27
+ Xi = X[i : i + chunk]
28
+ A += Xi.T @ (y[i : i + chunk, None] * Xi)
29
+ return (2.0 / n) * A
30
+
31
+
32
+ def top2(A):
33
+ """Top two eigenvalues + top eigenvector.
34
+
35
+ Full eigendecomposition is faster than LOBPCG below d ~ 3000 (LOBPCG is
36
+ kernel-launch bound at small d); above that we fall back to LOBPCG with k=2.
37
+ """
38
+ d = A.shape[0]
39
+ if d <= 3000:
40
+ ev, evec = torch.linalg.eigh(A.double())
41
+ return float(ev[-1]), float(ev[-2]), evec[:, -1]
42
+ try:
43
+ vals, vecs = torch.lobpcg(A.double(), k=2, largest=True, niter=400, tol=1e-10)
44
+ return float(vals[0]), float(vals[1]), vecs[:, 0]
45
+ except Exception:
46
+ ev, evec = torch.linalg.eigh(A.double())
47
+ return float(ev[-1]), float(ev[-2]), evec[:, -1]
48
+
49
+
50
+ def main():
51
+ p = argparse.ArgumentParser()
52
+ p.add_argument("--act", default="trunc", choices=["quad", "trunc", "smooth"])
53
+ p.add_argument("--dims", default="64,128,256,512,1024,2048,4096")
54
+ p.add_argument("--delta-min", type=float, default=0.5)
55
+ p.add_argument("--delta-max", type=float, default=11.0)
56
+ p.add_argument("--delta-step", type=float, default=0.5)
57
+ p.add_argument("--seeds", default="32,32,32,16,16,8,8", help="per dim")
58
+ p.add_argument("--M", type=float, default=8.0)
59
+ p.add_argument("--eta", type=float, default=0.1)
60
+ p.add_argument("--T", type=int, default=3000, help="steps for non-quad activations")
61
+ p.add_argument("--spectrum", action="store_true", help="also record lam1/lam2/v1(A*)")
62
+ p.add_argument("--out", required=True)
63
+ args = p.parse_args()
64
+
65
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
66
+ dims = [int(v) for v in args.dims.split(",")]
67
+ seeds = [int(v) for v in args.seeds.split(",")]
68
+ assert len(seeds) == len(dims)
69
+ deltas = [
70
+ round(args.delta_min + i * args.delta_step, 4)
71
+ for i in range(int(round((args.delta_max - args.delta_min) / args.delta_step)) + 1)
72
+ ]
73
+ print(f"device={dev} act={args.act} dims={dims} seeds={seeds} deltas={deltas}", flush=True)
74
+
75
+ rows = []
76
+ t_start = time.time()
77
+ for d, ns in zip(dims, seeds):
78
+ # quadratic: A* is constant along the flow -> iterate on the d x d matrix (exact,
79
+ # and far cheaper); truncated: A(theta) is time-varying -> matrix-free matvecs.
80
+ use_matrix = args.act == "quad"
81
+ T = sim.log2_steps(d) if use_matrix else args.T
82
+ for delta in deltas:
83
+ n = int(round(delta * d))
84
+ for s in range(ns):
85
+ seed = 1000 * d + 7 * s + int(delta * 2)
86
+ t0 = time.time()
87
+ data = sim.make_data(d, n, seed, args.act, args.M, dev, torch.float32)
88
+ lam1 = lam2 = ov_v1 = float("nan")
89
+ if use_matrix or args.spectrum:
90
+ A = a_star_chunked(data.X, data.y).double()
91
+ lam1, lam2, v1 = top2(A)
92
+ ov_v1 = float((v1 @ data.theta_star.double()) ** 2)
93
+ th0 = sim.rand_sphere(d, 500_000 + seed, dev, torch.float32)
94
+ if use_matrix:
95
+ dd = sim.Data(data.X, data.y, data.theta_star.double())
96
+ theta = th0.double()
97
+ ts = dd.theta_star
98
+ prev_r = prev_o = None
99
+ steps = T
100
+ for t in range(T):
101
+ Ath = A @ theta
102
+ ray = theta @ Ath
103
+ grad = Ath - ray * theta
104
+ theta = theta + args.eta * grad
105
+ theta = theta / theta.norm()
106
+ if (t + 1) % 200 == 0:
107
+ r, o = float(ray), float((theta @ ts) ** 2)
108
+ if (
109
+ prev_r is not None
110
+ and abs(r - prev_r) <= 1e-13 * abs(r)
111
+ and abs(o - prev_o) <= 1e-13
112
+ ):
113
+ steps = t + 1
114
+ break
115
+ prev_r, prev_o = r, o
116
+ ov = float((theta @ ts) ** 2)
117
+ else:
118
+ theta, steps, _ = sim.spherical_flow(
119
+ data, th0, args.act, args.M, eta=args.eta, T=T,
120
+ tol=0.0, check_every=10 ** 9,
121
+ )
122
+ ov = float((theta @ data.theta_star) ** 2)
123
+ rows.append(
124
+ dict(act=args.act, d=d, delta=delta, n=n, seed=seed, M=args.M,
125
+ eta=args.eta, T=T, steps=steps, sq_overlap=round(ov, 6),
126
+ lam1=lam1, lam2=lam2, sq_overlap_v1Astar=ov_v1,
127
+ secs=round(time.time() - t0, 3))
128
+ )
129
+ del data
130
+ if use_matrix or args.spectrum:
131
+ del A
132
+ torch.cuda.empty_cache() if dev == "cuda" else None
133
+ m = [r["sq_overlap"] for r in rows if r["d"] == d and r["delta"] == delta]
134
+ print(
135
+ f"[{time.time()-t_start:7.1f}s] d={d:5d} delta={delta:5.1f} "
136
+ f"mean ov2={sum(m)/len(m):.4f} (n={n}, {ns} seeds)",
137
+ flush=True,
138
+ )
139
+
140
+ with open(args.out, "w", newline="") as f:
141
+ w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
142
+ w.writeheader()
143
+ w.writerows(rows)
144
+ print(f"wrote {args.out} ({len(rows)} rows, {time.time()-t_start:.1f}s)")
145
+
146
+
147
+ if __name__ == "__main__":
148
+ main()
scripts/sweep_squared_gd.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Full-batch Euclidean GD on the squared loss from small initialisation.
2
+
3
+ Reproduces Figures 2a/2b/2c of arXiv:2602.02431 and audits Theorem 4.1 (Claim 3)
4
+ and the two-phase trajectory decomposition of Section 4 (Claim 4).
5
+
6
+ sigma(z) = min(z^2, M), M = 8, eta = 0.1 / M^2, delta = n/d = 10,
7
+ theta_0 ~ Unif(r0 * S^{d-1}), r0 in {d^-2 (paper figures), d^-15 (Theorem 4.1)}.
8
+
9
+ All runs are float64 so that r0 = d^-15 (down to ~1e-54) does not underflow.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import csv
16
+ import json
17
+ import math
18
+ import os
19
+ import sys
20
+ import time
21
+
22
+ import torch
23
+
24
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
25
+ import sim
26
+
27
+
28
+ def main():
29
+ p = argparse.ArgumentParser()
30
+ p.add_argument("--act", default="trunc", choices=["quad", "trunc", "smooth"])
31
+ p.add_argument("--dims", default="64,128,256,512,1024,2048,4096")
32
+ p.add_argument("--seeds", default="8", help="int, or one value per dim")
33
+ p.add_argument("--M", type=float, default=8.0)
34
+ p.add_argument("--delta", type=float, default=10.0)
35
+ p.add_argument("--eta-c", type=float, default=0.1, help="eta = c / M^2")
36
+ p.add_argument("--r0-exp", type=float, default=2.0, help="r0 = d^-exp")
37
+ p.add_argument("--T", type=int, default=6000)
38
+ p.add_argument("--record-every", type=int, default=5)
39
+ p.add_argument("--stop-err", type=float, default=1e-13)
40
+ p.add_argument("--out-prefix", required=True)
41
+ args = p.parse_args()
42
+
43
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
44
+ dims = [int(v) for v in args.dims.split(",")]
45
+ seed_list = [int(v) for v in args.seeds.split(",")]
46
+ if len(seed_list) == 1:
47
+ seed_list = seed_list * len(dims)
48
+ assert len(seed_list) == len(dims)
49
+ eta = args.eta_c / (args.M ** 2)
50
+ traj_rows, summ_rows = [], []
51
+ t_start = time.time()
52
+ for d, nseeds in zip(dims, seed_list):
53
+ n = int(round(args.delta * d))
54
+ r0 = float(d) ** (-args.r0_exp)
55
+ for s in range(nseeds):
56
+ seed = 90000 + 137 * d + s
57
+ t0 = time.time()
58
+ data = sim.make_data(d, n, seed, args.act, args.M, dev, torch.float64)
59
+ th0 = sim.rand_sphere(d, 800_000 + seed, dev, torch.float64) * r0
60
+ rec = sim.squared_gd(
61
+ data, th0, args.act, args.M, eta, args.T,
62
+ record_every=args.record_every, stop_err=args.stop_err,
63
+ )
64
+ for i in range(len(rec["step"])):
65
+ traj_rows.append(dict(
66
+ act=args.act, d=d, delta=args.delta, M=args.M, eta=eta,
67
+ r0_exp=args.r0_exp, seed=seed, step=rec["step"][i],
68
+ sq_overlap=rec["sq_overlap"][i], norm=rec["norm"][i],
69
+ dist2=rec["dist2"][i], loss=rec["loss"][i]))
70
+ summ_rows.append(dict(
71
+ act=args.act, d=d, n=n, delta=args.delta, M=args.M, eta=eta,
72
+ r0_exp=args.r0_exp, r0=r0, seed=seed,
73
+ steps_run=rec["step"][-1], final_sq_overlap=rec["sq_overlap"][-1],
74
+ final_norm=rec["norm"][-1], final_dist2=rec["dist2"][-1],
75
+ final_loss=rec["loss"][-1], secs=round(time.time() - t0, 2)))
76
+ del data
77
+ torch.cuda.empty_cache() if dev == "cuda" else None
78
+ fin = [r["final_dist2"] for r in summ_rows if r["d"] == d]
79
+ stp = [r["steps_run"] for r in summ_rows if r["d"] == d]
80
+ print(f"[{time.time()-t_start:7.1f}s] d={d:5d} n={n} r0={r0:.3e} "
81
+ f"median dist2={sorted(fin)[len(fin)//2]:.3e} median steps={sorted(stp)[len(stp)//2]}",
82
+ flush=True)
83
+
84
+ with open(args.out_prefix + "_traj.csv", "w", newline="") as f:
85
+ w = csv.DictWriter(f, fieldnames=list(traj_rows[0].keys()))
86
+ w.writeheader()
87
+ w.writerows(traj_rows)
88
+ with open(args.out_prefix + "_summary.csv", "w", newline="") as f:
89
+ w = csv.DictWriter(f, fieldnames=list(summ_rows[0].keys()))
90
+ w.writeheader()
91
+ w.writerows(summ_rows)
92
+ print(f"wrote {args.out_prefix}_{{traj,summary}}.csv "
93
+ f"({len(traj_rows)} traj rows, {time.time()-t_start:.1f}s)")
94
+
95
+
96
+ if __name__ == "__main__":
97
+ main()
scripts/thm32_bound.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Quantitative audit of the Theorem 3.2 guarantee (Claim 2).
2
+
3
+ lim_t |<theta(t), theta*>| >= 1 - C (e^{-M/2} + (d/n)^{1/5}), n >= C M^4 d.
4
+
5
+ We run the full-batch spherical flow with the truncated activation on a grid of
6
+ (M, delta = n/d) at fixed d, and report the realised deficit 1 - |<theta_inf, theta*>|
7
+ against the theorem's rate e^{-M/2} + (d/n)^{1/5}. A single constant C should
8
+ dominate the whole grid inside the theorem's regime delta >= C M^4.
9
+ Also includes the M -> small control, where the guarantee degrades as predicted.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import csv
16
+ import math
17
+ import os
18
+ import sys
19
+ import time
20
+
21
+ import torch
22
+
23
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
24
+ import sim
25
+
26
+
27
+ def main():
28
+ p = argparse.ArgumentParser()
29
+ p.add_argument("--d", type=int, default=512)
30
+ p.add_argument("--Ms", default="1,2,4,8,16,32")
31
+ p.add_argument("--deltas", default="8,16,32,64,128,256")
32
+ p.add_argument("--seeds", type=int, default=8)
33
+ p.add_argument("--act", default="trunc", choices=["trunc", "smooth", "quad"])
34
+ p.add_argument("--eta", type=float, default=0.1)
35
+ p.add_argument("--T", type=int, default=3000)
36
+ p.add_argument("--out", required=True)
37
+ args = p.parse_args()
38
+
39
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
40
+ Ms = [float(v) for v in args.Ms.split(",")]
41
+ deltas = [float(v) for v in args.deltas.split(",")]
42
+ d = args.d
43
+ rows = []
44
+ t0 = time.time()
45
+ for M in Ms:
46
+ for delta in deltas:
47
+ n = int(round(delta * d))
48
+ for s in range(args.seeds):
49
+ seed = 5000 + 31 * s + int(delta) + int(100 * M)
50
+ data = sim.make_data(d, n, seed, args.act, M, dev, torch.float32)
51
+ th0 = sim.rand_sphere(d, 600_000 + seed, dev, torch.float32)
52
+ th, steps, _ = sim.spherical_flow(data, th0, args.act, M, eta=args.eta,
53
+ T=args.T, tol=0.0, check_every=10 ** 9)
54
+ ov = abs(float(th @ data.theta_star))
55
+ rate = math.exp(-M / 2) + (d / n) ** 0.2
56
+ rows.append(dict(act=args.act, d=d, M=M, delta=delta, n=n, seed=seed,
57
+ abs_overlap=round(ov, 6), deficit=round(1 - ov, 6),
58
+ rate=round(rate, 6),
59
+ C_implied=round((1 - ov) / rate, 6),
60
+ in_regime=int(delta >= M ** 4 / 100)))
61
+ del data
62
+ torch.cuda.empty_cache() if dev == "cuda" else None
63
+ sub = [r["deficit"] for r in rows if r["M"] == M and r["delta"] == delta]
64
+ print(f"[{time.time()-t0:6.1f}s] M={M:5.1f} delta={delta:6.1f} "
65
+ f"mean deficit={sum(sub)/len(sub):.4f}", flush=True)
66
+
67
+ with open(args.out, "w", newline="") as f:
68
+ w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
69
+ w.writeheader()
70
+ w.writerows(rows)
71
+ print("wrote", args.out, len(rows), "rows")
72
+
73
+
74
+ if __name__ == "__main__":
75
+ main()