File size: 36,196 Bytes
c8420ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d65fc2e
 
 
1777460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1777460
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1777460
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1777460
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1777460
 
d65fc2e
1777460
 
 
 
 
d65fc2e
 
 
 
 
 
 
1777460
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1777460
d65fc2e
 
 
 
 
 
 
 
1777460
d65fc2e
 
 
1777460
d65fc2e
1777460
 
d65fc2e
 
1777460
d65fc2e
 
 
 
1777460
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1777460
d65fc2e
1777460
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1777460
d65fc2e
 
 
 
 
 
 
 
 
 
 
 
 
1777460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Set-5 probes on frozen features, built on the set 1-2 code (probes12.py = repa-probe/probe/probes.py, unchanged:
reference-centred float64 ridge statistics, per-fold z-scoring, NYU depth design / metrics, logistic regression).

Validation: seed j holds out fold j of the training split; that fold picks the regularisation strength (and, across
layers and noise levels, the best (layer, s)).  Test numbers come from the fixed test split.  CIs: 95% bootstrap over
test images of the seed-averaged per-image metric (2000 resamples), alongside the std over seeds.
"""
from __future__ import annotations

import math
import sys
from pathlib import Path

import numpy as np
import torch
import torch.nn.functional as F

sys.path.insert(0, str(Path(__file__).resolve().parent))
import probes12 as P  # noqa: E402

FIELDS = ["model", "method", "teacher", "steps", "layer", "s", "task", "metric", "mean", "std", "n",
          "size", "group", "depth_rel", "split", "ci_lo", "ci_hi"]


def bootstrap_ci(per_image, n_boot=2000, seed=0):
    v = np.asarray(per_image, float)
    rng = np.random.default_rng(seed)
    means = v[rng.integers(0, len(v), size=(n_boot, len(v)))].mean(1)
    return float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5))


@torch.no_grad()
def depth_probe(feats_fn, data, blocks, seeds=(0, 1, 2), bs=32, device="cuda"):
    """feats_fn(idx) -> list over blocks of [B, 256, D].  Returns (rows, per_image, choices).
    rows: dicts(layer, task, metric, mean, std, n, split, ci_lo, ci_hi); per_image[metric]: [L, seeds, n_test]."""
    split, fold = data["split"], torch.from_numpy(data["fold"]).to(device)
    tr, te = np.flatnonzero(split == 0), np.flatnonzero(split == 1)
    A = P.upsample_matrix(device=device)
    L = len(blocks)
    stats = None
    for i0 in range(0, len(tr), bs):
        idx = tr[i0:i0 + bs]
        dep = torch.from_numpy(np.ascontiguousarray(data["depth"][idx])).to(device)
        G, b, c, n = P.depth_design(dep, A)
        f = feats_fn(idx)
        if stats is None:
            stats = P.RidgeStats(L, f[0].shape[-1], 1, device=device)
        stats.add_weighted(f, G, b, c, n, fold[torch.from_numpy(idx).to(device)])
    del A
    fits = {(l, sd): stats.fit_seed(l, sd) for l in range(L) for sd in seeds}
    ref = stats.centre.ref
    del stats
    torch.cuda.empty_cache()
    mets = ("rmse", "delta1", "absrel", "rmse_log")
    per = {m: np.zeros((L, len(seeds), len(te))) for m in mets}
    for i0 in range(0, len(te), bs):
        idx = te[i0:i0 + bs]
        f = feats_fn(idx)
        dep = torch.from_numpy(np.ascontiguousarray(data["depth"][idx])).to(device)
        for l in range(L):
            for si, sd in enumerate(seeds):
                pred = P.RidgeStats.predict(f[l], fits[(l, sd)][0], ref[l])[..., 0]
                for j, d in enumerate(P.depth_metrics(pred, dep)):
                    for m in mets:
                        per[m][l, si, i0 + j] = d[m]
    rows, choices = [], []
    for l in range(L):
        for m in mets:
            seed_means = per[m][l].mean(1)
            lo, hi = bootstrap_ci(per[m][l].mean(0))
            rows.append(dict(layer=blocks[l], task="nyu_depth", metric=m, mean=float(seed_means.mean()),
                             std=float(seed_means.std(ddof=1)), n=len(seeds), split="test", ci_lo=lo, ci_hi=hi))
        val = [min(fits[(l, sd)][2]) for sd in seeds]
        rows.append(dict(layer=blocks[l], task="nyu_depth", metric="val_mse_logdepth", mean=float(np.mean(val)),
                         std=float(np.std(val, ddof=1)), n=len(seeds), split="val", ci_lo="", ci_hi=""))
        choices.append(dict(layer=blocks[l], task="nyu_depth", alphas=[fits[(l, sd)][1] for sd in seeds],
                            val_curves=[fits[(l, sd)][2] for sd in seeds]))
    return rows, per, choices


def train_logreg(Xtr, ytr, Xva, yva, Xte, yte, seed, n_classes=1000, epochs=60, bs=1024, lr=1e-3,
                 lambdas=P.LOGREG_LAMBDAS):
    """probes12.train_logreg (same optimiser, schedule, lambdas, z-scoring) that also returns per-image test
    correctness at the validation-selected lambda.  X*: [L, N, D] on GPU."""
    L, N, D = Xtr.shape
    mu, sd = Xtr.mean(1, keepdim=True), Xtr.std(1, keepdim=True) + 1e-6
    Xtr_n, Xva_n, Xte_n = (Xtr - mu) / sd, (Xva - mu) / sd, (Xte - mu) / sd
    nl = len(lambdas)
    H = L * nl
    lam = torch.tensor(lambdas, device=Xtr.device).repeat(L)
    W = torch.zeros(H, D, n_classes, device=Xtr.device, requires_grad=True)
    b = torch.zeros(H, 1, n_classes, device=Xtr.device, requires_grad=True)
    opt = torch.optim.Adam([W, b], lr=lr)
    g = torch.Generator(device="cpu").manual_seed(seed)
    spe = math.ceil(N / bs)
    total = epochs * spe
    sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: 0.5 * (1 + math.cos(math.pi * min(s, total) / total)))
    for _ in range(epochs):
        perm = torch.randperm(N, generator=g).to(Xtr.device)
        for i in range(spe):
            idx = perm[i * bs:(i + 1) * bs]
            logits = torch.baddbmm(b, Xtr_n[:, idx].repeat_interleave(nl, dim=0), W)
            ce = F.cross_entropy(logits.reshape(-1, n_classes), ytr[idx].repeat(H), reduction="none")
            loss = ce.reshape(H, -1).mean(1).sum() + (lam * (W ** 2).sum((1, 2))).sum()
            opt.zero_grad(set_to_none=True)
            loss.backward()
            opt.step()
            sched.step()

    @torch.no_grad()
    def correct(Xn, y):
        out = torch.zeros(H, Xn.shape[1], device=Xn.device)
        for i in range(0, Xn.shape[1], 2048):
            pred = torch.baddbmm(b, Xn[:, i:i + 2048].repeat_interleave(nl, dim=0), W).argmax(-1)
            out[:, i:i + 2048] = (pred == y[i:i + 2048][None]).float()
        return out.reshape(L, nl, -1).cpu().numpy()

    va, te = correct(Xva_n, yva).mean(-1), correct(Xte_n, yte)
    res = []
    for l in range(L):
        k = int(np.argmax(va[l]))
        res.append(dict(best_lambda=lambdas[k], val_acc=float(va[l, k]), test_acc=float(te[l, k].mean()),
                        test_correct=te[l, k], val_curve=[float(v) for v in va[l]]))
    return res


def cls_probe(Xtr, ytr, fold_tr, Xte, yte, names, seeds=(0, 1, 2), epochs=60):
    """Pooled features X*: [L, N, D] (GPU).  names: label per row of L.  Returns (rows, per_image, choices)."""
    per = np.zeros((len(names), len(seeds), Xte.shape[1]))
    rows, choices, val = [], [], np.zeros((len(names), len(seeds)))
    for si, sd in enumerate(seeds):
        trm, vam = fold_tr != sd, fold_tr == sd
        res = train_logreg(Xtr[:, trm], ytr[trm], Xtr[:, vam], ytr[vam], Xte, yte, seed=sd, epochs=epochs)
        for l, r in enumerate(res):
            per[l, si] = r["test_correct"]
            val[l, si] = r["val_acc"]
            choices.append(dict(layer=names[l], task="imagenet_cls", seed=sd, best_lambda=r["best_lambda"],
                                val_acc=r["val_acc"], val_curve=r["val_curve"]))
    for l, nm in enumerate(names):
        seed_means = per[l].mean(1)
        lo, hi = bootstrap_ci(per[l].mean(0))
        rows.append(dict(layer=nm, task="imagenet_cls", metric="top1", mean=float(seed_means.mean()),
                         std=float(seed_means.std(ddof=1)), n=len(seeds), split="test", ci_lo=lo, ci_hi=hi))
        rows.append(dict(layer=nm, task="imagenet_cls", metric="val_top1", mean=float(val[l].mean()),
                         std=float(val[l].std(ddof=1)), n=len(seeds), split="val", ci_lo="", ci_hi=""))
    return rows, per, choices


# ============================================================================= phase 3: NYU depth + normals, ADE20K
GRID = 16  # tokens per side; 16 for every phase-3/4 run, 14 for the native-224 check of patch-16 encoders (phase 5)


def depth_metrics_g(pred_tok_log, depth):
    """probes12.depth_metrics with the token grid GRID x GRID (identical for GRID = 16)."""
    B = depth.shape[0]
    p = F.interpolate(pred_tok_log.reshape(B, 1, GRID, GRID).float(), size=depth.shape[-2:], mode="bilinear",
                      align_corners=False)[:, 0]
    pd = p.exp().clamp(P.DEPTH_MIN, P.DEPTH_MAX)
    m = P.depth_mask(depth)
    out = []
    for i in range(B):
        g, q = depth[i][m[i]], pd[i][m[i]]
        ratio = torch.maximum(q / g, g / q)
        out.append(dict(rmse=float(((q - g) ** 2).mean().sqrt()), delta1=float((ratio < 1.25).float().mean()),
                        absrel=float(((q - g).abs() / g).mean()), rmse_log=float(((q.log() - g.log()) ** 2).mean().sqrt())))
    return out
class RidgeStatsK(P.RidgeStats):
    """RidgeStats with k pixel-level outputs (normals): per image, loss = sum_p m_p ||A_p Xb W - y_p||^2."""

    @torch.no_grad()
    def add_weighted_k(self, feats, G, B, c, n, fold):
        """G = A'diag(m)A [b, T, T]; B = A'(m*y) [b, T, k]; c = sum_p m_p y_p^2 [b, k]; n = sum m [b]."""
        for f in fold.unique().tolist():
            sel = fold == f
            self.C[f] += c[sel].double().sum(0)
            self.N[f] += n[sel].double().sum()
            Gs, Bs = G[sel].to(P.ACC_DTYPE), B[sel].to(P.ACC_DTYPE)
            for li, x in enumerate(feats):
                xb = self._aug(self.centre(li, x[sel])).to(P.ACC_DTYPE)
                self.M[f, li] += torch.einsum("btd,bte->de", xb, torch.bmm(Gs, xb)).double()
                self.V[f, li] += torch.einsum("btd,btk->dk", xb, Bs).double()


@torch.no_grad()
def normals_design(nrm, valid, A):
    """nrm [b, 480, 480, 3], valid [b, 480, 480] -> G [b,T,T], B [b,T,3], c [b,3], n [b]."""
    b = nrm.shape[0]
    m = valid.reshape(b, -1).float()
    y = nrm.reshape(b, -1, 3).float()
    G = torch.stack([(A * mi[:, None]).T @ A for mi in m])
    my = m[..., None] * y
    return G, torch.einsum("pt,bpk->btk", A, my), (my * y).sum(1), m.sum(1)


@torch.no_grad()
def nyu_designs(data, idx, device="cuda", bs=32):
    """Depth and normals ridge designs for NYU train images idx (model independent; cached by the caller)."""
    A = P.upsample_matrix(src=GRID, device=device)
    out = {k: [] for k in ("dG", "db", "dc", "dn", "nG", "nB", "nc", "nn")}
    for i0 in range(0, len(idx), bs):
        j = idx[i0:i0 + bs]
        dep = torch.from_numpy(np.ascontiguousarray(data["depth"][j])).to(device)
        for k, v in zip(("dG", "db", "dc", "dn"), P.depth_design(dep, A)):
            out[k].append(v.cpu())
        nrm = torch.from_numpy(np.ascontiguousarray(data["normals"][j])).to(device)
        val = torch.from_numpy(np.ascontiguousarray(data["normals_valid"][j])).to(device)
        for k, v in zip(("nG", "nB", "nc", "nn"), normals_design(nrm, val, A)):
            out[k].append(v.cpu())
    del A
    torch.cuda.empty_cache()
    return {k: torch.cat(v) for k, v in out.items()}


ANG_BINS = 720  # 0.25 degree bins on [0, 180)


@torch.no_grad()
def normals_image_stats(pred_tok, nrm, valid):
    """pred_tok [b, 256, 3] -> per image (n, sum_angle, n<11.25, n<22.5, n<30, histogram[720]) over valid pixels."""
    b = pred_tok.shape[0]
    p = F.interpolate(pred_tok.reshape(b, GRID, GRID, 3).permute(0, 3, 1, 2).float(), size=nrm.shape[1:3],
                      mode="bilinear", align_corners=False)
    p = F.normalize(p, dim=1)
    g = F.normalize(nrm.permute(0, 3, 1, 2).float(), dim=1)
    ang = torch.rad2deg(torch.acos((p * g).sum(1).clamp(-1, 1)))
    out = np.zeros((b, 5 + ANG_BINS), np.float64)
    for i in range(b):
        a = ang[i][valid[i]]
        out[i, 0], out[i, 1] = a.numel(), float(a.double().sum())
        out[i, 2:5] = [(a < t).sum().item() for t in (11.25, 22.5, 30.0)]
        out[i, 5:] = torch.histc(a, bins=ANG_BINS, min=0, max=180).cpu().numpy()
    return out


def normals_metrics_from(stats):
    """stats [..., N, 5+bins] summed over images (pixel-pooled, as Probe3D) -> dict of metrics."""
    s = stats.sum(-2)
    n = s[..., 0]
    cum = np.cumsum(s[..., 5:], -1)
    half = (n / 2)[..., None]
    k = (cum < half).sum(-1)
    prev = np.take_along_axis(np.concatenate([np.zeros_like(cum[..., :1]), cum], -1), k[..., None], -1)[..., 0]
    inbin = np.take_along_axis(s[..., 5:], np.minimum(k, ANG_BINS - 1)[..., None], -1)[..., 0]
    med = (k + (half[..., 0] - prev) / np.maximum(inbin, 1)) * (180.0 / ANG_BINS)
    return {"mean_angle": s[..., 1] / n, "median_angle": med, "pct_11.25": 100 * s[..., 2] / n,
            "pct_22.5": 100 * s[..., 3] / n, "pct_30": 100 * s[..., 4] / n}


def boot_weights(n, n_boot=2000, seed=0):
    """Multinomial resampling counts [n_boot, n] for bootstrap sums over images."""
    rng = np.random.default_rng(seed)
    return rng.multinomial(n, np.full(n, 1.0 / n), size=n_boot).astype(np.float64)


@torch.no_grad()
def nyu_probe(feats_fn, data, design, blocks, seeds=(0, 1, 2), bs=32, device="cuda"):
    """Depth (ridge, sets 1-2) and normals (ridge on unit-vector targets) from one feature pass per split.
    Returns rows, per-image arrays, choices."""
    split, fold = data["split"], torch.from_numpy(data["fold"]).to(device)
    tr, te = np.flatnonzero(split == 0), np.flatnonzero(split == 1)
    L = len(blocks)
    sd_, sn_ = None, None
    for i0 in range(0, len(tr), bs):
        idx = tr[i0:i0 + bs]
        f = feats_fn(idx)
        if sd_ is None:
            sd_ = P.RidgeStats(L, f[0].shape[-1], 1, device=device)
            sn_ = RidgeStatsK(L, f[0].shape[-1], 3, device=device)
        sl = slice(i0, i0 + len(idx))
        fo = fold[torch.from_numpy(idx).to(device)]
        g = {k: v[sl].to(device) for k, v in design.items()}
        sd_.add_weighted(f, g["dG"], g["db"], g["dc"], g["dn"], fo)
        sn_.add_weighted_k(f, g["nG"], g["nB"], g["nc"], g["nn"], fo)
    fd = {(l, s): sd_.fit_seed(l, s) for l in range(L) for s in seeds}
    fn = {(l, s): sn_.fit_seed(l, s) for l in range(L) for s in seeds}
    rd, rn = sd_.centre.ref, sn_.centre.ref
    del sd_, sn_
    torch.cuda.empty_cache()
    dm = ("rmse", "delta1", "absrel", "rmse_log")
    dper = {m: np.zeros((L, len(seeds), len(te))) for m in dm}
    nst = np.zeros((L, len(seeds), len(te), 5 + ANG_BINS))
    for i0 in range(0, len(te), bs):
        idx = te[i0:i0 + bs]
        f = feats_fn(idx)
        dep = torch.from_numpy(np.ascontiguousarray(data["depth"][idx])).to(device)
        nrm = torch.from_numpy(np.ascontiguousarray(data["normals"][idx])).to(device)
        val = torch.from_numpy(np.ascontiguousarray(data["normals_valid"][idx])).to(device)
        for l in range(L):
            for si, s in enumerate(seeds):
                pd = P.RidgeStats.predict(f[l], fd[(l, s)][0], rd[l])[..., 0]
                for j, d in enumerate(depth_metrics_g(pd, dep)):
                    for m in dm:
                        dper[m][l, si, i0 + j] = d[m]
                pn = P.RidgeStats.predict(f[l], fn[(l, s)][0], rn[l])
                nst[l, si, i0:i0 + len(idx)] = normals_image_stats(pn, nrm, val)
    rows, choices = [], []
    W = boot_weights(len(te))
    for l in range(L):
        for m in dm:
            sm = dper[m][l].mean(1)
            lo, hi = bootstrap_ci(dper[m][l].mean(0))
            rows.append(dict(layer=blocks[l], task="nyu_depth", metric=m, mean=float(sm.mean()), std=float(sm.std(ddof=1)),
                             n=len(seeds), split="test", ci_lo=lo, ci_hi=hi))
        nm = normals_metrics_from(nst[l])                                  # per seed
        bs_ = np.einsum("bn,snk->bsk", W, nst[l])                           # bootstrap sums [boot, seed, k]
        nb = normals_metrics_from(bs_[:, :, None, :])                       # [boot, seed]
        for m, v in nm.items():
            lo, hi = np.percentile(nb[m].mean(1), [2.5, 97.5])
            rows.append(dict(layer=blocks[l], task="nyu_normals", metric=m, mean=float(v.mean()),
                             std=float(v.std(ddof=1)), n=len(seeds), split="test", ci_lo=float(lo), ci_hi=float(hi)))
        for task, fits in (("nyu_depth", fd), ("nyu_normals", fn)):
            val = [min(fits[(l, s)][2]) for s in seeds]
            rows.append(dict(layer=blocks[l], task=task, metric="val_mse", mean=float(np.mean(val)),
                             std=float(np.std(val, ddof=1)), n=len(seeds), split="val", ci_lo="", ci_hi=""))
            choices.append(dict(layer=blocks[l], task=task, alphas=[fits[(l, s)][1] for s in seeds],
                                val_curves=[fits[(l, s)][2] for s in seeds]))
    per = {**{f"depth_{m}": v for m, v in dper.items()}, "normals_stats": nst.astype(np.float32)}
    return rows, per, choices


# ----------------------------------------------------------------------------- ADE20K linear segmentation
N_SEG = 150


@torch.no_grad()
def token_targets(lbl):
    """lbl [b, 256, 256] uint8 (0 ignore) -> per-token class counts [b, T, 150] over its 16x16 pixels (T = GRID^2;
    for GRID < 16 the labels are first resized, nearest, to the model's GRID*16 px input)."""
    b = lbl.shape[0]
    if GRID != 16:
        lbl = F.interpolate(lbl[:, None].float(), size=(GRID * 16, GRID * 16), mode="nearest")[:, 0].to(torch.uint8)
    T = GRID * GRID
    t = lbl.long().reshape(b, GRID, 16, GRID, 16).permute(0, 1, 3, 2, 4).reshape(b, T, 256)
    cnt = torch.zeros(b, T, N_SEG + 1, device=lbl.device).scatter_add_(2, t, torch.ones_like(t, dtype=torch.float))
    return cnt[..., 1:]


@torch.no_grad()
def seg_counts(logits_tok, lbl):
    """logits_tok [h, b, 256, C] -> per head and image (TP, FP, FN) per class [h, b, 3, C] (pixel level, 256x256)."""
    h, b = logits_tok.shape[:2]
    up = F.interpolate(logits_tok.reshape(h * b, GRID, GRID, N_SEG).permute(0, 3, 1, 2), size=(256, 256),
                       mode="bilinear", align_corners=False).argmax(1).reshape(h, b, -1)
    gt = lbl.reshape(1, b, -1).long() - 1                                  # -1 = ignore
    ok = gt >= 0
    out = torch.zeros(h, b, 3, N_SEG, device=logits_tok.device)
    for hi in range(h):
        for i in range(b):
            g, p = gt[0, i][ok[0, i]], up[hi, i][ok[0, i]]
            cm = torch.bincount(g * N_SEG + p, minlength=N_SEG * N_SEG).reshape(N_SEG, N_SEG).float()
            tp = cm.diagonal()
            out[hi, i, 0], out[hi, i, 1], out[hi, i, 2] = tp, cm.sum(0) - tp, cm.sum(1) - tp
    return out


def miou_from(c):
    """c [..., 3, C] (summed over images) -> mIoU over classes present in GT or prediction."""
    tp, fp, fn = c[..., 0, :], c[..., 1, :], c[..., 2, :]
    den = tp + fp + fn
    iou = np.where(den > 0, tp / np.maximum(den, 1), np.nan)
    return np.nanmean(iou, -1)


def seg_probe(feats_fn_tr, feats_fn_te, ade_tr, ade_te, blocks, seeds=(0, 1, 2), lambdas=P.LOGREG_LAMBDAS, epochs=8,
              bs_tok=8192, lr=1e-3, device="cuda"):
    """Linear per-token classifier (150 classes), soft-label cross-entropy on the 16x16 pixel class histogram of each
    token, trained per layer on the ADE train subset (features held in CPU RAM, centred, bf16); seed j holds out fold j
    of the train subset to choose the weight decay by pixel mIoU; test = ADE val (pixel mIoU on the 256 px crop)."""
    L, n_tr, T = len(blocks), len(ade_tr["img"]), GRID * GRID
    fold_img = torch.from_numpy(ade_tr["fold"])
    X, ref, S1, S2, cnt, Q = None, None, None, None, torch.zeros(10, dtype=torch.float64), None
    with torch.no_grad():
        for i0 in range(0, n_tr, 64):
            idx = np.arange(i0, min(n_tr, i0 + 64))
            f = feats_fn_tr(idx)
            if X is None:
                D = f[0].shape[-1]
                X = torch.empty(L, n_tr * T, D, dtype=torch.bfloat16)
                ref = [x.reshape(-1, D).double().mean(0) for x in f]
                S1 = torch.zeros(10, L, D, dtype=torch.float64, device=device)
                S2 = torch.zeros_like(S1)
                Q = torch.empty(n_tr * T, N_SEG, dtype=torch.float16)
            lb = torch.from_numpy(np.ascontiguousarray(ade_tr["lbl"][idx])).to(device)
            Q[i0 * T:(i0 + len(idx)) * T] = token_targets(lb).reshape(-1, N_SEG).half().cpu()
            fo = fold_img[idx].to(device).repeat_interleave(T)
            for l in range(L):
                xc = (f[l].reshape(-1, D).double() - ref[l]).bfloat16()
                X[l, i0 * T:(i0 + len(idx)) * T] = xc.cpu()
                xd = xc.double()
                S1[:, l].index_add_(0, fo, xd)
                S2[:, l].index_add_(0, fo, xd * xd)
            cnt += torch.bincount(fo.cpu(), minlength=10).double()
    tok_fold = fold_img.repeat_interleave(T)
    wt = Q.float().sum(-1)                                                  # labelled pixels per token
    has = wt > 0
    nl, C = len(lambdas), N_SEG
    heads, val_miou, choices = {}, np.zeros((L, len(seeds))), []
    for l in range(L):
        Xl = X[l].to(device)
        for si, sd in enumerate(seeds):
            trm = (tok_fold != sd) & has
            tri = torch.nonzero(trm).squeeze(1)
            n_t = cnt.clone()
            n_t[sd] = 0
            mu = (S1[:, l].sum(0) - S1[sd, l]) / n_t.sum()
            var = (S2[:, l].sum(0) - S2[sd, l]) / n_t.sum() - mu ** 2
            mu, sdv = mu.float(), (var.clamp_min(0).sqrt() + 1e-6).float()
            Wt = torch.zeros(nl, D, C, device=device, requires_grad=True)
            bt = torch.zeros(nl, 1, C, device=device, requires_grad=True)
            opt = torch.optim.Adam([Wt, bt], lr=lr)
            g = torch.Generator().manual_seed(sd)
            spe = math.ceil(len(tri) / bs_tok)
            total = epochs * spe
            sch = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: 0.5 * (1 + math.cos(math.pi * min(s, total) / total)))
            lam = torch.tensor(lambdas, device=device)
            for _ in range(epochs):
                perm = tri[torch.randperm(len(tri), generator=g)]
                for k in range(spe):
                    b_ = perm[k * bs_tok:(k + 1) * bs_tok]
                    xb = (Xl[b_.to(device)].float() - mu) / sdv
                    q = Q[b_].to(device).float()
                    w = q.sum(-1)
                    logp = torch.log_softmax(torch.baddbmm(bt, xb.expand(nl, -1, -1), Wt), -1)
                    ce = -(q[None] * logp).sum(-1).sum(-1) / w.sum()
                    loss = ce.sum() + (lam * (Wt ** 2).sum((1, 2))).sum()
                    opt.zero_grad(set_to_none=True)
                    loss.backward()
                    opt.step()
                    sch.step()
            # validation fold: pixel mIoU per weight decay
            vimg = np.flatnonzero(ade_tr["fold"] == sd)
            vc = torch.zeros(nl, 3, C, device=device)
            with torch.no_grad():
                for j0 in range(0, len(vimg), 16):
                    ii = vimg[j0:j0 + 16]
                    tok = torch.from_numpy((ii[:, None] * T + np.arange(T)).reshape(-1))
                    xb = (Xl[tok.to(device)].float() - mu) / sdv
                    lg = torch.baddbmm(bt, xb.expand(nl, -1, -1), Wt).reshape(nl, len(ii), T, C)
                    lb = torch.from_numpy(np.ascontiguousarray(ade_tr["lbl"][ii])).to(device)
                    vc += seg_counts(lg, lb).sum(1)
            vm = miou_from(vc.cpu().numpy())
            kbest = int(np.nanargmax(vm))
            heads[(l, si)] = (Wt.detach()[kbest].clone(), bt.detach()[kbest].clone(), mu, sdv)
            val_miou[l, si] = vm[kbest]
            choices.append(dict(layer=blocks[l], task="ade_seg", seed=sd, best_lambda=lambdas[kbest],
                                val_miou_curve=[float(v) for v in vm]))
        del Xl
        torch.cuda.empty_cache()
    del X, Q
    # test: ADE val, per image (TP, FP, FN) per class for each layer and seed
    n_te = len(ade_te["img"])
    per = np.zeros((L, len(seeds), n_te, 3, C), np.int32)
    with torch.no_grad():
        for i0 in range(0, n_te, 32):
            idx = np.arange(i0, min(n_te, i0 + 32))
            f = feats_fn_te(idx)
            lb = torch.from_numpy(np.ascontiguousarray(ade_te["lbl"][idx])).to(device)
            for l in range(L):
                xc = (f[l].reshape(-1, D).double() - ref[l]).bfloat16().float()
                lg = []
                for si in range(len(seeds)):
                    Wb, bb, mu, sdv = heads[(l, si)]
                    lg.append((((xc - mu) / sdv) @ Wb + bb).reshape(len(idx), T, C))
                per[l, :, i0:i0 + len(idx)] = seg_counts(torch.stack(lg), lb).cpu().numpy().astype(np.int32)
    rows = []
    Wb_ = boot_weights(n_te)
    for l in range(L):
        ms = np.array([miou_from(per[l, si].sum(0)) for si in range(len(seeds))])
        bsum = np.einsum("bn,snkc->bskc", Wb_, per[l].astype(np.float64))
        bm = miou_from(bsum).mean(1)
        lo, hi = np.percentile(bm, [2.5, 97.5])
        rows.append(dict(layer=blocks[l], task="ade_seg", metric="miou", mean=float(ms.mean()), std=float(ms.std(ddof=1)),
                         n=len(seeds), split="test", ci_lo=float(lo), ci_hi=float(hi)))
        rows.append(dict(layer=blocks[l], task="ade_seg", metric="val_miou", mean=float(val_miou[l].mean()),
                         std=float(val_miou[l].std(ddof=1)), n=len(seeds), split="val", ci_lo="", ci_hi=""))
    return rows, {"ade_counts": per}, choices


