Datasets:
Download scripts/figures.py from Cross-Mergeability/crossarch-accuracy: direct link, hf CLI and curl.
- Browser
- Download file 7.53 kB
-
https://huggingface.co/datasets/Cross-Mergeability/crossarch-accuracy/resolve/main/scripts/figures.py
- Command line
-
hf download hf://datasets/Cross-Mergeability/crossarch-accuracy/scripts/figures.py
-
curl -L -o figures.py https://huggingface.co/datasets/Cross-Mergeability/crossarch-accuracy/resolve/main/scripts/figures.py
7.53 kB
| """Figures 1 and 2. | |
| Figure 1 answers: does the accuracy analogue of the LMC barrier cross zero at the same | |
| trajectory separation as the barrier in nats, and does merge *usability* (accuracy against the | |
| better parent) cross zero anywhere at all? | |
| The two y-axes are scaled so that y = 0 sits at the same height on both, otherwise the visual | |
| comparison of two zero-crossings is meaningless. | |
| """ | |
| import json, os, sys | |
| import numpy as np, pandas as pd | |
| import matplotlib; matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| sys.path.insert(0, "/root/crossarch-accuracy/scripts") | |
| from analyze import crossover, perm_corr | |
| ROOT = "/root/crossarch-accuracy" | |
| DIAG = "/root/crossarch-diagnostics/results/checkpoint_pairs.csv" | |
| C_BAR, C_ACC, C_USE, C_GREY = "#3B5BDB", "#E8590C", "#C2255C", "#B0B4BA" | |
| TRAINED_MIN_STEP = 2000 # earlier endpoint must itself be above chance on the suite | |
| def _align_zero(ax, ax2): | |
| """Rescale ax2 so its zero lands at the same figure height as ax's zero.""" | |
| l1, u1 = ax.get_ylim(); l2, u2 = ax2.get_ylim() | |
| if not (l1 < 0 < u1): return | |
| f = (0 - l1) / (u1 - l1) # fractional height of zero on ax | |
| span = max(u2 - 0, 1e-9) / max(1 - f, 1e-9) if f < 1 else (u2 - l2) | |
| ax2.set_ylim(-f * span, (1 - f) * span) | |
| def fig1(df, fam="pythia", trained_only=True, tag=""): | |
| g = df[df.family == fam].copy() | |
| dall = pd.read_csv(DIAG); dg = dall[dall.family == fam].copy() | |
| if trained_only: | |
| g = g[g.step_a >= TRAINED_MIN_STEP]; dg = dg[dg.step_a >= TRAINED_MIN_STEP] | |
| g = g.sort_values("log10_step_ratio") | |
| if len(g) < 4: return None | |
| cb = crossover(dg.log10_step_ratio.values, dg.barrier.values) | |
| ca = crossover(g.log10_step_ratio.values, g.acc_barrier.values) | |
| cu = crossover(g.log10_step_ratio.values, g.d_acc_vs_better.values) | |
| fig, (ax, axu) = plt.subplots(2, 1, figsize=(9.0, 7.4), sharex=True, | |
| gridspec_kw=dict(height_ratios=[2.05, 1])) | |
| ax2 = ax.twinx() | |
| ax.scatter(dg.log10_step_ratio, dg.barrier, s=26, c=C_GREY, alpha=.55, zorder=2, | |
| label=f"LMC barrier, nats — all {len(dg)} diagnostic pairs") | |
| ax.scatter(g.log10_step_ratio, g.barrier, s=58, c=C_BAR, edgecolor="w", lw=.7, zorder=4, | |
| label=f"LMC barrier, nats — evaluated (n={len(g)})") | |
| ax2.scatter(g.log10_step_ratio, 100 * g.acc_barrier, s=58, c=C_ACC, marker="s", | |
| edgecolor="w", lw=.7, zorder=5, | |
| label="accuracy barrier — mean parent − merge (pts)") | |
| axu.scatter(g.log10_step_ratio, 100 * g.d_acc_vs_better, s=56, facecolor="none", | |
| edgecolor=C_USE, lw=1.6, marker="D", zorder=6) | |
| xs = np.linspace(0, max(g.log10_step_ratio.max(), 2.2), 100) | |
| ax.plot(xs, cb["ols_intercept"] + cb["ols_slope"] * xs, c=C_BAR, lw=1.5, alpha=.85) | |
| ax2.plot(xs, 100 * (ca["ols_intercept"] + ca["ols_slope"] * xs), c=C_ACC, lw=1.5, alpha=.85) | |
| axu.plot(xs, 100 * (cu["ols_intercept"] + cu["ols_slope"] * xs), c=C_USE, lw=1.4, | |
| alpha=.8, ls="--") | |
| ax.axhline(0, color="k", lw=1.0, ls=":") | |
| axu.axhline(0, color="k", lw=1.0, ls=":") | |
| _align_zero(ax, ax2) | |
| for c, col in ((cb, C_BAR), (ca, C_ACC)): | |
| x0 = c.get("x0_ols", np.nan) | |
| if np.isfinite(x0) and 0 <= x0 <= 2.5: | |
| axu.axvline(x0, color=col, ls="--", lw=1.2, alpha=.7) | |
| nb = int(g.beats_better_parent.sum()) | |
| axu.set_ylabel("usability (pts)\nmerge − better parent", color=C_USE, fontsize=9) | |
| axu.tick_params(axis="y", colors=C_USE) | |
| axu.set_xlabel("trajectory separation log₁₀(step_b / step_a) [decades]") | |
| axu.set_title(f"merge beats the better parent in {nb} / {len(g)} pairs " | |
| f"(median inside half a decade: " | |
| f"{100*g[g.log10_step_ratio<=0.5].d_acc_vs_better.median():+.2f} pts)", | |
| fontsize=9.4, color=C_USE) | |
| for c, col, lab, y in ((cb, C_BAR, "nats barrier", .97), (ca, C_ACC, "accuracy barrier", .90)): | |
| x0 = c.get("x0_ols", np.nan) | |
| if np.isfinite(x0) and 0 <= x0 <= 2.5: | |
| ax.axvline(x0, color=col, ls="--", lw=1.3, alpha=.85) | |
| lo, hi = c.get("x0_ols_ci", [np.nan, np.nan]) | |
| ax.axvspan(lo, hi, color=col, alpha=.07) | |
| ax.text(x0 + .03, y, f"{lab} → 0\nat {x0:.2f} dec\n[{lo:.2f}, {hi:.2f}]", | |
| color=col, va="top", fontsize=8.6, transform=ax.get_xaxis_transform()) | |
| ax.set_ylabel("LMC barrier (nats/token)", color=C_BAR) | |
| ax2.set_ylabel("accuracy (points)", color=C_ACC) | |
| ax.tick_params(axis="y", colors=C_BAR); ax2.tick_params(axis="y", colors=C_ACC) | |
| h1, l1 = ax.get_legend_handles_labels(); h2, l2 = ax2.get_legend_handles_labels() | |
| ax.legend(h1 + h2, l1 + l2, fontsize=8.2, loc="lower right", framealpha=.93) | |
| sub = ("earlier endpoint ≥ step 2000 (both parents above chance)" if trained_only | |
| else "all evaluated pairs") | |
| r = perm_corr(g.barrier.values, g.acc_barrier.values) | |
| ax.set_title("Figure 1 — the barrier crosses zero in nats and in accuracy at the same place;\n" | |
| f"usability against the better parent never does. {fam}, {sub}.\n" | |
| f"nats barrier vs accuracy barrier: r = {r['pearson_r']:.2f}, " | |
| f"p_perm < {max(1/max(r['n_perm'],1), r['p_permutation']):.3f}, n = {r['n']}", | |
| fontsize=10.2) | |
| fig.tight_layout() | |
| fig.savefig(f"{ROOT}/figures/fig1_crossover_{fam}{tag}.png", dpi=170) | |
| plt.close(fig) | |
| return dict(nats_barrier=cb, acc_barrier=ca, usability_vs_better_parent=cu, | |
| nats_vs_acc_barrier=r, n=len(g), | |
| n_beats_better_parent=int(g.beats_better_parent.sum())) | |
| def fig2(df): | |
| fig, axes = plt.subplots(1, 2, figsize=(10.6, 4.6)) | |
| for ax, (yc, lab, sc) in zip(axes, [("gain_best", "best-merge gain (nats) — existing", 1), | |
| ("d_acc_vs_better", "Δaccuracy vs better parent (pts) — new", 100)]): | |
| for fam, col, mk in [("pythia", C_BAR, "o"), ("zhpythia", C_ACC, "s")]: | |
| gg = df[df.family == fam] | |
| if len(gg) == 0: continue | |
| ax.scatter(gg.cka, sc * gg[yc], s=42, c=col, marker=mk, alpha=.85, label=fam, | |
| edgecolor="w", lw=.5) | |
| s = perm_corr(df.cka.values, df[yc].values) | |
| ax.set_xlabel("CKA (pooled activations)"); ax.set_ylabel(lab) | |
| ax.axhline(0, color="k", lw=.7, ls=":") | |
| ax.set_title(f"r = {s['pearson_r']:.2f} ρ = {s['spearman_rho']:.2f}\n" | |
| f"p_perm = {s['p_permutation']:.4f}, n = {s['n']}", fontsize=9.6) | |
| ax.legend(fontsize=8) | |
| fig.suptitle("Figure 2 — CKA against merge gain in nats (left) and in accuracy (right)", | |
| fontsize=11) | |
| fig.tight_layout(); fig.savefig(f"{ROOT}/figures/fig2_cka_vs_gain.png", dpi=170) | |
| plt.close(fig) | |
| return {yc: perm_corr(df.cka.values, df[yc].values) | |
| for yc in ("gain_best", "d_acc_vs_better", "acc_barrier")} | |
| if __name__ == "__main__": | |
| df = pd.read_csv(f"{ROOT}/results/table1_checkpoint_accuracy.csv") | |
| out = {} | |
| for fam in df.family.unique(): | |
| if (df.family == fam).sum() >= 4: | |
| out[fam] = fig1(df, fam, trained_only=True) | |
| out[fam + "_allpairs"] = fig1(df, fam, trained_only=False, tag="_allpairs") | |
| out["fig2_correlations"] = fig2(df) | |
| json.dump(out, open(f"{ROOT}/results/fig1_crossovers.json", "w"), indent=2, default=str) | |
| print(json.dumps({k: v for k, v in out.items() if v}, indent=2, default=str)[:2500]) | |