File size: 29,925 Bytes
8c7bdb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
#!/usr/bin/env python3
"""Table 5 ablation of "Machine Unlearning in Low-Dimensional Feature Subspace"
(arXiv 2601.22456v3), against author code pinned at d91dbd3bbe677536dad8ae5ae3e1991d5ca8150b.

Arms (the loss of eq. (1) / main_subspace.py:112, restricted to one term):
    none     : 0 optimization steps -> the random orthogonal U init of models/swin.py:596
    jfg      : loss = J_fg**2                    (forgotten-variance suppression only)
    jrm      : loss = J_rm**2                    (retained-variance preservation only)
    joint    : loss = J_rm**2 + J_fg**2          (eq. 1, equal weights, as in the paper)
    identity : U = I_d, i.e. fpre with no projection at all (sanity reference, Table 1 fpre)

Pipeline (paper + author code):
    fpre   : Swin-T (torchvision IMAGENET1K_V1) fine-tuned 20 ep on all 100k train images
    fexact : same init, 20 ep on D_rm only, one model per forgetting partition
    LOFT   : sigma_r / sigma_f from one-shot features of fpre, s=250, 50 Riemannian-Adam
             steps, lr=1, wd=0.05
    metrics: Acc_tr_rm, Acc_tr_fg, Acc_te_rm, Acc_te_fg, MIA (RBF SVC C=3 gamma=auto on
             true-label confidence, equal retained-train members vs test nonmembers, then
             the outer 1-helper -> forgotten-member prediction rate).
"""
import argparse
import json
import os
import random
import re
import shutil
import subprocess
import sys
import time
import urllib.request
import zipfile

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, Subset
from torchvision.datasets import ImageFolder

AUTHOR_SHA = "d91dbd3bbe677536dad8ae5ae3e1991d5ca8150b"
AUTHOR_ZIP = (
    f"https://github.com/fanghenshaometeor/unlearning-feat-subspace/archive/{AUTHOR_SHA}.zip"
)
HUB_REPO = "mendoanjoe/loft-table5-ablation"
WORK = "/work"
DATA_DIR = os.path.join(WORK, "tiny-imagenet-200")
OUT = os.path.join(WORK, "out")
AROOT = os.path.join(WORK, "author_repo")
PARTITIONS = [[11, 83, 115, 153], [44, 65, 150, 168], [53, 57, 108, 179]]
ARMS = ["none", "jfg", "jrm", "joint"]
N_CLASSES = 200
D_FEAT = 768
METRICS = ["acc_tr_rm", "acc_tr_fg", "acc_te_rm", "acc_te_fg", "mia"]

_MODS = None


# --------------------------------------------------------------------------- infra
def author_modules():
    global _MODS
    if _MODS is None:
        import models  # noqa: F401
        import utils  # noqa: F401
        import utils_data  # noqa: F401
        from mia_evaluation.svc_mia import SVC_fit_predict

        _MODS = {"models": models, "utils": utils, "utils_data": utils_data,
                 "svc": SVC_fit_predict}
    return _MODS


def fetch_author_repo():
    if os.path.isdir(os.path.join(AROOT, "models")):
        if AROOT not in sys.path:
            sys.path.insert(0, AROOT)
        return
    zpath = os.path.join(WORK, "author.zip")
    if not os.path.exists(zpath):
        print(f"downloading {AUTHOR_ZIP}", flush=True)
        urllib.request.urlretrieve(AUTHOR_ZIP, zpath)
    with zipfile.ZipFile(zpath) as zf:
        zf.extractall(WORK)
    src = os.path.join(WORK, f"unlearning-feat-subspace-{AUTHOR_SHA}")
    if os.path.isdir(AROOT):
        shutil.rmtree(AROOT)
    os.rename(src, AROOT)
    sys.path.insert(0, AROOT)


