-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy patheval_reproduce_reg_write_subspace_adv.py
More file actions
1996 lines (1688 loc) · 71.8 KB
/
eval_reproduce_reg_write_subspace_adv.py
File metadata and controls
1996 lines (1688 loc) · 71.8 KB
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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
zer0int 2026 ~ github.com/zer0int/CLIP-fine-tune
______________________________________________________________
----- VARIANT: Adversarial Dataset (included in this repo) -----
CLIP ViT-L/14 late-half probing + hidden-space reps + survival-aware head writes + plotting + dyslexify.
1) Dyslexify JSON production:
- Writes a block->disabled_heads JSON you can feed back via --dyslexify_json.
- By default uses a survival-weighted score per head (configurable below).
2) Dyslexify-only mode:
- If --dyslexify_json is provided, the script runs ONLY dyslexify evaluation + related outputs (no EXP1/EXP2 full rerun).
3) Plots (lots):
- Per-model line plots over blocks for:
reg_attn_mass, reg_write_norm, reg_write_survival, delta(attn_frac - write_frac)
- Per-model heatmaps (heads x blocks) for the same.
- Per-block (for each probed block): side-by-side pies (attn_frac vs write_frac), plus scatter attn vs write.
- Per-model correlation curve corr(attn_frac, write_frac) over blocks.
"""
from __future__ import annotations
import os
import re
import json
import csv
import math
import argparse
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import torch
from tqdm import tqdm
from colorama import Fore, Style, init as colorama_init
colorama_init(autoreset=True)
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import attnclipdecouple as clip # capture: last_probs/last_v
from utils_clip_loader.cliptools import fix_random_seed
fix_random_seed()
from utils_clip_loader.clip_anything_to_openai import load_openai_clip_anything
# ============================================================
# Models: OpenAI / local path .pt .safetensors / HuggingFace Hub
# ============================================================
MODELS: List[Tuple[str, str]] = [
("pretrained", "ViT-L/14"),
("gmp-clip", "zer0int/CLIP-GmP-ViT-L-14"),
("ko-clip", "zer0int/CLIP-KO-LITE-TypoAttack-Attn-Dropout-ViT-L-14"),
("regr-norm", "zer0int/CLIP-Regression-ViT-L-14"),
("regr-brut", "zer0int/CLIP-Regression-BRUT-ViT-L-14"),
]
@dataclass
class PairSample:
image: Any # PIL
correct_label: str
distractor_label: str
meta: Dict[str, Any]
@dataclass
class DatasetBundle:
"""
mode:
- "paired": two variants with shared keys (clean vs typo) for delta-style analyses
- "single": one split only (typo images only) -> EXP1 is skipped; EXP2 still runs
"""
mode: str
variant_a: str
variant_b: str
ordered_keys: List[str]
map_a: Dict[str, PairSample]
map_b: Dict[str, PairSample]
map_single: Dict[str, PairSample]
dataset_name: str
def _is_image_file(p: str) -> bool:
ext = os.path.splitext(p)[1].lower()
return ext in [".jpg", ".jpeg", ".png", ".webp", ".bmp"]
def _safe_stem(p: str) -> str:
return os.path.splitext(os.path.basename(p))[0]
def _try_load_json(path: str) -> Optional[Any]:
if not os.path.isfile(path):
return None
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return None
def _try_load_jsonl(path: str) -> Optional[List[Dict[str, Any]]]:
if not os.path.isfile(path):
return None
rows = []
try:
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
rows.append(json.loads(line))
return rows
except Exception:
return None
def _try_load_csv(path: str) -> Optional[List[Dict[str, Any]]]:
if not os.path.isfile(path):
return None
try:
with open(path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
return [dict(r) for r in reader]
except Exception:
return None
def _normalize_meta_entry(entry: Dict[str, Any]) -> Tuple[str, str, str, Optional[str], Optional[str]]:
"""
Returns: (img_path_or_name, correct_label, distractor_label, clean_path, typo_path)
Supports many key spellings because your local datasets tend to evolve.
"""
def pick(*keys, default=""):
for k in keys:
if k in entry and entry[k] not in (None, ""):
return entry[k]
return default
img = pick("image", "img", "path", "file", "filename", "relpath", "image_path", "img_path", default="")
correct = pick("correct_label", "object_label", "label", "gt", "class", "y", default="")
distract = pick("distractor_label", "attack_word", "attack", "typo", "word", "target", default="")
clean_path = pick("clean_image", "clean_path", "orig_image", "original_image", "image_clean", default=None)
typo_path = pick("typo_image", "adv_image", "attack_image", "image_adv", "image_typo", default=None)
return str(img), str(correct), str(distract), (str(clean_path) if clean_path else None), (str(typo_path) if typo_path else None)
def _find_first_existing(base_dir: str, candidates: List[str]) -> Optional[str]:
for name in candidates:
p = os.path.join(base_dir, name)
if os.path.isfile(p):
return p
return None
def load_typoattack_bundle(
base_dir: str = "image_sets/adv_dataset/typoattack",
limit: Optional[int] = None,
) -> DatasetBundle:
"""
Local dataset loader for typoattack.
Priority order:
1) Paired layout via subfolders (clean/orig vs typo/adv/attack) paired by filename stem.
2) Metadata file describing pairs (json/jsonl/csv) with clean_path + typo_path.
3) Single split: just images in base_dir (or in "images/" subfolder) with optional metadata for labels.
If labels are absent, correct_label/distractor_label are set to "" (but EXP2 still runs).
"""
base_dir = os.path.normpath(base_dir)
# (1) folder-pair heuristic
subdirs = {d.lower(): os.path.join(base_dir, d) for d in os.listdir(base_dir) if os.path.isdir(os.path.join(base_dir, d))}
clean_dir = None
typo_dir = None
for k in ["clean", "orig", "original", "noattack", "no_attack", "base"]:
if k in subdirs:
clean_dir = subdirs[k]
break
for k in ["typo", "adv", "attack", "attacked", "adversarial", "perturbed"]:
if k in subdirs:
typo_dir = subdirs[k]
break
if clean_dir is not None and typo_dir is not None:
clean_imgs = [os.path.join(clean_dir, f) for f in os.listdir(clean_dir) if _is_image_file(f)]
typo_imgs = [os.path.join(typo_dir, f) for f in os.listdir(typo_dir) if _is_image_file(f)]
clean_map = { _safe_stem(p): p for p in clean_imgs }
typo_map = { _safe_stem(p): p for p in typo_imgs }
keys = sorted(set(clean_map.keys()).intersection(set(typo_map.keys())))
if limit is not None:
keys = keys[:limit]
from PIL import Image
map_a, map_b = {}, {}
for k in keys:
map_a[k] = PairSample(
image=Image.open(clean_map[k]).convert("RGB"),
correct_label="",
distractor_label="",
meta=dict(id=k, pair_key=k, dataset="typoattack", variant="clean", path=clean_map[k]),
)
map_b[k] = PairSample(
image=Image.open(typo_map[k]).convert("RGB"),
correct_label="",
distractor_label="",
meta=dict(id=k, pair_key=k, dataset="typoattack", variant="typo", path=typo_map[k]),
)
return DatasetBundle(
mode="paired",
variant_a="clean",
variant_b="typo",
ordered_keys=keys,
map_a=map_a,
map_b=map_b,
map_single={},
dataset_name="typoattack",
)
# (2) metadata-driven pairing or labeling
meta_path = _find_first_existing(base_dir, [
"pairs.json", "annotations.json", "metadata.json", "dataset.json",
"pairs.jsonl", "annotations.jsonl", "metadata.jsonl",
"pairs.csv", "annotations.csv", "metadata.csv",
])
meta_obj = None
meta_rows = None
if meta_path:
if meta_path.endswith(".json"):
meta_obj = _try_load_json(meta_path)
elif meta_path.endswith(".jsonl"):
meta_rows = _try_load_jsonl(meta_path)
elif meta_path.endswith(".csv"):
meta_rows = _try_load_csv(meta_path)
# Normalize metadata rows to list[dict]
rows: List[Dict[str, Any]] = []
if isinstance(meta_obj, dict):
# dict mapping -> allow { "relpath": [correct, distract] } or { "relpath": {...} }
for k, v in meta_obj.items():
if isinstance(v, list) and len(v) >= 2:
rows.append({"image": k, "correct_label": v[0], "distractor_label": v[1]})
elif isinstance(v, dict):
vv = dict(v)
vv.setdefault("image", k)
rows.append(vv)
else:
rows.append({"image": k})
elif isinstance(meta_obj, list):
rows = [dict(x) for x in meta_obj]
elif isinstance(meta_rows, list):
rows = [dict(x) for x in meta_rows]
# If metadata provides explicit clean+typo paths -> paired
has_pairs = False
for r in rows[: min(50, len(rows))]:
_, _, _, c, t = _normalize_meta_entry(r)
if c and t:
has_pairs = True
break
if has_pairs:
from PIL import Image
map_a, map_b = {}, {}
keys = []
for r in rows:
img, corr, dist, clean_path, typo_path = _normalize_meta_entry(r)
if not clean_path or not typo_path:
continue
cpath = clean_path if os.path.isabs(clean_path) else os.path.join(base_dir, clean_path)
tpath = typo_path if os.path.isabs(typo_path) else os.path.join(base_dir, typo_path)
if not (os.path.isfile(cpath) and os.path.isfile(tpath)):
continue
key = str(r.get("pair_key", "")) or _safe_stem(cpath)
keys.append(key)
map_a[key] = PairSample(
image=Image.open(cpath).convert("RGB"),
correct_label=corr,
distractor_label=dist,
meta=dict(id=key, pair_key=key, dataset="typoattack", variant="clean", path=cpath, meta=r),
)
map_b[key] = PairSample(
image=Image.open(tpath).convert("RGB"),
correct_label=corr,
distractor_label=dist,
meta=dict(id=key, pair_key=key, dataset="typoattack", variant="typo", path=tpath, meta=r),
)
keys = [k for k in keys if (k in map_a and k in map_b)]
keys = sorted(dict.fromkeys(keys)) # stable unique
if limit is not None:
keys = keys[:limit]
return DatasetBundle(
mode="paired",
variant_a="clean",
variant_b="typo",
ordered_keys=keys,
map_a={k: map_a[k] for k in keys},
map_b={k: map_b[k] for k in keys},
map_single={},
dataset_name="typoattack",
)
# Otherwise: single split
# Find images in base_dir or images/ subdir
img_root = base_dir
images_sub = os.path.join(base_dir, "images")
if os.path.isdir(images_sub):
img_root = images_sub
all_imgs = []
for root, _, files in os.walk(img_root):
for f in files:
if _is_image_file(f):
all_imgs.append(os.path.join(root, f))
all_imgs = sorted(all_imgs)
if limit is not None:
all_imgs = all_imgs[:limit]
# Optional labels from metadata: map by relpath or stem
label_by_key: Dict[str, Tuple[str, str]] = {}
if rows:
for r in rows:
img, corr, dist, _, _ = _normalize_meta_entry(r)
if not img:
continue
key = str(r.get("id", "")) or str(r.get("pair_key", "")) or _safe_stem(img)
label_by_key[key] = (corr, dist)
from PIL import Image
map_single = {}
keys = []
for p in all_imgs:
key = _safe_stem(p)
corr, dist = label_by_key.get(key, ("", ""))
keys.append(key)
map_single[key] = PairSample(
image=Image.open(p).convert("RGB"),
correct_label=corr,
distractor_label=dist,
meta=dict(id=key, pair_key=key, dataset="typoattack", variant="single", path=p),
)
return DatasetBundle(
mode="single",
variant_a="single",
variant_b="",
ordered_keys=keys,
map_a={},
map_b={},
map_single=map_single,
dataset_name="typoattack",
)
# ============================================================
# Math helpers (PCA + subspace angles)
# ============================================================
def pca_evr_topk(X: np.ndarray, k: int = 8) -> List[float]:
"""
X: [N, D] (centered inside)
returns: top-k explained variance ratios
"""
Xc = X - X.mean(axis=0, keepdims=True)
# economy SVD
_, S, _ = np.linalg.svd(Xc, full_matrices=False)
var = (S ** 2)
evr = var / (var.sum() + 1e-12)
return evr[:k].tolist()
def principal_angles_deg(U: np.ndarray, V: np.ndarray, k: int = 8) -> List[float]:
"""
U: [D, k] orthonormal basis
V: [D, k] orthonormal basis
Returns k principal angles in degrees.
"""
M = U.T @ V
_, s, _ = np.linalg.svd(M, full_matrices=False)
s = np.clip(s, -1.0, 1.0)
ang = np.arccos(s)
return (ang * (180.0 / np.pi)).tolist()
def orthonormal_basis_from_samples(X: np.ndarray, k: int = 8) -> np.ndarray:
"""
X: [N, D], returns basis [D, k]
"""
Xc = X - X.mean(axis=0, keepdims=True)
_, _, Vt = np.linalg.svd(Xc, full_matrices=False)
B = Vt[:k].T # [D,k]
return B
def decompose_delta_into_subspace(
dZ: np.ndarray, # [N,D]
basis: np.ndarray, # [D,k] orthonormal
) -> Tuple[np.ndarray, np.ndarray]:
"""
Returns (dz_reg, dz_non) per-sample norms:
dz_reg = ||P_basis(dZ)||
dz_non = ||dZ - P_basis(dZ)||
"""
# projection: P = B B^T (since orthonormal)
proj = dZ @ basis @ basis.T # [N,D]
dz_reg = np.linalg.norm(proj, axis=1)
dz_non = np.linalg.norm(dZ - proj, axis=1)
return dz_reg, dz_non
# ============================================================
# Register mask helper
# ============================================================
def make_implicit_register_mask(
patch_token_norms: torch.Tensor, # [B, P]
register_threshold: float = 70.0,
max_registers: Optional[int] = 8,
min_registers: int = 1
) -> torch.Tensor:
"""
Returns bool mask [B, P] where True = register.
NOTE: this function stays "pure". The block-13 fallback is implemented in BlockCapture.
"""
B, P = patch_token_norms.shape
mask = patch_token_norms > register_threshold
if max_registers is not None:
out = torch.zeros_like(mask)
for b in range(B):
idx = torch.nonzero(mask[b], as_tuple=False).flatten()
if idx.numel() == 0:
topk = torch.topk(patch_token_norms[b], k=min_registers, largest=True).indices
out[b, topk] = True
else:
k = min(max_registers, idx.numel())
topk = idx[torch.topk(patch_token_norms[b, idx], k=k, largest=True).indices]
out[b, topk] = True
return out
out = mask.clone()
for b in range(B):
if out[b].sum().item() < min_registers:
topk = torch.topk(patch_token_norms[b], k=min_registers, largest=True).indices
out[b, topk] = True
return out
@torch.no_grad()
def tokens_to_final_embedding(visual: torch.nn.Module, x_lnd: torch.Tensor) -> torch.Tensor:
"""
x_lnd: [T,B,C] token stream after some block (or final block),
runs ln_post + proj on CLS token to produce image embedding (unnormalized).
"""
x_btn = x_lnd.permute(1, 0, 2) # [B,T,C]
cls_h = x_btn[:, 0, :] # [B,C] pre-ln_post
cls = visual.ln_post(cls_h) # [B,C]
if getattr(visual, "proj", None) is not None:
cls = cls @ visual.proj # [B,D]
return cls
# ============================================================
# EXP plumbing via forward hooks
# ============================================================
class BlockCapture:
"""
Captures per-block hidden reps + attention caches when capture_layers includes the block index.
Stores only what we need (mostly CPU) to avoid VRAM bloat.
# supports a "register reference mask" inferred from a ref block (default 13).
If a layer has *zero* tokens above threshold, we reuse the ref mask indices for that sample.
"""
def __init__(
self,
blocks: List[int],
rep_blocks: List[int],
survival_blocks: List[int],
register_threshold: float,
max_registers: int,
min_registers: int,
n_heads: int,
head_dim: int,
width: int,
keep_gpu_for_survival: bool = True,
):
self.blocks = set(blocks)
self.rep_blocks = set(rep_blocks)
self.survival_blocks = set(survival_blocks)
self.register_threshold = float(register_threshold)
self.max_registers = int(max_registers)
self.min_registers = int(min_registers)
self.n_heads = int(n_heads)
self.head_dim = int(head_dim)
self.width = int(width)
# per-batch captures (cleared each forward)
self.batch_cls_hidden: Dict[int, torch.Tensor] = {}
self.batch_patch_pool: Dict[int, torch.Tensor] = {}
self.batch_reg_pool: Dict[int, torch.Tensor] = {}
self.batch_reg_attn_mass: Dict[int, torch.Tensor] = {}
self.batch_reg_write_norm: Dict[int, torch.Tensor] = {}
self.keep_gpu_for_survival = bool(keep_gpu_for_survival)
self.batch_x_out_gpu: Dict[int, torch.Tensor] = {}
self.batch_write_vecs_gpu: Dict[int, torch.Tensor] = {}
self.suspend: bool = False # IMPORTANT
self.ref_reg_mask_device: Optional[torch.Tensor] = None # [B,P] bool on device for the *current batch*
def set_ref_reg_mask(self, mask_device: Optional[torch.Tensor]):
self.ref_reg_mask_device = mask_device
def clear_batch(self):
self.batch_cls_hidden.clear()
self.batch_patch_pool.clear()
self.batch_reg_pool.clear()
self.batch_reg_attn_mass.clear()
self.batch_reg_write_norm.clear()
if self.keep_gpu_for_survival:
self.batch_x_out_gpu.clear()
self.batch_write_vecs_gpu.clear()
self.ref_reg_mask_device = None
def hook_for_block(self, block_idx: int):
def _hook(module: torch.nn.Module, inputs: Tuple[torch.Tensor, ...], output: torch.Tensor):
if self.suspend:
return
if not isinstance(output, torch.Tensor) or output.dim() != 3:
return
x_lnd = output
T, B, C = x_lnd.shape
x_btn = x_lnd.permute(1, 0, 2) # [B,T,C]
cls_h = x_btn[:, 0, :] # [B,C]
patches = x_btn[:, 1:, :] # [B,P,C]
patch_norms = patches.norm(dim=-1) # [B,P]
reg_mask = make_implicit_register_mask(
patch_token_norms=patch_norms,
register_threshold=self.register_threshold,
max_registers=self.max_registers,
min_registers=self.min_registers
) # [B,P] bool
# block-13-based fallback when *none* above threshold.
if self.ref_reg_mask_device is not None:
# detect "none above threshold" (true none, not the min_registers fill)
none_above = (patch_norms > self.register_threshold).sum(dim=1) == 0 # [B]
if none_above.any():
ref = self.ref_reg_mask_device
if ref.shape == reg_mask.shape:
reg_mask = torch.where(none_above.unsqueeze(1), ref, reg_mask)
non_mask = ~reg_mask
non_cnt = non_mask.sum(dim=1).clamp_min(1).unsqueeze(-1)
reg_cnt = reg_mask.sum(dim=1).clamp_min(1).unsqueeze(-1)
patch_pool = (patches * non_mask.unsqueeze(-1)).sum(dim=1) / non_cnt
reg_pool = (patches * reg_mask.unsqueeze(-1)).sum(dim=1) / reg_cnt
if block_idx in self.rep_blocks:
self.batch_cls_hidden[block_idx] = cls_h.detach().float().cpu()
self.batch_patch_pool[block_idx] = patch_pool.detach().float().cpu()
self.batch_reg_pool[block_idx] = reg_pool.detach().float().cpu()
attn = getattr(module, "attn", None)
if attn is None:
return
probs = getattr(attn, "last_probs", None) # [B,H,T,S]
v = getattr(attn, "last_v", None) # [B,H,S,D]
if probs is None or v is None:
return
if probs.shape[0] != B or v.shape[0] != B:
return
P = reg_mask.shape[1]
S = 1 + P
src_reg = torch.zeros((B, S), dtype=torch.bool, device=probs.device)
src_reg[:, 1:] = reg_mask.to(device=probs.device)
probs_cls = probs[:, :, 0, :] # [B,H,S]
reg_mass = (probs_cls * src_reg.unsqueeze(1).float()).sum(dim=-1) # [B,H]
reg_mass_mean = reg_mass.mean(dim=0).detach().float().cpu() # [H]
v_reg = v * src_reg.unsqueeze(1).unsqueeze(-1).float() # [B,H,S,D]
head_out = (probs_cls.unsqueeze(-1) * v_reg).sum(dim=2) # [B,H,D]
out_proj = getattr(attn, "out_proj", None)
if out_proj is None:
return
W = out_proj.weight # [E,E]
writes = []
for h in range(self.n_heads):
w_slice = W[:, h * self.head_dim:(h + 1) * self.head_dim] # [E,D]
wh = head_out[:, h, :] @ w_slice.T # [B,E]
writes.append(wh)
write_vecs = torch.stack(writes, dim=1) # [B,H,E]
write_norm = write_vecs.norm(dim=-1).mean(dim=0).detach().float().cpu() # [H]
self.batch_reg_attn_mass[block_idx] = reg_mass_mean
self.batch_reg_write_norm[block_idx] = write_norm
if self.keep_gpu_for_survival and (block_idx in self.survival_blocks):
self.batch_x_out_gpu[block_idx] = x_lnd.detach()
self.batch_write_vecs_gpu[block_idx] = write_vecs.detach()
return _hook
# ============================================================
# Inter-model deltas ### NEW
# ============================================================
def _align_blocks_and_heads(
blocks_a: List[int], mat_a: np.ndarray,
blocks_b: List[int], mat_b: np.ndarray,
) -> Tuple[List[int], np.ndarray, np.ndarray]:
"""
Align by intersection of blocks; assumes same H.
Returns (blocks_common, a_common, b_common)
"""
set_a = set(blocks_a)
set_b = set(blocks_b)
common = sorted(set_a.intersection(set_b))
if not common:
return [], np.zeros((0, mat_a.shape[1]), dtype=np.float32), np.zeros((0, mat_b.shape[1]), dtype=np.float32)
ia = [blocks_a.index(b) for b in common]
ib = [blocks_b.index(b) for b in common]
return common, mat_a[ia], mat_b[ib]
def _top_abs_deltas(delta_mat: np.ndarray, blocks: List[int], k: int = 12) -> List[Tuple[int, int, float]]:
"""
Returns list of (block, head, delta) sorted by |delta| desc.
"""
if delta_mat.size == 0:
return []
flat = delta_mat.reshape(-1)
idx = np.argsort(np.abs(flat))[::-1][:k]
out = []
H = delta_mat.shape[1]
for j in idx:
bi = int(j // H)
hi = int(j % H)
out.append((int(blocks[bi]), hi, float(delta_mat[bi, hi])))
return out
def write_inter_delta_summary_txt(
out_path: str,
model_a: str,
model_b: str,
blocks_common: List[int],
d_attn: np.ndarray,
d_write: np.ndarray,
d_surv_blocks: List[int],
d_surv: Optional[np.ndarray],
d_delta_frac: np.ndarray,
):
lines = []
lines.append(f"Inter-model deltas: {model_a} - {model_b}")
lines.append(f"Blocks(attn/write): {blocks_common}")
if d_surv is not None:
lines.append(f"Blocks(survival): {d_surv_blocks}")
lines.append("")
lines.append("Most stark deltas by |value|:")
lines.append(" reg_attn_mass:")
for b, h, v in _top_abs_deltas(d_attn, blocks_common, k=10):
lines.append(f" b{b:02d} h{h:02d}: {v:+.6f}")
lines.append(" reg_write_norm:")
for b, h, v in _top_abs_deltas(d_write, blocks_common, k=10):
lines.append(f" b{b:02d} h{h:02d}: {v:+.6f}")
lines.append(" delta(attn_frac - write_frac):")
for b, h, v in _top_abs_deltas(d_delta_frac, blocks_common, k=10):
lines.append(f" b{b:02d} h{h:02d}: {v:+.6f}")
if d_surv is not None and len(d_surv_blocks) > 0:
lines.append(" reg_write_survival:")
for b, h, v in _top_abs_deltas(d_surv, d_surv_blocks, k=10):
lines.append(f" b{b:02d} h{h:02d}: {v:+.6f}")
with open(out_path, "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
def dump_inter_delta_csvs(
out_dir: str,
model_a: str,
model_b: str,
blocks_common: List[int],
d_attn: np.ndarray,
d_write: np.ndarray,
d_delta_frac: np.ndarray,
surv_blocks_common: List[int],
d_surv: Optional[np.ndarray],
):
ensure_dir(out_dir)
# head stats
p1 = os.path.join(out_dir, "inter_delta_head_stats_blocks.csv")
with open(p1, "w", encoding="utf-8") as f:
f.write("model_a,model_b,block,head,d_reg_attn_mass,d_reg_write_norm,d_delta_attn_minus_write_frac\n")
for i, b in enumerate(blocks_common):
for h in range(d_attn.shape[1]):
f.write(
f"{model_a},{model_b},{b},{h},"
f"{d_attn[i,h]:+.6f},{d_write[i,h]:+.6f},{d_delta_frac[i,h]:+.6f}\n"
)
# survival
if d_surv is not None and len(surv_blocks_common) > 0:
p2 = os.path.join(out_dir, "inter_delta_survival_blocks.csv")
with open(p2, "w", encoding="utf-8") as f:
f.write("model_a,model_b,block,head,d_reg_write_survival\n")
for i, b in enumerate(surv_blocks_common):
for h in range(d_surv.shape[1]):
f.write(f"{model_a},{model_b},{b},{h},{d_surv[i,h]:+.6f}\n")
def run_inter_model_deltas(
out_root: str,
results: Dict[str, Dict[str, Any]],
base_tag: str = "pretrained",
all_inter_deltas: bool = False,
):
"""
results[tag] must contain:
blocks_sorted, attn_mat, write_mat, surv_blocks_sorted, surv_mat (or None)
"""
if base_tag not in results:
print(Fore.YELLOW + f"[inter_deltas] base_tag '{base_tag}' not found; skipping." + Style.RESET_ALL)
return
inter_root = os.path.join(out_root, "_inter_deltas")
ensure_dir(inter_root)
tags = list(results.keys())
base = results[base_tag]
def do_pair(a: str, b: str):
ra = results[a]
rb = results[b]
blocks_common, a_attn, b_attn = _align_blocks_and_heads(ra["blocks_sorted"], ra["attn_mat"], rb["blocks_sorted"], rb["attn_mat"])
_, a_write, b_write = _align_blocks_and_heads(ra["blocks_sorted"], ra["write_mat"], rb["blocks_sorted"], rb["write_mat"])
if not blocks_common:
return
# delta matrices
d_attn = a_attn - b_attn
d_write = a_write - b_write
# delta of delta(frac): compute per-model frac then subtract
a_attn_frac = a_attn / (a_attn.sum(axis=1, keepdims=True) + 1e-12)
a_write_frac = a_write / (a_write.sum(axis=1, keepdims=True) + 1e-12)
b_attn_frac = b_attn / (b_attn.sum(axis=1, keepdims=True) + 1e-12)
b_write_frac = b_write / (b_write.sum(axis=1, keepdims=True) + 1e-12)
d_delta_frac = (a_attn_frac - a_write_frac) - (b_attn_frac - b_write_frac)
# survival align
d_surv = None
surv_blocks_common = []
if (ra.get("surv_mat") is not None) and (rb.get("surv_mat") is not None):
surv_blocks_common, a_surv, b_surv = _align_blocks_and_heads(
ra["surv_blocks_sorted"], ra["surv_mat"],
rb["surv_blocks_sorted"], rb["surv_mat"],
)
if surv_blocks_common:
d_surv = a_surv - b_surv
pair_dir = os.path.join(inter_root, f"{a}_minus_{b}")
plots_dir = os.path.join(pair_dir, "plots")
ensure_dir(pair_dir)
ensure_dir(plots_dir)
# CSV + summary
dump_inter_delta_csvs(
out_dir=pair_dir,
model_a=a,
model_b=b,
blocks_common=blocks_common,
d_attn=d_attn,
d_write=d_write,
d_delta_frac=d_delta_frac,
surv_blocks_common=surv_blocks_common,
d_surv=d_surv,
)
write_inter_delta_summary_txt(
out_path=os.path.join(pair_dir, "summary.txt"),
model_a=a,
model_b=b,
blocks_common=blocks_common,
d_attn=d_attn,
d_write=d_write,
d_surv_blocks=surv_blocks_common,
d_surv=d_surv,
d_delta_frac=d_delta_frac,
)
# plots (reuse your existing helpers)
plot_line_over_blocks(
blocks_common, d_attn,
out_path=os.path.join(plots_dir, f"{a}_minus_{b}__reg_attn_mass_delta_line.png"),
title=f"{a} - {b}: Δ reg_attn_mass over blocks (per head)",
ylabel="Δ reg_attn_mass",
legend=True,
)
plot_line_over_blocks(
blocks_common, d_write,
out_path=os.path.join(plots_dir, f"{a}_minus_{b}__reg_write_norm_delta_line.png"),
title=f"{a} - {b}: Δ reg_write_norm over blocks (per head)",
ylabel="Δ reg_write_norm",
legend=True,
)
plot_line_over_blocks(
blocks_common, d_delta_frac,
out_path=os.path.join(plots_dir, f"{a}_minus_{b}__delta_attn_minus_write_frac_delta_line.png"),
title=f"{a} - {b}: Δ[attn_frac - write_frac] over blocks (per head)",
ylabel="Δ(attn_frac - write_frac)",
legend=True,
)
plot_heatmap(
blocks_common, d_attn,
out_path=os.path.join(plots_dir, f"{a}_minus_{b}__reg_attn_mass_delta_heatmap.png"),
title=f"{a} - {b}: Δ reg_attn_mass heatmap (heads x blocks)",
)
plot_heatmap(
blocks_common, d_write,
out_path=os.path.join(plots_dir, f"{a}_minus_{b}__reg_write_norm_delta_heatmap.png"),
title=f"{a} - {b}: Δ reg_write_norm heatmap (heads x blocks)",
)
plot_heatmap(
blocks_common, d_delta_frac,
out_path=os.path.join(plots_dir, f"{a}_minus_{b}__delta_attn_minus_write_frac_delta_heatmap.png"),
title=f"{a} - {b}: Δ[attn_frac - write_frac] heatmap (heads x blocks)",
)
if d_surv is not None and len(surv_blocks_common) > 0:
plot_line_over_blocks(
surv_blocks_common, d_surv,
out_path=os.path.join(plots_dir, f"{a}_minus_{b}__reg_write_survival_delta_line.png"),
title=f"{a} - {b}: Δ reg_write_survival over blocks (per head)",
ylabel="Δ reg_write_survival",
legend=True,
)
plot_heatmap(
surv_blocks_common, d_surv,
out_path=os.path.join(plots_dir, f"{a}_minus_{b}__reg_write_survival_delta_heatmap.png"),
title=f"{a} - {b}: Δ reg_write_survival heatmap (heads x blocks)",
)
print(Fore.CYAN + f"[inter_deltas] wrote: {pair_dir}" + Style.RESET_ALL)
# (A) everyone vs base
for tag in tags:
if tag == base_tag:
continue
do_pair(tag, base_tag)
# (B) optionally compare all non-base models to each other
if all_inter_deltas:
non_base = [t for t in tags if t != base_tag]
for i in range(len(non_base)):
for j in range(i + 1, len(non_base)):
do_pair(non_base[i], non_base[j])
# ============================================================
# EXP1: hidden-space metrics
# ============================================================
def compute_exp1_hidden_metrics(
reps_noscam: Dict[str, Dict[str, np.ndarray]],
reps_synth: Dict[str, Dict[str, np.ndarray]],
rep_blocks: List[int],
k: int = 8
) -> Dict[str, Any]:
"""
reps_*: pair_key -> {"cls_b22":..., "patch_b22":..., "reg_b22":..., ...}
Returns:
metrics dict with PCA EVR and principal angles for each rep choice.
"""
keys = sorted(set(reps_noscam.keys()).intersection(set(reps_synth.keys())))
if len(keys) < 32:
raise RuntimeError(f"Too few paired samples for EXP1: {len(keys)}")
out: Dict[str, Any] = {}
# We compute for b22/b23 only (or whatever is in rep_blocks).
# We also compute patch_delta_b23m22 if both present.
def has(block: int, name: str) -> bool:
k0 = keys[0]
return f"{name}_b{block}" in reps_noscam[k0]
# build patch_delta if possible
if (22 in rep_blocks) and (23 in rep_blocks) and has(22, "patch") and has(23, "patch"):
for d in (reps_noscam, reps_synth):
for kk in keys:
d[kk]["patch_delta_b23m22"] = d[kk]["patch_b23"] - d[kk]["patch_b22"]
rep_specs: List[Tuple[str, str]] = []
for b in rep_blocks:
rep_specs.extend([
(f"cls_b{b}", f"reg_b{b}"),
(f"patch_b{b}", f"reg_b{b}"),
])
if "patch_delta_b23m22" in reps_noscam[keys[0]]:
rep_specs.append(("patch_delta_b23m22", "reg_b23"))
for rep_name, reg_name in rep_specs:
dZ = np.stack([reps_synth[kk][rep_name] - reps_noscam[kk][rep_name] for kk in keys], axis=0) # [N,D]
R = np.stack([reps_noscam[kk][reg_name] for kk in keys], axis=0) # [N,D]
evr = pca_evr_topk(dZ, k=k)
U = orthonormal_basis_from_samples(dZ, k=k)
V = orthonormal_basis_from_samples(R, k=k)
ang = principal_angles_deg(U, V, k=k)
out[rep_name] = dict(
n_pairs=len(keys),
pca_evr_topk=evr,
principal_angles_deg=ang,
)
return out
# ============================================================
# EXP2 survival-aware: inject per-head write vectors at block output, run remaining blocks once
# ============================================================
@torch.no_grad()
def compute_survival_scores_for_block(
visual: torch.nn.Module,
transformer: torch.nn.Module,
block_idx: int,
x_out_lnd: torch.Tensor, # [T,B,C] after block block_idx
write_vecs: torch.Tensor, # [B,H,C] write vectors in width space
) -> torch.Tensor:
"""
Returns survival score per head: mean ||delta(final_embedding)|| over batch. Shape [H].
Vectorized across heads: remainder forward sees batch size B*H.
"""
T, B, C = x_out_lnd.shape
H = write_vecs.shape[1]
# baseline remainder
x_rem = x_out_lnd
for j in range(block_idx + 1, transformer.layers):
x_rem = transformer.resblocks[j](x_rem)
emb_base = tokens_to_final_embedding(visual, x_rem) # [B,D]
# expanded stream for all heads
x_rep = x_out_lnd.repeat_interleave(H, dim=1) # [T, B*H, C]
add = write_vecs.reshape(B * H, C) # [B*H,C]
x_rep = x_rep.clone()
x_rep[0, :, :] = x_rep[0, :, :] + add # inject into CLS token