AbstractPhil commited on
Commit
2f11039
Β·
verified Β·
1 Parent(s): 34c064c

Create universal_diagnostic.py

Browse files
Files changed (1) hide show
  1. universal_diagnostic.py +693 -0
universal_diagnostic.py ADDED
@@ -0,0 +1,693 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Universal SVAE Diagnostic Battery
3
+ ===================================
4
+ One script. Any checkpoint. Every dataset.
5
+
6
+ Usage:
7
+ python universal_diagnostic.py # local best.pt
8
+ python universal_diagnostic.py --hf v13_imagenet256 # HF version
9
+ python universal_diagnostic.py --checkpoint /path/to.pt # explicit path
10
+
11
+ Tests across:
12
+ - CIFAR-10 (32Γ—32, resized to model native)
13
+ - MNIST (28×28, resized, grayscale→RGB)
14
+ - TinyImageNet (64Γ—64)
15
+ - ImageNet-128 (128Γ—128)
16
+ - ImageNet-256 (256Γ—256)
17
+ - 16 noise types (native resolution)
18
+ - Text bytes (5 sentences)
19
+ - Piecemeal tiling (4Γ— resolution)
20
+ - Geometric fingerprint per dataset
21
+ - Spectrum analysis
22
+ - Alpha profile
23
+ - Compression metrics
24
+ """
25
+
26
+ import os, sys, json, math, time
27
+ import numpy as np
28
+ import torch
29
+ import torch.nn as nn
30
+ import torch.nn.functional as F
31
+ import torchvision
32
+ import torchvision.transforms as T
33
+ from collections import defaultdict
34
+
35
+ DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
36
+
37
+ # ── Model ────────────────────────────────────────────────────────
38
+
39
+ class BoundarySmooth(nn.Module):
40
+ def __init__(self, channels=3, mid=16):
41
+ super().__init__()
42
+ self.net = nn.Sequential(nn.Conv2d(channels, mid, 3, padding=1), nn.GELU(),
43
+ nn.Conv2d(mid, channels, 3, padding=1))
44
+ nn.init.zeros_(self.net[-1].weight); nn.init.zeros_(self.net[-1].bias)
45
+ def forward(self, x): return x + self.net(x)
46
+
47
+ class SpectralCrossAttention(nn.Module):
48
+ def __init__(self, D, n_heads=4, max_alpha=0.2, alpha_init=-2.0):
49
+ super().__init__()
50
+ self.n_heads = n_heads; self.head_dim = D // n_heads
51
+ self.max_alpha = max_alpha
52
+ self.qkv = nn.Linear(D, 3*D); self.out_proj = nn.Linear(D, D)
53
+ self.norm = nn.LayerNorm(D); self.scale = self.head_dim**-0.5
54
+ self.alpha_logits = nn.Parameter(torch.full((D,), alpha_init))
55
+ @property
56
+ def alpha(self): return self.max_alpha * torch.sigmoid(self.alpha_logits)
57
+ def forward(self, S):
58
+ B, N, D = S.shape; S_n = self.norm(S)
59
+ qkv = self.qkv(S_n).reshape(B,N,3,self.n_heads,self.head_dim).permute(2,0,3,1,4)
60
+ q, k, v = qkv[0], qkv[1], qkv[2]
61
+ out = (((q @ k.transpose(-2,-1))*self.scale).softmax(-1) @ v).transpose(1,2).reshape(B,N,D)
62
+ return S * (1.0 + self.alpha.unsqueeze(0).unsqueeze(0) * torch.tanh(self.out_proj(out)))
63
+
64
+ class PatchSVAE(nn.Module):
65
+ def __init__(self, V=256, D=16, ps=16, hidden=768, depth=4, n_cross=2):
66
+ super().__init__()
67
+ self.matrix_v, self.D, self.patch_size = V, D, ps
68
+ self.patch_dim = 3*ps*ps; self.mat_dim = V*D
69
+ self.enc_in = nn.Linear(self.patch_dim, hidden)
70
+ self.enc_blocks = nn.ModuleList([nn.Sequential(
71
+ nn.LayerNorm(hidden), nn.Linear(hidden, hidden),
72
+ nn.GELU(), nn.Linear(hidden, hidden)) for _ in range(depth)])
73
+ self.enc_out = nn.Linear(hidden, self.mat_dim)
74
+ self.dec_in = nn.Linear(self.mat_dim, hidden)
75
+ self.dec_blocks = nn.ModuleList([nn.Sequential(
76
+ nn.LayerNorm(hidden), nn.Linear(hidden, hidden),
77
+ nn.GELU(), nn.Linear(hidden, hidden)) for _ in range(depth)])
78
+ self.dec_out = nn.Linear(hidden, self.patch_dim)
79
+ nn.init.orthogonal_(self.enc_out.weight)
80
+ self.cross_attn = nn.ModuleList([
81
+ SpectralCrossAttention(D, n_heads=min(4,D)) for _ in range(n_cross)])
82
+ self.boundary_smooth = BoundarySmooth(channels=3, mid=16)
83
+
84
+ def _svd(self, A):
85
+ orig = A.dtype
86
+ with torch.amp.autocast('cuda', enabled=False):
87
+ A_d = A.double()
88
+ G = torch.bmm(A_d.transpose(1,2), A_d)
89
+ G.diagonal(dim1=-2, dim2=-1).add_(1e-12)
90
+ eig, V = torch.linalg.eigh(G)
91
+ eig = eig.flip(-1); V = V.flip(-1)
92
+ S = torch.sqrt(eig.clamp(min=1e-24))
93
+ U = torch.bmm(A_d, V) / S.unsqueeze(1).clamp(min=1e-16)
94
+ Vh = V.transpose(-2,-1).contiguous()
95
+ return U.to(orig), S.to(orig), Vh.to(orig)
96
+
97
+ def encode_patches(self, patches):
98
+ B, N, _ = patches.shape
99
+ h = F.gelu(self.enc_in(patches.reshape(B*N,-1)))
100
+ for block in self.enc_blocks: h = h + block(h)
101
+ M = F.normalize(self.enc_out(h).reshape(B*N, self.matrix_v, self.D), dim=-1)
102
+ U, S, Vt = self._svd(M)
103
+ U = U.reshape(B,N,self.matrix_v,self.D); S = S.reshape(B,N,self.D)
104
+ Vt = Vt.reshape(B,N,self.D,self.D); M = M.reshape(B,N,self.matrix_v,self.D)
105
+ S_c = S
106
+ for layer in self.cross_attn: S_c = layer(S_c)
107
+ return {'U':U, 'S_orig':S, 'S':S_c, 'Vt':Vt, 'M':M}
108
+
109
+ def decode_patches(self, U, S, Vt):
110
+ B, N, V, D = U.shape
111
+ M_hat = torch.bmm(U.reshape(B*N,V,D)*S.reshape(B*N,D).unsqueeze(1), Vt.reshape(B*N,D,D))
112
+ h = F.gelu(self.dec_in(M_hat.reshape(B*N,-1)))
113
+ for block in self.dec_blocks: h = h + block(h)
114
+ return self.dec_out(h).reshape(B, N, -1)
115
+
116
+ def forward(self, images):
117
+ B, C, H, W = images.shape
118
+ ps = self.patch_size
119
+ gh, gw = H//ps, W//ps
120
+ p = images.reshape(B,C,gh,ps,gw,ps).permute(0,2,4,1,3,5).reshape(B,gh*gw,C*ps*ps)
121
+ svd = self.encode_patches(p)
122
+ dec = self.decode_patches(svd['U'], svd['S'], svd['Vt'])
123
+ dec = dec.reshape(B,gh,gw,3,ps,ps).permute(0,3,1,4,2,5).reshape(B,3,gh*ps,gw*ps)
124
+ return {'recon': self.boundary_smooth(dec), 'svd': svd}
125
+
126
+ @staticmethod
127
+ def effective_rank(S):
128
+ p = S / (S.sum(-1, keepdim=True)+1e-8); p = p.clamp(min=1e-8)
129
+ return (-(p * p.log()).sum(-1)).exp()
130
+
131
+
132
+ def load_model(hf_version=None, checkpoint_path=None, hf_file=None):
133
+ from huggingface_hub import hf_hub_download
134
+ if checkpoint_path and os.path.exists(checkpoint_path):
135
+ path = checkpoint_path
136
+ elif hf_file:
137
+ path = hf_hub_download(repo_id='AbstractPhil/geolip-SVAE',
138
+ filename=hf_file, repo_type='model')
139
+ elif hf_version:
140
+ path = hf_hub_download(repo_id='AbstractPhil/geolip-SVAE',
141
+ filename=f'{hf_version}/checkpoints/best.pt', repo_type='model')
142
+ else:
143
+ path = '/content/checkpoints/best.pt'
144
+ print(f" Loading: {path}")
145
+ ckpt = torch.load(path, map_location='cpu', weights_only=False)
146
+ cfg = ckpt['config']
147
+ print(f" Epoch: {ckpt.get('epoch')}, MSE: {ckpt.get('test_mse','?'):.6f}")
148
+ print(f" Config: {cfg}")
149
+ model = PatchSVAE(V=cfg['V'], D=cfg['D'], ps=cfg['patch_size'],
150
+ hidden=cfg['hidden'], depth=cfg['depth'],
151
+ n_cross=cfg['n_cross_layers'])
152
+ model.load_state_dict(ckpt['model_state_dict'], strict=True)
153
+ model = model.to(DEVICE).eval()
154
+ print(f" Params: {sum(p.numel() for p in model.parameters()):,}")
155
+ return model, cfg
156
+
157
+
158
+ # ── Noise Generators ─────────────────────────────────────────────
159
+
160
+ NOISE_NAMES = {
161
+ 0:'gaussian', 1:'uniform', 2:'uniform_scaled', 3:'poisson',
162
+ 4:'pink', 5:'brown', 6:'salt_pepper', 7:'sparse',
163
+ 8:'block', 9:'gradient', 10:'checkerboard', 11:'mixed',
164
+ 12:'structural', 13:'cauchy', 14:'exponential', 15:'laplace',
165
+ }
166
+
167
+ def _pink(shape):
168
+ w = torch.randn(shape); S = torch.fft.rfft2(w)
169
+ h, ww = shape[-2], shape[-1]
170
+ fy = torch.fft.fftfreq(h).unsqueeze(-1).expand(-1, ww//2+1)
171
+ fx = torch.fft.rfftfreq(ww).unsqueeze(0).expand(h, -1)
172
+ return torch.fft.irfft2(S / torch.sqrt(fx**2 + fy**2).clamp(min=1e-8), s=(h, ww))
173
+
174
+ def _brown(shape):
175
+ w = torch.randn(shape); S = torch.fft.rfft2(w)
176
+ h, ww = shape[-2], shape[-1]
177
+ fy = torch.fft.fftfreq(h).unsqueeze(-1).expand(-1, ww//2+1)
178
+ fx = torch.fft.rfftfreq(ww).unsqueeze(0).expand(h, -1)
179
+ return torch.fft.irfft2(S / (fx**2 + fy**2).clamp(min=1e-8), s=(h, ww))
180
+
181
+ def generate_noise(noise_type, n, s):
182
+ rng = np.random.RandomState(42)
183
+ imgs = []
184
+ for _ in range(n):
185
+ if noise_type == 0: img = torch.randn(3,s,s)
186
+ elif noise_type == 1: img = torch.rand(3,s,s)*2-1
187
+ elif noise_type == 2: img = (torch.rand(3,s,s)-0.5)*4
188
+ elif noise_type == 3:
189
+ lam = rng.uniform(0.5,20.0)
190
+ img = torch.poisson(torch.full((3,s,s),lam))/lam-1.0
191
+ elif noise_type == 4: img = _pink((3,s,s)); img = img/(img.std()+1e-8)
192
+ elif noise_type == 5: img = _brown((3,s,s)); img = img/(img.std()+1e-8)
193
+ elif noise_type == 6:
194
+ img = torch.where(torch.rand(3,s,s)>0.5, torch.ones(3,s,s)*2, -torch.ones(3,s,s)*2)
195
+ img = img + torch.randn(3,s,s)*0.1
196
+ elif noise_type == 7: img = torch.randn(3,s,s)*(torch.rand(3,s,s)>0.9).float()*3
197
+ elif noise_type == 8:
198
+ b = rng.randint(2,16); sm = torch.randn(3,s//b+1,s//b+1)
199
+ img = F.interpolate(sm.unsqueeze(0), size=s, mode='nearest').squeeze(0)
200
+ elif noise_type == 9:
201
+ gy = torch.linspace(-2,2,s).unsqueeze(1).expand(s,s)
202
+ gx = torch.linspace(-2,2,s).unsqueeze(0).expand(s,s)
203
+ a = rng.uniform(0,2*math.pi)
204
+ img = (math.cos(a)*gx+math.sin(a)*gy).unsqueeze(0).expand(3,-1,-1)+torch.randn(3,s,s)*0.5
205
+ elif noise_type == 10:
206
+ cs = rng.randint(2,16); cy = torch.arange(s)//cs; cx = torch.arange(s)//cs
207
+ img = ((cy.unsqueeze(1)+cx.unsqueeze(0))%2).float().unsqueeze(0).expand(3,-1,-1)*2-1+torch.randn(3,s,s)*0.3
208
+ elif noise_type == 11:
209
+ alpha = rng.uniform(0.2,0.8)
210
+ img = alpha*torch.randn(3,s,s)+(1-alpha)*(torch.rand(3,s,s)*2-1)
211
+ elif noise_type == 12:
212
+ img = torch.zeros(3,s,s); h2 = s//2
213
+ img[:,:h2,:h2] = torch.randn(3,h2,h2)
214
+ img[:,:h2,h2:] = torch.rand(3,h2,h2)*2-1
215
+ img[:,h2:,:h2] = _pink((3,h2,h2))/2
216
+ img[:,h2:,h2:] = torch.where(torch.rand(3,h2,h2)>0.5, torch.ones(3,h2,h2), -torch.ones(3,h2,h2))
217
+ elif noise_type == 13: img = torch.tan(math.pi*(torch.rand(3,s,s)-0.5)).clamp(-3,3)
218
+ elif noise_type == 14: img = torch.empty(3,s,s).exponential_(1.0)-1.0
219
+ elif noise_type == 15:
220
+ u = torch.rand(3,s,s)-0.5; img = -torch.sign(u)*torch.log1p(-2*u.abs())
221
+ else: img = torch.randn(3,s,s)
222
+ imgs.append(img.clamp(-4,4))
223
+ return torch.stack(imgs)
224
+
225
+
226
+ # ── Batched Forward ──────────────────────────────────────────────
227
+
228
+ def batched_forward(model, images, max_batch=16):
229
+ """Forward pass in chunks to avoid OOM."""
230
+ all_recon = []; all_S = []; all_S_orig = []; all_M = []
231
+ model.eval()
232
+ with torch.no_grad():
233
+ for i in range(0, len(images), max_batch):
234
+ batch = images[i:i+max_batch].to(DEVICE)
235
+ out = model(batch)
236
+ all_recon.append(out['recon'].cpu())
237
+ all_S.append(out['svd']['S'].cpu())
238
+ all_S_orig.append(out['svd']['S_orig'].cpu())
239
+ all_M.append(out['svd']['M'].cpu())
240
+ return {
241
+ 'recon': torch.cat(all_recon),
242
+ 'S': torch.cat(all_S),
243
+ 'S_orig': torch.cat(all_S_orig),
244
+ 'M': torch.cat(all_M),
245
+ }
246
+
247
+
248
+ # ── Dataset Loaders ──────────────────────────────────────────────
249
+
250
+ def load_dataset_batch(name, s, n=100):
251
+ """Load n images from a dataset, resized to sΓ—s, normalized.
252
+ Returns: (tensor [N,3,H,W], mean, std, ds_name)
253
+ """
254
+ from datasets import load_dataset as hf_load
255
+
256
+ if name == 'cifar10':
257
+ transform = T.Compose([T.Resize(s), T.ToTensor(),
258
+ T.Normalize((0.4914,0.4822,0.4465),(0.2470,0.2435,0.2616))])
259
+ ds = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
260
+ imgs = [ds[i][0] for i in range(min(n, len(ds)))]
261
+ return torch.stack(imgs), (0.4914,0.4822,0.4465), (0.2470,0.2435,0.2616), f'CIFAR-10β†’{s}'
262
+
263
+ elif name == 'mnist':
264
+ transform = T.Compose([T.Resize(s), T.Grayscale(3), T.ToTensor(),
265
+ T.Normalize((0.1307,0.1307,0.1307),(0.3081,0.3081,0.3081))])
266
+ ds = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
267
+ imgs = [ds[i][0] for i in range(min(n, len(ds)))]
268
+ return torch.stack(imgs), (0.1307,0.1307,0.1307), (0.3081,0.3081,0.3081), f'MNIST→{s}'
269
+
270
+ elif name == 'tiny_imagenet':
271
+ ds = hf_load('zh-plus/tiny-imagenet', split='valid', streaming=True)
272
+ transform = T.Compose([T.Resize(s), T.CenterCrop(s), T.ToTensor(),
273
+ T.Normalize((0.4802,0.4481,0.3975),(0.2770,0.2691,0.2821))])
274
+ imgs = []
275
+ for i, sample in enumerate(ds):
276
+ imgs.append(transform(sample['image'].convert('RGB')))
277
+ if i >= n-1: break
278
+ return torch.stack(imgs), (0.4802,0.4481,0.3975), (0.2770,0.2691,0.2821), f'TinyImageNet→{s}'
279
+
280
+ elif name == 'imagenet128':
281
+ ds = hf_load('benjamin-paine/imagenet-1k-128x128', split='validation', streaming=True)
282
+ transform = T.Compose([T.Resize(s), T.CenterCrop(s), T.ToTensor(),
283
+ T.Normalize((0.485,0.456,0.406),(0.229,0.224,0.225))])
284
+ imgs = []
285
+ for i, sample in enumerate(ds):
286
+ imgs.append(transform(sample['image'].convert('RGB')))
287
+ if i >= n-1: break
288
+ return torch.stack(imgs), (0.485,0.456,0.406), (0.229,0.224,0.225), f'ImageNet-128β†’{s}'
289
+
290
+ elif name == 'imagenet256':
291
+ ds = hf_load('benjamin-paine/imagenet-1k-256x256', split='validation', streaming=True)
292
+ transform = T.Compose([T.Resize(s), T.CenterCrop(s), T.ToTensor(),
293
+ T.Normalize((0.485,0.456,0.406),(0.229,0.224,0.225))])
294
+ imgs = []
295
+ for i, sample in enumerate(ds):
296
+ imgs.append(transform(sample['image'].convert('RGB')))
297
+ if i >= n-1: break
298
+ return torch.stack(imgs), (0.485,0.456,0.406), (0.229,0.224,0.225), f'ImageNet-256β†’{s}'
299
+
300
+ raise ValueError(f"Unknown dataset: {name}")
301
+
302
+
303
+ # ════════════════════════════════════════════════════════════════
304
+ # TESTS
305
+ # ════════════════════════════════════════════════════════════════
306
+
307
+ IMAGE_DATASETS = ['cifar10', 'mnist', 'tiny_imagenet', 'imagenet128', 'imagenet256']
308
+
309
+
310
+ def test_image_datasets(model, cfg, n=100):
311
+ """Reconstruction MSE + geometry across all image datasets."""
312
+ s = cfg['img_size']
313
+ D = cfg['D']
314
+ bs = max(4, 64 // max(1, (s // 64) ** 2))
315
+ print(f"\n{'='*80}")
316
+ print(f"IMAGE DATASET BATTERY ({s}Γ—{s}, n={n})")
317
+ print(f"{'='*80}")
318
+ print(f" {'dataset':22s} {'MSE':>10s} {'std':>10s} {'min':>10s} {'max':>10s} | "
319
+ f"{'S0':>6s} {'SD':>6s} {'ratio':>6s} {'erank':>6s}")
320
+ print("-" * 100)
321
+
322
+ results = {}
323
+ for ds_name in IMAGE_DATASETS:
324
+ try:
325
+ imgs, mean, std, label = load_dataset_batch(ds_name, s, n)
326
+ out = batched_forward(model, imgs, max_batch=bs)
327
+ mse = F.mse_loss(out['recon'], imgs, reduction='none').mean(dim=(1,2,3))
328
+ S_mean = out['S'].mean(dim=(0,1))
329
+ ratio = (S_mean[0] / (S_mean[-1]+1e-8)).item()
330
+ erank = model.effective_rank(out['S'].reshape(-1, D)).mean().item()
331
+
332
+ results[ds_name] = {
333
+ 'label': label,
334
+ 'mse_mean': mse.mean().item(), 'mse_std': mse.std().item(),
335
+ 'mse_min': mse.min().item(), 'mse_max': mse.max().item(),
336
+ 'S0': S_mean[0].item(), 'SD': S_mean[-1].item(),
337
+ 'ratio': ratio, 'erank': erank,
338
+ 'fidelity': (1 - mse.mean()).item() * 100,
339
+ }
340
+ print(f" {label:22s} {mse.mean():10.6f} {mse.std():10.6f} "
341
+ f"{mse.min():10.6f} {mse.max():10.6f} | "
342
+ f"{S_mean[0]:6.3f} {S_mean[-1]:6.3f} {ratio:6.2f} {erank:6.2f}")
343
+ except Exception as e:
344
+ print(f" {ds_name:22s} FAILED: {e}")
345
+ results[ds_name] = {'error': str(e)}
346
+ return results
347
+
348
+
349
+ def test_noise_types(model, cfg, n=64):
350
+ """Per-type noise reconstruction + geometry."""
351
+ s = cfg['img_size']
352
+ D = cfg['D']
353
+ bs = max(4, 64 // max(1, (s // 64) ** 2))
354
+ print(f"\n{'='*80}")
355
+ print(f"NOISE TYPE BATTERY ({s}Γ—{s}, n={n})")
356
+ print(f"{'='*80}")
357
+ print(f" {'type':18s} {'MSE':>10s} {'std':>10s} | "
358
+ f"{'S0':>6s} {'SD':>6s} {'ratio':>6s} {'erank':>6s} | "
359
+ f"{'byte_acc':>8s} {'Β±1_acc':>8s}")
360
+ print("-" * 100)
361
+
362
+ results = {}
363
+ for t in range(16):
364
+ name = NOISE_NAMES[t]
365
+ imgs = generate_noise(t, n, s)
366
+ out = batched_forward(model, imgs, max_batch=bs)
367
+ mse = F.mse_loss(out['recon'], imgs, reduction='none').mean(dim=(1,2,3))
368
+ S_mean = out['S'].mean(dim=(0,1))
369
+ ratio = (S_mean[0] / (S_mean[-1]+1e-8)).item()
370
+ erank = model.effective_rank(out['S'].reshape(-1, D)).mean().item()
371
+
372
+ # Byte accuracy
373
+ orig_q = ((imgs + 4) / 8 * 255).round().clamp(0,255).long()
374
+ recon_q = ((out['recon'] + 4) / 8 * 255).round().clamp(0,255).long()
375
+ byte_acc = (orig_q == recon_q).float().mean().item()
376
+ byte_1 = ((orig_q - recon_q).abs() <= 1).float().mean().item()
377
+
378
+ results[name] = {
379
+ 'mse_mean': mse.mean().item(), 'mse_std': mse.std().item(),
380
+ 'S0': S_mean[0].item(), 'SD': S_mean[-1].item(),
381
+ 'ratio': ratio, 'erank': erank,
382
+ 'byte_exact': byte_acc, 'byte_within1': byte_1,
383
+ }
384
+ print(f" {name:18s} {mse.mean():10.6f} {mse.std():10.6f} | "
385
+ f"{S_mean[0]:6.3f} {S_mean[-1]:6.3f} {ratio:6.2f} {erank:6.2f} | "
386
+ f"{byte_acc*100:7.2f}% {byte_1*100:7.2f}%")
387
+ return results
388
+
389
+
390
+ def test_text_bytes(model, cfg):
391
+ """Text-as-bytes reconstruction."""
392
+ s = cfg['img_size']
393
+ print(f"\n{'='*80}")
394
+ print(f"TEXT BYTE RECONSTRUCTION ({s}Γ—{s})")
395
+ print(f"{'='*80}")
396
+
397
+ texts = [
398
+ "Hello, world! This is a test of the geometric encoder.",
399
+ "The quick brown fox jumps over the lazy dog. 0123456789",
400
+ "import torch; model = PatchSVAE(); output = model(x)",
401
+ "E = mcΒ² β€” Albert Einstein, theoretical physicist, 1905",
402
+ "To be, or not to be, that is the question. β€” Shakespeare",
403
+ "βˆ«β‚€^∞ e^(-xΒ²) dx = βˆšΟ€/2 β€” Gaussian integral",
404
+ "01101000 01100101 01101100 01101100 01101111 β€” binary hello",
405
+ "SELECT * FROM models WHERE cv BETWEEN 0.20 AND 0.23;",
406
+ ]
407
+
408
+ n_bytes = 3 * s * s
409
+ results = {}
410
+ model.eval()
411
+
412
+ for text in texts:
413
+ raw = text.encode('utf-8')
414
+ actual_len = min(len(raw), n_bytes)
415
+ padded = (raw + b'\x00' * n_bytes)[:n_bytes]
416
+
417
+ arr = np.frombuffer(padded, dtype=np.uint8).copy()
418
+ tensor = torch.from_numpy(arr).float()
419
+ tensor = (tensor / 127.5) - 1.0
420
+ tensor = tensor.reshape(1, 3, s, s).to(DEVICE)
421
+
422
+ with torch.no_grad():
423
+ out = model(tensor)
424
+ recon = out['recon']
425
+ mse = F.mse_loss(recon, tensor).item()
426
+
427
+ orig_b = ((tensor.squeeze(0).cpu().flatten() + 1.0) * 127.5).round().clamp(0,255).byte()
428
+ recon_b = ((recon.squeeze(0).cpu().flatten() + 1.0) * 127.5).round().clamp(0,255).byte()
429
+ exact_acc = (orig_b[:actual_len] == recon_b[:actual_len]).float().mean().item()
430
+ recovered = recon_b[:actual_len].numpy().tobytes().decode('utf-8', errors='replace')
431
+
432
+ results[text[:40]] = {'mse': mse, 'byte_acc': exact_acc}
433
+ print(f"\n In: '{text[:60]}'")
434
+ print(f" Out: '{recovered[:60]}'")
435
+ print(f" MSE: {mse:.6f} Byte: {exact_acc*100:.1f}%")
436
+ return results
437
+
438
+
439
+ def test_piecemeal(model, cfg):
440
+ """Piecemeal tiling at 4Γ— resolution."""
441
+ s = cfg['img_size']
442
+ src = max(256, s * 4)
443
+ bs = max(2, 32 // max(1, (s // 64) ** 2))
444
+ print(f"\n{'='*80}")
445
+ print(f"PIECEMEAL {src}β†’{s} TILED RECONSTRUCTION")
446
+ print(f"{'='*80}")
447
+ model.eval()
448
+ results = {}
449
+
450
+ test_types = [0, 1, 4, 6, 13] # Gaussian, Uniform, Pink, Salt-pepper, Cauchy
451
+ with torch.no_grad():
452
+ for t in test_types:
453
+ img_src = generate_noise(t, 1, src).squeeze(0)
454
+ tiles = []
455
+ gh, gw = src // s, src // s
456
+ for gy in range(gh):
457
+ for gx in range(gw):
458
+ tiles.append(img_src[:, gy*s:(gy+1)*s, gx*s:(gx+1)*s])
459
+
460
+ # Batch tiles through model
461
+ all_recon = []
462
+ tile_t = torch.stack(tiles)
463
+ for i in range(0, len(tile_t), bs):
464
+ batch = tile_t[i:i+bs].to(DEVICE)
465
+ out = model(batch)
466
+ all_recon.append(out['recon'].cpu())
467
+ recon_tiles = torch.cat(all_recon)
468
+
469
+ recon_full = torch.zeros(3, src, src)
470
+ idx = 0
471
+ for gy in range(gh):
472
+ for gx in range(gw):
473
+ recon_full[:, gy*s:(gy+1)*s, gx*s:(gx+1)*s] = recon_tiles[idx]
474
+ idx += 1
475
+
476
+ mse = F.mse_loss(recon_full, img_src).item()
477
+ results[NOISE_NAMES[t]] = mse
478
+ print(f" {NOISE_NAMES[t]:18s}: {gh*gw} tiles, MSE={mse:.6f}")
479
+ return results
480
+
481
+
482
+ def test_signal_survival(model, cfg, n=32):
483
+ """Signal energy survival and SNR per dataset."""
484
+ s = cfg['img_size']
485
+ bs = max(4, 64 // max(1, (s // 64) ** 2))
486
+ print(f"\n{'='*80}")
487
+ print(f"SIGNAL ENERGY SURVIVAL")
488
+ print(f"{'='*80}")
489
+ print(f" {'source':22s} {'survival':>10s} {'SNR_dB':>10s} {'orig_E':>10s} {'recon_E':>10s}")
490
+ print("-" * 70)
491
+
492
+ results = {}
493
+
494
+ # Image datasets
495
+ for ds_name in IMAGE_DATASETS:
496
+ try:
497
+ imgs, _, _, label = load_dataset_batch(ds_name, s, n)
498
+ out = batched_forward(model, imgs, max_batch=bs)
499
+ orig_E = (imgs**2).mean().item()
500
+ recon_E = (out['recon']**2).mean().item()
501
+ err_E = ((imgs - out['recon'])**2).mean().item()
502
+ survival = recon_E / (orig_E + 1e-8) * 100
503
+ snr = 10 * math.log10(orig_E / (err_E + 1e-8))
504
+ results[ds_name] = {'survival': survival, 'snr': snr}
505
+ print(f" {label:22s} {survival:9.1f}% {snr:9.1f}dB {orig_E:10.4f} {recon_E:10.4f}")
506
+ except:
507
+ pass
508
+
509
+ # Key noise types
510
+ for t in [0, 4, 6, 13]:
511
+ imgs = generate_noise(t, n, s)
512
+ out = batched_forward(model, imgs, max_batch=bs)
513
+ orig_E = (imgs**2).mean().item()
514
+ recon_E = (out['recon']**2).mean().item()
515
+ err_E = ((imgs - out['recon'])**2).mean().item()
516
+ survival = recon_E / (orig_E + 1e-8) * 100
517
+ snr = 10 * math.log10(orig_E / (err_E + 1e-8))
518
+ results[NOISE_NAMES[t]] = {'survival': survival, 'snr': snr}
519
+ print(f" noise/{NOISE_NAMES[t]:17s} {survival:9.1f}% {snr:9.1f}dB {orig_E:10.4f} {recon_E:10.4f}")
520
+
521
+ return results
522
+
523
+
524
+ def test_alpha_profile(model):
525
+ """Cross-attention alpha analysis."""
526
+ print(f"\n{'='*80}")
527
+ print("ALPHA PROFILE")
528
+ print(f"{'='*80}")
529
+ results = {}
530
+ for li, layer in enumerate(model.cross_attn):
531
+ alpha = layer.alpha.detach().cpu()
532
+ results[f'layer_{li}'] = {
533
+ 'mean': alpha.mean().item(), 'max': alpha.max().item(),
534
+ 'min': alpha.min().item(), 'std': alpha.std().item(),
535
+ 'values': alpha.tolist(),
536
+ }
537
+ print(f"\n Layer {li}: mean={alpha.mean():.5f} max={alpha.max():.5f} "
538
+ f"min={alpha.min():.5f} std={alpha.std():.6f}")
539
+ bar_scale = 50 / (alpha.max().item() + 1e-8)
540
+ for d in range(len(alpha)):
541
+ bar = "β–ˆ" * int(alpha[d].item() * bar_scale)
542
+ print(f" Ξ±[{d:2d}]: {alpha[d]:.5f} {bar}")
543
+ return results
544
+
545
+
546
+ def test_compression(model, cfg):
547
+ """Compression metrics."""
548
+ s = cfg['img_size']
549
+ D = cfg['D']; ps = cfg['patch_size']
550
+ n_patches = (s // ps) ** 2
551
+ input_vals = 3 * s * s
552
+ latent_vals = D * n_patches
553
+ ratio = input_vals / latent_vals
554
+ print(f"\n{'='*80}")
555
+ print("COMPRESSION METRICS")
556
+ print(f"{'='*80}")
557
+ print(f" Input: {s}Γ—{s}Γ—3 = {input_vals:,} values")
558
+ print(f" Latent: {D}Γ—{n_patches} = {latent_vals:,} omega tokens")
559
+ print(f" Ratio: {ratio:.1f}:1")
560
+ for bits in [8, 16, 32]:
561
+ ib = input_vals * (bits//8)
562
+ lb = latent_vals * (bits//8)
563
+ print(f" {bits}-bit: input={ib/1024:.1f}KB latent={lb/1024:.1f}KB ratio={ib/lb:.1f}:1")
564
+ return {'input_values': input_vals, 'latent_values': latent_vals, 'ratio': ratio}
565
+
566
+
567
+ def test_reconstruction_grid(model, cfg):
568
+ """Save visual grid: 5 image datasets + 4 key noise types."""
569
+ s = cfg['img_size']
570
+ print(f"\n{'='*80}")
571
+ print("RECONSTRUCTION GRID")
572
+ print(f"{'='*80}")
573
+ import matplotlib
574
+ matplotlib.use('Agg')
575
+ import matplotlib.pyplot as plt
576
+
577
+ rows = []
578
+ labels = []
579
+
580
+ # Image datasets
581
+ for ds_name in IMAGE_DATASETS:
582
+ try:
583
+ imgs, mean, std, label = load_dataset_batch(ds_name, s, 2)
584
+ mean_t = torch.tensor(mean).reshape(1,3,1,1)
585
+ std_t = torch.tensor(std).reshape(1,3,1,1)
586
+ out = batched_forward(model, imgs[:1], max_batch=1)
587
+ orig_vis = (imgs[:1] * std_t + mean_t).clamp(0,1)
588
+ recon_vis = (out['recon'][:1] * std_t + mean_t).clamp(0,1)
589
+ rows.append((orig_vis[0], recon_vis[0]))
590
+ labels.append(label)
591
+ except:
592
+ pass
593
+
594
+ # Key noise types
595
+ for t in [0, 6, 13, 4]:
596
+ imgs = generate_noise(t, 1, s)
597
+ out = batched_forward(model, imgs, max_batch=1)
598
+ o = imgs[0].clamp(-3,3); r = out['recon'][0].clamp(-3,3)
599
+ o = (o - o.min())/(o.max()-o.min()+1e-8)
600
+ r = (r - r.min())/(r.max()-r.min()+1e-8)
601
+ rows.append((o, r))
602
+ labels.append(f'noise/{NOISE_NAMES[t]}')
603
+
604
+ n_rows = len(rows)
605
+ fig, axes = plt.subplots(n_rows, 3, figsize=(9, n_rows*3))
606
+ if n_rows == 1: axes = axes.reshape(1, -1)
607
+ for i, (orig, recon) in enumerate(rows):
608
+ diff = (orig - recon).abs().clamp(0,1)
609
+ axes[i,0].imshow(orig.permute(1,2,0).numpy())
610
+ axes[i,1].imshow(recon.permute(1,2,0).numpy())
611
+ axes[i,2].imshow((diff * 5).clamp(0,1).permute(1,2,0).numpy())
612
+ axes[i,0].set_ylabel(labels[i], fontsize=8)
613
+ for j in range(3): axes[i,j].axis('off')
614
+ axes[0,0].set_title('Original', fontsize=9)
615
+ axes[0,1].set_title('Recon', fontsize=9)
616
+ axes[0,2].set_title('|Err|Γ—5', fontsize=9)
617
+ plt.tight_layout()
618
+ fname = 'universal_diagnostic_grid.png'
619
+ plt.savefig(fname, dpi=150, bbox_inches='tight')
620
+ print(f" Saved: {fname}")
621
+ plt.close()
622
+
623
+
624
+ # ════════════════════════════════════════════════════════════════
625
+ # MAIN
626
+ # ════════════════════════════════════════════════════════════════
627
+
628
+ def run(hf_version=None, checkpoint_path=None, hf_file=None, n_samples=64):
629
+ """
630
+ Run full diagnostic battery.
631
+
632
+ Usage in Colab cell:
633
+ run(hf_version='v13_imagenet256') # best.pt
634
+ run(hf_file='v18_johanna_curriculum/checkpoints/epoch_0300.pt') # specific file
635
+ run(checkpoint_path='/content/checkpoints/best.pt') # local
636
+ """
637
+ print("=" * 80)
638
+ print("UNIVERSAL SVAE DIAGNOSTIC BATTERY")
639
+ print("=" * 80)
640
+
641
+ model, cfg = load_model(hf_version=hf_version, checkpoint_path=checkpoint_path, hf_file=hf_file)
642
+
643
+ # Infer img_size if not in config
644
+ if 'img_size' not in cfg:
645
+ ds = cfg.get('dataset', '')
646
+ if '256' in ds: cfg['img_size'] = 256
647
+ elif '128' in ds: cfg['img_size'] = 128
648
+ elif 'tiny' in ds: cfg['img_size'] = 64
649
+ elif 'cifar' in ds: cfg['img_size'] = 32
650
+ else: cfg['img_size'] = 64
651
+ print(f" Inferred img_size={cfg['img_size']} from dataset='{ds}'")
652
+
653
+ s = cfg['img_size']
654
+ n = min(n_samples, max(16, 100 // max(1, (s // 64) ** 2)))
655
+ print(f" Resolution: {s}Γ—{s}, samples_per_test: {n}")
656
+
657
+ results = {'config': cfg}
658
+
659
+ results['image_datasets'] = test_image_datasets(model, cfg, n=n)
660
+ results['noise_types'] = test_noise_types(model, cfg, n=n)
661
+ results['text'] = test_text_bytes(model, cfg)
662
+ results['piecemeal'] = test_piecemeal(model, cfg)
663
+ results['signal_survival'] = test_signal_survival(model, cfg, n=n)
664
+ results['alpha'] = test_alpha_profile(model)
665
+ results['compression'] = test_compression(model, cfg)
666
+ test_reconstruction_grid(model, cfg)
667
+
668
+ tag = hf_version or (hf_file or 'local').replace('/','_').replace('.pt','')
669
+ out_path = f'diagnostic_{tag}.json'
670
+ with open(out_path, 'w') as f:
671
+ json.dump(results, f, indent=2, default=str)
672
+ print(f"\n Results: {out_path}")
673
+ print(f"\n{'='*80}")
674
+ print("DIAGNOSTIC COMPLETE")
675
+ print(f"{'='*80}")
676
+ return results
677
+
678
+
679
+ # ── CONFIG: Change this per run ──────────────────────────────────
680
+ # Uncomment the model you want to diagnose:
681
+
682
+ # HF_VERSION = 'v13_imagenet256' # Fresnel-base 256 (best.pt)
683
+ # HF_VERSION = 'v16_johanna_omega' # Johanna-small 128 (best.pt)
684
+ # HF_VERSION = 'v18_johanna_curriculum' # Johanna-tiny 64 (best.pt = ep10 pre-crash!)
685
+
686
+ # For specific checkpoints use hf_file:
687
+ HF_FILE = 'v18_johanna_curriculum/checkpoints/epoch_0300.pt' # Johanna-tiny FULL curriculum
688
+
689
+ if __name__ == "__main__":
690
+ if 'HF_FILE' in dir() and HF_FILE:
691
+ run(hf_file=HF_FILE)
692
+ else:
693
+ run(hf_version=HF_VERSION)