class Hub:
    """Thin wrapper so every stage can be resumed from the Hub."""

    def __init__(self, enabled):
        self.enabled = enabled
        self.api = None
        self._files = set()
        if enabled:
            from huggingface_hub import HfApi

            self.api = HfApi(token=os.environ.get("HF_TOKEN"))
            self.api.create_repo(HUB_REPO, repo_type="model", exist_ok=True, private=False)
            self._files = set(self.api.list_repo_files(HUB_REPO, repo_type="model"))

    def has(self, path):
        if not self.enabled:
            return False
        if path not in self._files:
            self._files = set(self.api.list_repo_files(HUB_REPO, repo_type="model"))
        return path in self._files

    def fetch(self, remote, local_name=None):
        """Download remote to OUT/<local_name> (default: basename) and return that path."""
        from huggingface_hub import hf_hub_download

        p = hf_hub_download(HUB_REPO, remote, repo_type="model", local_dir=OUT)
        dest = os.path.join(OUT, local_name or os.path.basename(remote))
        if os.path.abspath(p) != os.path.abspath(dest):
            shutil.copyfile(p, dest)
        return dest

    def put(self, local, path, msg=None):
        if not self.enabled:
            return
        self.api.upload_file(HUB_REPO, path_in_repo=path, path_or_fileobj=local,
                             commit_message=msg or f"add {path}", repo_type="model")
        self._files.add(path)


# --------------------------------------------------------------------------- models
def build_model(s=None):
    m = author_modules()["models"].swin_t(weights="DEFAULT", s=s)
    m.head = nn.Linear(m.head.in_features, N_CLASSES)
    return m.cuda()


def load_ckpt(model, path):
    ck = torch.load(path, map_location="cpu", weights_only=False)
    sd = ck["state_dict"] if isinstance(ck, dict) and "state_dict" in ck else ck
    model.load_state_dict(sd, strict=False)
    return model


def test_transform():
    return transforms.Compose([
        transforms.Resize(64),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
    ])


def train_transform():
    return transforms.Compose([
        transforms.Resize(64),
        transforms.RandomCrop(64, padding=4),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
    ])


def targets_of(split):
    return np.array(ImageFolder(os.path.join(DATA_DIR, split)).targets)


@torch.no_grad()
def extract_features(model, dataset, bs=256, workers=8, dtype=np.float64):
    """Same as main_subspace.extract_feat: float64 buffer (the paper's '~300 MB' is the
    float32 payload; the float64 buffer is 614.4 MB for 100k x 768)."""
    loader = DataLoader(dataset, batch_size=bs, shuffle=False, num_workers=workers,
                        pin_memory=True)
    feat = np.zeros((len(dataset), D_FEAT), dtype=dtype)
    correct, n = 0, 0
    t0 = time.time()
    for bi, (x, y) in enumerate(loader):
        x, y = x.cuda(), y.cuda()
        z, logit = model.forward_feat(x)
        correct += (logit.argmax(1) == y).sum().item()
        n += y.numel()
        s = bi * bs
        feat[s:min(s + bs, len(dataset)), :] = z.detach().cpu().numpy()
    dt = time.time() - t0
    print(f"    extracted {feat.shape} in {dt:.1f}s (top1={100.0 * correct / n:.2f})", flush=True)
    return feat, 100.0 * correct / n, dt


# --------------------------------------------------------------------------- LOFT
def optimise_U(sigma_f, sigma_r, arm, seed, steps, s, lr, wd, log=None):
    import geoopt
    from geoopt.optim import RiemannianAdam

    torch.manual_seed(seed)
    d = sigma_r.shape[0]
    U = geoopt.ManifoldParameter(
        nn.Parameter(nn.init.orthogonal_(torch.Tensor(d, s))), manifold=geoopt.Stiefel(),
        requires_grad=True,
    ).cuda()
    tr_f, tr_r = torch.trace(sigma_f), torch.trace(sigma_r)
    if arm == "none" or steps == 0:
        if log is not None:
            log({"loft/j_fg": float(torch.trace(U.t() @ sigma_f @ U) / tr_f),
                 "loft/j_rm": float(torch.trace(sigma_r - U @ U.t() @ sigma_r @ U @ U.t()) / tr_r)},
                step=0)
        return U.detach()
    opt = RiemannianAdam([U], lr=lr, weight_decay=wd)
    hist = []
    t0 = time.time()
    for step in range(steps):
        jf = torch.trace(U.t() @ sigma_f @ U) / tr_f
        jr = torch.trace(sigma_r - U @ U.t() @ sigma_r @ U @ U.t()) / tr_r
        if arm == "jfg":
            loss = jf * jf
        elif arm == "jrm":
            loss = jr * jr
        else:
            loss = jr * jr + jf * jf
        opt.zero_grad()
        loss.backward()
        opt.step()
        hist.append((float(jf), float(jr)))
        if log is not None and (step % 10 == 0 or step == steps - 1):
            log({"loft/loss": float(loss), "loft/j_fg": float(jf), "loft/j_rm": float(jr)},
                step=step + 1)
    print(f"    U optimised ({arm}, seed={seed}) in {time.time() - t0:.2f}s "
          f"j_fg={hist[-1][0]:.4f} j_rm={hist[-1][1]:.4f}", flush=True)
    return U.detach()


