File size: 15,885 Bytes
608ff17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
"""
Cumulative Parameter Drift in SEQUENTIAL Diffusion Unlearning
Does forgetting concepts one after another destroy the model, and can the
order of removal change the damage?

WHY THIS, AND NOT SINGLE-CONCEPT UNLEARNING
-------------------------------------------
Single-concept unlearning is a crowded field: ESD, UCE, RECE, SalUn all do it,
and my own redirection method re-derives ESD. There is no gap there.

SEQUENTIAL unlearning is different. The literature names it as open:

  "after unlearning 12 concepts the model fails to generate meaningful
   content. Our analysis attributes this failure to cumulative parameter
   drift."                        -- continual unlearning study, 2026

  "they often encounter conflicting weight updates, where updates from
   different concepts interfere with each other."   -- Forget Many, Forget Right

  ESD reportedly falls to 12.05% by the sixth concept.

Nobody has characterised HOW the damage accumulates, or whether the ORDER of
removal matters. Both are measurable at small scale, which is why this fits a
laptop: 10 digit classes give 10 sequential removals, and a full order sweep is
affordable where it would be impossible on Stable Diffusion.

THREE QUESTIONS
---------------
  Q1  How does retain quality decay as concepts are removed one by one?
      Is the collapse gradual, or is there a cliff?
  Q2  Does the ORDER of removal change the final damage? If removing
      {3,5,8} in a different order ends in a different place, unlearning is
      path-dependent -- and nobody reports that.
  Q3  Does drift accumulate in weights even when outputs still look fine?
      i.e. is there hidden damage before the visible cliff?

Runtime ~12 min CPU. sklearn load_digits, no download.
"""

import itertools
import json
import os

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
DIM = 64
EPOCHS = 260
UNLEARN_STEPS = 120


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))
        return self.net(torch.cat([x, te, self.cls(y)], dim=-1))


BETAS = torch.linspace(1e-4, 0.08, T)
ALPHAS = 1.0 - BETAS
AB = torch.cumprod(ALPHAS, 0)


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, lr=2e-3):
    m = Denoiser()
    opt = torch.optim.Adam(m.parameters(), lr=lr)
    for _ in range(epochs):
        idx = torch.randint(0, len(X), (256,))
        x0, y = X[idx], Y[idx]
        t = torch.randint(0, T, (len(idx),))
        noise = torch.randn_like(x0)
        loss = ((m(diffuse(x0, t, noise), t, y) - noise) ** 2).mean()
        opt.zero_grad()
        loss.backward()
        opt.step()
    return m


@torch.no_grad()
def sample(model, cls, n=32):
    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)
        x = torch.nan_to_num(x, nan=0.0, posinf=3.0, neginf=-3.0).clamp(-4, 4)
    return x


def unlearn_one(model, Xr, Yr, forget_cls, steps=UNLEARN_STEPS, lr=5e-4,
                anchor_w=1.0, k=3.0):
    """Per-timestep anchored redirection -- the best single-concept method
    from experiment.py. Used here as the FIXED inner operator so that what we
    measure is the effect of SEQUENCE, not of method choice."""
    m = Denoiser()
    m.load_state_dict(model.state_dict())
    ref_model = model
    ref_model.eval()
    opt = torch.optim.Adam(m.parameters(), lr=lr)
    for _ in range(steps):
        ri = torch.randint(0, len(Xr), (96,))
        x0 = Xr[ri]
        yf = torch.full((len(ri),), forget_cls, dtype=torch.long)
        t = torch.randint(0, T, (len(ri),))
        noise = torch.randn_like(x0)
        wf = (t.float() / T).clamp(min=0.15)
        redirect = (wf * ((m(diffuse(x0, t, noise), t, yf) - noise) ** 2).mean(-1)).mean()

        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 = ref_model(xtr, tr, yr)
        wt = 1.0 + k * (1.0 - tr.float() / T)
        anchor = (wt * ((m(xtr, tr, yr) - ref) ** 2).mean(-1)).mean()

        loss = redirect + anchor_w * anchor
        opt.zero_grad()
        loss.backward()
        opt.step()
    return m


