File size: 20,760 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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
"""
Which Concepts Are Expensive to Unlearn TOGETHER?
Measuring pairwise interference, and whether similarity predicts it.

WHY THIS QUESTION
-----------------
Scalable multi-concept removal is largely solved -- ScaPre unlearns 50 concepts
in ~120 seconds -- so a better unlearning operator is not the open problem.

The open problem is that this line of work names interference as the obstacle
and then engineers AROUND it:

    "they often encounter CONFLICTING WEIGHT UPDATES, where updates from
     different concepts interfere with each other."

Nobody characterises its STRUCTURE:

  Q1  Is interference symmetric? Does unlearning A then B cost the same as
      B then A?
  Q2  Does CONCEPT SIMILARITY predict interference? If similar concepts
      interfere less (shared machinery removed once) or more (shared machinery
      destroyed twice), that is a scheduling rule.
  Q3  Is there a cheap signal, available BEFORE unlearning, that predicts
      which pairs will be expensive?

Q3 is the useful one. If interference is predictable in advance, a multi-concept
system can ORDER or GROUP removals to avoid it -- which is scheduling, not a new
unlearning operator, and composes with ScaPre rather than competing with it.

Runtime ~10 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 = 240
USTEPS = 100
CONCEPTS = [0, 1, 3, 7, 8]          # includes visually close pairs: 3/8, 1/7


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


@torch.no_grad()
def sample(model, cls, n=24):
    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(model, Xr, Yr, c, steps=USTEPS, lr=5e-4, anchor_w=1.0, k=3.0):
    """Per-timestep anchored redirection, held FIXED so what varies is the pair."""
    m = Denoiser(); m.load_state_dict(model.state_dict())
    ref = model; ref.eval()
    opt = torch.optim.Adam(m.parameters(), lr=lr)
    for _ in range(steps):
        i = torch.randint(0, len(Xr), (96,))
        x0 = Xr[i]
        yf = torch.full((len(i),), c, dtype=torch.long)
        t = torch.randint(0, T, (len(i),))
        n = torch.randn_like(x0)
        wf = (t.float() / T).clamp(min=0.15)
        red = (wf * ((m(diffuse(x0, t, n), t, yf) - n) ** 2).mean(-1)).mean()
        j = torch.randint(0, len(Xr), (96,))
        xr, yr = Xr[j], Yr[j]
        tr = torch.randint(0, T, (len(j),))
        nr = torch.randn_like(xr)
        xtr = diffuse(xr, tr, nr)
        with torch.no_grad():
            rf = ref(xtr, tr, yr)
        wt = 1.0 + k * (1.0 - tr.float() / T)
        anc = (wt * ((m(xtr, tr, yr) - rf) ** 2).mean(-1)).mean()
        loss = red + anchor_w * anc
        opt.zero_grad(); loss.backward(); opt.step()
    return m


@torch.no_grad()
def activation_profile(model, cls, X, n=256):
    """
    Which hidden units does this concept actually use?

    Pixel similarity failed as a predictor. The signal that should work is
    REPRESENTATION overlap -- two concepts interfere when they rely on the same
    machinery, because unlearning one damages what the other needs. This is the
    quantity concept-aware neuron masking (Forget-It-All) already computes.

    We hook the denoiser's first hidden layer and record mean |activation| per
    unit when conditioning on `cls`, averaged over timesteps.
    """
    idx = torch.randint(0, len(X), (n,))
    x0 = X[idx]
    y = torch.full((n,), cls, dtype=torch.long)
    t = torch.randint(0, T, (n,))
    noise = torch.randn_like(x0)
    xt = diffuse(x0, t, noise)
    te = torch.sin(model.tim(t.float().unsqueeze(-1) / T))
    h = torch.cat([xt, te, model.cls(y)], dim=-1)
    # first Linear + SiLU of model.net
    a = model.net[1](model.net[0](h))
    return a.abs().mean(0)


def overlap(pa, pb):
    """Cosine overlap between two concepts' activation profiles."""
    return float(pa @ pb / (pa.norm() * pb.norm() + 1e-9))