# --------------------------------------------------------------------------- metrics
def _acc(logits, y):
    return 100.0 * (logits.argmax(1) == y).float().mean().item()


def _conf(logits, y):
    p = F.softmax(logits.float(), dim=-1)
    return p.gather(1, y[:, None])[:, 0]


def make_ctx(z_tr, z_te, train_targets, test_targets, labels, retain_idx, forget_idx):
    te_forget = np.where(np.isin(test_targets, labels))[0]
    te_retain = np.setdiff1d(np.arange(len(test_targets)), te_forget)
    c = lambda a: torch.from_numpy(np.asarray(a, dtype=np.int64)).cuda()  # noqa: E731
    return {
        "z_tr": torch.from_numpy(z_tr).cuda(),
        "z_te": torch.from_numpy(z_te).cuda(),
        "y_tr": c(train_targets),
        "y_te": c(test_targets),
        "retain_idx": c(retain_idx),
        "forget_idx": c(forget_idx),
        "te_retain": c(te_retain),
        "te_forget": c(te_forget),
    }


def evaluate(U, ctx, W, b):
    P = U @ U.t()
    lt = (ctx["z_tr"] @ P) @ W.t() + b
    le = (ctx["z_te"] @ P) @ W.t() + b
    ri, fi = ctx["retain_idx"], ctx["forget_idx"]
    r = {
        "acc_tr_rm": _acc(lt[ri], ctx["y_tr"][ri]),
        "acc_tr_fg": _acc(lt[fi], ctx["y_tr"][fi]),
        "acc_te_rm": _acc(le[ctx["te_retain"]], ctx["y_te"][ctx["te_retain"]]),
        "acc_te_fg": _acc(le[ctx["te_forget"]], ctx["y_te"][ctx["te_forget"]]),
    }
    mem_rows = ri[ctx["mia_member"]]
    non_rows = ctx["mia_nonmember"]
    return r, (
        _conf(lt[mem_rows], ctx["y_tr"][mem_rows]).cpu(),
        _conf(le[non_rows], ctx["y_te"][non_rows]).cpu(),
        _conf(lt[fi], ctx["y_tr"][fi]).cpu(),
    )


def _svc_job(payload):
    from mia_evaluation.svc_mia import SVC_fit_predict

    mem, non, tgt = payload
    return float(SVC_fit_predict(mem, non, None, tgt))


def run_svc_batch(payloads, n_jobs=10):
    import multiprocessing as mp

    if n_jobs <= 1 or len(payloads) == 0:
        return [_svc_job(p) for p in payloads]
    with mp.get_context("fork").Pool(min(n_jobs, len(payloads))) as pool:
        return pool.map(_svc_job, payloads)


def mia_from_svc(acc_test):
    """author code: acc_test = 1 - predict(target).mean(); report (1 - confidence)*100."""
    return float((1.0 - acc_test) * 100.0)


def avg_g(arm_metrics, fexact_metrics):
    return float(np.mean([abs(arm_metrics[k] - fexact_metrics[k]) for k in METRICS]))


def mia_indices(n_retain, n_test, seed):
    """main_subspace.py: random.sample over retained-train and test, equal counts."""
    rng = random.Random(seed)
    n = min(n_retain, n_test)
    return (np.array(rng.sample(range(n_retain), n)),
            np.array(rng.sample(range(n_test), n)))


