File size: 11,506 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
231
232
233
234
235
236
237
"""Analysis + figures for the squared-loss GD trajectories (Claims 3 and 4).

Theorem 4.1:  ||theta_t - theta*||^2 <= C (1 - eta alpha)^{t - tbar},  tbar <= C log d / eta.
Section 4:    phase 1 = angle reduction + norm growth (O(log d / eta) steps),
              phase 2 = geometric refinement.
"""

from __future__ import annotations

import glob
import json
import math
import os

import numpy as np
import pandas as pd
import plotly.graph_objects as go

from analyze import PALETTE, _c, linfit, write_fig, thresholds_fig

RES = "results"


def load(prefix):
    t = pd.read_csv(f"{RES}/{prefix}_traj.csv")
    s = pd.read_csv(f"{RES}/{prefix}_summary.csv")
    return t, s


def mean_traj(t):
    return (t.groupby(["d", "step"])[["sq_overlap", "norm", "dist2", "loss"]]
             .mean().reset_index())


def first_cross(steps, vals, target, above=True):
    steps, vals = np.asarray(steps), np.asarray(vals)
    m = vals >= target if above else vals <= target
    return float(steps[np.argmax(m)]) if m.any() else np.nan


def traj_fig(mt, ycol, title, ytitle, logy=False, hline=None):
    dims = sorted(mt["d"].unique())
    fig = go.Figure()
    for i, d in enumerate(dims):
        s = mt[mt["d"] == d]
        fig.add_trace(go.Scatter(x=s["step"], y=s[ycol], mode="lines", name=f"d={d}",
                                 line=dict(color=_c(i, len(dims)), width=2)))
    if hline is not None:
        fig.add_hline(y=hline, line_dash="dot", line_color="#888")
    fig.update_layout(title=title, xaxis_title="GD step t", yaxis_title=ytitle,
                      template="plotly_white", height=460)
    if logy:
        fig.update_yaxes(type="log")
    return fig


def phase_table(t, eta, targets=(0.9,)):
    rows = []
    for (d, seed), g in t.groupby(["d", "seed"]):
        g = g.sort_values("step")
        st, ov, nr, d2 = (g["step"].values, g["sq_overlap"].values,
                          g["norm"].values, g["dist2"].values)
        t_angle = first_cross(st, ov, 0.9)
        t_norm = first_cross(st, nr, 0.25)
        tbar = np.nanmax([t_angle, t_norm])
        rate = np.nan
        if np.isfinite(tbar):
            m = (st >= tbar) & (d2 > 1e-11) & (d2 < 1e2)
            if m.sum() >= 5:
                b, a = np.polyfit(st[m], np.log(d2[m]), 1)
                rate = float(b)
        rows.append(dict(d=int(d), seed=int(seed), t_angle=t_angle, t_norm=t_norm,
                         tbar=tbar, log_rate_per_step=rate,
                         rho=math.exp(rate) if np.isfinite(rate) else np.nan,
                         alpha_implied=(1 - math.exp(rate)) / eta
                         if np.isfinite(rate) else np.nan,
                         t_star_angle_pred=3 * math.log(d) / math.log(1 + 1.99 * eta)))
    return pd.DataFrame(rows)