def weight_drift(a, b):
    """L2 distance between two models' parameters, normalised.

    Parameters carry requires_grad=True, so detach before reducing to a
    scalar -- otherwise torch warns and we would be building graph nodes
    for a pure measurement.
    """
    with torch.no_grad():
        num = sum(float(((p - q) ** 2).sum())
                  for p, q in zip(a.parameters(), b.parameters()))
        den = sum(float((p ** 2).sum()) for p in a.parameters())
    return float(np.sqrt(num / max(den, 1e-12)))


def evaluate(model, judge, removed, n=32):
    """forget: P(judge says c) averaged over REMOVED classes (lower better)
       retain: judge accuracy on remaining classes (higher better)"""
    f, r = [], []
    for c in range(10):
        g = np.nan_to_num(sample(model, c, n).numpy(), nan=0.0,
                          posinf=1.0, neginf=-1.0)
        hit = float((judge.predict(g) == c).mean())
        (f if c in removed else r).append(hit)
    return (float(np.mean(f)) if f else float("nan"),
            float(np.mean(r)) if r else float("nan"))


def main():
    print("=" * 78)
    print("Cumulative Parameter Drift in SEQUENTIAL Diffusion Unlearning")
    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("\n[1/4] Judge classifier + base diffusion model ...")
    judge = MLPClassifier(hidden_layer_sizes=(128,), max_iter=800,
                          random_state=0).fit(Xn, d.target)
    base = train_model(X, Y)
    for p in base.parameters():
        p.requires_grad_(False)
    f0, r0 = evaluate(base, judge, removed=set())
    print(f"      judge acc {judge.score(Xn, d.target):.4f};  base model "
          f"retain {r0:.4f}")

    # ---------------- Q1: how does damage accumulate? ----------------
    print("\n[2/4] Q1 -- sequential removal of 6 concepts, one at a time")
    order = [3, 8, 5, 0, 6, 9]
    model = base
    prev = base
    rows = []
    removed = set()
    print("      {:>5} {:>8} {:>10} {:>10} {:>12} {:>12}".format(
        "step", "removed", "forget", "retain", "drift(step)", "drift(cum)"))
    print("      {:>5} {:>8} {:>10.4f} {:>10.4f} {:>12} {:>12}".format(
        0, "-", float("nan"), r0, "-", "-"))
    for i, c in enumerate(order, start=1):
        keep = ~torch.isin(Y, torch.tensor(sorted(removed | {c})))
        Xr, Yr = X[keep], Y[keep]
        new = unlearn_one(model, Xr, Yr, c)
        removed.add(c)
        f, r = evaluate(new, judge, removed)
        d_step = weight_drift(prev, new)
        d_cum = weight_drift(base, new)
        rows.append({"step": i, "class": c, "forget": f, "retain": r,
                     "drift_step": d_step, "drift_cum": d_cum})
        print("      {:>5} {:>8} {:>10.4f} {:>10.4f} {:>12.4f} {:>12.4f}".format(
            i, c, f, r, d_step, d_cum))
        prev, model = new, new

    retains = [r0] + [x["retain"] for x in rows]
    drops = [retains[i] - retains[i + 1] for i in range(len(retains) - 1)]
    worst = int(np.argmax(drops)) + 1
    print(f"\n      largest single-step retain drop at step {worst} "
          f"({drops[worst-1]:.4f})")
    print(f"      cumulative drift grew {rows[0]['drift_cum']:.4f} -> "
          f"{rows[-1]['drift_cum']:.4f}")

    # ---------------- Q2: does ORDER matter? ----------------
    print("\n[3/4] Q2 -- is sequential unlearning PATH-DEPENDENT?")
    print("      Removing the same 3 classes in all 6 orders.")
    trio = [3, 8, 5]
    ORDER_SEEDS = [0, 1, 2]          # repeat each permutation; 1 seed was
                                     # not enough to separate signal from noise
    order_rows = []
    print("      {:>12} {:>16} {:>16} {:>12}".format(
        "order", "forget (95% CI)", "retain (95% CI)", "drift(cum)"))
    for perm in itertools.permutations(trio):
        fs, rs, ds = [], [], []
        for sd in ORDER_SEEDS:
            torch.manual_seed(sd)
            m = base
            rm = set()
            for c in perm:
                keep = ~torch.isin(Y, torch.tensor(sorted(rm | {c})))
                m = unlearn_one(m, X[keep], Y[keep], c)
                rm.add(c)
            f, r = evaluate(m, judge, rm)
            fs.append(f); rs.append(r); ds.append(weight_drift(base, m))
        ci = lambda v: float(1.96 * np.std(v, ddof=1) / np.sqrt(len(v)))
        order_rows.append({"order": list(perm),
                           "forget": float(np.mean(fs)), "forget_ci": ci(fs),
                           "retain": float(np.mean(rs)), "retain_ci": ci(rs),
                           "drift_cum": float(np.mean(ds))})
        print("      {:>12} {:>9.4f}+/-{:.3f} {:>9.4f}+/-{:.3f} {:>12.4f}".format(
            "-".join(map(str, perm)), float(np.mean(fs)), ci(fs),
            float(np.mean(rs)), ci(rs), float(np.mean(ds))))

    rr = [o["retain"] for o in order_rows]
    ff = [o["forget"] for o in order_rows]
    print(f"\n      retain spread across orders: {min(rr):.4f} - {max(rr):.4f} "
          f"(range {max(rr)-min(rr):.4f})")
    print(f"      forget spread across orders: {min(ff):.4f} - {max(ff):.4f} "
          f"(range {max(ff)-min(ff):.4f})")
    # CI-aware: path dependence is only claimed if the best and worst
    # orders have non-overlapping intervals
    bi = int(np.argmax(rr)); wi = int(np.argmin(rr))
    hi_lo = order_rows[bi]["retain"] - order_rows[bi]["retain_ci"]
    lo_hi = order_rows[wi]["retain"] + order_rows[wi]["retain_ci"]
    if hi_lo > lo_hi:
        print("      -> PATH-DEPENDENT: best and worst orders have disjoint CIs")
    else:
        print("      -> INCONCLUSIVE: best/worst order CIs overlap")

    # ---------------- Q3: hidden drift before visible damage ----------------
    print("\n[4/4] Q3 -- does weight drift lead visible damage?")
    print("      step  retain  cum-drift   (is drift rising while retain holds?)")
    lead = 0
    for i, x in enumerate(rows):
        prev_r = r0 if i == 0 else rows[i - 1]["retain"]
        rising = x["drift_cum"] > (rows[i - 1]["drift_cum"] if i else 0)
        held = x["retain"] >= prev_r - 0.02
        if rising and held:
            lead += 1
        print("      {:>4}  {:.4f}  {:>9.4f}   {}".format(
            x["step"], x["retain"], x["drift_cum"],
            "drift up, retain held" if (rising and held) else ""))
    print(f"      steps where drift rose while retain held: {lead}/{len(rows)}")
    print("      NOTE: cumulative drift is a running sum of non-negative")
    print("            per-step norms, so it rises at every step BY")
    print("            CONSTRUCTION. Its monotonicity is arithmetic, not")
    print("            evidence. The only testable question is whether the")
    print("            per-step drift carries information about damage.")

    print("")
    print("[4b] Does PER-STEP drift predict the retain drop?")
    sd_ = np.array([x["drift_step"] for x in rows], dtype=float)
    rr_ = np.array([r0] + [x["retain"] for x in rows], dtype=float)
    drop_ = rr_[:-1] - rr_[1:]
    print("      {:>6} {:>12} {:>12}".format("step", "drift(step)", "retain drop"))
    for i, x in enumerate(rows):
        print("      {:>6} {:>12.4f} {:>12.4f}".format(x["step"], sd_[i], drop_[i]))
    mono_step = bool(np.all(np.diff(sd_) >= 0))
    print("")
    print("      per-step drift monotone?        {}".format(mono_step))
    print("      retain monotone?                {}".format(
        bool(np.all(drop_ >= 0))))
    c_same = (float(np.corrcoef(sd_, drop_)[0, 1])
              if sd_.std() > 0 and drop_.std() > 0 else float("nan"))
    print("      corr(drift[t], drop[t])       = {:+.3f}".format(c_same))
    if len(sd_) >= 3:
        a, b = sd_[:-1], drop_[1:]
        c_lead = (float(np.corrcoef(a, b)[0, 1])
                  if a.std() > 0 and b.std() > 0 else float("nan"))
        print("      corr(drift[t], drop[t+1])     = {:+.3f}   (n={} pairs)".format(
            c_lead, len(a)))
    else:
        c_lead = float("nan")
    print("      argmax drift = step {} ; argmax drop = step {}".format(
        int(np.argmax(sd_)) + 1, int(np.argmax(drop_)) + 1))
    print("")
    if not np.isnan(c_lead) and abs(c_lead) > 0.7 and abs(c_same) < 0.4:
        print("      -> SUGGESTIVE LEAD: per-step drift tracks the NEXT step's")
        print("         damage far better than the current one. With n={} pairs".format(
            len(sd_) - 1))
        print("         and a SINGLE seed this is a hypothesis, not a result --")
        print("         it needs multi-seed replication before any claim.")
    elif not np.isnan(c_same) and abs(c_same) > 0.7:
        print("      -> per-step drift tracks same-step damage directly.")
    else:
        print("      -> per-step drift carries no usable signal about damage")
        print("         at this length. Weight-space monitoring is NOT")
        print("         demonstrated here.")

    with open(os.path.join(OUT, "results_sequential.json"), "w") as f:
        json.dump({"base_retain": r0, "order": order, "sequence": rows,
                   "permutations": order_rows,
                   "drift_pred_same_step": c_same,
                   "drift_pred_lead": c_lead,
                   "per_step_drift_monotone": mono_step,
                   "retain_spread": float(max(rr) - min(rr)),
                   "forget_spread": float(max(ff) - min(ff))}, f, indent=2)

    fig, ax = plt.subplots(1, 3, figsize=(14, 4.2))
    steps = [0] + [x["step"] for x in rows]
    ax[0].plot(steps, retains, marker="o")
    ax[0].set_xlabel("concepts removed")
    ax[0].set_ylabel("retain quality")
    ax[0].set_title("Q1: does retain collapse, and when?")
    ax[0].grid(alpha=0.3)

    ax[1].plot([x["step"] for x in rows], [x["drift_cum"] for x in rows],
               marker="s", label="cumulative")
    ax[1].plot([x["step"] for x in rows], [x["drift_step"] for x in rows],
               marker="^", label="per step")
    ax[1].set_xlabel("concepts removed")
    ax[1].set_ylabel("relative weight drift")
    ax[1].set_title("Q3: parameter drift")
    ax[1].legend()
    ax[1].grid(alpha=0.3)

    labels = ["-".join(map(str, o["order"])) for o in order_rows]
    ax[2].bar(range(len(order_rows)), [o["retain"] for o in order_rows])
    ax[2].set_xticks(range(len(order_rows)))
    ax[2].set_xticklabels(labels, rotation=45, fontsize=7)
    ax[2].set_ylabel("retain after same 3 removals")
    ax[2].set_title("Q2: path dependence")
    ax[2].grid(alpha=0.3, axis="y")
    plt.tight_layout()
    plt.savefig(os.path.join(OUT, "figure_sequential.png"), dpi=140)
    print("\nDone. Wrote results_sequential.json and figure_sequential.png")


if __name__ == "__main__":
    main()