# --------------------------------------------------------------------------- stages
def stage_data(args):
    tr = os.path.join(DATA_DIR, "train")
    if os.path.isdir(tr) and len(os.listdir(tr)) == 200:
        print("[data] already materialised", flush=True)
        return
    print("[data] materialising ImageFolder", flush=True)
    subprocess.run([sys.executable, os.path.join(WORK, "prepare_data.py"), DATA_DIR], check=True)


def stage_fpre(args, state, hub, log=None):
    local = os.path.join(OUT, "fpre.pth.tar")
    if os.path.exists(local):
        print("[fpre] checkpoint present locally", flush=True)
        return local
    if hub.has("checkpoints/fpre.pth.tar"):
        print("[fpre] fetching checkpoint from Hub", flush=True)
        return hub.fetch("checkpoints/fpre.pth.tar", "fpre.pth.tar")
    print(f"[fpre] training Swin-T on all 100k images, {args.epochs} epochs", flush=True)
    cmd = [sys.executable, "main_pretrain.py", "--arch", "swin_t", "--dataset", "tinyimagenet",
           "--data_dir", DATA_DIR, "--lr", "1e-4", "--epochs", str(args.epochs), "--optim",
           "adamw", "--batch_size", "128", "--weight_decay", "0.05", "--seed", "0",
           "--save_dir", os.path.join(OUT, "fpre")]
    t0 = time.time()
    proc = subprocess.Popen(cmd, cwd=AROOT, stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT, text=True)
    ep_times = []
    for line in proc.stdout:
        line = line.rstrip()
        print("  " + line, flush=True)
        m = re.search(r"one epoch duration:([\d.]+)", line)
        if m:
            ep_times.append(float(m.group(1)))
        m = re.search(r"train_accuracy ([\d.]+)", line)
        if m and log is not None:
            log({"fpre/train_acc": float(m.group(1))}, step=len(ep_times))
    proc.wait()
    assert proc.returncode == 0, f"main_pretrain failed ({proc.returncode})"
    state["fpre_train_seconds"] = time.time() - t0
    state["fpre_epoch_seconds"] = ep_times
    src = os.path.join(OUT, "fpre", "ckpt_pretrain.pth.tar")
    shutil.copyfile(src, local)
    hub.put(local, "checkpoints/fpre.pth.tar", "fpre checkpoint")
    hub.put(os.path.join(OUT, "fpre", "train.log"), "logs/fpre_train.log", "fpre log")
    return local


def stage_features(args, state, hub, ckpt, log=None):
    tr_path = os.path.join(OUT, "feat_pre_train.npy")
    te_path = os.path.join(OUT, "feat_pre_test.npy")
    if not (os.path.exists(tr_path) and os.path.exists(te_path)):
        if hub.has("state/feat_pre_train.npy"):
            tr_path = hub.fetch("state/feat_pre_train.npy", "feat_pre_train.npy")
            te_path = hub.fetch("state/feat_pre_test.npy", "feat_pre_test.npy")
        else:
            print("[features] extracting from fpre", flush=True)
            model = load_ckpt(build_model(s=None), ckpt).eval()
            tr = ImageFolder(os.path.join(DATA_DIR, "train"), transform=test_transform())
            te = ImageFolder(os.path.join(DATA_DIR, "val"), transform=test_transform())
            f_tr, a_tr, t_tr = extract_features(model, tr)
            f_te, a_te, t_te = extract_features(model, te)
            state["fpre_identity_acc"] = {"acc_tr_all": a_tr, "acc_te_all": a_te,
                                          "extract_train_s": t_tr, "extract_test_s": t_te}
            f32 = f_tr.astype(np.float32)
            print(f"[features] float64 buffer {f_tr.nbytes / 1e6:.1f} MB -> stored float32 "
                  f"{f32.nbytes / 1e6:.1f} MB", flush=True)
            np.save(tr_path, f32)
            np.save(te_path, f_te.astype(np.float32))
            hub.put(tr_path, "state/feat_pre_train.npy", "fpre train features float32")
            hub.put(te_path, "state/feat_pre_test.npy", "fpre test features float32")
    return np.load(tr_path), np.load(te_path)