def main():
    out = {}
    targets = [0.1, 0.2, 0.3, 0.4, 0.5]

    # ------------------------------------------------ main run: r0 = d^-2 ----
    t, s = load("gd_trunc_r2")
    eta = float(s["eta"].iloc[0])
    mt = mean_traj(t)
    mt.to_csv(f"{RES}/agg_gd_trunc_r2.csv", index=False)
    write_fig(traj_fig(mt, "sq_overlap",
                       "Squared-loss full-batch GD — overlap vs steps (truncated σ, M=8, δ=10)",
                       "Squared overlap ⟨θ*, θ̂⟩²"), "gd_overlap")
    write_fig(traj_fig(mt, "norm",
                       "Squared-loss full-batch GD — ‖θ_t‖ vs steps (truncated σ, M=8, δ=10)",
                       "‖θ_t‖", hline=1.0), "gd_norm")
    write_fig(traj_fig(mt, "dist2",
                       "Strong recovery: ‖θ_t − θ*‖² vs steps (truncated σ, M=8, δ=10)",
                       "‖θ_t − θ*‖²", logy=True), "gd_dist2")

    thr = []
    for d in sorted(mt["d"].unique()):
        g = mt[mt["d"] == d].sort_values("step")
        for tg in targets:
            thr.append(dict(target=tg, d=int(d), logd=math.log(d),
                            value=first_cross(g["step"], g["sq_overlap"], tg)))
    tdf = pd.DataFrame(thr)
    tdf.to_csv(f"{RES}/gd_time_thresholds.csv", index=False)
    write_fig(thresholds_fig(thr, "Iteration complexity vs log d — full-batch GD, squared loss",
                             ytitle="GD steps T to reach target overlap"), "gd_T_vs_logd")
    out["T_vs_logd_fits"] = [
        dict(target=tg, **linfit(tdf[tdf["target"] == tg]["logd"],
                                 tdf[tdf["target"] == tg]["value"]))
        for tg in targets]

    ph = phase_table(t, eta)
    ph.to_csv(f"{RES}/gd_phases.csv", index=False)
    phm = ph.groupby("d").median(numeric_only=True).reset_index()
    phm["logd"] = np.log(phm["d"])
    out["eta"] = eta
    out["phases_median"] = phm.to_dict("records")
    out["tbar_vs_logd"] = linfit(phm["logd"], phm["tbar"])
    out["alpha_implied"] = dict(median=float(phm["alpha_implied"].median()),
                                min=float(phm["alpha_implied"].min()),
                                max=float(phm["alpha_implied"].max()))
    out["final"] = s.groupby("d")[["final_dist2", "final_sq_overlap", "final_norm",
                                   "final_loss"]].median().reset_index().to_dict("records")

    # phase figure: two-phase decomposition for one dimension
    dsel = 1024 if 1024 in set(mt["d"]) else sorted(mt["d"])[-1]
    g = mt[mt["d"] == dsel].sort_values("step")
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=g["step"], y=g["norm"], name="‖θ_t‖",
                             line=dict(color=PALETTE[1], width=2)))
    fig.add_trace(go.Scatter(x=g["step"], y=g["sq_overlap"], name="⟨θ*, θ̂⟩²",
                             line=dict(color=PALETTE[5], width=2)))
    fig.add_trace(go.Scatter(x=g["step"], y=g["dist2"], name="‖θ_t − θ*‖²",
                             line=dict(color=PALETTE[3], width=2, dash="dot"),
                             yaxis="y2"))
    tb = float(phm[phm["d"] == dsel]["tbar"].iloc[0])
    fig.add_vline(x=tb, line_dash="dash", line_color="#444",
                  annotation_text=f"t̄ ≈ {tb:.0f}", annotation_position="top")
    fig.update_layout(
        title=f"Two-phase trajectory (d={dsel}): angle reduction + norm growth, then geometric refinement",
        xaxis_title="GD step t", yaxis_title="overlap² / ‖θ_t‖",
        yaxis2=dict(title="‖θ_t − θ*‖²", overlaying="y", side="right", type="log"),
        template="plotly_white", height=470)
    write_fig(fig, "gd_two_phase")

    # ------------------------------------------------ r0 = d^-15 (Theorem) --
    if os.path.exists(f"{RES}/gd_trunc_r15_traj.csv"):
        t15, s15 = load("gd_trunc_r15")
        mt15 = mean_traj(t15)
        mt15.to_csv(f"{RES}/agg_gd_trunc_r15.csv", index=False)
        write_fig(traj_fig(mt15, "norm",
                           "Theorem 4.1 initialisation r₀ = d⁻¹⁵ — norm growth",
                           "‖θ_t‖", logy=True), "gd_norm_r15")
        thr15 = []
        for d in sorted(mt15["d"].unique()):
            g = mt15[mt15["d"] == d].sort_values("step")
            for tg in targets:
                thr15.append(dict(target=tg, d=int(d), logd=math.log(d),
                                  value=first_cross(g["step"], g["sq_overlap"], tg)))
        write_fig(thresholds_fig(thr15, "Iteration complexity vs log d — r₀ = d⁻¹⁵",
                                 ytitle="GD steps T to reach target overlap"),
                  "gd_T_vs_logd_r15")
        pd.DataFrame(thr15).to_csv(f"{RES}/gd_time_thresholds_r15.csv", index=False)
        out["r15_T_vs_logd_fits"] = [
            dict(target=tg, **linfit([r["logd"] for r in thr15 if r["target"] == tg],
                                     [r["value"] for r in thr15 if r["target"] == tg]))
            for tg in targets]
        ph15 = phase_table(t15, float(s15["eta"].iloc[0]))
        ph15.to_csv(f"{RES}/gd_phases_r15.csv", index=False)
        out["r15_phases_median"] = (ph15.groupby("d").median(numeric_only=True)
                                    .reset_index().to_dict("records"))
        out["r15_final"] = s15.groupby("d")[["final_dist2", "final_sq_overlap"]] \
            .median().reset_index().to_dict("records")

    # ------------------------------------------------ eta scaling (Claim 4) --
    eta_rows = []
    for path in sorted(glob.glob(f"{RES}/gd_trunc_eta*_summary.csv")) + \
            [f"{RES}/gd_trunc_r2_summary.csv"]:
        pre = path.replace("_summary.csv", "").split("/")[-1]
        tt, ss = load(pre)
        e = float(ss["eta"].iloc[0])
        p = phase_table(tt, e).groupby("d").median(numeric_only=True).reset_index()
        for r in p.itertuples():
            eta_rows.append(dict(eta=e, d=int(r.d), tbar=r.tbar,
                                 tbar_times_eta=r.tbar * e,
                                 alpha_implied=r.alpha_implied))
    if eta_rows:
        edf = pd.DataFrame(eta_rows)
        edf.to_csv(f"{RES}/gd_eta_scaling.csv", index=False)
        fig = go.Figure()
        for i, d in enumerate(sorted(edf["d"].unique())):
            s2 = edf[edf["d"] == d].sort_values("eta")
            fig.add_trace(go.Scatter(x=1 / s2["eta"], y=s2["tbar"], mode="lines+markers",
                                     name=f"d={d}", line=dict(color=_c(i, edf["d"].nunique()))))
        fig.update_layout(title="Phase-1 length t̄ scales as 1/η (fixed d, δ=10)",
                          xaxis_title="1/η", yaxis_title="t̄ (steps)",
                          template="plotly_white", height=440)
        write_fig(fig, "gd_tbar_vs_eta")
        out["eta_scaling"] = edf.to_dict("records")

    # ------------------------------------------------ control: quadratic ----
    if os.path.exists(f"{RES}/gd_quad_r2_summary.csv"):
        _, sq = load("gd_quad_r2")
        out["control_quad_final"] = (sq.groupby("d")[["final_dist2", "final_sq_overlap",
                                                      "final_norm", "final_loss"]]
                                     .median().reset_index().to_dict("records"))
        cmp_rows = []
        for act, dfx in (("trunc", s), ("quad", sq)):
            for r in (dfx.groupby("d")[["final_dist2"]].median().reset_index()).itertuples():
                cmp_rows.append(dict(act=act, d=int(r.d), final_dist2=float(r.final_dist2)))
        cdf = pd.DataFrame(cmp_rows)
        fig = go.Figure()
        for i, act in enumerate(["trunc", "quad"]):
            s2 = cdf[cdf["act"] == act].sort_values("d")
            fig.add_trace(go.Bar(x=[str(int(v)) for v in s2["d"]], y=s2["final_dist2"],
                                 name={"trunc": "truncated σ (Thm 4.1)",
                                       "quad": "untruncated σ(z)=z² (control)"}[act],
                                 marker_color=PALETTE[1 if act == "trunc" else 5]))
        fig.update_layout(title="Strong recovery control: final ‖θ_T − θ*‖² at δ=10, T=6000",
                          xaxis_title="d", yaxis_title="‖θ_T − θ*‖²", yaxis_type="log",
                          template="plotly_white", height=440, barmode="group")
        write_fig(fig, "gd_control_quad")
        cdf.to_csv(f"{RES}/gd_control_quad.csv", index=False)

    with open(f"{RES}/gd_analysis_summary.json", "w") as f:
        json.dump(out, f, indent=2, default=float)
    print(json.dumps({k: v for k, v in out.items()
                      if k in ("eta", "T_vs_logd_fits", "tbar_vs_logd", "alpha_implied",
                               "phases_median", "final")}, indent=2, default=float))


if __name__ == "__main__":
    main()