"""Generate the paper's headline figures from cached results (no GPU). python figures.py # writes figures/*.pdf + *.png from results_A/ """ from __future__ import annotations import json from pathlib import Path import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import metrics from config import MODELS from run_pipeline import (_para_rotation, _iid_split_rotation, _mean_ood_rotation, _mean_ood_drop) OUT = Path("figures"); OUT.mkdir(exist_ok=True) PREDS = ["raptor_stability", "pac", "augmentation_robustness", "whitened_cosine_id", "fragility", "xie_feature_dispersion", "sip_eigengap"] LBL = {"raptor_stability": "RAPTOR\n(dispersion)", "pac": "PAC (ours)", "augmentation_robustness": "aug-robust", "whitened_cosine_id": "whitened-cos", "fragility": "Fragility", "xie_feature_dispersion": "Xie-disp", "sip_eigengap": "SIP"} def load_rows(results_dir, predfile="predictors.jsonl"): R = Path(results_dir) evals = [json.loads(l) for l in (R / "eval.jsonl").read_text().splitlines() if l.strip()] preds = {(p["model"], p["dataset"], p["seed"]): p["predictors"] for p in (json.loads(l) for l in (R / predfile).read_text().splitlines() if l.strip())} rows = [] for e in evals: if e.get("probe") != "logreg": continue k = (e["model"], e["dataset"], e["seed"]) if k not in preds: continue para, iids = _para_rotation(e), _iid_split_rotation(e) excess = (para - iids) if (para == para and iids == iids) else np.nan rows.append({"model": e["model"], "naive": _mean_ood_rotation(e), "placebo": iids, "excess": excess, "drop": _mean_ood_drop(e), **preds[k]}) return rows def rho(rows, pred, target): s = np.array([r.get(pred, np.nan) for r in rows], float) y = np.array([r[target] for r in rows], float) ok = ~(np.isnan(s) | np.isnan(y)) return metrics.spearman(s[ok], -y[ok])[0] if ok.sum() >= 8 else np.nan def fig_circularity(rows): targets = [("naive", "naive rotation"), ("placebo", "IID-resample\n(placebo)"), ("excess", "EXCESS\n(shift-specific)")] x = np.arange(len(PREDS)); w = 0.26 fig, ax = plt.subplots(figsize=(9, 4.2)) colors = ["#4C72B0", "#999999", "#C44E52"] for i, (t, name) in enumerate(targets): vals = [rho(rows, p, t) for p in PREDS] ax.bar(x + (i - 1) * w, vals, w, label=name, color=colors[i]) ax.axhline(0, color="k", lw=0.8) ax.set_xticks(x); ax.set_xticklabels([LBL[p] for p in PREDS], fontsize=8) ax.set_ylabel("Spearman ρ (predictor, −target)") ax.set_title("Predicting probe direction rotation: naive ρ is circular (≈ placebo);\n" "on EXCESS dispersion turns anti-predictive while augmentation is least-bad") ax.legend(fontsize=8, loc="lower left"); ax.set_ylim(-0.45, 1.0) fig.tight_layout(); fig.savefig(OUT / "fig1_circularity.pdf"); fig.savefig(OUT / "fig1_circularity.png", dpi=150) plt.close(fig) def fig_sizeladder(rows): models = sorted({r["model"] for r in rows}, key=lambda m: MODELS[m].params_m if m in MODELS else 0) xs = [MODELS[m].params_m for m in models if m in MODELS] fig, axes = plt.subplots(1, 2, figsize=(10, 4)) for ax, tgt, title in [(axes[0], "naive", "naive rotation"), (axes[1], "excess", "EXCESS rotation")]: for p, c in [("raptor_stability", "#4C72B0"), ("augmentation_robustness", "#C44E52"), ("pac", "#55A868")]: ys = [rho([r for r in rows if r["model"] == m], p, tgt) for m in models if m in MODELS] ax.plot(xs, ys, "o-", label=LBL[p].replace("\n", " "), color=c) ax.axhline(0, color="k", lw=0.6); ax.set_xscale("log") ax.set_xlabel("params (M, log)"); ax.set_ylabel("Spearman ρ"); ax.set_title(title) ax.legend(fontsize=8) fig.suptitle("Size-ladder: predictability structure is scale-invariant (no inverse-scaling)") fig.tight_layout(); fig.savefig(OUT / "fig2_sizeladder.pdf"); fig.savefig(OUT / "fig2_sizeladder.png", dpi=150) plt.close(fig) def fig_mechanism(rows): """Why augmentation > dispersion on EXCESS: dispersion (IID bootstrap) is unrelated/anti to the shift-specific component; augmentation (a label-preserving perturbation) tracks it.""" fig, axes = plt.subplots(1, 2, figsize=(9, 4), sharey=True) for ax, p, c in [(axes[0], "raptor_stability", "#4C72B0"), (axes[1], "augmentation_robustness", "#C44E52")]: s = np.array([r.get(p, np.nan) for r in rows], float) y = np.array([r["excess"] for r in rows], float) ok = ~(np.isnan(s) | np.isnan(y)) s, y = s[ok], y[ok] ax.scatter(s, y, s=8, alpha=0.3, color=c) if len(s) > 2: b, a = np.polyfit(s, y, 1) xs = np.linspace(s.min(), s.max(), 20) ax.plot(xs, a + b * xs, color="k", lw=1.5) r = metrics.spearman(s, -y)[0] ax.set_title(f"{LBL[p].replace(chr(10),' ')}\nρ(score,−excess)={r:+.2f}") ax.set_xlabel(f"{p} (a-priori stability)"); ax.axhline(0, color="grey", lw=0.6) axes[0].set_ylabel("EXCESS rotation (shift-specific)") fig.suptitle("Mechanism: dispersion is blind to shift-specific fragility; augmentation is not") fig.tight_layout(); fig.savefig(OUT / "fig3_mechanism.pdf"); fig.savefig(OUT / "fig3_mechanism.png", dpi=150) plt.close(fig) if __name__ == "__main__": rows = load_rows("results_A/results") print(f"loaded {len(rows)} configs") fig_circularity(rows) fig_sizeladder(rows) fig_mechanism(rows) print("wrote figures/fig1_circularity, fig2_sizeladder, fig3_mechanism (.pdf/.png)")