AbstractPhil commited on
Commit
797187d
Β·
verified Β·
1 Parent(s): 28359d7

Create analyze_soup.py

Browse files
Files changed (1) hide show
  1. analyze_soup.py +498 -0
analyze_soup.py ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ BASE TIER SOUP ANALYSIS
4
+ ========================
5
+ Load the trained 800K param soup and examine:
6
+ - Anchor geometry on the 128-d hypersphere
7
+ - Projector alignment (do the 3 experts converge?)
8
+ - Triangulation patterns (which anchors are used?)
9
+ - Patchwork compartment activation profiles
10
+ - Per-expert projected distributions
11
+ - CV and volume geometry of the learned space
12
+ - Per-class anchor affinity (which anchors serve which COCO classes?)
13
+ """
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ import numpy as np
19
+ import math
20
+ import os
21
+ import gc
22
+
23
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
24
+
25
+ D_EXPERT = 768
26
+ D_ANCHOR = 128
27
+ N_ANCHORS = 256
28
+ N_CLASSES = 80
29
+ N_COMP = 8
30
+ D_COMP = 64
31
+ EXPERTS = ["clip_l14_openai", "dinov2_b14", "siglip_b16_384"]
32
+
33
+ print("=" * 65)
34
+ print("BASE TIER SOUP ANALYSIS")
35
+ print(f" Device: {DEVICE}")
36
+ print("=" * 65)
37
+
38
+
39
+ # ══════════════════════════════════════════════════════════════════
40
+ # LOAD MODEL + DATA
41
+ # ══════════════════════════════════════════════════════════════════
42
+
43
+ # Rebuild model class (minimal, for loading)
44
+ class ExpertProjector(nn.Module):
45
+ def __init__(self, d_in=D_EXPERT, d_out=D_ANCHOR):
46
+ super().__init__()
47
+ self.proj = nn.Sequential(nn.Linear(d_in, d_out), nn.LayerNorm(d_out))
48
+ def forward(self, x):
49
+ return F.normalize(self.proj(x), dim=-1)
50
+
51
+ class Constellation(nn.Module):
52
+ def __init__(self, n_anchors=N_ANCHORS, d=D_ANCHOR):
53
+ super().__init__()
54
+ self.n_anchors = n_anchors
55
+ self.anchors = nn.Parameter(F.normalize(torch.randn(n_anchors, d), dim=-1))
56
+ def triangulate(self, emb):
57
+ a = F.normalize(self.anchors, dim=-1)
58
+ cos = emb @ a.T
59
+ return 1.0 - cos, cos.argmax(dim=-1)
60
+
61
+ class Patchwork(nn.Module):
62
+ def __init__(self, n_anchors=N_ANCHORS, n_comp=N_COMP, d_comp=D_COMP):
63
+ super().__init__()
64
+ self.n_comp = n_comp
65
+ asgn = torch.arange(n_anchors) % n_comp
66
+ self.register_buffer("asgn", asgn)
67
+ self.comps = nn.ModuleList([nn.Sequential(
68
+ nn.Linear((asgn == k).sum().item(), d_comp * 2), nn.GELU(),
69
+ nn.Linear(d_comp * 2, d_comp), nn.LayerNorm(d_comp))
70
+ for k in range(n_comp)])
71
+ def forward(self, tri):
72
+ return torch.cat([self.comps[k](tri[:, self.asgn == k])
73
+ for k in range(self.n_comp)], -1)
74
+
75
+ class BaseTierSoup(nn.Module):
76
+ def __init__(self):
77
+ super().__init__()
78
+ self.n_experts = 3
79
+ self.projectors = nn.ModuleList([ExpertProjector() for _ in range(3)])
80
+ self.constellation = Constellation()
81
+ self.patchwork = Patchwork()
82
+ pw_dim = N_COMP * D_COMP
83
+ self.classifier = nn.Sequential(
84
+ nn.Linear(pw_dim + D_ANCHOR, pw_dim), nn.GELU(),
85
+ nn.LayerNorm(pw_dim), nn.Dropout(0.1),
86
+ nn.Linear(pw_dim, N_CLASSES))
87
+ def forward(self, expert_embeddings, apply_autograd=False):
88
+ projected = [self.projectors[i](expert_embeddings[i]) for i in range(3)]
89
+ fused = F.normalize(sum(projected) / 3, dim=-1)
90
+ tri, nearest = self.constellation.triangulate(fused)
91
+ pw = self.patchwork(tri)
92
+ logits = self.classifier(torch.cat([pw, fused], -1))
93
+ return logits, fused, tri, nearest, projected
94
+
95
+ print(f"\n Loading checkpoint...")
96
+ ckpt = torch.load("checkpoints/base_tier_best.pt", map_location="cpu", weights_only=False)
97
+ model = BaseTierSoup()
98
+ model.load_state_dict(ckpt["state_dict"])
99
+ model = model.eval().to(DEVICE)
100
+ print(f" Loaded: mAP={ckpt['mAP']:.3f} cv={ckpt['cv']:.4f} epoch={ckpt['epoch']}")
101
+
102
+ # Load val data
103
+ from datasets import load_dataset
104
+ ref = load_dataset("AbstractPhil/bulk-coco-features", EXPERTS[0], split="val")
105
+ val_ids = ref["image_id"]; N_val = len(val_ids)
106
+ id_map = {iid: i for i, iid in enumerate(val_ids)}
107
+ val_labels = torch.zeros(N_val, N_CLASSES)
108
+ for i, labs in enumerate(ref["labels"]):
109
+ for l in labs:
110
+ if l < N_CLASSES: val_labels[i, l] = 1.0
111
+
112
+ val_feats = []
113
+ for name in EXPERTS:
114
+ ds = load_dataset("AbstractPhil/bulk-coco-features", name, split="val")
115
+ feats = torch.zeros(N_val, D_EXPERT)
116
+ for row in ds:
117
+ if row["image_id"] in id_map:
118
+ feats[id_map[row["image_id"]]] = torch.tensor(row["features"], dtype=torch.float32)
119
+ val_feats.append(feats.to(DEVICE))
120
+ print(f" {name} loaded")
121
+ del ds; gc.collect()
122
+
123
+ # Run full val through model
124
+ print(f"\n Running inference on {N_val} val images...")
125
+ all_logits, all_fused, all_tri, all_nearest, all_proj = [], [], [], [], [[], [], []]
126
+ BATCH = 256
127
+ with torch.no_grad():
128
+ for j in range(0, N_val, BATCH):
129
+ end = min(j + BATCH, N_val)
130
+ batch = [val_feats[e][j:end] for e in range(3)]
131
+ lo, fu, tr, ne, pr = model(batch)
132
+ all_logits.append(lo.cpu())
133
+ all_fused.append(fu.cpu())
134
+ all_tri.append(tr.cpu())
135
+ all_nearest.append(ne.cpu())
136
+ for e in range(3):
137
+ all_proj[e].append(pr[e].cpu())
138
+
139
+ logits = torch.cat(all_logits)
140
+ fused = torch.cat(all_fused)
141
+ tri = torch.cat(all_tri)
142
+ nearest = torch.cat(all_nearest)
143
+ proj = [torch.cat(all_proj[e]) for e in range(3)]
144
+ print(f" Done: fused={fused.shape} tri={tri.shape}")
145
+
146
+
147
+ # ══════════════════════════════════════════════════════════════════
148
+ # SCAN 1: ANCHOR GEOMETRY
149
+ # ══════════════════════════════════════════════════════════════════
150
+
151
+ print(f"\n{'='*65}")
152
+ print("SCAN 1: ANCHOR GEOMETRY")
153
+ print(f"{'='*65}")
154
+
155
+ anchors = F.normalize(model.constellation.anchors.detach().cpu(), dim=-1)
156
+
157
+ # Pairwise cosine
158
+ anchor_sim = anchors @ anchors.T
159
+ anchor_sim.fill_diagonal_(0)
160
+
161
+ print(f" Anchor pairwise cosine:")
162
+ print(f" mean={anchor_sim.mean():.4f} std={anchor_sim.std():.4f}")
163
+ print(f" max={anchor_sim.max():.4f} min={anchor_sim.min():.4f}")
164
+
165
+ # Distribution of max-neighbor cosine
166
+ max_neighbor = anchor_sim.max(dim=1).values
167
+ print(f" Max neighbor cosine per anchor:")
168
+ print(f" mean={max_neighbor.mean():.4f} std={max_neighbor.std():.4f}")
169
+ print(f" max={max_neighbor.max():.4f} min={max_neighbor.min():.4f}")
170
+
171
+ # Anchor norms (should be ~1.0 after normalize)
172
+ anchor_norms = anchors.norm(dim=-1)
173
+ print(f" Anchor norms: mean={anchor_norms.mean():.6f} std={anchor_norms.std():.6f}")
174
+
175
+ # SVD of anchor matrix
176
+ sv = torch.linalg.svdvals(anchors)
177
+ eff_rank = ((sv.sum()**2) / (sv.pow(2).sum() + 1e-12)).item()
178
+ print(f" Anchor spectral: eff_rank={eff_rank:.1f}/{min(anchors.shape)}")
179
+ print(f" sv_max={sv[0]:.4f} sv_10={sv[9]:.4f} sv_50={sv[49]:.4f} sv_min={sv[-1]:.6f}")
180
+
181
+ # Volume CV of anchors
182
+ def cayley_menger_vol2(pts):
183
+ pts = pts.float()
184
+ diff = pts.unsqueeze(-2) - pts.unsqueeze(-3)
185
+ d2 = (diff * diff).sum(-1)
186
+ B, V, _ = d2.shape
187
+ cm = torch.zeros(B, V+1, V+1, device=d2.device, dtype=torch.float32)
188
+ cm[:, 0, 1:] = 1; cm[:, 1:, 0] = 1; cm[:, 1:, 1:] = d2
189
+ s = (-1.0)**V; f = math.factorial(V-1)
190
+ return s / ((2.0**(V-1)) * f*f) * torch.linalg.det(cm)
191
+
192
+ vols = []
193
+ for _ in range(500):
194
+ idx = torch.randperm(N_ANCHORS)[:5]
195
+ v2 = cayley_menger_vol2(anchors[idx].unsqueeze(0))
196
+ v = torch.sqrt(F.relu(v2[0]) + 1e-12).item()
197
+ if v > 0: vols.append(v)
198
+ anchor_cv = np.std(vols) / (np.mean(vols) + 1e-8)
199
+ print(f" Anchor pentachoron CV: {anchor_cv:.4f}")
200
+ print(f" mean_vol={np.mean(vols):.6f} std_vol={np.std(vols):.6f}")
201
+
202
+
203
+ # ══════════════════════════════════════════════════════════════════
204
+ # SCAN 2: ANCHOR UTILIZATION
205
+ # ══════════════════════════════════════════════════════════════════
206
+
207
+ print(f"\n{'='*65}")
208
+ print("SCAN 2: ANCHOR UTILIZATION")
209
+ print(f"{'='*65}")
210
+
211
+ # How many images use each anchor as nearest
212
+ anchor_counts = torch.bincount(nearest, minlength=N_ANCHORS).float()
213
+ active = (anchor_counts > 0).sum().item()
214
+ print(f" Active anchors: {active}/{N_ANCHORS} ({active/N_ANCHORS*100:.1f}%)")
215
+ print(f" Visit counts: mean={anchor_counts.mean():.1f} std={anchor_counts.std():.1f}")
216
+ print(f" max={anchor_counts.max():.0f} min={anchor_counts.min():.0f}")
217
+ print(f" top 10: {anchor_counts.topk(10).values.long().tolist()}")
218
+ print(f" bottom 10: {anchor_counts.sort().values[:10].long().tolist()}")
219
+
220
+ # Entropy of anchor distribution
221
+ probs = anchor_counts / anchor_counts.sum()
222
+ entropy = -(probs[probs > 0] * probs[probs > 0].log()).sum().item()
223
+ max_entropy = math.log(N_ANCHORS)
224
+ print(f" Anchor entropy: {entropy:.4f} / {max_entropy:.4f} ({entropy/max_entropy*100:.1f}%)")
225
+
226
+ # Per-anchor mean cosine to fused embeddings
227
+ print(f"\n Per-anchor embedding density:")
228
+ anchor_mean_cos = []
229
+ for a_idx in range(N_ANCHORS):
230
+ mask = nearest == a_idx
231
+ if mask.sum() < 2:
232
+ anchor_mean_cos.append(0.0)
233
+ continue
234
+ cluster_embs = fused[mask]
235
+ mean_cos = F.cosine_similarity(
236
+ cluster_embs.unsqueeze(0), cluster_embs.unsqueeze(1), dim=-1)
237
+ mean_cos.fill_diagonal_(0)
238
+ n = cluster_embs.shape[0]
239
+ avg = mean_cos.sum().item() / max(n * (n-1), 1)
240
+ anchor_mean_cos.append(avg)
241
+ amc = np.array(anchor_mean_cos)
242
+ print(f" Intra-cluster cosine: mean={amc[amc>0].mean():.4f} std={amc[amc>0].std():.4f}")
243
+
244
+
245
+ # ═══════════════════════════════════════════════════════════���══════
246
+ # SCAN 3: PROJECTOR ANALYSIS
247
+ # ══════════════════════════════════════════════════════════════════
248
+
249
+ print(f"\n{'='*65}")
250
+ print("SCAN 3: PROJECTOR ANALYSIS")
251
+ print(f"{'='*65}")
252
+
253
+ expert_names = ["clip_l14", "dinov2_b14", "siglip_b16"]
254
+
255
+ # Per-expert projection stats
256
+ for e, name in enumerate(expert_names):
257
+ p = proj[e]
258
+ print(f"\n {name}:")
259
+ print(f" norm: mean={p.norm(dim=-1).mean():.6f} (should be 1.0)")
260
+ print(f" self-sim off-diag: {(F.normalize(p,dim=-1) @ F.normalize(p,dim=-1).T).fill_diagonal_(0).mean():.4f}")
261
+
262
+ # SVD of projected embeddings
263
+ pc = p.float() - p.float().mean(0, keepdim=True)
264
+ sv = torch.linalg.svdvals(pc)
265
+ eff_dim = ((sv.sum()**2) / (sv.pow(2).sum() + 1e-12)).item()
266
+ print(f" eff_dim: {eff_dim:.1f}/{D_ANCHOR}")
267
+
268
+ # Pairwise agreement
269
+ print(f"\n Expert agreement (cosine in 128-d):")
270
+ for i in range(3):
271
+ for j in range(i+1, 3):
272
+ cos = F.cosine_similarity(proj[i], proj[j], dim=-1)
273
+ print(f" {expert_names[i]:<15} Γ— {expert_names[j]:<15}: "
274
+ f"mean={cos.mean():.4f} std={cos.std():.4f} min={cos.min():.4f}")
275
+
276
+ # How different are the nearest anchors per expert?
277
+ print(f"\n Per-expert nearest anchor agreement:")
278
+ expert_nearest = []
279
+ for e in range(3):
280
+ a = F.normalize(anchors, dim=-1)
281
+ cos = proj[e] @ a.T
282
+ en = cos.argmax(dim=-1)
283
+ expert_nearest.append(en)
284
+ for i in range(3):
285
+ for j in range(i+1, 3):
286
+ agree = (expert_nearest[i] == expert_nearest[j]).float().mean().item()
287
+ print(f" {expert_names[i]:<15} Γ— {expert_names[j]:<15}: "
288
+ f"same_anchor={agree:.4f} ({agree*100:.1f}%)")
289
+
290
+ # Projector weight analysis
291
+ print(f"\n Projector weight comparison:")
292
+ proj_weights = []
293
+ for e in range(3):
294
+ w = model.projectors[e].proj[0].weight.detach().float() # (128, 768)
295
+ proj_weights.append(w)
296
+ sv = torch.linalg.svdvals(w)
297
+ eff_r = ((sv.sum()**2) / (sv.pow(2).sum() + 1e-12)).item()
298
+ print(f" {expert_names[e]:<15}: norm={w.norm():.4f} eff_rank={eff_r:.1f}/{min(w.shape)}")
299
+
300
+ # Cross-projector cosine
301
+ for i in range(3):
302
+ for j in range(i+1, 3):
303
+ cos = F.cosine_similarity(
304
+ proj_weights[i].reshape(-1).unsqueeze(0),
305
+ proj_weights[j].reshape(-1).unsqueeze(0)).item()
306
+ print(f" {expert_names[i]:<15} Γ— {expert_names[j]:<15} weight_cos={cos:.4f}")
307
+
308
+
309
+ # ══════════════════════════════════════════════════════════════════
310
+ # SCAN 4: PATCHWORK COMPARTMENT ANALYSIS
311
+ # ══════════════════════════════════════════════════════════════════
312
+
313
+ print(f"\n{'='*65}")
314
+ print("SCAN 4: PATCHWORK COMPARTMENTS")
315
+ print(f"{'='*65}")
316
+
317
+ # Which anchors are in which compartment
318
+ asgn = model.patchwork.asgn.cpu()
319
+ for k in range(N_COMP):
320
+ anchor_ids = (asgn == k).nonzero(as_tuple=True)[0]
321
+ print(f" Comp {k}: {len(anchor_ids)} anchors")
322
+
323
+ # Patchwork output analysis
324
+ with torch.no_grad():
325
+ pw_all = []
326
+ for j in range(0, N_val, BATCH):
327
+ end = min(j + BATCH, N_val)
328
+ pw = model.patchwork(tri[j:end].to(DEVICE))
329
+ pw_all.append(pw.cpu())
330
+ pw_cat = torch.cat(pw_all)
331
+
332
+ print(f"\n Patchwork output: {pw_cat.shape}")
333
+ print(f" norm: mean={pw_cat.norm(dim=-1).mean():.4f} std={pw_cat.norm(dim=-1).std():.4f}")
334
+
335
+ # Per-compartment output magnitude
336
+ for k in range(N_COMP):
337
+ comp_out = pw_cat[:, k*D_COMP:(k+1)*D_COMP]
338
+ print(f" comp {k}: norm={comp_out.norm(dim=-1).mean():.4f} "
339
+ f"std_across_dims={comp_out.std(dim=0).mean():.4f}")
340
+
341
+
342
+ # ══════════════════════════════════════════════════════════════════
343
+ # SCAN 5: TRIANGULATION PATTERN ANALYSIS
344
+ # ══════════════════════════════════════════════════════════════════
345
+
346
+ print(f"\n{'='*65}")
347
+ print("SCAN 5: TRIANGULATION PATTERNS")
348
+ print(f"{'='*65}")
349
+
350
+ # Triangulation distance stats
351
+ print(f" Triangulation distances (1-cosine):")
352
+ print(f" mean={tri.mean():.4f} std={tri.std():.4f}")
353
+ print(f" min={tri.min():.4f} max={tri.max():.4f}")
354
+
355
+ # Nearest anchor distance
356
+ nearest_dist = tri.gather(1, nearest.unsqueeze(1)).squeeze(1)
357
+ print(f" Nearest anchor distance:")
358
+ print(f" mean={nearest_dist.mean():.4f} std={nearest_dist.std():.4f}")
359
+ print(f" max={nearest_dist.max():.4f} min={nearest_dist.min():.4f}")
360
+
361
+ # How many anchors are "close" (cosine > 0.5, i.e. dist < 0.5)
362
+ close_count = (tri < 0.5).float().sum(dim=1)
363
+ print(f" Anchors within cos>0.5 per image:")
364
+ print(f" mean={close_count.mean():.1f} std={close_count.std():.1f}")
365
+
366
+ # Top-k nearest anchors β€” how spread are they?
367
+ topk_dists = tri.topk(10, dim=1, largest=False)
368
+ print(f" Top-10 nearest anchor distances:")
369
+ for k_idx in range(10):
370
+ d = topk_dists.values[:, k_idx]
371
+ print(f" k={k_idx}: mean={d.mean():.4f} std={d.std():.4f}")
372
+
373
+
374
+ # ══════════════════════════════════════════════════════════════════
375
+ # SCAN 6: PER-CLASS ANCHOR AFFINITY
376
+ # ══════════════════════════════════════════════════════════════════
377
+
378
+ print(f"\n{'='*65}")
379
+ print("SCAN 6: PER-CLASS ANCHOR AFFINITY")
380
+ print(f"{'='*65}")
381
+
382
+ # COCO class names (subset)
383
+ coco_names = ["person", "bicycle", "car", "motorcycle", "airplane",
384
+ "bus", "train", "truck", "boat", "traffic light",
385
+ "fire hydrant", "stop sign", "parking meter", "bench", "bird",
386
+ "cat", "dog", "horse", "sheep", "cow"]
387
+
388
+ # For each class, which anchors are most associated?
389
+ print(f"\n Top-3 anchors per class (first 20 classes):")
390
+ for c in range(min(20, N_CLASSES)):
391
+ mask = val_labels[:, c] > 0
392
+ if mask.sum() < 5: continue
393
+ class_nearest = nearest[mask]
394
+ counts = torch.bincount(class_nearest, minlength=N_ANCHORS)
395
+ top3 = counts.topk(3)
396
+ name = coco_names[c] if c < len(coco_names) else f"class_{c}"
397
+ total = mask.sum().item()
398
+ pcts = [f"{top3.indices[k]}({top3.values[k].item()}/{total})" for k in range(3)]
399
+ print(f" {name:<15} (n={total:4d}): {' '.join(pcts)}")
400
+
401
+ # Anchor specialization: how many classes does each anchor serve?
402
+ anchor_class_count = torch.zeros(N_ANCHORS)
403
+ for a in range(N_ANCHORS):
404
+ mask = nearest == a
405
+ if mask.sum() < 1: continue
406
+ class_present = val_labels[mask].sum(0) > 0
407
+ anchor_class_count[a] = class_present.sum().item()
408
+ print(f"\n Anchor specialization:")
409
+ print(f" classes per anchor: mean={anchor_class_count[anchor_class_count>0].mean():.1f} "
410
+ f"std={anchor_class_count[anchor_class_count>0].std():.1f}")
411
+ print(f" max={anchor_class_count.max():.0f} min={anchor_class_count[anchor_class_count>0].min():.0f}")
412
+
413
+
414
+ # ══════════════════════════════════════════════════════════════════
415
+ # SCAN 7: FUSED EMBEDDING GEOMETRY
416
+ # ══════════════════════════════════════════════════════════════════
417
+
418
+ print(f"\n{'='*65}")
419
+ print("SCAN 7: FUSED EMBEDDING GEOMETRY")
420
+ print(f"{'='*65}")
421
+
422
+ # Norms (should be 1.0)
423
+ fused_norms = fused.norm(dim=-1)
424
+ print(f" Norms: mean={fused_norms.mean():.6f} std={fused_norms.std():.6f}")
425
+
426
+ # Self-similarity
427
+ fused_n = F.normalize(fused, dim=-1)
428
+ self_sim = fused_n @ fused_n.T
429
+ self_sim_off = (self_sim.sum() - self_sim.diag().sum()) / (N_val**2 - N_val)
430
+ print(f" Self-sim (off-diag): {self_sim_off:.4f}")
431
+
432
+ # SVD
433
+ fc = fused.float() - fused.float().mean(0, keepdim=True)
434
+ sv = torch.linalg.svdvals(fc)
435
+ eff_dim = ((sv.sum()**2) / (sv.pow(2).sum() + 1e-12)).item()
436
+ print(f" Effective dim: {eff_dim:.1f}/{D_ANCHOR}")
437
+ cumvar = sv.pow(2).cumsum(0) / sv.pow(2).sum()
438
+ for k in [5, 10, 20, 50, 100]:
439
+ if k-1 < len(cumvar):
440
+ print(f" top-{k} SVs explain {cumvar[k-1]*100:.1f}%")
441
+
442
+ # CV
443
+ vols = []
444
+ for _ in range(500):
445
+ idx = torch.randperm(N_val)[:5]
446
+ v2 = cayley_menger_vol2(fused_n[idx].unsqueeze(0))
447
+ v = torch.sqrt(F.relu(v2[0]) + 1e-12).item()
448
+ if v > 0: vols.append(v)
449
+ fused_cv = np.std(vols) / (np.mean(vols) + 1e-8)
450
+ print(f" Pentachoron CV: {fused_cv:.4f}")
451
+
452
+
453
+ # ══════════════════════════════════════════════════════════════════
454
+ # SCAN 8: EXPERT CONTRIBUTION ANALYSIS
455
+ # ══════════════════════════════════════════════════════════════════
456
+
457
+ print(f"\n{'='*65}")
458
+ print("SCAN 8: EXPERT CONTRIBUTION")
459
+ print(f"{'='*65}")
460
+
461
+ # How much does each expert contribute to the fused embedding?
462
+ # cos(expert_proj, fused) tells us alignment
463
+ for e, name in enumerate(expert_names):
464
+ cos = F.cosine_similarity(proj[e], fused, dim=-1)
465
+ print(f" {name:<15}: cos_to_fused mean={cos.mean():.4f} std={cos.std():.4f}")
466
+
467
+ # Residual after removing each expert
468
+ for e, name in enumerate(expert_names):
469
+ others = [proj[i] for i in range(3) if i != e]
470
+ fused_without = F.normalize(sum(others) / 2, dim=-1)
471
+ delta = F.cosine_similarity(fused, fused_without, dim=-1)
472
+ print(f" Without {name:<15}: cos_to_full={delta.mean():.4f} (uniqueness={1-delta.mean():.4f})")
473
+
474
+ # Per-image expert disagreement
475
+ print(f"\n Per-image expert disagreement:")
476
+ all_cos = []
477
+ for i in range(3):
478
+ for j in range(i+1, 3):
479
+ cos = F.cosine_similarity(proj[i], proj[j], dim=-1)
480
+ all_cos.append(cos)
481
+ stacked = torch.stack(all_cos, dim=1) # (N, 3)
482
+ per_image_agree = stacked.mean(dim=1)
483
+ per_image_disagree = stacked.std(dim=1)
484
+ print(f" Agreement: mean={per_image_agree.mean():.4f} std={per_image_agree.std():.4f}")
485
+ print(f" Disagreement: mean={per_image_disagree.mean():.4f} std={per_image_disagree.std():.4f}")
486
+
487
+ # Most agreed and disagreed images
488
+ most_agree_idx = per_image_agree.argmax().item()
489
+ most_disagree_idx = per_image_agree.argmin().item()
490
+ print(f"\n Most agreed image ({most_agree_idx}): agreement={per_image_agree[most_agree_idx]:.4f}")
491
+ print(f" labels: {val_labels[most_agree_idx].nonzero(as_tuple=True)[0].tolist()}")
492
+ print(f" Most disagreed image ({most_disagree_idx}): agreement={per_image_agree[most_disagree_idx]:.4f}")
493
+ print(f" labels: {val_labels[most_disagree_idx].nonzero(as_tuple=True)[0].tolist()}")
494
+
495
+
496
+ print(f"\n{'='*65}")
497
+ print("ANALYSIS COMPLETE")
498
+ print(f"{'='*65}")