def stage_covariances(state, hub, feat_tr):
    targets = targets_of("train")
    for pi, labels in enumerate(PARTITIONS):
        sr = os.path.join(OUT, f"sigma_r_{pi}.npy")
        sf = os.path.join(OUT, f"sigma_f_{pi}.npy")
        if os.path.exists(sr) and os.path.exists(sf):
            continue
        if hub.has(f"state/sigma_r_{pi}.npy"):
            sr = hub.fetch(f"state/sigma_r_{pi}.npy", f"sigma_r_{pi}.npy")
            sf = hub.fetch(f"state/sigma_f_{pi}.npy", f"sigma_f_{pi}.npy")
            continue
        forget_idx = np.where(np.isin(targets, labels))[0]
        retain_idx = np.setdiff1d(np.arange(len(targets)), forget_idx)
        # main_subspace.py: np.cov(feat_retain, rowvar=False), float64, saved as .npy
        np.save(sr, np.cov(feat_tr[retain_idx].astype(np.float64), rowvar=False))
        np.save(sf, np.cov(feat_tr[forget_idx].astype(np.float64), rowvar=False))
        print(f"[cov] {labels}: |D_fg|={len(forget_idx)} |D_rm|={len(retain_idx)}", flush=True)
        hub.put(sr, f"state/sigma_r_{pi}.npy", f"sigma_r {labels}")
        hub.put(sf, f"state/sigma_f_{pi}.npy", f"sigma_f {labels}")


def train_one_epoch(model, loader, criterion, optimizer):
    utils = author_modules()["utils"]
    model.train()
    losses, top1 = utils.AverageMeter(), utils.AverageMeter()
    for image, target in loader:
        image, target = image.cuda(), target.cuda()
        output = model(image)
        loss = criterion(output, target)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        losses.update(loss.float().item(), image.size(0))
        top1.update(utils.accuracy(output.float().data, target)[0].item(), image.size(0))
    return losses.avg, top1.avg


def stage_fexact(args, state, hub, log=None):
    train_targets = targets_of("train")
    test_targets = targets_of("val")
    state.setdefault("fexact", {})
    for pi, labels in enumerate(PARTITIONS):
        key = ",".join(map(str, labels))
        if key in state["fexact"]:
            print(f"[fexact] metrics present for {key}", flush=True)
            continue
        ck = os.path.join(OUT, f"fexact_{pi}.pth.tar")
        if not os.path.exists(ck) and hub.has(f"checkpoints/fexact_{pi}.pth.tar"):
            ck = hub.fetch(f"checkpoints/fexact_{pi}.pth.tar", f"fexact_{pi}.pth.tar")
        forget_idx = np.where(np.isin(train_targets, labels))[0]
        retain_idx = np.setdiff1d(np.arange(len(train_targets)), forget_idx)
        if not os.path.exists(ck):
            print(f"[fexact] retraining on |D_rm|={len(retain_idx)} for {labels}", flush=True)
            train_set = ImageFolder(os.path.join(DATA_DIR, "train"), transform=train_transform())
            loader = DataLoader(Subset(train_set, retain_idx), batch_size=128, shuffle=True,
                                num_workers=8, pin_memory=True)
            model = build_model(s=None)
            crit = nn.CrossEntropyLoss()
            opt = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=0.05)
            sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=args.epochs)
            for ep in range(args.epochs):
                t0 = time.time()
                loss, acc = train_one_epoch(model, loader, crit, opt)
                sched.step()
                print(f"  fexact ep {ep + 1}/{args.epochs} loss {loss:.4f} acc {acc:.2f} "
                      f"({time.time() - t0:.0f}s)", flush=True)
                if log is not None:
                    log({"fexact/train_acc": acc, "fexact/train_loss": loss,
                         "fexact/epoch": ep + 1}, step=ep + 1)
            torch.save({"state_dict": model.state_dict()}, ck)
            hub.put(ck, f"checkpoints/fexact_{pi}.pth.tar", f"fexact {labels}")

        model = load_ckpt(build_model(s=None), ck).eval()
        tr = ImageFolder(os.path.join(DATA_DIR, "train"), transform=test_transform())
        te = ImageFolder(os.path.join(DATA_DIR, "val"), transform=test_transform())
        f_tr, _, _ = extract_features(model, tr)
        f_te, _, _ = extract_features(model, te)
        ctx = make_ctx(f_tr.astype(np.float32), f_te.astype(np.float32), train_targets,
                       test_targets, labels, retain_idx, forget_idx)
        n = min(len(retain_idx), len(test_targets))
        ctx["mia_member"], ctx["mia_nonmember"] = (
            torch.from_numpy(a).cuda() for a in mia_indices(len(retain_idx), len(test_targets), 0))
        W = model.head.weight.detach().cuda()
        b = model.head.bias.detach().cuda()
        eye = torch.eye(D_FEAT, device="cuda", dtype=torch.float32)
        m, confs = evaluate(eye, ctx, W, b)
        m["mia"] = mia_from_svc(_svc_job(confs))
        state["fexact"][key] = m
        print(f"[fexact] {labels}: " + " ".join(f"{k}={v:.2f}" for k, v in m.items()), flush=True)
        save_state(state, hub)
        del model, tr, te, f_tr, f_te, ctx
        torch.cuda.empty_cache()


