Download demo_core.py from Fareeha20Amir/diffusion-unlearning-interference: direct link, hf CLI and curl.
- Browser
- Download file 6.99 kB
-
https://huggingface.co/spaces/Fareeha20Amir/diffusion-unlearning-interference/resolve/main/demo_core.py
- Command line
-
hf download hf://spaces/Fareeha20Amir/diffusion-unlearning-interference/demo_core.py
-
curl -L -o demo_core.py https://huggingface.co/spaces/Fareeha20Amir/diffusion-unlearning-interference/resolve/main/demo_core.py
6.99 kB
| """Making a diffusion model forget one digit class, and what it costs the rest. | |
| Runs in the browser on the NumPy port in unlearn_np.py. The base model and the | |
| judge classifier are the exact ones the PyTorch run produced; the unlearning | |
| itself is recomputed here, step for step. | |
| """ | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import unlearn_np as U | |
| TITLE = "Is multi-concept interference schedulable?" | |
| FORGET = U.FORGET_CLASS | |
| METHODS = { | |
| "ascent": "push the forget class's loss up (unbounded)", | |
| "finetune-retain": "fine-tune on the retain set only", | |
| "anchored-ascent": "ascent, capped, with the retain set anchored", | |
| "redirect (flat)": "re-point the forget label at retain content", | |
| "redirect+per-t (ours)": "the same, scheduled per diffusion timestep", | |
| } | |
| INTRO = f"""The model is a small conditional diffusion model over 8×8 | |
| digits. The task is to make it forget class **{FORGET}** without retraining | |
| from scratch, and without wrecking the other nine. | |
| **Pick a method and run it.** The images are real samples drawn from the model | |
| before and after.""" | |
| NOTE = """The base model and judge are the trained PyTorch ones, loaded from | |
| `weights.npz`; the unlearning steps are recomputed here in NumPy. The two | |
| descent-based methods reproduce the published scores closely. The two | |
| ascent-based ones vary more between runs, which is the instability the report | |
| is about rather than a porting artefact.""" | |
| EXPLAIN = r"""**What the experiment does.** It takes a diffusion model trained | |
| on all ten digits and applies one unlearning operator, then measures two things | |
| that pull against each other: how well the target class was removed, and how | |
| much of the model's ability on the other nine survived. | |
| **The images are the output, and they are real samples.** The top two rows | |
| condition the model on the class it was told to forget, before and after. The | |
| bottom two condition it on a class it was supposed to keep. **A method has only | |
| worked if the top row changes and the bottom row does not.** | |
| **The two scores.** *Forget score* is how often an independent judge classifier | |
| still recognises a forget-conditioned sample as that digit — lower is better. | |
| *Retain score* is the judge's accuracy on the other nine classes — higher is | |
| better. Either number alone is easy to win: the interesting question is whether | |
| a method can move one without wrecking the other. | |
| **What to try, in this order.** | |
| - `ascent` — the obvious approach. The class vanishes and so does everything | |
| else: retain collapses. Look at the bottom row, it is noise. | |
| - `finetune-retain` — the safe approach. Retain is untouched and the class is | |
| still there. Nothing was forgotten. | |
| - `redirect (flat)` — forgets without collapsing, by re-pointing the label at | |
| retain content rather than pushing its loss up. | |
| - `redirect+per-t (ours)` — the same idea, but anchored harder at low-noise | |
| timesteps, where image detail is written. It recovers the retain quality that | |
| the flat version gives away. | |
| **Why per-timestep matters.** Class identity is decided at high-noise steps; | |
| fine appearance detail at low-noise steps. Redirection only needs the former, | |
| so the latter can be anchored hard. That is the scheduling claim in the | |
| title.""" | |
| CONTROLS = [ | |
| {"id": "method", "label": "Unlearning method", "type": "dropdown", | |
| "choices": list(METHODS), "value": "redirect+per-t (ours)"}, | |
| {"id": "steps", "label": "Unlearning steps", "type": "slider", | |
| "min": 20, "max": 220, "step": 20, "value": 140}, | |
| {"id": "anchor", "label": "Anchor weight", "type": "slider", | |
| "min": 0.0, "max": 2.0, "step": 0.1, "value": 1.0}, | |
| {"id": "keep", "label": "Class to watch for collateral damage", | |
| "type": "dropdown", "choices": [c for c in range(10) if c != FORGET], | |
| "value": 7}, | |
| {"id": "seed", "label": "Random seed", "type": "slider", | |
| "min": 0, "max": 20, "step": 1, "value": 0}, | |
| ] | |
| ACTIONS = [{"id": "run", "label": "Unlearn the class", "primary": True}] | |
| _S = {} | |
| def setup(): | |
| if "orig" not in _S: | |
| X, Y = U.digits() | |
| fm = Y == FORGET | |
| _S.update(orig=U.Denoiser.load(), judge=U.Judge.load(), | |
| Xf=X[fm], Yf=Y[fm], Xr=X[~fm], Yr=Y[~fm]) | |
| _S["base"] = U.evaluate(_S["orig"], _S["judge"], | |
| rng=np.random.default_rng(7)) | |
| return _S | |
| def _strip(model, cls, n=8, seed=0): | |
| x = U.sample(model, cls, n, rng=np.random.default_rng(seed)) | |
| return np.concatenate(list(x.reshape(n, 8, 8)), axis=1) | |
| def run(method, steps, anchor, keep, seed): | |
| plt.close("all") | |
| s = setup() | |
| f0, r0 = s["base"] | |
| keep = int(keep) | |
| m = U.unlearn(s["orig"], method, s["Xf"], s["Yf"], s["Xr"], s["Yr"], | |
| steps=int(steps), anchor_w=float(anchor), | |
| rng=np.random.default_rng(100 + int(seed))) | |
| f1, r1 = U.evaluate(m, s["judge"], rng=np.random.default_rng(7)) | |
| fig, ax = plt.subplots(4, 1, figsize=(10, 5.2)) | |
| rows = [(s["orig"], FORGET, f"BEFORE — conditioned on the forget class ({FORGET})"), | |
| (m, FORGET, f"AFTER — conditioned on the forget class ({FORGET})"), | |
| (s["orig"], keep, f"BEFORE — a class it must keep ({keep})"), | |
| (m, keep, f"AFTER — a class it must keep ({keep})")] | |
| for a, (mm, cls, ttl) in zip(ax, rows): | |
| a.imshow(_strip(mm, cls, seed=int(seed)), cmap="gray_r", | |
| vmin=-1, vmax=1, aspect="equal") | |
| a.set_title(ttl, fontsize=9, loc="left") | |
| a.axis("off") | |
| fig.tight_layout() | |
| if f1 < 0.15 and r1 > 0.75: | |
| verdict = ("**Worked.** The class is gone and the model still " | |
| "generates the digits it was asked to keep.") | |
| elif f1 < 0.15: | |
| verdict = ("**Forgot, but broke the model.** The class is gone, and so " | |
| "is much of the quality on the classes that were supposed " | |
| "to survive. That is collateral damage, not unlearning.") | |
| elif r1 > 0.75: | |
| verdict = ("**Did not forget.** Retain quality held up, but the model " | |
| "still produces the class it was told to drop.") | |
| else: | |
| verdict = ("**Failed on both axes** — neither removed the class " | |
| "nor preserved the others.") | |
| def arrow(b, a_): | |
| return f"{b:.3f} → **{a_:.3f}** ({'+' if a_ >= b else ''}{a_-b:.3f})" | |
| md = (f"{verdict}\n\n" | |
| f"| | before → after |\n|---|---|\n" | |
| f"| forget score (lower is better) | {arrow(f0, f1)} |\n" | |
| f"| retain score (higher is better) | {arrow(r0, r1)} |\n\n" | |
| f"*Method: {method} — {METHODS[method]}, {int(steps)} steps. " | |
| f"Forget score is how often the judge still calls a " | |
| f"forget-conditioned sample a {FORGET}; retain score is its accuracy " | |
| f"on the other nine classes.*") | |
| return md, fig | |
| def call(action, v): | |
| return run(v["method"], v["steps"], v["anchor"], v["keep"], v["seed"]) | |