File size: 9,809 Bytes
1f48ccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""Render poster PNGs (3200x2000, aspect 1.6) from the reproduction CSVs."""

from __future__ import annotations

import math
import os

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from analyze import linfit

RES, OUT = "results", "images"
os.makedirs(OUT, exist_ok=True)

ACC = "#1f4e79"
ACC2 = "#c2410c"
GOLD = "#b45309"
GREY = "#6b7280"
CMAP = plt.get_cmap("plasma")

plt.rcParams.update({
    "font.size": 26, "axes.labelsize": 30, "axes.titlesize": 32,
    "legend.fontsize": 24, "xtick.labelsize": 25, "ytick.labelsize": 25,
    "axes.linewidth": 2.2, "lines.linewidth": 4.0, "grid.alpha": 0.28,
    "figure.dpi": 200, "savefig.bbox": "tight", "savefig.pad_inches": 0.25,
})
FS = (16, 10)
FS_WIDE = (17.6, 8.0)


def _dcolors(dims):
    return {d: CMAP(0.06 + 0.82 * i / max(len(dims) - 1, 1)) for i, d in enumerate(dims)}


def fig_overlap(act, title, fname, annotate=None):
    a = pd.read_csv(f"{RES}/agg_{act}.csv")
    dims = sorted(a["d"].unique())
    cols = _dcolors(dims)
    fig, ax = plt.subplots(figsize=FS)
    for d in dims:
        s = a[a["d"] == d].sort_values("delta")
        ax.plot(s["delta"], s["mean"], "-o", ms=8, color=cols[d], label=f"d={d}")
    ax.set_xlabel(r"$\delta = n/d$")
    ax.set_ylabel(r"squared overlap $\langle\theta^\star,\hat\theta\rangle^2$")
    ax.set_title(title, pad=14)
    ax.grid(True, ls=":")
    ax.legend(ncol=2, frameon=False, loc="lower right")
    if annotate:
        ax.annotate(annotate, xy=(0.03, 0.95), xycoords="axes fraction", va="top",
                    fontsize=26, color=ACC2, weight="bold")
    fig.savefig(f"{OUT}/{fname}", dpi=200)
    plt.close(fig)


def fig_separation():
    t = pd.read_csv(f"{RES}/thresholds.csv")
    fig, ax = plt.subplots(figsize=(16, 10.6))
    combos = [("one-pass-sgd", "trunc", "one-pass SGD, truncated", ACC2, "o"),
              ("full-batch", "quad", "full-batch GD, quadratic", GOLD, "s"),
              ("full-batch", "trunc", "full-batch GD, truncated", ACC, "D")]
    for meth, act, lab, col, mk in combos:
        s = t[(t["method"] == meth) & (t["act"] == act) & (t["target"] == 0.3)].sort_values("logd")
        s = s[np.isfinite(s["value"])]
        f = linfit(s["logd"], s["value"])
        ax.plot(s["logd"], s["value"], mk, ms=16, color=col,
                label=f"{lab} — slope {f['slope']:.2f}")
        xs = np.linspace(s["logd"].min(), s["logd"].max(), 10)
        ax.plot(xs, f["intercept"] + f["slope"] * xs, "-", color=col, lw=3.5, alpha=0.8)
    ax.set_xlabel(r"$\log d$")
    ax.set_ylabel(r"threshold $\delta = n/d$ for overlap$^2 = 0.3$")
    ax.set_title("Sample complexity: full-batch removes the $\\log d$ factor", pad=14)
    ax.grid(True, ls=":")
    ax.legend(frameon=False, loc="upper left")
    fig.savefig(f"{OUT}/pf_separation.png", dpi=200)
    plt.close(fig)


def fig_strong():
    a = pd.read_csv(f"{RES}/agg_gd_trunc_r2.csv")
    dims = sorted(a["d"].unique())
    cols = _dcolors(dims)
    fig, ax = plt.subplots(figsize=FS_WIDE)
    for d in dims:
        s = a[a["d"] == d].sort_values("step")
        ax.semilogy(s["step"], np.maximum(s["dist2"], 1e-13), color=cols[d], label=f"d={d}")
    ax.set_xlabel("GD step $t$")
    ax.set_ylabel(r"$\|\theta_t-\theta^\star\|^2$")
    ax.set_title(r"Strong recovery: geometric convergence after the search phase", pad=14)
    ax.grid(True, ls=":", which="both")
    ax.legend(ncol=2, frameon=False, loc="upper right")
    fig.savefig(f"{OUT}/pf_strong.png", dpi=200)
    plt.close(fig)


def fig_two_phase():
    a = pd.read_csv(f"{RES}/agg_gd_trunc_r2.csv")
    ph = pd.read_csv(f"{RES}/gd_phases.csv").groupby("d").median(numeric_only=True)
    d = 1024 if 1024 in set(a["d"]) else sorted(a["d"])[-1]
    s = a[a["d"] == d].sort_values("step")
    tb = float(ph.loc[d, "tbar"])
    fig, ax = plt.subplots(figsize=FS_WIDE)
    ax.plot(s["step"], s["norm"], color=ACC, label=r"$\|\theta_t\|$")
    ax.plot(s["step"], s["sq_overlap"], color=ACC2, label=r"overlap$^2$")
    ax.axvline(tb, color="#374151", ls="--", lw=3)
    ax.axvspan(0, tb, color=GOLD, alpha=0.09)
    ax.text(tb * 0.5, 0.55, "Phase 1\nangle ↓, norm ↑", ha="center", fontsize=26, color=GOLD)
    ax.text(tb * 1.35, 0.30, "Phase 2\ngeometric", ha="left", fontsize=26, color=ACC)
    ax2 = ax.twinx()
    ax2.semilogy(s["step"], np.maximum(s["dist2"], 1e-13), color=GREY, ls=":", lw=3.5,
                 label=r"$\|\theta_t-\theta^\star\|^2$")
    ax2.set_ylabel(r"$\|\theta_t-\theta^\star\|^2$", color=GREY)
    ax.set_xlim(0, min(float(s["step"].max()), tb * 2.6))
    ax.set_xlabel("GD step $t$")
    ax.set_ylabel(r"$\|\theta_t\|$  /  overlap$^2$")
    ax.set_title(f"Two-phase trajectory (d={d}, $\\bar t\\approx${tb:.0f})", pad=14)
    ax.grid(True, ls=":")
    ax.legend(frameon=False, loc="center right")
    fig.savefig(f"{OUT}/pf_two_phase.png", dpi=200)
    plt.close(fig)


def fig_time():
    t = pd.read_csv(f"{RES}/gd_time_thresholds.csv")
    ph = pd.read_csv(f"{RES}/gd_phases.csv").groupby("d").median(numeric_only=True).reset_index()
    fig, ax = plt.subplots(figsize=FS)
    tg = sorted(t["target"].unique())
    for i, g in enumerate(tg):
        s = t[t["target"] == g].sort_values("logd")
        f = linfit(s["logd"], s["value"])
        c = CMAP(0.08 + 0.75 * i / max(len(tg) - 1, 1))
        ax.plot(s["logd"], s["value"], "o", ms=14, color=c,
                label=f"overlap$^2$={g} ($R^2$={f['r2']:.2f})")
        xs = np.linspace(s["logd"].min(), s["logd"].max(), 10)
        ax.plot(xs, f["intercept"] + f["slope"] * xs, "-", color=c, lw=3, alpha=0.85)
    f = linfit(np.log(ph["d"]), ph["tbar"])
    ax.plot(np.log(ph["d"]), ph["tbar"], "k^--", ms=15, lw=3,
            label=f"$\\bar t$ (phase 1 end), $R^2$={f['r2']:.2f}")
    ax.set_xlabel(r"$\log d$")
    ax.set_ylabel("GD steps")
    ax.set_title(r"Iteration complexity grows like $\log d$", pad=14)
    ax.grid(True, ls=":")
    ax.legend(frameon=False, loc="upper left", ncol=2)
    fig.savefig(f"{OUT}/pf_time.png", dpi=200)
    plt.close(fig)


def fig_spectrum():
    a = pd.read_csv(f"{RES}/audit_spectrum.csv")
    fig, ax = plt.subplots(figsize=FS)
    q = a[(a["act"] == "quad")].groupby(["d", "delta"])[["lam1", "lam2"]].mean().reset_index()
    tr = a[(a["act"] == "trunc") & (a["M"] == 8.0)].groupby(["d", "delta"])[["lam1", "lam2"]] \
          .mean().reset_index()
    dims = sorted(set(q["d"]) & set(tr["d"]))
    cols = _dcolors(dims)
    for d in dims:
        s = q[q["d"] == d].sort_values("delta")
        ax.plot(s["delta"], s["lam1"], "--o", ms=9, color=cols[d], alpha=0.85)
        s = tr[tr["d"] == d].sort_values("delta")
        ax.plot(s["delta"], s["lam1"], "-D", ms=9, color=cols[d])
    ax.axhline(6, color="#111", ls=":", lw=3)
    ax.text(a["delta"].max() * 0.55, 6.4, r"population $\lambda_1=6$", fontsize=25)
    ax.set_xscale("log")
    ax.set_yscale("log")
    ax.set_xlabel(r"$\delta = n/d$")
    ax.set_ylabel(r"$\lambda_1(A^\star)$")
    ax.set_title(r"BBP spike survives only under truncation (solid) — quadratic (dashed) diverges",
                 pad=14, fontsize=27)
    ax.grid(True, ls=":", which="both")
    hd = [plt.Line2D([], [], color="k", ls="-", marker="D", label="truncated $\\sigma$"),
          plt.Line2D([], [], color="k", ls="--", marker="o", label="quadratic $\\sigma$")]
    hd += [plt.Line2D([], [], color=cols[d], lw=5, label=f"d={d}") for d in dims]
    ax.legend(handles=hd, frameon=False, ncol=2, loc="upper right")
    fig.savefig(f"{OUT}/pf_spectrum.png", dpi=200)
    plt.close(fig)


def fig_scorecard():
    rows = [
        ("1", "Quadratic σ: no full-batch gain (Thm 3.1)", "SUPPORTED",
         "δ* ∝ log d, slope 0.65–0.95, R² 0.97–0.99"),
        ("2", "Truncated σ: weak recovery at n ≳ d (Thm 3.2)", "SUPPORTED",
         "curves collapse: spread 0.020 vs 0.126"),
        ("3", "Strong recovery, T ≳ log d (Thm 4.1)", "SUPPORTED",
         "‖θ_T−θ*‖² → 1e-13 at r₀ = d⁻¹⁵"),
        ("4", "Two-phase trajectory (Sec. 4)", "SUPPORTED",
         "t̄ ∝ log d (R² 0.97) and ∝ 1/η; α ≈ 2.7"),
        ("5", "Matches the n ≳ d lower bound (Thm 3.2)", "SUPPORTED",
         "slope 0.04 vs 1.52 for one-pass SGD"),
    ]
    fig, ax = plt.subplots(figsize=FS)
    ax.axis("off")
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    y = 0.90
    ax.text(0.02, 0.985, "Verdict by claim", fontsize=34, weight="bold", color=ACC, va="top")
    for num, name, verdict, ev in rows:
        ax.add_patch(plt.Rectangle((0.015, y - 0.145), 0.97, 0.14, facecolor="#f6f7f9",
                                   edgecolor="#d7dbe0", lw=2))
        ax.add_patch(plt.Rectangle((0.015, y - 0.145), 0.012, 0.14, facecolor=ACC, lw=0))
        ax.text(0.045, y - 0.035, f"Claim {num} · {name}", fontsize=27, weight="bold", va="top")
        ax.text(0.045, y - 0.098, ev, fontsize=24, color="#334155", va="top")
        ax.text(0.965, y - 0.062, verdict, fontsize=26, weight="bold", color="#166534",
                ha="right", va="center")
        y -= 0.165
    ax.text(0.02, 0.055, "5/5 claims reproduced · 2× RTX 4000 Ada · ~5.6 GPU-hours · $0 cloud spend",
            fontsize=25, color=GREY, va="center")
    fig.savefig(f"{OUT}/pf_scorecard.png", dpi=200)
    plt.close(fig)


if __name__ == "__main__":
    fig_overlap("quad", r"Quadratic $\sigma(z)=z^2$: threshold drifts right with $d$",
                "pf_quad.png")
    fig_overlap("trunc", r"Truncated $\sigma(z)=\min(z^2,8)$: curves collapse",
                "pf_trunc.png")
    fig_separation()
    fig_strong()
    fig_two_phase()
    fig_time()
    try:
        fig_spectrum()
    except FileNotFoundError:
        print("skip spectrum (audit not finished)")
    fig_scorecard()
    print("wrote", sorted(os.listdir(OUT)))