File size: 5,444 Bytes
bf5f52e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Generate Plotly HTML figures (CDN, self-contained data) for the logbook."""
import json, math, sys
import plotly.graph_objects as go


def fig_noise():
    d = json.load(open("noise_audit_results.json"))
    r = d["rows"]
    B = [x["B"] for x in r]
    fig = go.Figure()
    fig.add_scatter(x=B, y=[x["N3_median"] for x in r], mode="lines+markers",
                    name="measured N₃ (median)")
    fig.add_scatter(x=B, y=[x["pred_Eq1"] for x in r], mode="lines+markers",
                    name="(B/d_model)·√(d_k log m)  [Eq.1, up to const]", line=dict(dash="dash"))
    fig.add_scatter(x=B, y=[x["signal"] for x in r], mode="lines+markers",
                    name="true-edge signal (≈ d_k, block-independent)", line=dict(dash="dot"))
    fig.add_hline(y=d["d_k"] / 2, line=dict(color="red", dash="dot"),
                  annotation_text="τ = d_k/2 (separation fails above)")
    fig.update_layout(title=f"Claim 3 — superposition noise N₃(B) grows linearly in block size B "
                            f"(m={d['m']}, d_model={d['d_model']}, d_k={d['d_k']})",
                      xaxis_title="block size B (= targets served by a head)",
                      yaxis_title="score", xaxis_type="log", yaxis_type="log",
                      template="plotly_white", legend=dict(y=0.02, x=0.02))
    fig.write_html("fig_claim3.html", include_plotlyjs="cdn")
    # raw csv
    with open("fig_claim3.csv", "w") as f:
        f.write("B,signal,N3_median,N3_max,pred_Eq1\n")
        for x in r:
            f.write(f"{x['B']},{x['signal']:.2f},{x['N3_median']:.2f},{x['N3_max']:.2f},{x['pred_Eq1']:.2f}\n")
    print("wrote fig_claim3.html / .csv")


def fig_claim4():
    d = json.load(open("results_base.json"))
    S = [r for r in d["summary"] if "D_K_star" in r]
    x = [r["x"] for r in S]; y = [r["D_K_star"] for r in S]
    slope = d.get("fit", {}).get("slope"); r2 = d.get("fit", {}).get("r2")
    fig = go.Figure()
    fig.add_scatter(x=x, y=y, mode="markers+text",
                    text=[f"({r['m']},{r['d_model']})" for r in S],
                    textposition="top center", name="D_K* (measured)",
                    marker=dict(size=10, color=["red" if r["d_model"] == 16 and r["m"] > 64 else "royalblue" for r in S]))
    xs = [0, max(x) * 1.05]
    if slope:
        fig.add_scatter(x=xs, y=[slope * v for v in xs], mode="lines",
                        name=f"fit: D_K*={slope:.2f}·x (R²={r2:.3f})", line=dict(dash="dash"))
    fig.update_layout(title="Claim 4 — empirical capacity law D_K* vs m·log(m)/d_model "
                            "(red = d_model=16, m>64 outliers)",
                      xaxis_title="x = m·log m / d_model", yaxis_title="D_K* (min key dim for 0.99 F1)",
                      template="plotly_white")
    fig.write_html("fig_claim4.html", include_plotlyjs="cdn")
    with open("fig_claim4.csv", "w") as f:
        f.write("m,d_model,x,D_K_star,h_star,d_k_star\n")
        for r in S:
            f.write(f"{r['m']},{r['d_model']},{r['x']:.2f},{r['D_K_star']},{r.get('h_star')},{r.get('d_k_star')}\n")
    print(f"wrote fig_claim4.html / .csv (n={len(S)})")


def fig_claim5():
    d = json.load(open("results_gpt2.json"))
    agg = {}
    for r in d["records"]:
        agg.setdefault((r["D_K"], r["h"]), []).append(r["test_acc"])
    DKs = sorted({k[0] for k in agg}); hs = sorted({k[1] for k in agg})
    fig = go.Figure()
    for h in hs:
        xs = [dk for dk in DKs if (dk, h) in agg]
        ys = [sum(agg[(dk, h)]) / len(agg[(dk, h)]) for dk in xs]
        fig.add_scatter(x=xs, y=ys, mode="lines+markers", name=f"h={h}")
    fig.update_layout(title="Claim 5 — GPT-2 block: test accuracy vs D_K by head count "
                            f"(m={d['config']['m']}, d_model=768, ℓ={d['config']['ell']})",
                      xaxis_title="D_K (total key dim)", yaxis_title="test accuracy",
                      template="plotly_white")
    fig.write_html("fig_claim5.html", include_plotlyjs="cdn")
    with open("fig_claim5.csv", "w") as f:
        f.write("D_K,h,mean_test_acc,n\n")
        for (dk, h), v in sorted(agg.items()):
            f.write(f"{dk},{h},{sum(v)/len(v):.4f},{len(v)}\n")
    print("wrote fig_claim5.html / .csv")


def fig_claim6():
    d = json.load(open("results_claim6.json"))
    fig = go.Figure()
    for (m, dm) in sorted({(r["m"], r["d_model"]) for r in d}):
        rows = [r for r in d if r["m"] == m and r["d_model"] == dm]
        rows.sort(key=lambda r: r["D_K"])
        xs = [r["D_K"] for r in rows]
        for tag, name in [("t16e16", "train16/eval16"), ("t32e32", "train32/eval32"), ("t16e32", "train16/eval32")]:
            fig.add_scatter(x=xs, y=[r[tag] for r in rows], mode="lines+markers",
                            name=f"({m},{dm}) {name}")
    fig.update_layout(title="Claim 6 — capacity threshold vs context length ℓ∈{16,32} and length generalization",
                      xaxis_title="D_K", yaxis_title="test micro-F1", template="plotly_white")
    fig.write_html("fig_claim6.html", include_plotlyjs="cdn")
    print("wrote fig_claim6.html")


if __name__ == "__main__":
    which = sys.argv[1] if len(sys.argv) > 1 else "all"
    fns = {"noise": fig_noise, "claim4": fig_claim4, "claim5": fig_claim5, "claim6": fig_claim6}
    if which == "all":
        for f in fns.values():
            try: f()
            except Exception as e: print("skip", f.__name__, e)
    else:
        fns[which]()