nmaher's picture
Add exp6-8 drivers, results JSON, figures, poster, dataset card; drop duplicated root-level code copies
857044b verified
Raw
History Blame Contribute Delete
20.9 kB
"""Build the Plotly figures (HTML + raw CSV) for each claim page from summary.json."""
import csv
import json
import os
import numpy as np
import plotly.graph_objects as go
HERE = os.path.dirname(os.path.abspath(__file__))
RES = os.path.join(HERE, "results")
FIG = os.path.join(HERE, "figs")
os.makedirs(FIG, exist_ok=True)
S = json.load(open(os.path.join(RES, "summary.json")))
LAYOUT = dict(
template="plotly_white", width=760, height=460,
margin=dict(l=70, r=30, t=60, b=60),
font=dict(family="Inter, system-ui, sans-serif", size=13),
legend=dict(bgcolor="rgba(255,255,255,0.75)", bordercolor="#d0d0d0",
borderwidth=1),
)
PAL = ["#3B6FE0", "#E07B39", "#2E9E6B", "#B5446E", "#7A5AC6", "#8A8F98"]
# Poster cards need rasters, not interactive HTML. Export at 3x so a ~760px
# figure lands ~2280px wide -- above posterly's 1.5x asset floor for a print card.
PNG = os.environ.get("CL_FIG_PNG", "") == "1"
def save(fig, name, rows, header):
fig.update_layout(**LAYOUT)
fig.write_html(os.path.join(FIG, name + ".html"), include_plotlyjs="cdn")
if PNG:
fig.write_image(os.path.join(FIG, name + ".png"), scale=3)
with open(os.path.join(FIG, name + ".csv"), "w", newline="") as f:
w = csv.writer(f)
w.writerow(header)
w.writerows(rows)
print("wrote", name)
def ref(x, y0, slope, x0=None):
"""power-law reference line through (x0, y0)."""
x = np.asarray(x, float)
x0 = x0 if x0 is not None else x[0]
return y0 * (x / x0) ** slope
# ---------------------------------------------------------------- Claim 1
if "claim1" in S:
c = S["claim1"]
# F1: finite-width remainder vs m
r = c["remainder_vs_m"]
m = np.array(r["m"], float)
fig = go.Figure()
fig.add_scatter(x=m, y=r["remainder"], mode="markers+lines", name="|measured − first-order|",
line=dict(color=PAL[0], width=2), marker=dict(size=9))
fig.add_scatter(x=m, y=ref(m, r["remainder"][0], -0.5),
mode="lines", name="m<sup>−1/2</sup> reference (Thm 1, 3rd term)",
line=dict(color=PAL[0], width=1.5, dash="dash"))
fig.add_scatter(x=m, y=r["remainder_M"], mode="markers+lines",
name="residual after using empirical (1/m)WᵀW",
line=dict(color=PAL[2], width=2), marker=dict(size=9, symbol="square"))
fig.add_scatter(x=m, y=r["first_order"], mode="lines",
name="first-order (kernel) term — m-independent",
line=dict(color=PAL[5], width=1.5, dash="dot"))
fig.update_xaxes(type="log", title="hidden width m")
fig.update_yaxes(type="log", title="|train-time forgetting| contribution")
fig.update_layout(title=f"Finite-width remainder decays as m<sup>{r['slope']:.2f}</sup> "
f"(Thm 1 predicts −0.5)")
save(fig, "c1_remainder_vs_m",
list(zip(r["m"], r["remainder"], r["remainder_M"], r["first_order"])),
["m", "abs_remainder", "abs_remainder_empiricalM", "abs_first_order"])
# F2: sampling vs population part of the first-order term, vs n
r = c["vs_n"]
n = np.array(r["n"], float)
fig = go.Figure()
fig.add_scatter(x=n, y=r["fo_fluct"], mode="markers+lines",
name="sampling part → ηT√(K−k)/(d√n)",
line=dict(color=PAL[0], width=2), marker=dict(size=9))
fig.add_scatter(x=n, y=ref(n, r["fo_fluct"][0], -0.5), mode="lines",
name="n<sup>−1/2</sup> reference",
line=dict(color=PAL[0], width=1.5, dash="dash"))
fig.add_scatter(x=n, y=r["fo_mean"], mode="markers+lines",
name="population part → ηT√(K−k)/(d²·polylog d) [n-independent floor]",
line=dict(color=PAL[1], width=2), marker=dict(size=9, symbol="square"))
fig.add_scatter(x=n, y=r["measured"], mode="markers",
name="total measured forgetting",
marker=dict(size=7, color=PAL[5], symbol="x"))
fig.update_xaxes(type="log", title="samples per task n")
fig.update_yaxes(type="log", title="|contribution to F<sup>tr</sup>|")
fig.update_layout(title=f"Sampling term ∝ n<sup>{r['slope_fluct']:.2f}</sup>; "
f"population term flat (slope {r['slope_mean']:+.2f})")
save(fig, "c1_terms_vs_n",
list(zip(r["n"], r["fo_fluct"], r["fo_mean"], r["measured"])),
["n", "abs_sampling_term", "abs_population_term", "abs_measured"])
# F3: sqrt(K-k)
r = c["vs_Kk"]
x = np.array(r["Kk"], float)
fig = go.Figure()
fig.add_scatter(x=x, y=r["forget"], error_y=dict(type="data", array=r["sem"]),
mode="markers+lines", name="measured |F<sup>tr</sup><sub>k,K</sub>|",
line=dict(color=PAL[0], width=2), marker=dict(size=10))
fig.add_scatter(x=x, y=ref(x, r["forget"][0], 0.5), mode="lines",
name="√(K−k) reference", line=dict(color=PAL[1], width=2, dash="dash"))
fig.update_xaxes(type="log", title="number of subsequent tasks K − k")
fig.update_yaxes(type="log", title="|train-time forgetting|")
fig.update_layout(title=f"Forgetting ∝ (K−k)<sup>{r['slope']:.2f}</sup> "
f"(Thm 1 predicts 0.50)")
save(fig, "c1_vs_Kk", list(zip(r["Kk"], r["forget"], r["sem"])),
["K_minus_k", "abs_forget", "sem"])
# F4: orthogonality control
r = c["overlap_control"]
fig = go.Figure()
fig.add_scatter(x=r["overlap"], y=r["forget"],
error_y=dict(type="data", array=r["sem"]),
mode="markers+lines", line=dict(color=PAL[3], width=2),
marker=dict(size=10), name="|F<sup>tr</sup><sub>1,K</sub>|")
fig.update_xaxes(title="cosine overlap between task-1 and later-task means")
fig.update_yaxes(type="log", title="|train-time forgetting|")
fig.update_layout(title="Control: relaxing the orthogonality assumption of Thm 1",
showlegend=False)
save(fig, "c1_overlap_control", list(zip(r["overlap"], r["forget"], r["sem"])),
["mean_overlap", "abs_forget", "sem"])
# ---------------------------------------------------------------- Claim 1 (GD)
if "claim1_gd" in S:
c = S["claim1_gd"]
fig = go.Figure()
names = {"n": "vs n (samples)", "m": "vs m (width)",
"etaT": "vs T (horizon, η fixed)", "eta": "vs η (T fixed)"}
rows = []
for i, (tag, lab) in enumerate(names.items()):
if tag not in c:
continue
d = c[tag]
x = np.array(d["x"], float)
y = np.array(d["train_forget"], float)
fig.add_scatter(x=x / x[0], y=y, error_y=dict(type="data", array=d["sem"]),
mode="markers+lines", name=f"{lab} (slope {d['slope']:+.2f})",
line=dict(color=PAL[i], width=2), marker=dict(size=9))
rows += [[tag, a, b, s] for a, b, s in zip(d["x"], d["train_forget"], d["sem"])]
fig.update_xaxes(type="log", title="parameter, relative to smallest value in sweep")
fig.update_yaxes(type="log", title="|train-time forgetting| of task 1")
fig.update_layout(title="Full GD (no linearization): forgetting vs each Thm-1 parameter")
save(fig, "c1_gd_sweeps", rows, ["sweep", "x", "abs_forget", "sem"])
# ---------------------------------------------------------------- Claim 2
if "claim2" in S:
c = S["claim2"]
lab = {"prescribed": "Thm 1 regime: n=Θ(d²K), ηT=Θ(d²), m large",
"fixed_n": "control: n held constant (violates n=Θ̃(d²K))",
"long_train": "control: ηT ∝ d³ (violates ηT=Θ(d²))",
"small_m": "control: m = 300 (violates the width condition)"}
fig = go.Figure()
rows = []
for i, (k, v) in enumerate(c.items()):
fig.add_scatter(x=v["d"], y=v["forget"], error_y=dict(type="data", array=v["sem"]),
mode="markers+lines", name=f"{lab.get(k,k)} (slope {v['slope']:+.2f})",
line=dict(color=PAL[i], width=2), marker=dict(size=10))
rows += [[k, a, b, s] for a, b, s in zip(v["d"], v["forget"], v["sem"])]
fig.update_xaxes(type="log", title="dimension d")
fig.update_yaxes(type="log", title="|train-time forgetting| of task 1")
fig.update_layout(title="Claim 2: forgetting → 0 with d only inside the prescribed regime")
save(fig, "c2_regime", rows, ["variant", "d", "abs_forget", "sem"])
# ---------------------------------------------------------------- Claim 3
if "claim3" in S:
c = S["claim3"]
# The error is identically 0 at every configuration, so a bar chart of it
# carries no information. What separates the configurations is the *loss*
# half of Theorem 2, which only becomes small at the prescribed horizon.
fig = go.Figure()
rows = []
for i, etaT in enumerate(sorted({rec["etaT"] for rec in c})):
g = [rec for rec in c if rec["etaT"] == etaT]
d2 = g[0]["etaT_over_d2"]
fig.add_bar(x=[f"n={r['n']}<br>m={r['m']}" for r in g],
y=[r["train_loss_end_max"] for r in g],
name=f"ηT={etaT:.0f} = {d2:.2f}·d²",
marker_color=PAL[i % len(PAL)])
for rec in c:
rows.append([rec["eta"], rec["etaT"], rec["n"], rec["m"],
rec["train_err_end_max"], rec["test_err_end_max"],
rec["train_loss_end_max"], rec["test_loss_end_max"]])
fig.add_hline(y=0.0, line=dict(color=PAL[5], width=1))
fig.update_yaxes(title="max over K tasks of train loss at w<sub>K</sub>")
fig.update_layout(
title=("Claim 3: misclassification error is 0 everywhere (all 32 runs);<br>"
"the <i>loss</i> half of Thm 2 is what needs ηT = Θ(d²)"),
barmode="group")
save(fig, "c3_loss_vs_horizon", rows,
["eta", "etaT", "n", "m", "max_train_err", "max_test_err",
"max_train_loss", "max_test_loss"])
# ------------------------------------------- Claim 3 control: cluster noise
if "claim3_noise" in S:
c = S["claim3_noise"]
rws = c["rows"]
sc = [r["sigma_c"] for r in rws]
fig = go.Figure()
for j, (key, lab, sym) in enumerate([
("train_err_max", "max train error at w<sub>K</sub>", "circle"),
("test_err_max", "max test error at w<sub>K</sub>", "square"),
("train_err_own_max", "max error on own task at w<sub>k</sub>", "diamond")]):
fig.add_scatter(x=sc, y=[r[key] for r in rws], mode="markers+lines",
name=lab, line=dict(color=PAL[j], width=2),
marker=dict(size=9, symbol=sym))
fig.add_hline(y=0.5, line=dict(color=PAL[5], width=1, dash="dot"),
annotation_text="chance", annotation_position="top left")
fig.add_vline(x=0.1, line=dict(color=PAL[4], width=1.5, dash="dash"),
annotation_text="σ_c prescribed by Thm 1/2",
annotation_position="top right")
fig.update_xaxes(title="cluster noise coefficient σ_c (σ = σ_c/√d)", type="log")
fig.update_yaxes(title="misclassification error", range=[-0.03, 0.58])
fig.update_layout(
title=(f"Claim 3 control: relaxing Theorem 2's noise condition "
f"(d={c['d']}, m={c['m']}, n={c['n']}, K={c['K']}, ηT={c['eta']*c['T']:.0f})"))
save(fig, "c3_noise_control",
[[r["sigma_c"], r["seeds"], r["train_err_max"], r["test_err_max"],
r["train_err_own_max"], r["train_loss_max"]] for r in rws],
["sigma_c", "seeds", "max_train_err", "max_test_err",
"max_own_task_err", "max_train_loss"])
# ---------------------------------------------------------------- Claims 4/5
if "claim45" in S:
c = S["claim45"]
if "n" in c:
d = c["n"]
x = np.array(d["x"], float)
g = np.abs(np.array(d["gap"]))
fig = go.Figure()
fig.add_scatter(x=x, y=g, error_y=dict(type="data", array=d["sem"]),
mode="markers+lines", name="measured 𝔼[F<sub>k</sub>(w<sub>K</sub>) − F̂<sub>k</sub>(w<sub>K</sub>)]",
line=dict(color=PAL[0], width=2), marker=dict(size=10))
fig.add_scatter(x=x, y=ref(x, g[0], -1.0), mode="lines",
name="1/n reference (Thm 3)",
line=dict(color=PAL[1], width=2, dash="dash"))
fig.update_xaxes(type="log", title="samples per task n")
fig.update_yaxes(type="log", title="delayed generalization gap")
fig.update_layout(title=f"Claim 4: gap ∝ n<sup>{d['slope_gap']:.2f}</sup> "
f"(Thm 3 predicts −1)")
save(fig, "c4_gap_vs_n", list(zip(d["x"], d["gap"], d["sem"], d["rhs_thm3"])),
["n", "gen_gap", "sem", "rhs_thm3_unscaled"])
if "T" in c:
d = c["T"]
x = np.array(d["x"], float)
g = np.abs(np.array(d["gap"]))
b3 = np.array(d["rhs_thm3"]) * d["c3"]
b4 = np.array(d["rhs_thm4"]) * d["c4"]
fig = go.Figure()
fig.add_scatter(x=x, y=g, error_y=dict(type="data", array=d["sem"]),
mode="markers+lines", name="measured gap",
line=dict(color=PAL[0], width=2.5), marker=dict(size=10))
fig.add_scatter(x=x, y=b3, mode="markers+lines",
name=f"Thm 3 bound ∝ ηT (fitted slope {d['slope_thm3']:+.2f})",
line=dict(color=PAL[1], width=2, dash="dash"), marker=dict(size=8))
fig.add_scatter(x=x, y=b4, mode="markers+lines",
name=f"Thm 4 bound ∝ Σ<sub>t</sub>F̂<sub>k</sub> (fitted slope {d['slope_thm4']:+.2f})",
line=dict(color=PAL[2], width=2, dash="dot"), marker=dict(size=8))
fig.update_xaxes(type="log", title="iterations per task T")
fig.update_yaxes(type="log", title="delayed generalization gap / bound")
fig.update_layout(title="Claim 5: Thm 4's bound grows far slower in T than Thm 3's")
save(fig, "c5_bounds_vs_T",
list(zip(d["x"], d["gap"], d["rhs_thm3"], d["rhs_thm4"], d["cum_train_loss"])),
["T", "gen_gap", "rhs_thm3_unscaled", "rhs_thm4_unscaled",
"cum_train_loss_task1"])
# ---------------------------------------------------------------- Claim 6
if "claim6" in S:
c = S["claim6"]
z = np.array(c["train_forget"])
fig = go.Figure(go.Heatmap(
z=np.log10(np.maximum(z, 1e-12)),
x=[str(m) for m in c["m"]], y=[str(n) for n in c["n"]],
colorscale="Viridis_r",
colorbar=dict(title="log₁₀|F<sup>tr</sup>|"),
text=[[f"{v:.2e}" for v in row] for row in z],
texttemplate="%{text}", textfont=dict(size=10)))
fig.update_xaxes(title="hidden width m")
fig.update_yaxes(title="samples per task n")
fig.update_layout(title="Claim 6: train-time forgetting over the joint (n, m) grid")
rows = [[c["n"][i], c["m"][j], c["train_forget"][i][j], c["test_forget"][i][j],
c["gen_gap"][i][j]] for i in range(len(c["n"])) for j in range(len(c["m"]))]
save(fig, "c6_joint_grid", rows, ["n", "m", "abs_train_forget",
"abs_test_forget", "gen_gap"])
# The claim is about the grid's *shape*, which the marginal slopes read off
# directly: a flat slope along one axis is the plateau an additive bound
# predicts when that axis' term is not the dominant one.
if "marginal_slopes" in c:
mg = c["marginal_slopes"]
fig = go.Figure()
fig.add_scatter(
x=[r["m"] for r in mg["vs_n"]], y=[r["slope"] for r in mg["vs_n"]],
error_y=dict(type="data", array=[r["slope_err"] for r in mg["vs_n"]]),
mode="markers+lines", name="d log|F<sup>tr</sup>| / d log n (at fixed m)",
line=dict(color=PAL[0], width=2), marker=dict(size=10))
fig.add_scatter(
x=[r["n"] for r in mg["vs_m"]], y=[r["slope"] for r in mg["vs_m"]],
error_y=dict(type="data", array=[r["slope_err"] for r in mg["vs_m"]]),
mode="markers+lines", name="d log|F<sup>tr</sup>| / d log m (at fixed n)",
line=dict(color=PAL[1], width=2), marker=dict(size=10, symbol="square"))
fig.add_hline(y=0.0, line=dict(color="#444", width=1),
annotation_text="flat = this axis alone does nothing")
fig.add_hline(y=-0.5, line=dict(color=PAL[5], width=1, dash="dash"),
annotation_text="−1/2 (Thm 1 n-term)",
annotation_position="bottom right")
fig.update_xaxes(title="the other axis' value (m for the n-slopes, n for the m-slopes)",
type="log")
fig.update_yaxes(title="marginal log-log slope")
fig.update_layout(title=("Claim 6: n reduces forgetting at every width; "
"m alone does not move it"))
save(fig, "c6_marginal_slopes",
[["vs_n", r["m"], r["slope"], r["slope_err"]] for r in mg["vs_n"]]
+ [["vs_m", r["n"], r["slope"], r["slope_err"]] for r in mg["vs_m"]],
["direction", "other_axis_value", "slope", "slope_err"])
# ------------------------------------------------- Claim 2 (eta*T consistency)
if "claim2_etaT" in S and S["claim2_etaT"].get("points"):
c = S["claim2_etaT"]
pts = c["points"]
ds = sorted({p["d"] for p in pts})
fig = go.Figure()
for i, dd in enumerate(ds):
sel = sorted([p for p in pts if p["d"] == dd], key=lambda p: p["m"])
fig.add_scatter(x=[p["m"] for p in sel], y=[p["etaT_needed"] for p in sel],
mode="markers+lines", name=f"d = {dd}",
line=dict(color=PAL[i % len(PAL)], width=2),
marker=dict(size=9))
# what the naive "effective horizon eta*T/sqrt(m)" argument would predict
sel = sorted([p for p in pts if p["d"] == ds[0]], key=lambda p: p["m"])
mref = np.array([p["m"] for p in sel], float)
fig.add_scatter(x=mref, y=ref(mref, sel[0]["etaT_needed"], 0.5), mode="lines",
name="m<sup>1/2</sup> reference (would break the regime)",
line=dict(color=PAL[5], width=1.5, dash="dash"))
fig.update_xaxes(type="log", title="hidden width m")
fig.update_yaxes(type="log", title="smallest ηT that fits one task")
beta = c.get("beta_m")
sub = (f"fitted ηT<sub>needed</sub> ∝ d<sup>{c['alpha_d']:.2f}</sup>"
f" m<sup>{beta:+.2f}</sup>") if beta is not None else ""
fig.update_layout(title="Claim 2 consistency: does the required ηT grow with width? "
+ sub)
save(fig, "c2_etaT_needed",
[[p["d"], p["m"], p["etaT_needed"], p["seeds"]] for p in pts],
["d", "m", "etaT_needed", "seeds"])
# ------------------------------- Claims 4/5: the non-vacuous corner (exp8)
if "claim45_nonvacuous" in S:
c = S["claim45_nonvacuous"]
rows = c["rows"]
ms = sorted({r["m"] for r in rows})
ns = sorted({r["n"] for r in rows})
fig = go.Figure()
# measured gap: one trace per (m, n); bounds: one trace per (m, n) too, dashed
i = 0
for mm in ms:
for nn in ns:
sel = sorted([r for r in rows if r["m"] == mm and r["n"] == nn],
key=lambda r: r["T"])
if not sel:
continue
col = PAL[i % len(PAL)]
i += 1
fig.add_scatter(x=[r["T"] for r in sel], y=[r["gap"] for r in sel],
mode="markers+lines", name=f"measured, m={mm}, n={nn}",
legendgroup=f"{mm}-{nn}",
line=dict(color=col, width=2), marker=dict(size=8))
fig.add_scatter(x=[r["T"] for r in sel], y=[r["rhs_thm4"] for r in sel],
mode="lines", name=f"Thm 4 bound, m={mm}, n={nn}",
legendgroup=f"{mm}-{nn}",
line=dict(color=col, width=1.5, dash="dash"))
fig.update_xaxes(type="log", title="steps per task T")
fig.update_yaxes(type="log", title="delayed generalization gap / bound")
fig.update_layout(
title=f"Claims 4–5: at η={c['eta']:g} the bounds are finite — "
f"tightest slack {c['tightest']['slack4']:.1f} decades "
f"(m={c['tightest']['m']}, n={c['tightest']['n']}, T={c['tightest']['T']})")
save(fig, "c45_nonvacuous",
[[r["T"], r["m"], r["n"], r["gap"], r["sem"], r["exponent_thm3"],
r["exponent_thm4"], r["rhs_thm3"], r["rhs_thm4"], r["slack3"],
r["slack4"]] for r in rows],
["T", "m", "n", "gap", "sem", "exponent_thm3", "exponent_thm4",
"rhs_thm3", "rhs_thm4", "slack3_decades", "slack4_decades"])
print("\nall figures ->", FIG)