Download src/make_figs.py from Ziruibest/jspace-unlearning: direct link, hf CLI and curl.
- Browser
- Download file 8.62 kB
-
https://huggingface.co/datasets/Ziruibest/jspace-unlearning/resolve/main/src/make_figs.py
- Command line
-
hf download hf://datasets/Ziruibest/jspace-unlearning/src/make_figs.py
-
curl -L -o make_figs.py https://huggingface.co/datasets/Ziruibest/jspace-unlearning/resolve/main/src/make_figs.py
8.62 kB
| """Generate all data figures for the paper (PDF + PNG preview). | |
| Fig 3 (audit): (a) 2x4 small-multiple FQ x J-Access scatter, each method | |
| highlighted against the full grid in gray; | |
| (b) layer profile with the workspace band shaded. | |
| Fig 4 (predict): 4x2 small multiples, one per unlearning method: nine | |
| checkpoints of pre-attack J-Access vs excess revival | |
| with a Theil-Sen fit. | |
| Fig 5 (goodhart): two panels sharing lambda: J-Access_K + UDS (left), revival | |
| (right); three-seed error bars. | |
| Palette: dataviz reference palette (light), <=3 categorical hues per | |
| all-pairs panel; identity via panel titles / direct labels, never color | |
| alone. One axis per panel. | |
| """ | |
| import json | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| from matplotlib.ticker import MaxNLocator | |
| from scipy import stats | |
| RES = "/workspace/jspace-unlearning/results" | |
| OUT = "/workspace/jspace-unlearning/paper/figs" | |
| BLUE, ORANGE, AQUA = "#2a78d6", "#eb6834", "#1baf7a" | |
| INK, MUTED, GRIDC = "#0b0b0b", "#52514e", "#e6e5e1" | |
| GRAY_PT = "#c9c8c2" | |
| plt.rcParams.update({ | |
| "font.size": 7.5, "axes.titlesize": 8, "axes.labelsize": 7.5, | |
| "xtick.labelsize": 7, "ytick.labelsize": 7, "legend.fontsize": 7, | |
| "axes.edgecolor": MUTED, "axes.linewidth": 0.6, | |
| "xtick.color": MUTED, "ytick.color": MUTED, | |
| "axes.labelcolor": INK, "text.color": INK, | |
| "figure.dpi": 200, "savefig.bbox": "tight", | |
| }) | |
| def style(ax): | |
| for s in ("top", "right"): | |
| ax.spines[s].set_visible(False) | |
| def save(fig, name): | |
| fig.savefig(f"{OUT}/{name}.pdf") | |
| fig.savefig(f"{OUT}/{name}.png") | |
| plt.close(fig) | |
| print("saved", name) | |
| # ------------------------------------------------------------------ fig 3 | |
| def fig3(): | |
| grid = json.load(open(f"{RES}/p0a_grid398.json")) | |
| # drop runs whose KS p-value underflowed to 0 (would pile up at the | |
| # clip value); the paper notes their omission | |
| models = {k: v for k, v in grid["models"].items() if v["fq"] > 1e-30} | |
| jf, jg = grid["digest"]["j_full"], grid["digest"]["j_gold"] | |
| lfq = {k: np.log10(v["fq"]) for k, v in models.items()} | |
| methods = sorted({v["method"] for v in models.values()}) | |
| fig, axes = plt.subplots(2, 4, figsize=(7.0, 3.6), sharex=True, | |
| sharey=True, constrained_layout=True) | |
| for ax, meth in zip(axes.flat, methods): | |
| style(ax) | |
| xs_all = [lfq[k] for k in models] | |
| ys_all = [models[k]["jocc10"] for k in models] | |
| ax.scatter(xs_all, ys_all, s=4, color=GRAY_PT, linewidths=0, | |
| zorder=2, rasterized=True) | |
| sel = {k: v for k, v in models.items() if v["method"] == meth} | |
| succ = {k: v for k, v in sel.items() | |
| if v["fq"] > 0.05 and v["mu"] >= 0.9 * 0.5994} | |
| ax.scatter([lfq[k] for k in sel], [v["jocc10"] for v in sel.values()], | |
| s=7, color=BLUE, linewidths=0, zorder=3) | |
| ax.scatter([lfq[k] for k in succ], [v["jocc10"] for v in succ.values()], | |
| s=16, facecolors="none", edgecolors=INK, linewidths=0.7, | |
| zorder=4) | |
| ax.axhline(jf, color=MUTED, lw=0.7, ls=(0, (4, 2)), zorder=1) | |
| ax.axhline(jg, color=MUTED, lw=0.7, ls=(0, (1, 1.5)), zorder=1) | |
| ax.set_title(meth, pad=2) | |
| ax.set_xlim(-31, 1.5) | |
| ax.set_ylim(-0.03, 0.85) | |
| fig.supxlabel(r"$\log_{10}$ Forget Quality $\;\longrightarrow\;$" | |
| " better behavioral forgetting", fontsize=7.5) | |
| fig.supylabel(r"Raw Target Access Rate $A_{10}$", fontsize=7.5) | |
| axes[0, 0].text(-30, jf + 0.02, r"$\theta_0$", fontsize=7, color=MUTED) | |
| axes[0, 0].text(-30, jg + 0.02, r"$\theta_g$", fontsize=7, color=MUTED) | |
| axes[0, 0].annotate("lower residual\naccess", xy=(-23, 0.01), | |
| xytext=(-23, 0.13), fontsize=6, color=MUTED, | |
| ha="center", va="bottom", | |
| arrowprops=dict(arrowstyle="->", color=MUTED, lw=0.7)) | |
| handles = [ | |
| plt.Line2D([], [], marker="o", ls="", ms=3, color=GRAY_PT, | |
| label="all runs (pooled)"), | |
| plt.Line2D([], [], marker="o", ls="", ms=3.5, color=BLUE, | |
| label="this method's runs"), | |
| plt.Line2D([], [], marker="o", ls="", ms=5, mfc="none", mec=INK, | |
| mew=0.7, label="passes FQ + utility gates"), | |
| plt.Line2D([], [], color=MUTED, lw=0.9, ls=(0, (4, 2)), | |
| label=r"Original model $\theta_0$"), | |
| plt.Line2D([], [], color=MUTED, lw=0.9, ls=(0, (1, 1.5)), | |
| label=r"Retain-only model $\theta_g$"), | |
| ] | |
| fig.legend(handles=handles, ncol=5, frameon=False, fontsize=6.5, | |
| loc="outside upper center", columnspacing=1.0, | |
| handletextpad=0.4, handlelength=1.6) | |
| save(fig, "fig3a_grid_scatter") | |
| prof = json.load(open(f"{RES}/p2b_layer_profile.json")) | |
| fig, ax = plt.subplots(figsize=(3.3, 2.1), constrained_layout=True) | |
| style(ax) | |
| ax.axvspan(11, 14, color=GRIDC, alpha=0.6, zorder=0) | |
| series = [("full", "full", BLUE, "-"), | |
| ("retain90", "gold (retain-only)", MUTED, (0, (4, 2))), | |
| ("NPO", "NPO (best FQ)", ORANGE, "-"), | |
| ("RMU", "RMU", AQUA, "-")] | |
| for key, label, color, ls in series: | |
| p = prof[key]["jocc10_by_layer_prefix"] | |
| xs = [int(k) for k in p if k != "15"] | |
| ys = [p[str(x)] for x in xs] | |
| ax.plot(xs, ys, color=color, lw=1.4, ls=ls, zorder=3) | |
| ax.annotate(label, (xs[-1], ys[-1]), textcoords="offset points", | |
| xytext=(3, 0), fontsize=6.5, color=INK, va="center") | |
| ax.set_xlabel("lens layer") | |
| ax.set_ylabel("J-Access (per layer)") | |
| ax.set_xlim(0, 17) | |
| ax.set_xticks(range(0, 15, 2)) | |
| ax.text(12.5, 0.55, "workspace\nband", fontsize=6.5, color=MUTED, | |
| ha="center") | |
| save(fig, "fig3b_layer_profile") | |
| # ------------------------------------------------------------------ fig 4 | |
| def fig4(): | |
| h2 = json.load(open(f"{RES}/h2_ckpt_stats.json")) | |
| methods = sorted({k.split("_")[0] for k in h2}) | |
| fig, axes = plt.subplots(4, 2, figsize=(3.1, 4.4), sharey=True, | |
| constrained_layout=True) | |
| for ax, meth in zip(axes.flat, methods): | |
| style(ax) | |
| xs, ye = map(np.array, zip(*[ | |
| (v["jocc_v2_mean"], v["excess_rate"]) for k, v in h2.items() | |
| if k.split("_")[0] == meth])) | |
| ax.axhline(0, color=GRAY_PT, lw=0.6) | |
| ax.scatter(xs, ye, s=8, color=BLUE, linewidths=0, zorder=3) | |
| slope, intercept, _, _ = stats.theilslopes(ye, xs) | |
| xf = np.array([xs.min(), xs.max()]) | |
| ax.plot(xf, intercept + slope * xf, color=INK, lw=0.9, | |
| ls=(0, (4, 2)), zorder=2) | |
| ax.set_title(meth, pad=2) | |
| ax.xaxis.set_major_locator(MaxNLocator(3)) | |
| ax.set_ylim(-0.6, 0.5) | |
| ax.set_yticks([-0.4, 0, 0.4]) | |
| fig.supxlabel("pre-attack J-Access", fontsize=7.5) | |
| fig.supylabel("excess revival", fontsize=7.5) | |
| save(fig, "fig4_prediction") | |
| # ------------------------------------------------------------------ fig 5 | |
| def fig5(): | |
| seeds = json.load(open(f"{RES}/p1b_seeds.json")) | |
| uds = json.load(open(f"{RES}/h3_uds_comparison.json")) | |
| lams = [0, 5, 10] | |
| def agg(field): | |
| m, s = [], [] | |
| for lam in lams: | |
| v = [r[field] for r in seeds.values() if r["lam"] == lam] | |
| m.append(np.mean(v)) | |
| s.append(np.std(v, ddof=1)) | |
| return np.array(m), np.array(s) | |
| jm, js = agg("JOcc2") | |
| rm, rs = agg("within_revive") | |
| um = [uds[f"WDd_l{lam}"]["UDS"] for lam in lams] | |
| fig, (a, b) = plt.subplots(1, 2, figsize=(3.92, 2.4), sharex=True, | |
| constrained_layout=True) | |
| # all text (labels, tick labels, annotations) left off: added by hand later | |
| for ax in (a, b): | |
| style(ax) | |
| ax.set_xticks(lams) | |
| ax.set_xticklabels([]) | |
| a.errorbar(lams, jm, yerr=js, color=BLUE, lw=1.4, marker="o", ms=3.5, | |
| capsize=2, elinewidth=0.8) | |
| a.plot(lams, um, color=MUTED, lw=1.2, ls=(0, (4, 2)), marker="s", ms=3) | |
| a.set_ylim(0.45, 0.85) | |
| a.set_yticks([0.5, 0.6, 0.7, 0.8]) | |
| a.set_yticklabels([]) | |
| b.errorbar(lams, rm, yerr=rs, color=ORANGE, lw=1.4, marker="o", ms=3.5, | |
| capsize=2, elinewidth=0.8) | |
| b.set_ylim(0.24, 0.42) | |
| b.set_yticks([0.25, 0.30, 0.35, 0.40]) | |
| b.set_yticklabels([]) | |
| save(fig, "fig5_goodhart") | |
| if __name__ == "__main__": | |
| import os | |
| os.makedirs(OUT, exist_ok=True) | |
| fig3() | |
| fig4() | |
| fig5() | |