def stage_ablate(args, state, hub, feat_tr, feat_te, log=None):
    train_targets = targets_of("train")
    test_targets = targets_of("val")
    head = load_ckpt(build_model(s=None), os.path.join(OUT, "fpre.pth.tar")).head
    W = head.weight.detach().cuda()
    b = head.bias.detach().cuda()
    state.setdefault("arms", {})
    state.setdefault("fpre_row", {})
    payloads, slots = [], []
    for pi in args.partition_idx:
        labels = PARTITIONS[pi]
        key = ",".join(map(str, labels))
        sigma_r = torch.from_numpy(
            np.load(os.path.join(OUT, f"sigma_r_{pi}.npy")).astype(np.float32)).cuda()
        sigma_f = torch.from_numpy(
            np.load(os.path.join(OUT, f"sigma_f_{pi}.npy")).astype(np.float32)).cuda()
        forget_idx = np.where(np.isin(train_targets, labels))[0]
        retain_idx = np.setdiff1d(np.arange(len(train_targets)), forget_idx)
        ctx = make_ctx(feat_tr, feat_te, train_targets, test_targets, labels,
                       retain_idx, forget_idx)
        ctx["mia_member"], ctx["mia_nonmember"] = (
            torch.from_numpy(a).cuda()
            for a in mia_indices(len(retain_idx), len(test_targets), 0))

        # fpre with no projection at all: our Table 1 'fpre' reference
        if key not in state["fpre_row"]:
            eye = torch.eye(D_FEAT, device="cuda", dtype=torch.float32)
            m, confs = evaluate(eye, ctx, W, b)
            payloads.append(confs)
            slots.append(("fpre_row", key, "identity", "0", m))

        state["arms"].setdefault(key, {})
        for arm in ARMS:
            for seed in args.seeds:
                if arm in state["arms"][key] and str(seed) in state["arms"][key][arm]:
                    continue
                print(f"[ablate] {labels} arm={arm} seed={seed}", flush=True)
                U = optimise_U(sigma_f, sigma_r, arm, seed, args.steps, args.s, args.lr,
                               args.wd, log)
                if args.verify_cache and not state.get("cache_check"):
                    state["cache_check"] = verify_cache(U, ctx, W, b)
                    print(f"[ablate] cached vs forward_U max|diff| = {state['cache_check']:.2e}",
                          flush=True)
                m, confs = evaluate(U, ctx, W, b)
                payloads.append(confs)
                slots.append(("arms", key, arm, str(seed), m))
                np.save(os.path.join(OUT, f"U_{pi}_{arm}_{seed}.npy"), U.cpu().numpy())
        del ctx, sigma_r, sigma_f
        torch.cuda.empty_cache()

    t_svc = time.time()
    accs = run_svc_batch(payloads, args.n_jobs)
    state["svc_seconds"] = time.time() - t_svc
    print(f"[ablate] {len(payloads)} SVC fits in {state['svc_seconds']:.1f}s", flush=True)
    for (bucket, key, arm, seed, m), acc in zip(slots, accs):
        m["mia"] = mia_from_svc(acc)
        if bucket == "fpre_row":
            state["fpre_row"][key] = m
        else:
            m["avg_g"] = avg_g(m, state["fexact"][key])
            state["arms"][key].setdefault(arm, {})[seed] = m
        print(f"[{bucket}] {key} {arm} s{seed}: "
              + " ".join(f"{k}={v:.2f}" for k, v in m.items()), flush=True)
    save_state(state, hub)


