"""NumPy port of the diffusion-unlearning experiment, so it can run in a browser. PyTorch is not available in the browser Python runtime. The denoiser is a small MLP and every unlearning operator is a weighted mean-squared error on it, so the forward pass, the gradients and Adam are written out by hand here. The base model is NOT retrained: `weights.npz` holds the exact parameters the PyTorch run produced, along with the judge classifier. Unlearning itself is then a few hundred steps of arithmetic, reproduced here. `verify_against_torch()` at the bottom runs both implementations and compares the forget/retain scores each operator reaches. """ import os import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) WEIGHTS = os.path.join(HERE, "weights.npz") T = 100 # diffusion steps DIM = 64 # 8x8 FORGET_CLASS = 3 def schedule(): betas = np.linspace(1e-4, 0.08, T) alphas = 1.0 - betas return betas, alphas, np.cumprod(alphas) BETAS, ALPHAS, AB = schedule() def diffuse(x0, t, noise): a = AB[t][:, None] return np.sqrt(a) * x0 + np.sqrt(1 - a) * noise def _sigmoid(z): return np.where(z >= 0, 1.0 / (1.0 + np.exp(-np.clip(z, -60, 60))), np.exp(np.clip(z, -60, 60)) / (1.0 + np.exp(np.clip(z, -60, 60)))) def _silu(z): return z * _sigmoid(z) def _dsilu(z): s = _sigmoid(z) return s * (1.0 + z * (1.0 - s)) class Denoiser: """Same architecture as the PyTorch model, same parameter layout. Linear weights keep torch's (out, in) shape so the saved tensors load without transposition. """ KEYS = ("Wt", "bt", "E", "W1", "b1", "W2", "b2", "W3", "b3") def __init__(self, **p): for k in self.KEYS: setattr(self, k, p[k].astype(np.float64)) @staticmethod def load(path=WEIGHTS, prefix="d_"): z = np.load(path) return Denoiser(**{k: z[prefix + k] for k in Denoiser.KEYS}) def copy(self): return Denoiser(**{k: getattr(self, k).copy() for k in self.KEYS}) def forward(self, x, t, y, cache=False): tt = (t.astype(np.float64) / T)[:, None] pre = tt @ self.Wt.T + self.bt te = np.sin(pre) ce = self.E[y] h0 = np.concatenate([x, te, ce], axis=-1) z1 = h0 @ self.W1.T + self.b1 a1 = _silu(z1) z2 = a1 @ self.W2.T + self.b2 a2 = _silu(z2) out = a2 @ self.W3.T + self.b3 if cache: return out, (tt, pre, h0, z1, a1, z2, a2, y) return out __call__ = forward def grads(self, c, g_out): """Backprop g_out (dL/d out) to every parameter.""" tt, pre, h0, z1, a1, z2, a2, y = c gW3 = g_out.T @ a2 gb3 = g_out.sum(0) ga2 = g_out @ self.W3 gz2 = ga2 * _dsilu(z2) gW2 = gz2.T @ a1 gb2 = gz2.sum(0) ga1 = gz2 @ self.W2 gz1 = ga1 * _dsilu(z1) gW1 = gz1.T @ h0 gb1 = gz1.sum(0) gh0 = gz1 @ self.W1 gte = gh0[:, DIM:DIM + 32] gce = gh0[:, DIM + 32:] gpre = gte * np.cos(pre) gWt = gpre.T @ tt gbt = gpre.sum(0) gE = np.zeros_like(self.E) np.add.at(gE, y, gce) return {"Wt": gWt, "bt": gbt, "E": gE, "W1": gW1, "b1": gb1, "W2": gW2, "b2": gb2, "W3": gW3, "b3": gb3} class Adam: def __init__(self, model, lr=5e-4, b1=0.9, b2=0.999, eps=1e-8): self.m = model self.lr, self.b1, self.b2, self.eps = lr, b1, b2, eps self.t = 0 self.mu = {k: np.zeros_like(getattr(model, k)) for k in Denoiser.KEYS} self.nu = {k: np.zeros_like(getattr(model, k)) for k in Denoiser.KEYS} def step(self, g): self.t += 1 for k in Denoiser.KEYS: if k not in g: continue self.mu[k] = self.b1 * self.mu[k] + (1 - self.b1) * g[k] self.nu[k] = self.b2 * self.nu[k] + (1 - self.b2) * g[k] ** 2 mh = self.mu[k] / (1 - self.b1 ** self.t) nh = self.nu[k] / (1 - self.b2 ** self.t) setattr(self.m, k, getattr(self.m, k) - self.lr * mh / (np.sqrt(nh) + self.eps)) def _mse_grad(out, target, w=None): """dL/d out for L = mean_b w_b * mean_dim (out - target)^2.""" B, D = out.shape g = 2.0 * (out - target) / (B * D) if w is not None: g = g * w[:, None] loss = float((((out - target) ** 2).mean(axis=-1) * (w if w is not None else 1.0)).mean()) return g, loss # --------------------------------------------------------------------------- # the unlearning operators # --------------------------------------------------------------------------- def unlearn(orig, method, Xf, Yf, Xr, Yr, steps=140, lr=5e-4, anchor_w=1.0, cap=4.0, k=3.0, rng=None): rng = rng or np.random.default_rng(0) m = orig.copy() opt = Adam(m, lr=lr) for _ in range(int(steps)): if method == "ascent": i = rng.integers(0, len(Xf), 128) x0, y = Xf[i], Yf[i] t = rng.integers(0, T, len(i)) noise = rng.standard_normal(x0.shape) out, c = m.forward(diffuse(x0, t, noise), t, y, cache=True) g, _ = _mse_grad(out, noise) opt.step({kk: -v for kk, v in m.grads(c, g).items()}) continue if method == "finetune-retain": i = rng.integers(0, len(Xr), 128) x0, y = Xr[i], Yr[i] t = rng.integers(0, T, len(i)) noise = rng.standard_normal(x0.shape) out, c = m.forward(diffuse(x0, t, noise), t, y, cache=True) g, _ = _mse_grad(out, noise) opt.step(m.grads(c, g)) continue if method == "anchored-ascent": fi = rng.integers(0, len(Xf), 96) x0, y = Xf[fi], Yf[fi] t = rng.integers(0, T, len(fi)) noise = rng.standard_normal(x0.shape) out, c = m.forward(diffuse(x0, t, noise), t, y, cache=True) g, f_loss = _mse_grad(out, noise) # -clamp(f_loss, max=cap): once the cap binds the term is constant # and contributes no gradient at all total = {kk: (0.0 if f_loss >= cap else -1.0) * v for kk, v in m.grads(c, g).items()} ri = rng.integers(0, len(Xr), 96) xr, yr = Xr[ri], Yr[ri] tr = rng.integers(0, T, len(ri)) nr = rng.standard_normal(xr.shape) xtr = diffuse(xr, tr, nr) ref = orig.forward(xtr, tr, yr) out2, c2 = m.forward(xtr, tr, yr, cache=True) g2, _ = _mse_grad(out2, ref) for kk, v in m.grads(c2, g2).items(): total[kk] = total[kk] + anchor_w * v opt.step(total) continue # redirect (flat) and redirect+per-t per_t = method.endswith("per-t (ours)") ri = rng.integers(0, len(Xr), 96) x0 = Xr[ri] yf = np.full(len(ri), FORGET_CLASS, dtype=int) t = rng.integers(0, T, len(ri)) noise = rng.standard_normal(x0.shape) xt = diffuse(x0, t, noise) ri2 = rng.integers(0, len(Xr), 96) xr, yr = Xr[ri2], Yr[ri2] tr = rng.integers(0, T, len(ri2)) nr = rng.standard_normal(xr.shape) xtr = diffuse(xr, tr, nr) ref = orig.forward(xtr, tr, yr) wf = np.clip(t / T, 0.15, None) if per_t else None wt = (1.0 + k * (1.0 - tr / T)) if per_t else None out1, c1 = m.forward(xt, t, yf, cache=True) g1, _ = _mse_grad(out1, noise, wf) total = m.grads(c1, g1) out2, c2 = m.forward(xtr, tr, yr, cache=True) g2, _ = _mse_grad(out2, ref, wt) for kk, v in m.grads(c2, g2).items(): total[kk] = total[kk] + anchor_w * v opt.step(total) return m # --------------------------------------------------------------------------- # sampling and scoring # --------------------------------------------------------------------------- def sample(model, cls, n=48, rng=None): rng = rng or np.random.default_rng(0) x = rng.standard_normal((n, DIM)) y = np.full(n, int(cls), dtype=int) for t in reversed(range(T)): tt = np.full(n, t, dtype=int) eps = model.forward(x, tt, y) a, ab = ALPHAS[t], AB[t] mean = (x - (1 - a) / np.sqrt(1 - ab) * eps) / np.sqrt(a) x = mean + (np.sqrt(BETAS[t]) * rng.standard_normal(x.shape) if t > 0 else 0.0) x = np.nan_to_num(x, nan=0.0, posinf=3.0, neginf=-3.0) x = np.clip(x, -4, 4) return x class Judge: """The sklearn MLPClassifier from the experiment, as a forward pass.""" def __init__(self, Ws, bs): self.Ws, self.bs = Ws, bs @staticmethod def load(path=WEIGHTS): z = np.load(path) n = int(z["j_n"]) return Judge([z[f"j_W{i}"] for i in range(n)], [z[f"j_b{i}"] for i in range(n)]) def predict(self, X): a = np.asarray(X, dtype=np.float64) for i, (W, b) in enumerate(zip(self.Ws, self.bs)): a = a @ W + b if i < len(self.Ws) - 1: a = np.maximum(a, 0) return np.argmax(a, axis=1) def evaluate(model, judge, n=48, rng=None): rng = rng or np.random.default_rng(1) g = sample(model, FORGET_CLASS, n, rng) pf = float((judge.predict(g) == FORGET_CLASS).mean()) accs = [] for c in range(10): if c == FORGET_CLASS: continue gc = sample(model, c, 24, rng) accs.append(float((judge.predict(gc) == c).mean())) return pf, float(np.mean(accs)) def digits(): from sklearn.datasets import load_digits d = load_digits() X = (d.data / 16.0) * 2 - 1 return X.astype(np.float64), d.target.astype(int) # --------------------------------------------------------------------------- def verify_against_torch(steps=140, reps=2): """Run both implementations on every operator and compare the scores.""" import torch import experiment as E Xn, Yn = digits() fm = Yn == FORGET_CLASS Xf, Yf, Xr, Yr = Xn[fm], Yn[fm], Xn[~fm], Yn[~fm] nm = Denoiser.load() judge = Judge.load() Xt = torch.tensor(Xn, dtype=torch.float32) Yt = torch.tensor(Yn, dtype=torch.long) tfm = Yt == FORGET_CLASS z = np.load(WEIGHTS) tm = E.Denoiser() with torch.no_grad(): tm.tim.weight.copy_(torch.tensor(z["d_Wt"])) tm.tim.bias.copy_(torch.tensor(z["d_bt"])) tm.cls.weight.copy_(torch.tensor(z["d_E"])) tm.net[0].weight.copy_(torch.tensor(z["d_W1"])) tm.net[0].bias.copy_(torch.tensor(z["d_b1"])) tm.net[2].weight.copy_(torch.tensor(z["d_W2"])) tm.net[2].bias.copy_(torch.tensor(z["d_b2"])) tm.net[4].weight.copy_(torch.tensor(z["d_W3"])) tm.net[4].bias.copy_(torch.tensor(z["d_b3"])) from sklearn.neural_network import MLPClassifier from sklearn.datasets import load_digits as _ld d = _ld() tjudge = MLPClassifier(hidden_layer_sizes=(128,), max_iter=800, random_state=0).fit((d.data / 16.0) * 2 - 1, d.target) # the forward passes should agree to floating-point noise t = np.random.default_rng(0).integers(0, T, 64) xb = Xn[:64] yb = Yn[:64] with torch.no_grad(): o_t = tm(torch.tensor(xb, dtype=torch.float32), torch.tensor(t), torch.tensor(yb)).numpy() o_n = nm.forward(xb, t, yb) print(f" forward max |numpy - torch| = {np.abs(o_n - o_t).max():.3e}") print(f" judge agreement on the training digits: " f"{(judge.predict((d.data/16.0)*2-1) == tjudge.predict((d.data/16.0)*2-1)).mean():.4f}") methods = ["ascent", "finetune-retain", "anchored-ascent", "redirect (flat)", "redirect+per-t (ours)"] print(f" {'method':<24} {'numpy forget/retain':<26} torch forget/retain") rows = [] for meth in methods: fn, rn = [], [] for r in range(reps): mm = unlearn(nm, meth, Xf, Yf, Xr, Yr, steps=steps, rng=np.random.default_rng(100 + r)) f, rr = evaluate(mm, judge, rng=np.random.default_rng(7)) fn.append(f); rn.append(rr) torch.manual_seed(0) if meth == "ascent": tmm = E.unlearn_ascent(tm, Xt[tfm], Yt[tfm], steps=steps) elif meth == "finetune-retain": tmm = E.unlearn_finetune(tm, Xt[~tfm], Yt[~tfm], steps=steps) elif meth == "anchored-ascent": tmm = E.unlearn_anchored(tm, Xt[tfm], Yt[tfm], Xt[~tfm], Yt[~tfm], steps=steps, cap=4.0) else: tmm = E.unlearn_redirect(tm, Xt[~tfm], Yt[~tfm], steps=steps, per_timestep=meth.endswith("per-t (ours)")) ft, rt = E.evaluate(tmm, tjudge, n=48) print(f" {meth:<24} {np.mean(fn):.3f} / {np.mean(rn):.3f}" f"{'':<12} {ft:.3f} / {rt:.3f}") rows.append((meth, np.mean(fn), np.mean(rn), ft, rt)) return rows if __name__ == "__main__": verify_against_torch()