Download experiment.py from Fareeha20Amir/diffusion-unlearning-interference: direct link, hf CLI and curl.
- Browser
- Download file 19.2 kB
-
https://huggingface.co/spaces/Fareeha20Amir/diffusion-unlearning-interference/resolve/main/experiment.py
- Command line
-
hf download hf://spaces/Fareeha20Amir/diffusion-unlearning-interference/experiment.py
-
curl -L -o experiment.py https://huggingface.co/spaces/Fareeha20Amir/diffusion-unlearning-interference/resolve/main/experiment.py
19.2 kB
| """ | |
| Anchored Unlearning in Diffusion Models: | |
| Separating Forgetting from Collateral Damage | |
| THE PROBLEM | |
| ----------- | |
| Unlearning a concept from a diffusion model is easy if you do not care what else | |
| breaks. Gradient ascent on the forget set destroys the target concept -- and | |
| degrades everything else at the same time. The literature reports forgetting | |
| quality prominently and collateral damage vaguely. | |
| CONTRIBUTION | |
| ------------ | |
| 1. A two-axis evaluation that scores FORGET QUALITY and RETAIN QUALITY | |
| separately, against the retrain-from-scratch gold standard. | |
| 2. ANCHORED ASCENT: gradient ascent on the forget set, constrained by an | |
| explicit anchor penalty that keeps predictions on the retain set close to the | |
| ORIGINAL model. The anchor is what converts indiscriminate damage into | |
| targeted forgetting. | |
| 3. A compute-cost comparison -- unlearning is only worth doing if it beats | |
| retraining, and that claim is rarely measured. | |
| Everything runs on CPU: a compact class-conditional DDPM over 8x8 digits | |
| (sklearn load_digits, NO DOWNLOAD). Runtime ~4-6 minutes. | |
| """ | |
| import json | |
| import os | |
| import time | |
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| from sklearn.datasets import load_digits | |
| from sklearn.neural_network import MLPClassifier | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| torch.manual_seed(0) | |
| np.random.seed(0) | |
| OUT = os.path.dirname(os.path.abspath(__file__)) | |
| T = 100 # diffusion steps | |
| DIM = 64 # 8x8 | |
| FORGET_CLASS = 3 | |
| EPOCHS = 260 | |
| UNLEARN_STEPS = 140 | |
| # --------------------------------------------------------------------------- | |
| # Compact class-conditional denoiser | |
| # --------------------------------------------------------------------------- | |
| class Denoiser(nn.Module): | |
| def __init__(self, dim=DIM, h=256, n_cls=10): | |
| super().__init__() | |
| self.cls = nn.Embedding(n_cls, 32) | |
| self.tim = nn.Linear(1, 32) | |
| self.net = nn.Sequential( | |
| nn.Linear(dim + 64, h), nn.SiLU(), | |
| nn.Linear(h, h), nn.SiLU(), | |
| nn.Linear(h, dim), | |
| ) | |
| def forward(self, x, t, y): | |
| te = torch.sin(self.tim(t.float().unsqueeze(-1) / T)) | |
| ce = self.cls(y) | |
| return self.net(torch.cat([x, te, ce], dim=-1)) | |
| def schedule(): | |
| betas = torch.linspace(1e-4, 0.08, T) | |
| alphas = 1.0 - betas | |
| ab = torch.cumprod(alphas, 0) | |
| return betas, alphas, ab | |
| BETAS, ALPHAS, AB = schedule() | |
| def diffuse(x0, t, noise): | |
| a = AB[t].unsqueeze(-1) | |
| return a.sqrt() * x0 + (1 - a).sqrt() * noise | |
| def train_model(X, Y, epochs=EPOCHS, init=None, lr=2e-3, verbose=False): | |
| m = Denoiser() | |
| if init is not None: | |
| m.load_state_dict(init) | |
| opt = torch.optim.Adam(m.parameters(), lr=lr) | |
| n = len(X) | |
| for ep in range(epochs): | |
| idx = torch.randint(0, n, (256,)) | |
| x0, y = X[idx], Y[idx] | |
| t = torch.randint(0, T, (len(idx),)) | |
| noise = torch.randn_like(x0) | |
| xt = diffuse(x0, t, noise) | |
| loss = ((m(xt, t, y) - noise) ** 2).mean() | |
| opt.zero_grad() | |
| loss.backward() | |
| opt.step() | |
| return m | |
| def sample(model, cls, n=64): | |
| x = torch.randn(n, DIM) | |
| y = torch.full((n,), cls, dtype=torch.long) | |
| for t in reversed(range(T)): | |
| tt = torch.full((n,), t, dtype=torch.long) | |
| eps = model(x, tt, y) | |
| a, ab = ALPHAS[t], AB[t] | |
| mean = (x - (1 - a) / (1 - ab).sqrt() * eps) / a.sqrt() | |
| x = mean + (BETAS[t].sqrt() * torch.randn_like(x) if t > 0 else 0) | |
| # a diverged (NaN/inf) model is a REAL outcome of unbounded ascent -- | |
| # sanitise so it is SCORED as garbage rather than crashing the harness | |
| x = torch.nan_to_num(x, nan=0.0, posinf=3.0, neginf=-3.0).clamp(-4, 4) | |
| return x | |
| # --------------------------------------------------------------------------- | |
| # Unlearning methods | |
| # --------------------------------------------------------------------------- | |
| def unlearn_ascent(orig, Xf, Yf, steps=UNLEARN_STEPS, lr=5e-4): | |
| """Plain gradient ASCENT on the forget set -- maximise its denoising loss.""" | |
| m = Denoiser() | |
| m.load_state_dict(orig.state_dict()) | |
| opt = torch.optim.Adam(m.parameters(), lr=lr) | |
| for _ in range(steps): | |
| idx = torch.randint(0, len(Xf), (128,)) | |
| x0, y = Xf[idx], Yf[idx] | |
| t = torch.randint(0, T, (len(idx),)) | |
| noise = torch.randn_like(x0) | |
| xt = diffuse(x0, t, noise) | |
| loss = -((m(xt, t, y) - noise) ** 2).mean() # ascent | |
| opt.zero_grad() | |
| loss.backward() | |
| opt.step() | |
| return m | |
| def unlearn_finetune(orig, Xr, Yr, steps=UNLEARN_STEPS, lr=5e-4): | |
| """Fine-tune on the retain set only -- hope the concept fades.""" | |
| m = Denoiser() | |
| m.load_state_dict(orig.state_dict()) | |
| opt = torch.optim.Adam(m.parameters(), lr=lr) | |
| for _ in range(steps): | |
| idx = torch.randint(0, len(Xr), (128,)) | |
| x0, y = Xr[idx], Yr[idx] | |
| t = torch.randint(0, T, (len(idx),)) | |
| noise = torch.randn_like(x0) | |
| xt = diffuse(x0, t, noise) | |
| loss = ((m(xt, t, y) - noise) ** 2).mean() | |
| opt.zero_grad() | |
| loss.backward() | |
| opt.step() | |
| return m | |
| def unlearn_anchored(orig, Xf, Yf, Xr, Yr, steps=UNLEARN_STEPS, lr=5e-4, | |
| anchor_w=1.0, cap=4.0): | |
| """ | |
| CONTRIBUTION -- anchored ascent. | |
| Two changes to plain ascent: | |
| (a) the ascent term is CAPPED, so once the forget loss is high enough the | |
| gradient stops pushing (unbounded ascent is what wrecks the model); | |
| (b) an ANCHOR penalty keeps the model's predictions on the RETAIN set | |
| close to the ORIGINAL model's predictions -- a functional constraint | |
| rather than a weight-space one. | |
| """ | |
| m = Denoiser() | |
| m.load_state_dict(orig.state_dict()) | |
| orig.eval() | |
| opt = torch.optim.Adam(m.parameters(), lr=lr) | |
| for _ in range(steps): | |
| fi = torch.randint(0, len(Xf), (96,)) | |
| x0, y = Xf[fi], Yf[fi] | |
| t = torch.randint(0, T, (len(fi),)) | |
| noise = torch.randn_like(x0) | |
| xt = diffuse(x0, t, noise) | |
| f_loss = ((m(xt, t, y) - noise) ** 2).mean() | |
| forget_term = -torch.clamp(f_loss, max=cap) # capped ascent | |
| ri = torch.randint(0, len(Xr), (96,)) | |
| xr, yr = Xr[ri], Yr[ri] | |
| tr = torch.randint(0, T, (len(ri),)) | |
| nr = torch.randn_like(xr) | |
| xtr = diffuse(xr, tr, nr) | |
| with torch.no_grad(): | |
| ref = orig(xtr, tr, yr) | |
| anchor = ((m(xtr, tr, yr) - ref) ** 2).mean() # functional anchor | |
| loss = forget_term + anchor_w * anchor | |
| opt.zero_grad() | |
| loss.backward() | |
| opt.step() | |
| return m | |
| def unlearn_redirect(orig, Xr, Yr, steps=UNLEARN_STEPS, lr=5e-4, anchor_w=1.0, | |
| per_timestep=False, k=3.0): | |
| """ | |
| CONCEPT REDIRECTION (the method that actually works here). | |
| Instead of pushing the forget concept's loss UP (ascent, which is unbounded | |
| and destroys shared weights), we REDIRECT the conditioning: train the model | |
| so that conditioning on FORGET_CLASS reconstructs RETAIN-class images. | |
| The forget label is not erased, it is re-pointed at benign content. The | |
| objective stays a normal descent problem, so it never diverges -- which is | |
| exactly the failure mode of ascent. | |
| """ | |
| m = Denoiser() | |
| m.load_state_dict(orig.state_dict()) | |
| orig.eval() | |
| opt = torch.optim.Adam(m.parameters(), lr=lr) | |
| for _ in range(steps): | |
| # retain images, but LABELLED as the forget class | |
| ri = torch.randint(0, len(Xr), (96,)) | |
| x0 = Xr[ri] | |
| yf = torch.full((len(ri),), FORGET_CLASS, dtype=torch.long) | |
| t = torch.randint(0, T, (len(ri),)) | |
| noise = torch.randn_like(x0) | |
| xt = diffuse(x0, t, noise) | |
| redirect = ((m(xt, t, yf) - noise) ** 2).mean() | |
| # keep the other classes behaving exactly as before | |
| ri2 = torch.randint(0, len(Xr), (96,)) | |
| xr, yr = Xr[ri2], Yr[ri2] | |
| tr = torch.randint(0, T, (len(ri2),)) | |
| nr = torch.randn_like(xr) | |
| xtr = diffuse(xr, tr, nr) | |
| with torch.no_grad(): | |
| ref = orig(xtr, tr, yr) | |
| if per_timestep: | |
| # PER-TIMESTEP ANCHORING. | |
| # Class identity is decided at HIGH-noise steps (large t); fine | |
| # appearance detail is written at LOW-noise steps (small t). | |
| # Redirection only needs to act on the former, so anchor the latter | |
| # hard -- that is where retain quality is lost. | |
| wt = 1.0 + k * (1.0 - tr.float() / T) # strong at small t | |
| per = ((m(xtr, tr, yr) - ref) ** 2).mean(dim=-1) | |
| anchor = (wt * per).mean() | |
| # correspondingly let redirection act mainly at high t | |
| wf = (t.float() / T).clamp(min=0.15) | |
| redir_per = ((m(xt, t, yf) - noise) ** 2).mean(dim=-1) | |
| redirect = (wf * redir_per).mean() | |
| else: | |
| anchor = ((m(xtr, tr, yr) - ref) ** 2).mean() | |
| loss = redirect + anchor_w * anchor | |
| opt.zero_grad() | |
| loss.backward() | |
| opt.step() | |
| return m | |
| def relearn(model, Xf, Yf, steps, lr=5e-4): | |
| """ | |
| RELEARNING ATTACK. | |
| The literature's sharpest criticism of diffusion unlearning is that methods | |
| SUPPRESS a concept rather than erase it: a few fine-tuning steps on the | |
| forgotten class bring it straight back. (See Meta-Unlearning, and | |
| "The Illusion of Unlearning".) | |
| The gold standard -- a model retrained from scratch without the class -- | |
| gives the reference. It can of course still LEARN the class, because any | |
| model can; what matters is whether an unlearned model recovers it | |
| *faster* than the gold standard does. Faster recovery means the information | |
| was still present, merely masked. | |
| """ | |
| m = Denoiser() | |
| m.load_state_dict(model.state_dict()) | |
| opt = torch.optim.Adam(m.parameters(), lr=lr) | |
| for _ in range(steps): | |
| idx = torch.randint(0, len(Xf), (96,)) | |
| x0, y = Xf[idx], Yf[idx] | |
| t = torch.randint(0, T, (len(idx),)) | |
| noise = torch.randn_like(x0) | |
| xt = diffuse(x0, t, noise) | |
| loss = ((m(xt, t, y) - noise) ** 2).mean() | |
| opt.zero_grad() | |
| loss.backward() | |
| opt.step() | |
| return m | |
| # --------------------------------------------------------------------------- | |
| # Two-axis evaluation | |
| # --------------------------------------------------------------------------- | |
| def evaluate(model, judge, n=64): | |
| """forget_score: P(judge says FORGET_CLASS) on forget-conditioned samples. | |
| retain_score: judge accuracy on samples conditioned on other classes.""" | |
| g = np.nan_to_num(sample(model, FORGET_CLASS, n).numpy(), nan=0.0, | |
| posinf=1.0, neginf=-1.0) | |
| pf = float((judge.predict(g) == FORGET_CLASS).mean()) | |
| accs = [] | |
| for c in range(10): | |
| if c == FORGET_CLASS: | |
| continue | |
| gc = np.nan_to_num(sample(model, c, 24).numpy(), nan=0.0, | |
| posinf=1.0, neginf=-1.0) | |
| accs.append(float((judge.predict(gc) == c).mean())) | |
| return pf, float(np.mean(accs)) | |
| def main(): | |
| print("=" * 78) | |
| print("Anchored Unlearning in Diffusion Models") | |
| print("=" * 78) | |
| d = load_digits() | |
| Xn = (d.data / 16.0) * 2 - 1 | |
| X = torch.tensor(Xn, dtype=torch.float32) | |
| Y = torch.tensor(d.target, dtype=torch.long) | |
| print(f"\n[1/5] Judge classifier on real 8x8 digits ...") | |
| judge = MLPClassifier(hidden_layer_sizes=(128,), max_iter=800, | |
| random_state=0).fit(Xn, d.target) | |
| print(f" judge train accuracy: {judge.score(Xn, d.target):.4f}") | |
| fm = (Y == FORGET_CLASS) | |
| Xf, Yf = X[fm], Y[fm] | |
| Xr, Yr = X[~fm], Y[~fm] | |
| print(f" forget class = {FORGET_CLASS} ({len(Xf)} samples), " | |
| f"retain = {len(Xr)}") | |
| print("\n[2/5] Training ORIGINAL diffusion model (all classes) ...") | |
| t0 = time.perf_counter() | |
| orig = train_model(X, Y) | |
| t_orig = time.perf_counter() - t0 | |
| print(f" {t_orig:.1f}s") | |
| print("\n[3/5] GOLD STANDARD: retrain from scratch without the class ...") | |
| t0 = time.perf_counter() | |
| gold = train_model(Xr, Yr) | |
| t_gold = time.perf_counter() - t0 | |
| print(f" {t_gold:.1f}s") | |
| print("\n[4/5] Unlearning methods ...") | |
| methods = {} | |
| t0 = time.perf_counter() | |
| methods["ascent"] = (unlearn_ascent(orig, Xf, Yf), time.perf_counter() - t0) | |
| t0 = time.perf_counter() | |
| methods["finetune-retain"] = (unlearn_finetune(orig, Xr, Yr), | |
| time.perf_counter() - t0) | |
| # sweep the anchor weight: this traces the forget/retain TRADE-OFF CURVE | |
| # rather than reporting one hand-tuned point | |
| sweep = [] | |
| for aw in [0.0, 0.1, 0.25, 0.5, 1.0, 2.0]: | |
| t0 = time.perf_counter() | |
| mm = unlearn_anchored(orig, Xf, Yf, Xr, Yr, anchor_w=aw, cap=4.0, | |
| steps=UNLEARN_STEPS) | |
| sweep.append((aw, mm, time.perf_counter() - t0)) | |
| methods["anchored-ascent"] = (sweep[3][1], sweep[3][2]) | |
| t0 = time.perf_counter() | |
| methods["redirect (flat)"] = (unlearn_redirect(orig, Xr, Yr), | |
| time.perf_counter() - t0) | |
| t0 = time.perf_counter() | |
| methods["redirect+per-t (ours)"] = ( | |
| unlearn_redirect(orig, Xr, Yr, per_timestep=True, anchor_w=1.0, k=3.0), | |
| time.perf_counter() - t0) | |
| print("\n[5/5] Two-axis evaluation ...") | |
| print("\n {:>18} {:>14} {:>14} {:>12}".format( | |
| "model", "forget score", "retain score", "cost (s)")) | |
| print(" {:>18} {:>14} {:>14} {:>12}".format( | |
| "", "(lower=better)", "(higher=better)", "")) | |
| rows = [] | |
| pf, pr = evaluate(orig, judge) | |
| rows.append({"model": "original", "forget": pf, "retain": pr, "cost": t_orig}) | |
| print(" {:>18} {:>14.4f} {:>14.4f} {:>12.1f}".format( | |
| "original", pf, pr, t_orig)) | |
| pf, pr = evaluate(gold, judge) | |
| gold_f, gold_r = pf, pr | |
| rows.append({"model": "retrain (gold)", "forget": pf, "retain": pr, | |
| "cost": t_gold}) | |
| print(" {:>18} {:>14.4f} {:>14.4f} {:>12.1f}".format( | |
| "retrain (gold)", pf, pr, t_gold)) | |
| for name, (m, cost) in methods.items(): | |
| pf, pr = evaluate(m, judge) | |
| rows.append({"model": name, "forget": pf, "retain": pr, "cost": cost}) | |
| print(" {:>18} {:>14.4f} {:>14.4f} {:>12.1f}".format( | |
| name, pf, pr, cost)) | |
| print("") | |
| print(" Anchor-weight sweep (the trade-off curve):") | |
| print(" {:>10} {:>14} {:>14} {:>14}".format("anchor_w","forget","retain","dist to gold")) | |
| sweep_rows = [] | |
| for aw, mm, cc in sweep: | |
| f_, r_ = evaluate(mm, judge) | |
| dd = float(np.hypot(f_ - gold_f, r_ - gold_r)) | |
| sweep_rows.append({"anchor_w": aw, "forget": f_, "retain": r_, "dist_to_gold": dd, "cost": cc}) | |
| print(" {:>10.2f} {:>14.4f} {:>14.4f} {:>14.4f}".format(aw, f_, r_, dd)) | |
| bestsw = min(sweep_rows, key=lambda z: z["dist_to_gold"]) | |
| print(" best anchor_w = {:.2f} (dist {:.4f})".format(bestsw["anchor_w"], bestsw["dist_to_gold"])) | |
| print("") | |
| print("\n Distance to the gold standard (lower is better):") | |
| print(" {:>18} {:>16}".format("model", "||(df, dr)||")) | |
| for r in rows: | |
| if r["model"] in ("retrain (gold)",): | |
| continue | |
| dist = float(np.hypot(r["forget"] - gold_f, r["retain"] - gold_r)) | |
| r["dist_to_gold"] = dist | |
| print(" {:>18} {:>16.4f}".format(r["model"], dist)) | |
| print("") | |
| print("[5b] RELEARNING ATTACK -- is the concept erased, or only masked?") | |
| print(" Fine-tuning each model on the forgotten class and measuring") | |
| print(" how fast the forget score climbs back.") | |
| relearn_steps = [0, 2, 4, 6, 8, 12, 20] # finer: the signal saturates by ~25 | |
| targets = {"retrain (gold)": gold, | |
| "ascent": methods["ascent"][0], | |
| "redirect+per-t (ours)": methods["redirect+per-t (ours)"][0]} | |
| print(" {:>22}".format("model") + "".join( | |
| "{:>10}".format("s=%d" % k) for k in relearn_steps)) | |
| relearn_rows = {} | |
| for name, mdl in targets.items(): | |
| row = [] | |
| for k in relearn_steps: | |
| mk = relearn(mdl, Xf, Yf, k) if k > 0 else mdl | |
| f_, _ = evaluate(mk, judge, n=48) | |
| row.append(f_) | |
| relearn_rows[name] = row | |
| print(" {:>22}".format(name) + "".join( | |
| "{:>10.4f}".format(v) for v in row)) | |
| print(" (forget score: higher = the concept is back)") | |
| gold_row = relearn_rows["retrain (gold)"] | |
| ours_row = relearn_rows["redirect+per-t (ours)"] | |
| # area under the recovery curve BEFORE saturation is the sensitive statistic; | |
| # a per-step threshold is too blunt once both curves hit the ceiling | |
| auc_ours = float(np.trapezoid(ours_row, relearn_steps)) | |
| auc_gold = float(np.trapezoid(gold_row, relearn_steps)) | |
| print(" recovery AUC (lower = slower to come back):") | |
| print(" retrain (gold) {:.3f} ours {:.3f} ratio {:.2f}x".format( | |
| auc_gold, auc_ours, auc_ours / max(auc_gold, 1e-9))) | |
| if auc_ours > 1.15 * auc_gold: | |
| print(" -> ours recovers FASTER than gold: residual information remains") | |
| elif auc_ours < 0.85 * auc_gold: | |
| print(" -> ours recovers SLOWER than gold") | |
| else: | |
| print(" -> recovery rates comparable; no evidence of mere suppression") | |
| speed = t_gold / max(methods["redirect+per-t (ours)"][1], 1e-9) | |
| print(f"\n Redirect unlearning is {speed:.1f}x faster than retraining") | |
| with open(os.path.join(OUT, "results.json"), "w") as f: | |
| json.dump({"rows": rows, "anchor_sweep": sweep_rows, | |
| "relearning": relearn_rows, "relearn_steps": relearn_steps, | |
| "recovery_auc": {"gold": auc_gold, "ours": auc_ours}, | |
| "forget_class": FORGET_CLASS, | |
| "speedup_vs_retrain": speed}, f, indent=2) | |
| fig, ax = plt.subplots(1, 2, figsize=(11, 4.4)) | |
| for r in rows: | |
| ax[0].scatter(r["forget"], r["retain"], s=90, label=r["model"], zorder=3) | |
| ax[0].set_xlabel("forget score (lower = better forgetting)") | |
| ax[0].set_ylabel("retain score (higher = less collateral damage)") | |
| ax[0].set_title("The two axes of unlearning") | |
| # Names go in a legend parked in the empty lower-right quadrant: point | |
| # labels placed at a fixed offset collide wherever the models cluster. | |
| ax[0].set_xlim(-0.08, 1.10) | |
| ax[0].set_ylim(-0.05, 1.08) | |
| ax[0].grid(alpha=0.3) | |
| ax[0].legend(loc="lower right", fontsize=7, frameon=True, | |
| framealpha=0.95, borderpad=0.6, labelspacing=0.45) | |
| names = [r["model"] for r in rows] | |
| ax[1].bar(range(len(rows)), [r["cost"] for r in rows]) | |
| ax[1].set_xticks(range(len(rows))) | |
| ax[1].set_xticklabels(names, rotation=25, ha="right", fontsize=7) | |
| ax[1].set_ylabel("compute cost (s)") | |
| ax[1].set_title("Unlearning vs retraining cost") | |
| ax[1].grid(alpha=0.3, axis="y") | |
| plt.tight_layout() | |
| plt.savefig(os.path.join(OUT, "figure_unlearning.png"), dpi=140) | |
| print("\nDone. Wrote results.json and figure_unlearning.png") | |
| if __name__ == "__main__": | |
| main() | |