Download scripts/make_figures.py from Cross-Mergeability/crossarch-1b-diagnostics: direct link, hf CLI and curl.
- Browser
- Download file 6.84 kB
-
https://huggingface.co/datasets/Cross-Mergeability/crossarch-1b-diagnostics/resolve/main/scripts/make_figures.py
- Command line
-
hf download hf://datasets/Cross-Mergeability/crossarch-1b-diagnostics/scripts/make_figures.py
-
curl -L -o make_figures.py https://huggingface.co/datasets/Cross-Mergeability/crossarch-1b-diagnostics/resolve/main/scripts/make_figures.py
6.84 kB
| """Figures: matched/shuffled CKA heatmap, diagnostic correlation heatmaps, merge results.""" | |
| import json, os | |
| import numpy as np, pandas as pd | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| ROOT = "/root/crossarch-diagnostics" | |
| FIG = f"{ROOT}/figures" | |
| os.makedirs(FIG, exist_ok=True) | |
| plt.rcParams.update({"font.size": 8, "figure.dpi": 160, "savefig.bbox": "tight"}) | |
| ORDER = ["EN_pythia", "ZH_pythia", "PT_tucano", "PL_bielik", "IT_minerva"] | |
| LABEL = {"EN_pythia": "Pythia\nEN", "ZH_pythia": "Zh-Pythia\nZH", "PT_tucano": "Tucano\nPT", | |
| "PL_bielik": "Bielik\nPL", "IT_minerva": "Minerva\nIT"} | |
| def fig_cka_heatmap(): | |
| df = pd.read_csv(f"{ROOT}/results/crossmodel_pairs.csv") | |
| n = len(ORDER) | |
| Mx = np.full((n, n), np.nan) | |
| for _, r in df.iterrows(): | |
| i, j = ORDER.index(r.model_a), ORDER.index(r.model_b) | |
| Mx[max(i, j), min(i, j)] = r.cka # lower triangle: matched | |
| Mx[min(i, j), max(i, j)] = r.cka_shuf # upper triangle: shuffled control | |
| np.fill_diagonal(Mx, 1.0) | |
| fig, ax = plt.subplots(figsize=(4.6, 4.0)) | |
| im = ax.imshow(Mx, cmap="viridis", vmin=0, vmax=1) | |
| for i in range(n): | |
| for j in range(n): | |
| if np.isfinite(Mx[i, j]): | |
| ax.text(j, i, f"{Mx[i, j]:.3f}", ha="center", va="center", fontsize=7, | |
| color="white" if Mx[i, j] < 0.6 else "black") | |
| ax.set_xticks(range(n)); ax.set_xticklabels([LABEL[m] for m in ORDER], fontsize=6.5) | |
| ax.set_yticks(range(n)); ax.set_yticklabels([LABEL[m] for m in ORDER], fontsize=6.5) | |
| ax.set_title("Last pre-logit layer, SGPT-pooled linear CKA\n" | |
| "lower triangle = matched | upper triangle = shuffled control", fontsize=8) | |
| fig.colorbar(im, ax=ax, fraction=0.046, label="linear CKA") | |
| fig.savefig(f"{FIG}/fig1_cka_matched_shuffled.png"); plt.close(fig) | |
| print("wrote fig1") | |
| def _corrheat(path, title, out, maxn=22): | |
| if not os.path.exists(path): | |
| print("skip", path); return | |
| m = pd.read_csv(path, index_col=0) | |
| if len(m) == 0: return | |
| m = m.iloc[:maxn, :maxn] | |
| fig, ax = plt.subplots(figsize=(0.42 * len(m) + 2.2, 0.42 * len(m) + 1.8)) | |
| im = ax.imshow(m.values, cmap="RdBu_r", vmin=-1, vmax=1) | |
| for i in range(len(m)): | |
| for j in range(len(m)): | |
| v = m.values[i, j] | |
| if np.isfinite(v): | |
| ax.text(j, i, f"{v:.2f}", ha="center", va="center", fontsize=5.2, | |
| color="white" if abs(v) > 0.6 else "black") | |
| ax.set_xticks(range(len(m))); ax.set_xticklabels(m.columns, rotation=90, fontsize=6) | |
| ax.set_yticks(range(len(m))); ax.set_yticklabels(m.index, fontsize=6) | |
| ax.set_title(title, fontsize=8) | |
| fig.colorbar(im, ax=ax, fraction=0.046, label="Spearman rho") | |
| fig.savefig(out); plt.close(fig) | |
| print("wrote", out) | |
| def fig_merge_results(): | |
| p = f"{ROOT}/results/checkpoint_pairs.csv" | |
| if not os.path.exists(p): return | |
| ck = pd.read_csv(p) | |
| fams = sorted(ck.family.unique()) | |
| fig, axes = plt.subplots(1, 3, figsize=(11, 3.2)) | |
| cols = {"pythia": "tab:blue", "zhpythia": "tab:red"} | |
| for f in fams: | |
| g = ck[ck.family == f] | |
| axes[0].scatter(g.log10_step_ratio, g.barrier, s=14, alpha=.75, | |
| c=cols.get(f, "k"), label=f) | |
| axes[1].scatter(g.log10_step_ratio, g.gain_best, s=14, alpha=.75, c=cols.get(f, "k")) | |
| axes[2].scatter(g.w_cos, g.barrier, s=14, alpha=.75, c=cols.get(f, "k")) | |
| axes[0].set_xlabel("trajectory distance log10(step_b / step_a)") | |
| axes[0].set_ylabel("LMC barrier (nats/token)") | |
| axes[0].axhline(0, lw=.6, c="k"); axes[0].legend(fontsize=6) | |
| axes[1].set_xlabel("trajectory distance log10(step_b / step_a)") | |
| axes[1].set_ylabel("best merge gain over best endpoint") | |
| axes[1].axhline(0, lw=.6, c="k") | |
| axes[2].set_xlabel("weight cosine similarity"); axes[2].set_ylabel("LMC barrier") | |
| axes[2].axhline(0, lw=.6, c="k") | |
| fig.suptitle("Native weight-space checkpoint merging (same run, same parameter space)", | |
| fontsize=9) | |
| fig.tight_layout() | |
| fig.savefig(f"{FIG}/fig3_checkpoint_merge.png"); plt.close(fig) | |
| print("wrote fig3") | |
| if __name__ == "__main__": | |
| fig_cka_heatmap() | |
| _corrheat(f"{ROOT}/results/corrmat_checkpoint_ALL.csv", | |
| "Diagnostic x diagnostic Spearman rho -- checkpoint arm (native weight merging)", | |
| f"{FIG}/fig2a_corr_checkpoint.png") | |
| _corrheat(f"{ROOT}/results/corrmat_crossmodel.csv", | |
| "Diagnostic x diagnostic Spearman rho -- cross-model arm (n=10, UNDERPOWERED)", | |
| f"{FIG}/fig2b_corr_crossmodel.png") | |
| fig_merge_results() | |
| def fig_transport(): | |
| p = f"{ROOT}/results/transport_merge.csv" | |
| if not os.path.exists(p): return | |
| df = pd.read_csv(p) | |
| fig, axes = plt.subplots(1, 3, figsize=(13.5, 3.6)) | |
| for (t, d), g in df.groupby(["target", "donor"]): | |
| g = g.sort_values("alpha") | |
| lab = f"{t.split('_')[0]}<-{d.split('_')[0]}" | |
| axes[0].plot(g.alpha, g.nll - g.nll.iloc[0], marker="o", ms=3, lw=.9, label=lab) | |
| axes[1].plot(g.alpha, g.nll_donor_lang - g.nll_donor_lang.iloc[0], marker="o", ms=3, lw=.9) | |
| for ax, ttl in zip(axes[:2], ["evaluated on the TARGET's language", | |
| "evaluated on the DONOR's language\n(target tokenizer)"]): | |
| ax.axhline(0, lw=.6, c="k"); ax.set_xlabel(r"fusion coefficient $\alpha$") | |
| ax.set_ylabel(r"$\Delta$ NLL vs $\alpha=0$ (nats/token)"); ax.set_title(ttl, fontsize=8) | |
| axes[0].legend(fontsize=5, ncol=2) | |
| # panel 3: the random-plan control. Negative = the OT plan beats a shuffled plan, i.e. the | |
| # learned neuron correspondence carries information. | |
| amax = df.alpha.max() | |
| g = df[df.alpha == amax].copy() | |
| g["lab"] = [f"{t.split('_')[0]}<-{d.split('_')[0]}" for t, d in zip(g.target, g.donor)] | |
| g["dt"] = g.nll - g.nll_randplan | |
| g["dd"] = g.nll_donor_lang - g.nll_donor_lang_randplan | |
| g = g.sort_values("dt") | |
| y = np.arange(len(g)) | |
| axes[2].barh(y - .2, g.dt, height=.4, label="target language", color="tab:blue") | |
| axes[2].barh(y + .2, g.dd, height=.4, label="donor language", color="tab:orange") | |
| axes[2].set_yticks(y); axes[2].set_yticklabels(g.lab, fontsize=5.5) | |
| axes[2].axvline(0, lw=.6, c="k") | |
| axes[2].set_xlabel("NLL(OT plan) - NLL(shuffled plan), nats/token") | |
| axes[2].set_title(f"random-plan control at $\\alpha$={amax}\n" | |
| "negative = the learned correspondence helps", fontsize=8) | |
| axes[2].legend(fontsize=6) | |
| fig.suptitle("Transport-and-Merge (Cui et al. 2026), fusion only, no post-fusion adaptation", | |
| fontsize=9) | |
| fig.tight_layout(); fig.savefig(f"{FIG}/fig4_transport_merge.png"); plt.close(fig) | |
| print("wrote fig4") | |
| if __name__ == "__main__": | |
| fig_transport() | |