@torch.no_grad()
def verify_cache(U, ctx, W, b, n=16):
    """Check that evaluating from cached features equals model.forward_U on real images."""
    model = load_ckpt(build_model(s=None), os.path.join(OUT, "fpre.pth.tar")).eval()
    model.U = nn.Parameter(U)
    ds = ImageFolder(os.path.join(DATA_DIR, "val"), transform=test_transform())
    idx = np.linspace(0, len(ds) - 1, n).astype(int)
    x = torch.stack([ds[i][0] for i in idx]).cuda()
    direct = model.forward_U(x)
    P = U @ U.t()
    cached = (ctx["z_te"][torch.from_numpy(idx).cuda()] @ P) @ W.t() + b
    del model
    torch.cuda.empty_cache()
    return float((direct - cached).abs().max())


# --------------------------------------------------------------------------- report
def summarise(state):
    out = {}
    for arm in ARMS:
        rows = {k: [] for k in METRICS + ["avg_g"]}
        for key, arms in state["arms"].items():
            if arm not in arms:
                continue
            vals = {k: [] for k in rows}
            for seed, m in arms[arm].items():
                for k in vals:
                    vals[k].append(m[k])
            for k in rows:
                rows[k].append(float(np.mean(vals[k])))
        out[arm] = {k: {"mean": float(np.mean(v)) if v else None,
                        "sd": float(np.std(v, ddof=1)) if len(v) > 1 else None,
                        "per_partition": v} for k, v in rows.items()}
    return out


def write_report(state, summary, path):
    cfg = state.get("config", {})
    L = ["# LOFT Table 5 ablation — reproduction", "",
         f"author code @ `{AUTHOR_SHA}`, s={cfg.get('s')}, steps={cfg.get('steps')}, "
         f"lr={cfg.get('lr')}, wd={cfg.get('wd')}, epochs={cfg.get('epochs')}", "",
         "## Ours (mean over seeds, ±SD over the 3 forgetting partitions)", "",
         "| objective | Acc_tr_rm | Acc_tr_fg | Acc_te_rm | Acc_te_fg | MIA | Avg.G↓ |",
         "|---|---|---|---|---|---|---|"]
    for arm in ARMS:
        s = summary.get(arm)
        if not s or s["acc_tr_rm"]["mean"] is None:
            continue

        def f(k):
            m, sd = s[k]["mean"], s[k]["sd"]
            return "—" if m is None else (f"{m:.2f}" if sd is None else f"{m:.2f}±{sd:.2f}")

        L.append(f"| {arm} | " + " | ".join(f(k) for k in METRICS + ["avg_g"]) + " |")
    L += ["", "## fpre with no projection (our Table-1 fpre reference)", "",
          "| partition | Acc_tr_rm | Acc_tr_fg | Acc_te_rm | Acc_te_fg | MIA |", "|---|---|---|---|---|---|"]
    for key, m in state.get("fpre_row", {}).items():
        L.append(f"| {key} | " + " | ".join(f"{m[k]:.2f}" for k in METRICS) + " |")
    L += ["", "## Exact-retrained reference (ours)", "",
          "| partition | Acc_tr_rm | Acc_tr_fg | Acc_te_rm | Acc_te_fg | MIA |", "|---|---|---|---|---|---|"]
    for key, m in state.get("fexact", {}).items():
        L.append(f"| {key} | " + " | ".join(f"{m[k]:.2f}" for k in METRICS) + " |")
    L += ["", "## Paper (Table 5)", "",
          "| objective | Acc_tr_rm | Acc_tr_fg | Acc_te_rm | Acc_te_fg | MIA |",
          "|---|---|---|---|---|---|",
          "| None | 97.11 | 98.10 | 71.61 | 65.00 | 86.10 |",
          "| Jfg only | 89.51 | 11.50 | 65.40 | 4.00 | 0.00 |",
          "| Jrm only | 99.19 | 87.80 | 75.07 | 53.00 | 58.35 |",
          "| Jrm + Jfg | 98.66 | 1.10 | 74.27 | 0.00 | 0.00 |", ""]
    txt = "\n".join(L) + "\n"
    open(path, "w").write(txt)
    return txt