# ============================================================================= phase 5: 2-layer token-wise MLP probes
MLP_HIDDEN, MLP_WDS, MLP_LR = 1024, (1e-4, 1e-2), 1e-3


class TokenMLP(torch.nn.Module):
    def __init__(self, d, k, hidden=MLP_HIDDEN):
        super().__init__()
        self.net = torch.nn.Sequential(torch.nn.Linear(d, hidden), torch.nn.GELU(), torch.nn.Linear(hidden, k))

    def forward(self, x):
        return self.net(x)


def _cosine(opt, total):
    return torch.optim.lr_scheduler.LambdaLR(opt, lambda s: 0.5 * (1 + math.cos(math.pi * min(s, total) / total)))


def mlp_nyu_probe(F_all, data, task, seeds=(0, 1, 2), wds=MLP_WDS, epochs=30, bs=16, lr=MLP_LR, device="cuda"):
    """2-layer MLP per token on frozen features of one (block, s) cell, same objective as the ridge probe: masked
    pixel MSE after bilinear upsampling to 480x480 (depth: log-depth in the Eigen crop; normals: unit vectors on the
    valid mask).  F_all [1449, T, D] on GPU.  Weight decay chosen on fold `seed` of the train split (3 seeds)."""
    split, fold = data["split"], data["fold"]
    tr, te = np.flatnonzero(split == 0), np.flatnonzero(split == 1)
    k = 1 if task == "depth" else 3
    H = W = 480

    def targets(idx):
        if task == "depth":
            d = torch.from_numpy(np.ascontiguousarray(data["depth"][idx])).to(device)
            return torch.log(d.clamp_min(P.DEPTH_MIN))[:, None], P.depth_mask(d)
        n = torch.from_numpy(np.ascontiguousarray(data["normals"][idx])).to(device).float().permute(0, 3, 1, 2)
        return n, torch.from_numpy(np.ascontiguousarray(data["normals_valid"][idx])).to(device)

    def predict(mdl, X, mu, sd):
        b = X.shape[0]
        out = mdl((X - mu) / sd)                                       # [b, T, k]
        return F.interpolate(out.reshape(b, GRID, GRID, k).permute(0, 3, 1, 2), size=(H, W), mode="bilinear",
                             align_corners=False)                      # [b, k, H, W]

    def masked_mse(pred, y, m):
        mm = m[:, None].float()
        return ((pred - y) ** 2 * mm).sum() / (mm.sum() * k).clamp_min(1)

    rows, choices = [], []
    dm = ("rmse", "delta1", "absrel", "rmse_log")
    dper = {m: np.zeros((len(seeds), len(te))) for m in dm}
    nst = np.zeros((len(seeds), len(te), 5 + ANG_BINS))
    val_best = []
    for si, sd in enumerate(seeds):
        trs, vas = tr[fold[tr] != sd], tr[fold[tr] == sd]
        Xtr = F_all[torch.from_numpy(trs).to(device)]
        mu, sdv = Xtr.mean((0, 1)), Xtr.std((0, 1)) + 1e-6
        best = None
        for wd in wds:
            g = torch.Generator().manual_seed(sd)
            torch.manual_seed(sd)
            mdl = TokenMLP(F_all.shape[-1], k).to(device)
            opt = torch.optim.AdamW(mdl.parameters(), lr=lr, weight_decay=wd)
            spe = math.ceil(len(trs) / bs)
            sch = _cosine(opt, epochs * spe)
            for _ in range(epochs):
                perm = trs[torch.randperm(len(trs), generator=g).numpy()]
                for i0 in range(0, len(perm), bs):
                    idx = perm[i0:i0 + bs]
                    y, m = targets(idx)
                    loss = masked_mse(predict(mdl, F_all[torch.from_numpy(idx).to(device)], mu, sdv), y, m)
                    opt.zero_grad(set_to_none=True)
                    loss.backward()
                    opt.step()
                    sch.step()
            with torch.no_grad():
                num = den = 0.0
                for i0 in range(0, len(vas), bs):
                    idx = vas[i0:i0 + bs]
                    y, m = targets(idx)
                    pr = predict(mdl, F_all[torch.from_numpy(idx).to(device)], mu, sdv)
                    mm = m[:, None].float()
                    num += float(((pr - y) ** 2 * mm).sum())
                    den += float(mm.sum() * k)
            v = num / max(den, 1)
            choices.append(dict(task=f"nyu_{task}_mlp", seed=sd, wd=wd, val_mse=v))
            if best is None or v < best[0]:
                best = (v, wd, mdl)
        val_best.append(best[0])
        mdl = best[2]
        with torch.no_grad():
            for i0 in range(0, len(te), bs):
                idx = te[i0:i0 + bs]
                X = F_all[torch.from_numpy(idx).to(device)]
                out = mdl((X - mu) / sdv)
                if task == "depth":
                    dep = torch.from_numpy(np.ascontiguousarray(data["depth"][idx])).to(device)
                    for j, d in enumerate(depth_metrics_g(out[..., 0], dep)):
                        for mname in dm:
                            dper[mname][si, i0 + j] = d[mname]
                else:
                    nrm = torch.from_numpy(np.ascontiguousarray(data["normals"][idx])).to(device)
                    val = torch.from_numpy(np.ascontiguousarray(data["normals_valid"][idx])).to(device)
                    nst[si, i0:i0 + len(idx)] = normals_image_stats(out, nrm, val)
    if task == "depth":
        for mname in dm:
            sm = dper[mname].mean(1)
            lo, hi = bootstrap_ci(dper[mname].mean(0))
            rows.append(dict(task="nyu_depth_mlp", metric=mname, mean=float(sm.mean()), std=float(sm.std(ddof=1)),
                             n=len(seeds), split="test", ci_lo=lo, ci_hi=hi))
        per = {f"depth_{m}": v for m, v in dper.items()}
    else:
        nm = normals_metrics_from(nst)
        nb = normals_metrics_from(np.einsum("bn,snk->bsk", boot_weights(len(te)), nst)[:, :, None, :])
        for mname, v in nm.items():
            lo, hi = np.percentile(nb[mname].mean(1), [2.5, 97.5])
            rows.append(dict(task="nyu_normals_mlp", metric=mname, mean=float(v.mean()), std=float(v.std(ddof=1)),
                             n=len(seeds), split="test", ci_lo=float(lo), ci_hi=float(hi)))
        per = {"normals_stats": nst.astype(np.float32)}
    rows.append(dict(task=f"nyu_{task}_mlp", metric="val_mse", mean=float(np.mean(val_best)),
                     std=float(np.std(val_best, ddof=1)), n=len(seeds), split="val", ci_lo="", ci_hi=""))
    return rows, per, choices