def retain_quality(model, judge, removed, n=24):
    accs = []
    for c in range(10):
        if c in removed:
            continue
        g = np.nan_to_num(sample(model, c, n).numpy(), nan=0.0, posinf=1., neginf=-1.)
        accs.append(float((judge.predict(g) == c).mean()))
    return float(np.mean(accs))


def forget_score(model, judge, c, n=24):
    g = np.nan_to_num(sample(model, c, n).numpy(), nan=0.0, posinf=1., neginf=-1.)
    return float((judge.predict(g) == c).mean())


def main():
    print("=" * 78)
    print("Pairwise concept interference in multi-concept 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)
    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)
    r0 = retain_quality(base, judge, set())
    print(f"\n[1/4] base model: retain {r0:.4f}, judge acc "
          f"{judge.score(Xn, d.target):.4f}")

    # cheap, pre-unlearning similarity: cosine between class means in pixel space
    means = {c: Xn[d.target == c].mean(0) for c in CONCEPTS}
    def sim(a, b):
        u, v = means[a], means[b]
        return float(u @ v / (np.linalg.norm(u) * np.linalg.norm(v) + 1e-9))

    print("\n[2/4] Q1 -- is interference symmetric? (A then B vs B then A)")
    print("      {:>10} {:>12} {:>12} {:>12} {:>10}".format(
        "pair", "A->B retain", "B->A retain", "asymmetry", "sim"))
    PAIR_SEEDS = [0, 1, 2]       # one run per order was not enough to tell
    rows = []                     # a real asymmetry from sampling noise
    for a, b in itertools.combinations(CONCEPTS, 2):
        keep_ab = ~torch.isin(Y, torch.tensor([a, b]))
        abs_, bas_ = [], []
        for sd in PAIR_SEEDS:
            torch.manual_seed(sd)
            m1 = unlearn(base, X[~torch.isin(Y, torch.tensor([a]))],
                         Y[~torch.isin(Y, torch.tensor([a]))], a)
            m1 = unlearn(m1, X[keep_ab], Y[keep_ab], b)
            abs_.append(retain_quality(m1, judge, {a, b}))
            torch.manual_seed(sd)
            m2 = unlearn(base, X[~torch.isin(Y, torch.tensor([b]))],
                         Y[~torch.isin(Y, torch.tensor([b]))], b)
            m2 = unlearn(m2, X[keep_ab], Y[keep_ab], a)
            bas_.append(retain_quality(m2, judge, {a, b}))
        ci = lambda v: float(1.96 * np.std(v, ddof=1) / np.sqrt(len(v)))
        r_ab, r_ba = float(np.mean(abs_)), float(np.mean(bas_))
        # asymmetry is only claimed when the two orders' intervals are disjoint
        disjoint = abs(r_ab - r_ba) > (ci(abs_) + ci(bas_))
        rows.append({"a": a, "b": b, "retain_ab": r_ab, "retain_ba": r_ba,
                     "ci_ab": ci(abs_), "ci_ba": ci(bas_),
                     "asymmetry": abs(r_ab - r_ba), "significant": bool(disjoint),
                     "similarity": sim(a, b), "damage": r0 - min(r_ab, r_ba)})
        print("      {:>10} {:>12.4f} {:>12.4f} {:>12.4f} {:>10.3f} {}".format(
            f"{a}&{b}", r_ab, r_ba, abs(r_ab - r_ba), sim(a, b),
            "*" if disjoint else ""))

    asym = np.array([r["asymmetry"] for r in rows])
    print(f"\n      mean asymmetry {asym.mean():.4f}, max {asym.max():.4f}")
    sig = [r for r in rows if r["significant"]]
    print(f"      pairs with DISJOINT intervals between the two orders: "
          f"{len(sig)}/{len(rows)}  (marked * above)")
    if sig:
        w = max(sig, key=lambda r: r["asymmetry"])
        print(f"      -> ORDER MATTERS for {len(sig)} pair(s). Largest: "
              f"{w['a']}&{w['b']} at {w['asymmetry']:.4f}")
    else:
        print("      -> NO pair shows a significant order effect once the")
        print("         intervals are respected. The apparent asymmetry in a")
        print("         single-seed run was sampling noise.")

    print("\n[3/4] Q2/Q3 -- does similarity predict the damage?")
    sims = np.array([r["similarity"] for r in rows])
    dmg = np.array([r["damage"] for r in rows])
    rr = float(np.corrcoef(sims, dmg)[0, 1]) if sims.std() > 0 else float("nan")
    print(f"      correlation(pixel-space similarity, retain damage) = {rr:.3f}")
    hi = [r for r in rows if r["similarity"] > np.median(sims)]
    lo = [r for r in rows if r["similarity"] <= np.median(sims)]
    print("      {:>18} {:>14} {:>14}".format("pair group", "mean damage", "n"))
    print("      {:>18} {:>14.4f} {:>14d}".format(
        "similar pairs", float(np.mean([r['damage'] for r in hi])), len(hi)))
    print("      {:>18} {:>14.4f} {:>14d}".format(
        "dissimilar pairs", float(np.mean([r['damage'] for r in lo])), len(lo)))
    gap = float(np.mean([r['damage'] for r in hi]) - np.mean([r['damage'] for r in lo]))
    if abs(rr) > 0.4:
        direction = "MORE" if rr > 0 else "LESS"
        print(f"      -> similar concepts interfere {direction}. Similarity is")
        print("         computable before any unlearning runs, so it can drive")
        print("         the removal schedule for free.")
    else:
        print("      -> pixel-space similarity does NOT predict interference")
        print("         here. A representation-space signal (e.g. overlap in")
        print("         which units each concept activates) is the next thing")
        print("         to try, and is what concept-aware masking already computes.")

    print("")
    print("[3b] The signal I claimed was right: REPRESENTATION overlap")
    print("     Pixel similarity failed. Does activation overlap predict damage?")
    profs = {c: activation_profile(base, c, X) for c in CONCEPTS}
    for r in rows:
        r["act_overlap"] = overlap(profs[r["a"]], profs[r["b"]])
    ov = np.array([r["act_overlap"] for r in rows])
    dmg2 = np.array([r["damage"] for r in rows])
    r_act = float(np.corrcoef(ov, dmg2)[0, 1]) if ov.std() > 0 else float("nan")
    print("     {:>10} {:>14} {:>14} {:>12}".format(
        "pair", "pixel sim", "act overlap", "damage"))
    for r in sorted(rows, key=lambda z: z["damage"]):
        print("     {:>10} {:>14.3f} {:>14.4f} {:>12.4f}".format(
            f"{r['a']}&{r['b']}", r["similarity"], r["act_overlap"], r["damage"]))
    print("")
    print("     correlation(PIXEL similarity, damage)      = {:+.3f}".format(rr))
    print("     correlation(ACTIVATION overlap, damage)    = {:+.3f}".format(r_act))
    if abs(r_act) > abs(rr) + 0.15:
        better = "BETTER" if abs(r_act) > 0.5 else "better, but still weak"
        print("     -> activation overlap is a {} predictor.".format(better))
        print("        It is computable from the base model alone, before any")
        print("        unlearning runs, so it could drive a removal schedule.")
    else:
        print("     -> activation overlap is NOT a better predictor either.")
        print("        Two plausible signals have now failed. The spread across")
        print("        pairs is NOT established as real (see [3b2]) and")
        print("        neither geometry nor representation overlap explains")
        print("        it -- which narrows the question rather than")
        print("        answering it.")

    print("")
    print("[3b2] Is the pair SPREAD itself significant, accounting for")
    print("      multiplicity? Comparing the best and worst rows only is")
    print("      a selected comparison; with 10 pairs there are 45 of them.")
    import itertools as _it
    _n_dis, _tot, _which = 0, 0, []
    for _x, _y in _it.combinations(rows, 2):
        _tot += 1
        _lo, _hi = (_x, _y) if _x["retain_ab"] < _y["retain_ab"] else (_y, _x)
        if _lo["retain_ab"] + _lo["ci_ab"] < _hi["retain_ab"] - _hi["ci_ab"]:
            _n_dis += 1
            _which.append("{}&{} vs {}&{}".format(
                _lo["a"], _lo["b"], _hi["a"], _hi["b"]))
    _expected = 0.05 * _tot
    print("      disjoint comparisons : {} of {}".format(_n_dis, _tot))
    print("      expected by chance   : {:.2f}  (alpha=0.05)".format(_expected))
    if _which:
        print("      which                : {}".format(", ".join(_which)))
    _rsorted = sorted(rows, key=lambda z: z["retain_ab"])
    _tied = [r for r in _rsorted
             if abs(r["retain_ab"] - _rsorted[0]["retain_ab"]) < 1e-9]
    if len(_tied) > 1:
        _cis = ["{}&{} (+/-{:.4f})".format(r["a"], r["b"], r["ci_ab"])
                for r in _tied]
        print("      NOTE: {} pairs TIE for worst retain: {}".format(
            len(_tied), ", ".join(_cis)))
        _best = _rsorted[-1]
        _calls = set()
        for r in _tied:
            _calls.add(r["retain_ab"] + r["ci_ab"] < _best["retain_ab"] - _best["ci_ab"])
        if len(_calls) > 1:
            print("      -> the best-vs-worst verdict FLIPS depending on which")
            print("         tied row is sorted first. That comparison is not")
            print("         usable; do not report it.")
    if _n_dis <= _expected:
        print("      -> the number of disjoint comparisons is at or below the")
        print("         chance rate. The pair spread is NOT established as a")
        print("         real effect by this test. Any claim about which pair to")
        print("         batch must rest on the joint analysis below, not on")
        print("         best-vs-worst.")
    else:
        print("      -> more disjoint comparisons than chance would give.")

    print("")
    print("[3c] ADDITIVITY -- is this a pair INTERACTION at all?")
    print("     In the table above, every pair containing concept 1 IMPROVES")
    print("     retain and every pair without it damages. That pattern suggests")
    print("     the effect is per-CONCEPT, not per-PAIR. If pair damage is just")
    print("     the sum of two single-concept effects, there is no interaction")
    print("     to schedule around -- and a greedy per-concept cost is enough.")
    singles = {}
    for c in CONCEPTS:
        vals = []
        for sd in PAIR_SEEDS:
            torch.manual_seed(sd)
            keep = ~torch.isin(Y, torch.tensor([c]))
            m = unlearn(base, X[keep], Y[keep], c)
            vals.append(retain_quality(m, judge, {c}))
        singles[c] = r0 - float(np.mean(vals))
    print("     single-concept damage (base retain {:.4f}):".format(r0))
    for c in sorted(singles, key=lambda k: singles[k]):
        print("       concept {}: {:+.4f}".format(c, singles[c]))

    pred = np.array([singles[r["a"]] + singles[r["b"]] for r in rows])
    obs = np.array([r["damage"] for r in rows])
    r_add = float(np.corrcoef(pred, obs)[0, 1]) if pred.std() > 0 else float("nan")
    resid = obs - pred
    print("")
    print("     {:>10} {:>14} {:>14} {:>14}".format(
        "pair", "predicted", "observed", "residual"))
    for r, p_, o_, e_ in sorted(zip(rows, pred, obs, resid), key=lambda z: z[2]):
        print("     {:>10} {:>14.4f} {:>14.4f} {:>14.4f}".format(
            f"{r['a']}&{r['b']}", p_, o_, e_))
    print("")
    print("     correlation(sum of single effects, pair damage) = {:+.3f}".format(r_add))
    print("     residual spread after removing additive part    = {:.4f}".format(
        float(resid.std())))
    print("     raw damage spread                               = {:.4f}".format(
        float(obs.std())))
    expl = 1 - (resid.var() / max(obs.var(), 1e-12))
    print("     variance explained by pure additivity           = {:.1%}".format(expl))
    if expl > 0.7:
        print("     -> MOSTLY ADDITIVE. The 'interference' is largely just the")
        print("        sum of per-concept costs. Scheduling does not need")
        print("        pairwise measurements: rank concepts individually and")
        print("        the pair ordering follows. That is O(n) instead of")
        print("        O(n^2) measurements for a multi-concept system.")
    elif expl > 0.4:
        print("     -> PARTLY additive. Per-concept cost explains much of it,")
        print("        with a genuine interaction residual on top.")
    else:
        print("     -> NOT additive: the pair interaction is real and does not")
        print("        reduce to per-concept costs.")

    print("\n[4/4] The scheduling consequence")
    best = min(rows, key=lambda r: r["damage"])
    worst = max(rows, key=lambda r: r["damage"])
    print(f"      cheapest pair to remove together: {best['a']}&{best['b']} "
          f"(damage {best['damage']:.4f})")
    print(f"      most expensive                  : {worst['a']}&{worst['b']} "
          f"(damage {worst['damage']:.4f})")
    print(f"      spread {worst['damage']-best['damage']:.4f} across pairs")
    print("")
    print("      Read this carefully. The best-vs-worst spread above is a")
    print("      SELECTED comparison, and [3b2] showed it does not survive")
    print("      multiplicity -- so this ranking is NOT evidence that pair")
    print("      choice matters on its own.")
    print("      What a scheduler can actually use is the DECOMPOSITION from")
    print("      [3c]: per-concept costs recover {:.1%} of the variance, so".format(expl))
    print("      ranking needs O(n) measurements instead of the O(n^2) full")
    print("      pairwise matrix, plus a positive allowance for the combining")
    print("      penalty (every residual was positive).")
    print("      The useful claim is the additive structure, not this table.")

    with open(os.path.join(OUT, "results_interference.json"), "w") as f:
        json.dump({"base_retain": r0, "pairs": rows,
                   "similarity_damage_corr": rr,
                   "activation_overlap_corr": r_act,
                   "single_concept_damage": {str(k): v for k, v in singles.items()},
                   "additivity_corr": r_add,
                   "n_disjoint_comparisons": _n_dis,
                   "n_comparisons": _tot,
                   "additive_variance_explained": float(expl),
                   "n_significant_asymmetries": int(len([r for r in rows if r["significant"]])),
                   "similar_minus_dissimilar": gap}, f, indent=2)

    fig, ax = plt.subplots(1, 2, figsize=(11, 4.2))
    labs = [f"{r['a']}&{r['b']}" for r in rows]
    ax[0].bar(range(len(rows)), [r["damage"] for r in rows])
    ax[0].set_xticks(range(len(rows)))
    ax[0].set_xticklabels(labs, rotation=45, fontsize=7)
    ax[0].set_ylabel("retain damage (base - after pair)")
    ax[0].set_title("Which pairs are expensive together?")
    ax[0].grid(alpha=0.3, axis="y")

    ax[1].scatter(sims, dmg, s=60)
    for r in rows:
        ax[1].annotate(f"{r['a']}&{r['b']}", (r["similarity"], r["damage"]),
                       fontsize=6, textcoords="offset points", xytext=(5, 4))
    ax[1].set_xlabel("pixel-space similarity")
    ax[1].set_ylabel("retain damage")
    ax[1].set_title(f"Does similarity predict cost? (r={rr:.2f})")
    ax[1].grid(alpha=0.3)
    plt.tight_layout()
    plt.savefig(os.path.join(OUT, "figure_interference.png"), dpi=140)
    print("\nDone. Wrote results_interference.json and figure_interference.png")


if __name__ == "__main__":
    main()