def save_state(state, hub):
    p = os.path.join(OUT, "results.json")
    json.dump(state, open(p, "w"), indent=1)
    hub.put(p, "results/results.json", "results")


# --------------------------------------------------------------------------- main
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--epochs", type=int, default=20)
    ap.add_argument("--steps", type=int, default=50)
    ap.add_argument("--s", type=int, default=250)
    ap.add_argument("--lr", type=float, default=1.0)
    ap.add_argument("--wd", type=float, default=0.05)
    ap.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2])
    ap.add_argument("--partition_idx", type=int, nargs="+", default=[0, 1, 2])
    ap.add_argument("--n_jobs", type=int, default=10)
    ap.add_argument("--stages", type=str, default="data,fpre,features,fexact,ablate")
    ap.add_argument("--no-push", action="store_true")
    ap.add_argument("--verify_cache", type=int, default=1)
    ap.add_argument("--trackio_space", type=str, default=None)
    args = ap.parse_args()

    os.makedirs(OUT, exist_ok=True)
    fetch_author_repo()
    hub = Hub(enabled=not args.no_push)

    log = None
    if args.trackio_space and not args.no_push:
        try:
            import trackio

            trackio.init(project="loft-table5-ablation", space_id=args.trackio_space)

            def log(d, step=None):
                trackio.log(d, step=step)
        except Exception as e:  # never lose the run to the dashboard
            print(f"[warn] trackio disabled: {e}", flush=True)

    sp = os.path.join(OUT, "results.json")
    if os.path.exists(sp):
        state = json.load(open(sp))
    elif hub.has("results/results.json"):
        state = json.load(open(hub.fetch("results/results.json", "results.json")))
    else:
        state = {}
    state["config"] = {"s": args.s, "steps": args.steps, "lr": args.lr, "wd": args.wd,
                       "epochs": args.epochs, "seeds": args.seeds, "partitions": PARTITIONS,
                       "author_sha": AUTHOR_SHA, "trackio_space": args.trackio_space}

    stages = args.stages.split(",")
    if "data" in stages:
        stage_data(args)
    ckpt = os.path.join(OUT, "fpre.pth.tar")
    if "fpre" in stages:
        ckpt = stage_fpre(args, state, hub, log)
    if "features" in stages:
        feat_tr, feat_te = stage_features(args, state, hub, ckpt, log)
        stage_covariances(state, hub, feat_tr)
        save_state(state, hub)
        del feat_tr, feat_te
    if "fexact" in stages:
        stage_fexact(args, state, hub, log)
    if "ablate" in stages:
        feat_tr = np.load(os.path.join(OUT, "feat_pre_train.npy"))
        feat_te = np.load(os.path.join(OUT, "feat_pre_test.npy"))
        stage_ablate(args, state, hub, feat_tr, feat_te, log)

    summary = summarise(state)
    state["summary"] = summary
    txt = write_report(state, summary, os.path.join(OUT, "results.md"))
    print("\n" + txt, flush=True)
    save_state(state, hub)
    hub.put(os.path.join(OUT, "results.md"), "results/results.md", "results table")
    hub.put(os.path.abspath(__file__), "code/loft_table5.py", "driver")
    if os.path.exists(os.path.join(WORK, "prepare_data.py")):
        hub.put(os.path.join(WORK, "prepare_data.py"), "code/prepare_data.py", "data prep")
    if log is not None:
        import trackio

        trackio.finish()


if __name__ == "__main__":
    main()