def mlp_seg_probe(feats_fn_tr, feats_fn_te, ade_tr, ade_te, seeds=(0, 1, 2), wds=MLP_WDS, epochs=8, bs_tok=8192,
                  lr=MLP_LR, device="cuda"):
    """2-layer MLP per token for ADE20K on one (block, s) cell: same data, targets (soft-label CE on the token's pixel
    class histogram), folds and evaluation (pixel mIoU, 256 px crop) as seg_probe."""
    n_tr, T, C = len(ade_tr["img"]), GRID * GRID, N_SEG
    fold_img = torch.from_numpy(ade_tr["fold"])
    X, ref, S1, S2, cnt, Q = None, None, None, None, torch.zeros(10, dtype=torch.float64), None
    with torch.no_grad():
        for i0 in range(0, n_tr, 64):
            idx = np.arange(i0, min(n_tr, i0 + 64))
            f = feats_fn_tr(idx)[0]
            if X is None:
                D = f.shape[-1]
                X = torch.empty(n_tr * T, D, dtype=torch.bfloat16)
                ref = f.reshape(-1, D).double().mean(0)
                S1 = torch.zeros(10, D, dtype=torch.float64, device=device)
                S2 = torch.zeros_like(S1)
                Q = torch.empty(n_tr * T, C, dtype=torch.float16)
            lb = torch.from_numpy(np.ascontiguousarray(ade_tr["lbl"][idx])).to(device)
            Q[i0 * T:(i0 + len(idx)) * T] = token_targets(lb).reshape(-1, C).half().cpu()
            fo = fold_img[idx].to(device).repeat_interleave(T)
            xc = (f.reshape(-1, D).double() - ref).bfloat16()
            X[i0 * T:(i0 + len(idx)) * T] = xc.cpu()
            S1.index_add_(0, fo, xc.double())
            S2.index_add_(0, fo, xc.double() ** 2)
            cnt += torch.bincount(fo.cpu(), minlength=10).double()
    tok_fold = fold_img.repeat_interleave(T)
    has = Q.float().sum(-1) > 0
    Xg = X.to(device)
    models, val_miou, choices = {}, [], []
    for si, sd in enumerate(seeds):
        tri = torch.nonzero((tok_fold != sd) & has).squeeze(1)
        n_t = cnt.clone()
        n_t[sd] = 0
        mu = ((S1.sum(0) - S1[sd]) / n_t.sum()).float()
        sdv = (((S2.sum(0) - S2[sd]) / n_t.sum() - ((S1.sum(0) - S1[sd]) / n_t.sum()) ** 2).clamp_min(0).sqrt()
               + 1e-6).float()
        vimg = np.flatnonzero(ade_tr["fold"] == sd)
        best = None
        for wd in wds:
            g = torch.Generator().manual_seed(sd)
            torch.manual_seed(sd)
            mdl = TokenMLP(D, C).to(device)
            opt = torch.optim.AdamW(mdl.parameters(), lr=lr, weight_decay=wd)
            spe = math.ceil(len(tri) / bs_tok)
            sch = _cosine(opt, epochs * spe)
            for _ in range(epochs):
                perm = tri[torch.randperm(len(tri), generator=g)]
                for kk in range(spe):
                    b_ = perm[kk * bs_tok:(kk + 1) * bs_tok]
                    q = Q[b_].to(device).float()
                    logp = torch.log_softmax(mdl((Xg[b_.to(device)].float() - mu) / sdv), -1)
                    loss = -(q * logp).sum() / q.sum()
                    opt.zero_grad(set_to_none=True)
                    loss.backward()
                    opt.step()
                    sch.step()
            vc = torch.zeros(1, 3, C, device=device)
            with torch.no_grad():
                for j0 in range(0, len(vimg), 16):
                    ii = vimg[j0:j0 + 16]
                    tok = torch.from_numpy((ii[:, None] * T + np.arange(T)).reshape(-1)).to(device)
                    lg = mdl((Xg[tok].float() - mu) / sdv).reshape(1, len(ii), T, C)
                    lb = torch.from_numpy(np.ascontiguousarray(ade_tr["lbl"][ii])).to(device)
                    vc += seg_counts(lg, lb).sum(1)
            vm = float(miou_from(vc.cpu().numpy())[0])
            choices.append(dict(task="ade_seg_mlp", seed=sd, wd=wd, val_miou=vm))
            if best is None or vm > best[0]:
                best = (vm, wd, mdl)
        val_miou.append(best[0])
        models[si] = (best[2], mu, sdv)
    del Xg, X, Q
    torch.cuda.empty_cache()
    n_te = len(ade_te["img"])
    per = np.zeros((len(seeds), n_te, 3, C), np.int32)
    with torch.no_grad():
        for i0 in range(0, n_te, 32):
            idx = np.arange(i0, min(n_te, i0 + 32))
            f = feats_fn_te(idx)[0]
            xc = (f.reshape(-1, D).double() - ref).bfloat16().float()
            lb = torch.from_numpy(np.ascontiguousarray(ade_te["lbl"][idx])).to(device)
            lg = torch.stack([mdl((xc - mu) / sdv).reshape(len(idx), T, C) for mdl, mu, sdv in
                              (models[si] for si in range(len(seeds)))])
            per[:, i0:i0 + len(idx)] = seg_counts(lg, lb).cpu().numpy().astype(np.int32)
    ms = np.array([miou_from(per[si].sum(0)) for si in range(len(seeds))])
    bm = miou_from(np.einsum("bn,snkc->bskc", boot_weights(n_te), per.astype(np.float64))).mean(1)
    lo, hi = np.percentile(bm, [2.5, 97.5])
    rows = [dict(task="ade_seg_mlp", metric="miou", mean=float(ms.mean()), std=float(ms.std(ddof=1)), n=len(seeds),
                 split="test", ci_lo=float(lo), ci_hi=float(hi)),
            dict(task="ade_seg_mlp", metric="val_miou", mean=float(np.mean(val_miou)), std=float(np.std(val_miou, ddof=1)),
                 n=len(seeds), split="val", ci_lo="", ci_hi="")]
    return rows, {"ade_counts": per}, choices