AbstractPhil commited on
Commit
486b1d0
Β·
verified Β·
1 Parent(s): 927d119

Create 18_j_cell_reformed.py

Browse files
Files changed (1) hide show
  1. 18_j_cell_reformed.py +609 -0
18_j_cell_reformed.py ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ═══════════════════════════════════════════════════════════════════════
2
+ # Cell J''' β€” per-patch axis-feature classifier
3
+ # ═══════════════════════════════════════════════════════════════════════
4
+ # Same task as J/J'/J''. Same architectures. Only the encode + feature
5
+ # extraction stages change.
6
+ #
7
+ # Key fix from J' and J'':
8
+ # J' : encode_axes(images, patch_idx=0) β†’ [B, V, n_axes]
9
+ # β†’ max-pool over V β†’ [B, n_axes]
10
+ # Used 1 of 256 patches per tile.
11
+ #
12
+ # J'' : same as J' but with V-stats instead of max-pool.
13
+ # Still using 1 of 256 patches per tile.
14
+ #
15
+ # J''': encode_axes(images) # no patch_idx β†’ [B, n_patches=256, V, n_axes]
16
+ # β†’ spatial stats over patches AND value stats over V
17
+ # Uses ALL 256 patches per tile. 256Γ— more spatial signal.
18
+ #
19
+ # Codebooks calibrated with the new per-patch averaging path
20
+ # (sample_agg='mean', patch_agg='mean') for codebooks that reflect the
21
+ # bank's spatial-mean response.
22
+
23
+ import json
24
+ import math
25
+ import time
26
+ from pathlib import Path
27
+
28
+ import matplotlib.pyplot as plt
29
+ import numpy as np
30
+ import torch
31
+ import torch.nn as nn
32
+ import torch.nn.functional as F
33
+
34
+ import geolip_svae.arrays
35
+ from transformers import AutoModel
36
+
37
+ array_model = globals().get('array_model')
38
+ if array_model is None:
39
+ array_model = AutoModel.from_pretrained("AbstractPhil/geolip-svae-h2-64")
40
+ array_model = (array_model.cuda().eval()
41
+ if torch.cuda.is_available() else array_model.eval())
42
+
43
+ DEVICE = next(array_model.parameters()).device
44
+ EXP_DIR = Path("/content/h2_64_exp")
45
+ EXP_DIR.mkdir(parents=True, exist_ok=True)
46
+ TILE_SIZE = 64
47
+
48
+ NOISE_NAMES = {
49
+ 0: 'gaussian', 1: 'uniform', 2: 'uniform_scaled', 3: 'poisson',
50
+ 4: 'pink', 5: 'brown', 6: 'salt_pepper', 7: 'sparse_impulses',
51
+ 8: 'block_upsampled', 9: 'gradient_gaussian', 10: 'checker',
52
+ 11: 'gauss_uniform_mix', 12: 'four_quadrant',
53
+ 13: 'cauchy', 14: 'exponential', 15: 'laplace',
54
+ }
55
+
56
+ # ══════════════════════════════════════════════════════════════════════
57
+ # Noise generators β€” inlined from Cell J so this cell is self-contained
58
+ # ══════════════════════════════════════════════════════════════════════
59
+
60
+ def _pink(shape, rng):
61
+ w = torch.randn(shape, generator=rng)
62
+ s = torch.fft.rfft2(w)
63
+ h, ww = shape[-2], shape[-1]
64
+ fy = torch.fft.fftfreq(h).unsqueeze(-1).expand(-1, ww // 2 + 1)
65
+ fx = torch.fft.rfftfreq(ww).unsqueeze(0).expand(h, -1)
66
+ return torch.fft.irfft2(s / torch.sqrt(fx**2 + fy**2).clamp(min=1e-8),
67
+ s=(h, ww))
68
+
69
+ def _brown(shape, rng):
70
+ w = torch.randn(shape, generator=rng)
71
+ s = torch.fft.rfft2(w)
72
+ h, ww = shape[-2], shape[-1]
73
+ fy = torch.fft.fftfreq(h).unsqueeze(-1).expand(-1, ww // 2 + 1)
74
+ fx = torch.fft.rfftfreq(ww).unsqueeze(0).expand(h, -1)
75
+ return torch.fft.irfft2(s / (fx**2 + fy**2).clamp(min=1e-8), s=(h, ww))
76
+
77
+ def gen_noise(noise_type, size, seed):
78
+ """Pure noise generator. size must be even (some generators use s//2)."""
79
+ rng_t = torch.Generator().manual_seed(seed)
80
+ rng_n = np.random.RandomState(seed)
81
+ s = size
82
+ if noise_type == 0:
83
+ img = torch.randn(3, s, s, generator=rng_t)
84
+ elif noise_type == 1:
85
+ img = torch.rand(3, s, s, generator=rng_t) * 2 - 1
86
+ elif noise_type == 2:
87
+ img = (torch.rand(3, s, s, generator=rng_t) - 0.5) * 4
88
+ elif noise_type == 3:
89
+ lam = rng_n.uniform(0.5, 20.0)
90
+ img = torch.poisson(torch.full((3, s, s), lam), generator=rng_t) / lam - 1.0
91
+ elif noise_type == 4:
92
+ img = _pink((3, s, s), rng_t); img = img / (img.std() + 1e-8)
93
+ elif noise_type == 5:
94
+ img = _brown((3, s, s), rng_t); img = img / (img.std() + 1e-8)
95
+ elif noise_type == 6:
96
+ mask = torch.rand(3, s, s, generator=rng_t) > 0.5
97
+ img = torch.where(mask, torch.ones(3, s, s) * 2, torch.ones(3, s, s) * -2)
98
+ img = img + torch.randn(3, s, s, generator=rng_t) * 0.1
99
+ elif noise_type == 7:
100
+ mask = torch.rand(3, s, s, generator=rng_t) > 0.9
101
+ img = torch.randn(3, s, s, generator=rng_t) * mask.float() * 3
102
+ elif noise_type == 8:
103
+ block = rng_n.randint(2, 16)
104
+ small = torch.randn(3, s // block + 1, s // block + 1, generator=rng_t)
105
+ img = F.interpolate(small.unsqueeze(0), size=s, mode='nearest').squeeze(0)
106
+ elif noise_type == 9:
107
+ gy = torch.linspace(-2, 2, s).unsqueeze(1).expand(s, s)
108
+ gx = torch.linspace(-2, 2, s).unsqueeze(0).expand(s, s)
109
+ angle = rng_n.uniform(0, 2 * math.pi)
110
+ grad = math.cos(angle) * gx + math.sin(angle) * gy
111
+ img = (grad.unsqueeze(0).expand(3, -1, -1)
112
+ + torch.randn(3, s, s, generator=rng_t) * 0.5)
113
+ elif noise_type == 10:
114
+ cs = rng_n.randint(2, 16)
115
+ cy = torch.arange(s) // cs; cx = torch.arange(s) // cs
116
+ checker = ((cy.unsqueeze(1) + cx.unsqueeze(0)) % 2).float() * 2 - 1
117
+ img = (checker.unsqueeze(0).expand(3, -1, -1)
118
+ + torch.randn(3, s, s, generator=rng_t) * 0.3)
119
+ elif noise_type == 11:
120
+ a = torch.randn(3, s, s, generator=rng_t)
121
+ b = torch.rand(3, s, s, generator=rng_t) * 2 - 1
122
+ alpha = rng_n.uniform(0.2, 0.8)
123
+ img = alpha * a + (1 - alpha) * b
124
+ elif noise_type == 12:
125
+ img = torch.zeros(3, s, s)
126
+ h2 = s // 2
127
+ img[:, :h2, :h2] = torch.randn(3, h2, h2, generator=rng_t)
128
+ img[:, :h2, h2:] = torch.rand(3, h2, h2, generator=rng_t) * 2 - 1
129
+ img[:, h2:, :h2] = _pink((3, h2, h2), rng_t) / 2
130
+ sp = torch.where(torch.rand(3, h2, h2, generator=rng_t) > 0.5,
131
+ torch.ones(3, h2, h2), -torch.ones(3, h2, h2))
132
+ img[:, h2:, h2:] = sp
133
+ elif noise_type == 13:
134
+ u = torch.rand(3, s, s, generator=rng_t)
135
+ img = torch.tan(math.pi * (u - 0.5)).clamp(-3, 3)
136
+ elif noise_type == 14:
137
+ img = torch.empty(3, s, s).exponential_(1.0, generator=rng_t) - 1.0
138
+ elif noise_type == 15:
139
+ u = torch.rand(3, s, s, generator=rng_t) - 0.5
140
+ img = -torch.sign(u) * torch.log1p(-2 * u.abs())
141
+ else:
142
+ raise ValueError(f"Unknown noise_type {noise_type}")
143
+ return img.clamp(-4, 4).float()
144
+
145
+
146
+ def gen_zone_matte(res, n_zones, seed):
147
+ """Spatially-mixed noise: n_zones grid of different noise types."""
148
+ assert n_zones in (4, 9, 16), "Use 2Γ—2, 3Γ—3, or 4Γ—4 grids"
149
+ side = int(math.sqrt(n_zones))
150
+ cell = res // side
151
+ assert cell % 2 == 0, f"cell size {cell} must be even for noise generators"
152
+ rng_n = np.random.RandomState(seed)
153
+ zone_types = rng_n.choice(16, size=n_zones, replace=False).tolist()
154
+ img = torch.zeros(3, res, res)
155
+ zone_map = torch.zeros(res, res, dtype=torch.long)
156
+ for i in range(side):
157
+ for j in range(side):
158
+ zi = i * side + j
159
+ nt = zone_types[zi]
160
+ cell_seed = seed * 1000 + zi + 1
161
+ cell_img = gen_noise(nt, cell, cell_seed)
162
+ img[:, i*cell:(i+1)*cell, j*cell:(j+1)*cell] = cell_img
163
+ zone_map[i*cell:(i+1)*cell, j*cell:(j+1)*cell] = zi
164
+ return img, zone_types, zone_map
165
+
166
+ SUBSET_BATTERY_IDS = list(range(16)) + [19, 20]
167
+ SUBSET_PHASE = 'best'
168
+ N_BATTERIES_SUB = len(SUBSET_BATTERY_IDS)
169
+ COMP_LABELS = {16: 'zone_4', 17: 'zone_9', 18: 'zone_16'}
170
+ N_CLASSES = 16 + len(COMP_LABELS)
171
+
172
+ def label_name(n):
173
+ return NOISE_NAMES.get(n, COMP_LABELS.get(n, f"?{n}"))
174
+
175
+ print("=" * 78)
176
+ print("PHASE J''' β€” PER-PATCH AXIS-FEATURE SCANNER")
177
+ print("=" * 78)
178
+ print(f"Subset: {N_BATTERIES_SUB} batteries, phase={SUBSET_PHASE}")
179
+ print(f"Per tile: 256 patches Γ— 32 V Γ— ~27 axes = ~221K activations")
180
+
181
+
182
+ # ══════════════════════════════════════════════════════════════════════
183
+ # Codebook calibration β€” use the new batched + per-patch API
184
+ # ══════════════════════════════════════════════════════════════════════
185
+
186
+ print(f"\nCalibrating codebooks (batched, per-patch averaging)...")
187
+ t0 = time.time()
188
+ g = torch.Generator().manual_seed(42)
189
+ calib_imgs = torch.randn(512, 3, 64, 64, generator=g)
190
+
191
+ targets = [(bid, SUBSET_PHASE) for bid in SUBSET_BATTERY_IDS]
192
+ codebooks_dict = array_model.compute_axis_codebooks(
193
+ targets=targets,
194
+ calibration_images=calib_imgs,
195
+ sample_agg='mean',
196
+ patch_agg='mean', # NEW: average across 256 patches per image
197
+ batch_size=64,
198
+ )
199
+
200
+ codebooks = {bid: codebooks_dict[(bid, SUBSET_PHASE)].to(DEVICE)
201
+ for bid in SUBSET_BATTERY_IDS}
202
+ for bid in SUBSET_BATTERY_IDS:
203
+ print(f" battery {bid:>2} ({label_name(bid):<22}): "
204
+ f"{codebooks[bid].shape[0]} axes")
205
+
206
+ MAX_AXES = max(cb.shape[0] for cb in codebooks.values())
207
+ print(f"Calibration time: {time.time() - t0:.1f}s, MAX_AXES: {MAX_AXES}")
208
+
209
+
210
+ # ══════════════════════════════════════════════════════════════════════
211
+ # Per-patch tile scan β€” uses encode_axes WITHOUT patch_idx
212
+ # ══════════════════════════════════════════════════════════════════════
213
+
214
+ @torch.no_grad()
215
+ def perpatch_tile_scan(image, codebooks, battery_ids, tile_size=TILE_SIZE):
216
+ """For each tile, get full per-patch activations against each bank.
217
+
218
+ Returns features condensed at scan-time (full tensor too big to store):
219
+ [n_tiles, n_banks, MAX_AXES, N_STATS]
220
+ where N_STATS = stats over (n_patches Γ— V) jointly.
221
+
222
+ Stats per (bank, axis): max, mean, std, top10_mean, entropy
223
+ Computed over the joint distribution of activations across both
224
+ patches AND V rows (because both contribute to "how does this tile
225
+ align with this axis").
226
+ """
227
+ C, H, W = image.shape
228
+ n_h, n_w = H // tile_size, W // tile_size
229
+ n_tiles = n_h * n_w
230
+
231
+ tiles = image.unfold(1, tile_size, tile_size).unfold(2, tile_size, tile_size)
232
+ tiles = tiles.permute(1, 2, 0, 3, 4).contiguous().reshape(
233
+ n_tiles, C, tile_size, tile_size).to(DEVICE)
234
+
235
+ n_banks = len(battery_ids)
236
+ out = torch.zeros(n_tiles, n_banks, MAX_AXES, N_STATS, dtype=torch.float32)
237
+
238
+ tile_batch = 32 # smaller because per-patch activations are larger
239
+ for b_i, bid in enumerate(battery_ids):
240
+ cb = codebooks[bid] # [n_axes_i, D]
241
+ n_axes_i = cb.shape[0]
242
+
243
+ for start in range(0, n_tiles, tile_batch):
244
+ end = min(start + tile_batch, n_tiles)
245
+ batch = tiles[start:end]
246
+ # Per-patch encoding: [B_t, n_patches=256, V=32, n_axes_i]
247
+ acts = array_model.encode_axes(
248
+ images=batch, battery_idx=bid,
249
+ phase=SUBSET_PHASE, codebook=cb,
250
+ )
251
+
252
+ B_t, P, V, n_ax = acts.shape
253
+
254
+ # Reshape to [B_t, P*V, n_axes_i] β€” joint patch+V distribution
255
+ joint = acts.reshape(B_t, P * V, n_ax).cpu()
256
+
257
+ # Stats over the joint patch+V dimension, per axis:
258
+ mx = joint.max(dim=1).values # [B_t, n_ax]
259
+ mn = joint.mean(dim=1) # [B_t, n_ax]
260
+ sd = joint.std(dim=1) # [B_t, n_ax]
261
+
262
+ k = min(10, P * V)
263
+ top_k = joint.topk(k, dim=1).values
264
+ top10 = top_k.mean(dim=1) # [B_t, n_ax]
265
+
266
+ # Entropy over softmax(activations across patchΓ—V): low entropy
267
+ # means a few specific (patch, V-row) positions dominate, high
268
+ # entropy means uniform alignment across the spatial-row plane.
269
+ sm = F.softmax(joint, dim=1) # [B_t, P*V, n_ax]
270
+ ent = -(sm * (sm + 1e-12).log()).sum(dim=1) # [B_t, n_ax]
271
+ ent = ent / math.log(P * V) # normalized
272
+
273
+ # Stack [B_t, n_axes_i, N_STATS] and place into output
274
+ stats = torch.stack([mx, mn, sd, top10, ent], dim=-1)
275
+ out[start:end, b_i, :n_axes_i, :] = stats
276
+
277
+ return out
278
+
279
+
280
+ N_STATS = 5 # max, mean, std, top10_mean, entropy
281
+ print(f"\nN_STATS per (bank, axis) per tile: {N_STATS}")
282
+
283
+
284
+ # ══════════════════════════════════════════════════════════════════════
285
+ # Build feature bank
286
+ # ══════════════════════════════════════════════════════════════════════
287
+
288
+ RESOLUTIONS = [256, 512, 1024]
289
+ N_IMAGES_PER_LABEL = 24
290
+
291
+ print(f"\nBuilding per-patch axis-stats scan bank...")
292
+ scan_bank = {}
293
+ t0 = time.time()
294
+
295
+ for res in RESOLUTIONS:
296
+ scan_bank[res] = {}
297
+ n_tiles = (res // TILE_SIZE) ** 2
298
+ print(f"\n res={res} ({n_tiles} tiles per image):")
299
+
300
+ for nt in range(16):
301
+ for img_idx in range(N_IMAGES_PER_LABEL):
302
+ seed = 1_000_000 + res * 100 + nt * 100 + img_idx
303
+ img = gen_noise(nt, res, seed)
304
+ stats = perpatch_tile_scan(img, codebooks, SUBSET_BATTERY_IDS)
305
+ scan_bank[res][(nt, img_idx)] = stats
306
+ print(f" {label_name(nt):<22} done")
307
+
308
+ for zone_n, zone_lbl in [(4, 16), (9, 17), (16, 18)]:
309
+ side = int(math.sqrt(zone_n))
310
+ if res % side != 0 or (res // side) % 2 != 0:
311
+ print(f" {label_name(zone_lbl):<22} SKIP")
312
+ continue
313
+ for img_idx in range(N_IMAGES_PER_LABEL):
314
+ seed = 2_000_000 + res * 100 + zone_n * 10 + img_idx
315
+ img, _, _ = gen_zone_matte(res, zone_n, seed)
316
+ stats = perpatch_tile_scan(img, codebooks, SUBSET_BATTERY_IDS)
317
+ scan_bank[res][(zone_lbl, img_idx)] = stats
318
+ print(f" {label_name(zone_lbl):<22} done")
319
+
320
+ print(f"\nTotal scan time: {time.time() - t0:.1f}s")
321
+
322
+
323
+ # ══════════════════════════════════════════════════════════════════════
324
+ # Feature builders β€” A''' summary, B''' attn-pool over tiles
325
+ # ═════════════════���════════════════════════════════════════════════════
326
+
327
+ def perpatch_summary_features(stats_scan):
328
+ """Aggregate over tiles via mean+max for each (bank, axis, stat).
329
+
330
+ stats_scan: [n_tiles, n_banks, MAX_AXES, N_STATS]
331
+ Returns: [n_banks * MAX_AXES * N_STATS * 2] flat
332
+ """
333
+ mn = stats_scan.mean(dim=0)
334
+ mx = stats_scan.max(dim=0).values
335
+ return torch.stack([mn, mx], dim=-1).flatten()
336
+
337
+
338
+ def perpatch_tile_grid_features(stats_scan, max_tiles=16):
339
+ """Tile-grid for attention pool. Flattens (bank, axis, stat) per tile.
340
+
341
+ Returns: [max_tiles, n_banks * MAX_AXES * N_STATS]
342
+ """
343
+ n_tiles, n_banks, n_ax, n_st = stats_scan.shape
344
+ flat = stats_scan.reshape(n_tiles, n_banks * n_ax * n_st)
345
+ if n_tiles >= max_tiles:
346
+ idx = torch.randperm(n_tiles)[:max_tiles]
347
+ return flat[idx]
348
+ pad = torch.zeros(max_tiles - n_tiles, n_banks * n_ax * n_st)
349
+ return torch.cat([flat, pad], dim=0)
350
+
351
+
352
+ print(f"\nBuilding feature tensors per resolution...")
353
+ features_A_by_res = {}
354
+ features_B_by_res = {}
355
+ labels_by_res = {}
356
+ MAX_TILES = 16
357
+
358
+ for res in RESOLUTIONS:
359
+ feat_A, feat_B, labs = [], [], []
360
+ for (lbl, img_idx), stats in scan_bank[res].items():
361
+ feat_A.append(perpatch_summary_features(stats))
362
+ feat_B.append(perpatch_tile_grid_features(stats, max_tiles=MAX_TILES))
363
+ labs.append(lbl)
364
+ features_A_by_res[res] = torch.stack(feat_A)
365
+ features_B_by_res[res] = torch.stack(feat_B)
366
+ labels_by_res[res] = torch.tensor(labs)
367
+ print(f" res={res}: {features_A_by_res[res].shape[0]} samples, "
368
+ f"A''' feat {features_A_by_res[res].shape[1]}-dim, "
369
+ f"B''' feat {tuple(features_B_by_res[res].shape[1:])}")
370
+
371
+
372
+ # ══════════════════════════════════════════════════════════════════════
373
+ # Classifiers (same as J/J'/J'' for fair comparison)
374
+ # ══════════════════════════════════════════════════════════════════════
375
+
376
+ class SummaryMLP(nn.Module):
377
+ def __init__(self, in_dim, hidden=128, n_classes=N_CLASSES):
378
+ super().__init__()
379
+ self.net = nn.Sequential(
380
+ nn.Linear(in_dim, hidden),
381
+ nn.ReLU(),
382
+ nn.Linear(hidden, n_classes),
383
+ )
384
+ def forward(self, x): return self.net(x)
385
+
386
+
387
+ class AttentionPoolMLP(nn.Module):
388
+ def __init__(self, n_features, hidden=128, n_classes=N_CLASSES):
389
+ super().__init__()
390
+ self.attn_scorer = nn.Linear(n_features, 1)
391
+ self.classifier = nn.Sequential(
392
+ nn.Linear(n_features, hidden),
393
+ nn.ReLU(),
394
+ nn.Linear(hidden, n_classes),
395
+ )
396
+ def forward(self, x):
397
+ scores = self.attn_scorer(x).squeeze(-1)
398
+ weights = torch.softmax(scores, dim=1)
399
+ pooled = (x * weights.unsqueeze(-1)).sum(dim=1)
400
+ return self.classifier(pooled)
401
+
402
+
403
+ def train_classifier(model_cls, train_x, train_y, test_x, test_y,
404
+ in_spec, n_epochs=200, lr=1e-2):
405
+ torch.manual_seed(42)
406
+ clf = model_cls(in_spec)
407
+ optimizer = torch.optim.Adam(clf.parameters(), lr=lr)
408
+ batch_size = 128
409
+ train_hist, test_hist = [], []
410
+ for epoch in range(n_epochs):
411
+ perm = torch.randperm(train_x.shape[0])
412
+ clf.train()
413
+ for i in range(0, train_x.shape[0], batch_size):
414
+ idx = perm[i:i + batch_size]
415
+ loss = F.cross_entropy(clf(train_x[idx]), train_y[idx])
416
+ optimizer.zero_grad(); loss.backward(); optimizer.step()
417
+ clf.eval()
418
+ with torch.no_grad():
419
+ train_acc = (clf(train_x).argmax(dim=1) == train_y).float().mean().item()
420
+ test_acc = (clf(test_x).argmax(dim=1) == test_y).float().mean().item()
421
+ train_hist.append(train_acc); test_hist.append(test_acc)
422
+
423
+ clf.eval()
424
+ with torch.no_grad():
425
+ preds = clf(test_x).argmax(dim=1)
426
+ classes = torch.unique(test_y).tolist()
427
+ per_class = {c: ((preds == test_y) & (test_y == c)).sum().item() /
428
+ max(1, (test_y == c).sum().item())
429
+ for c in classes}
430
+ return test_hist[-1], per_class, train_hist, test_hist
431
+
432
+
433
+ # ══════════════════════════════════════════════════════════════════════
434
+ # Train + compare against all priors
435
+ # ══════════════════════════════════════════════════════════════════════
436
+
437
+ ref_paths = {
438
+ 'cell_j': EXP_DIR / "results_expJ.json",
439
+ 'cell_jp': EXP_DIR / "results_expJ_axes.json",
440
+ 'cell_jpp': EXP_DIR / "results_expJ_vstats.json",
441
+ }
442
+ refs = {}
443
+ for k, p in ref_paths.items():
444
+ if p.exists():
445
+ with open(p) as f:
446
+ r = json.load(f)
447
+ refs[k] = {int(res): {'A': v['accuracy_A'], 'B': v['accuracy_B']}
448
+ for res, v in r['per_resolution'].items()}
449
+ print(f"\nLoaded {k}: {p}")
450
+
451
+ results = {}
452
+ for res in RESOLUTIONS:
453
+ print(f"\n{'─' * 78}")
454
+ print(f"Resolution {res}Γ—{res}")
455
+ print(f"{'─' * 78}")
456
+
457
+ n_items = features_A_by_res[res].shape[0]
458
+ rng = np.random.RandomState(42)
459
+ indices = rng.permutation(n_items)
460
+ n_train = int(n_items * 0.8)
461
+ train_idx, test_idx = indices[:n_train], indices[n_train:]
462
+ labels = labels_by_res[res]
463
+
464
+ # A'''
465
+ xA = features_A_by_res[res]
466
+ mA, sA = xA[train_idx].mean(dim=0), xA[train_idx].std(dim=0).clamp(min=1e-8)
467
+ xA = (xA - mA) / sA
468
+ accA, per_class_A, tA, vA = train_classifier(
469
+ SummaryMLP, xA[train_idx], labels[train_idx],
470
+ xA[test_idx], labels[test_idx], in_spec=xA.shape[1])
471
+
472
+ # B'''
473
+ xB = features_B_by_res[res]
474
+ flat = xB[train_idx].reshape(-1, xB.shape[-1])
475
+ mB, sB = flat.mean(dim=0), flat.std(dim=0).clamp(min=1e-8)
476
+ xB = (xB - mB) / sB
477
+ accB, per_class_B, tB, vB = train_classifier(
478
+ AttentionPoolMLP, xB[train_idx], labels[train_idx],
479
+ xB[test_idx], labels[test_idx], in_spec=xB.shape[-1])
480
+
481
+ print(f" A''' (per-patch summary): test={accA:.1%}")
482
+ if 'cell_j' in refs:
483
+ d = accA - refs['cell_j'][res]['A']
484
+ print(f" vs Cell J A (MSE): {refs['cell_j'][res]['A']:.1%} Ξ” {d:+.1%}")
485
+ if 'cell_jp' in refs:
486
+ d = accA - refs['cell_jp'][res]['A']
487
+ print(f" vs Cell J' A (max-axes): {refs['cell_jp'][res]['A']:.1%} Ξ” {d:+.1%}")
488
+ if 'cell_jpp' in refs:
489
+ d = accA - refs['cell_jpp'][res]['A']
490
+ print(f" vs Cell J'' A (V-stats): {refs['cell_jpp'][res]['A']:.1%} Ξ” {d:+.1%}")
491
+
492
+ print(f"\n B''' (per-patch attn): test={accB:.1%}")
493
+ if 'cell_j' in refs:
494
+ d = accB - refs['cell_j'][res]['B']
495
+ print(f" vs Cell J B (MSE): {refs['cell_j'][res]['B']:.1%} Ξ” {d:+.1%}")
496
+ if 'cell_jp' in refs:
497
+ d = accB - refs['cell_jp'][res]['B']
498
+ print(f" vs Cell J' B (max-axes): {refs['cell_jp'][res]['B']:.1%} Ξ” {d:+.1%}")
499
+ if 'cell_jpp' in refs:
500
+ d = accB - refs['cell_jpp'][res]['B']
501
+ print(f" vs Cell J'' B (V-stats): {refs['cell_jpp'][res]['B']:.1%} Ξ” {d:+.1%}")
502
+
503
+ print(f"\n {'Class':<22} {'A':>9} {'B':>9} {'Ξ”(B-A)':>9}")
504
+ for c in sorted(per_class_A.keys()):
505
+ a = per_class_A[c]; b = per_class_B.get(c, 0.0)
506
+ sym = '+' if b > a + 0.01 else '-' if b < a - 0.01 else ' '
507
+ print(f" {label_name(c):<22} {a:>9.1%} {b:>9.1%} {sym}{abs(b-a):>8.1%}")
508
+
509
+ results[res] = {
510
+ 'accuracy_A': accA, 'accuracy_B': accB,
511
+ 'per_class_A': {label_name(c): per_class_A[c] for c in per_class_A},
512
+ 'per_class_B': {label_name(c): per_class_B.get(c, 0.0) for c in per_class_A},
513
+ 'train_curve_A': tA, 'test_curve_A': vA,
514
+ 'train_curve_B': tB, 'test_curve_B': vB,
515
+ }
516
+
517
+
518
+ # ══════════════════════════════════════════════════════════════════════
519
+ # Plots + verdict
520
+ # ══════════════════════════════════════════════════════════════════════
521
+
522
+ fig, axes = plt.subplots(1, 2, figsize=(20, 6))
523
+ for idx, (clf_label, key_curve, key_acc) in enumerate(
524
+ [("A''' per-patch summary MLP", 'test_curve_A', 'accuracy_A'),
525
+ ("B''' per-patch attn-pool MLP", 'test_curve_B', 'accuracy_B')]
526
+ ):
527
+ ax = axes[idx]
528
+ for res in RESOLUTIONS:
529
+ ax.plot(results[res][key_curve],
530
+ label=f'{res} ({results[res][key_acc]:.1%})',
531
+ linewidth=1.5, alpha=0.85)
532
+ ax.axhline(1 / N_CLASSES, color='gray', linestyle='--', linewidth=1,
533
+ label=f'Random ({1/N_CLASSES:.1%})')
534
+ ax.set_xlabel('Epoch'); ax.set_ylabel('Test accuracy')
535
+ ax.set_title(clf_label)
536
+ ax.legend(loc='lower right'); ax.grid(linestyle=':', alpha=0.5)
537
+ ax.set_ylim(0, 1.05)
538
+ plt.tight_layout()
539
+ plt.savefig(EXP_DIR / 'expJ_perpatch_curves.png', dpi=120, bbox_inches='tight')
540
+ plt.show()
541
+
542
+
543
+ print(f"\n{'=' * 78}")
544
+ print(f"PHASE J''' VERDICT β€” per-patch axis features")
545
+ print(f"{'=' * 78}")
546
+
547
+ if 'cell_j' in refs:
548
+ print(f"\n{'Res':<6} | {'MSE':>7} {'maxax':>7} {'vstat':>7} {'perpatch':>9} "
549
+ f"| {'MSE':>7} {'maxax':>7} {'vstat':>7} {'perpatch':>9}")
550
+ print(f" | {'A':>7} {'A':>7} {'A':>7} {'A':>9} "
551
+ f"| {'B':>7} {'B':>7} {'B':>7} {'B':>9}")
552
+ print("-" * 100)
553
+ for res in RESOLUTIONS:
554
+ ja = refs['cell_j'][res]['A']; jb = refs['cell_j'][res]['B']
555
+ pa = refs.get('cell_jp', {}).get(res, {}).get('A', float('nan'))
556
+ pb = refs.get('cell_jp', {}).get(res, {}).get('B', float('nan'))
557
+ va = refs.get('cell_jpp', {}).get(res, {}).get('A', float('nan'))
558
+ vb = refs.get('cell_jpp', {}).get(res, {}).get('B', float('nan'))
559
+ ka = results[res]['accuracy_A']; kb = results[res]['accuracy_B']
560
+ print(f"{str(res):<6} | {ja:>6.1%} {pa:>6.1%} {va:>6.1%} {ka:>8.1%} "
561
+ f"| {jb:>6.1%} {pb:>6.1%} {vb:>6.1%} {kb:>8.1%}")
562
+
563
+ avg_dA_mse = np.mean([results[r]['accuracy_A'] - refs['cell_j'][r]['A']
564
+ for r in RESOLUTIONS])
565
+ avg_dB_mse = np.mean([results[r]['accuracy_B'] - refs['cell_j'][r]['B']
566
+ for r in RESOLUTIONS])
567
+
568
+ print(f"\nMean delta vs Cell J (MSE baseline):")
569
+ print(f" A (summary): {avg_dA_mse:+.1%}")
570
+ print(f" B (attn): {avg_dB_mse:+.1%}")
571
+
572
+ print()
573
+ if avg_dA_mse > 0.03 and avg_dB_mse > 0.03:
574
+ print("βœ“ PER-PATCH AXIS FEATURES BEAT MSE on both classifiers.")
575
+ print(" The 256Γ— spatial signal was the missing piece.")
576
+ elif avg_dA_mse > 0.03 or avg_dB_mse > 0.03:
577
+ print("~ PER-PATCH AXIS FEATURES BEAT MSE on one classifier.")
578
+ print(" Mixed result β€” investigate per-class.")
579
+ elif abs(avg_dA_mse) < 0.03 and abs(avg_dB_mse) < 0.03:
580
+ print("= PER-PATCH AXIS FEATURES MATCH MSE.")
581
+ print(" Comparable performance, axis pipeline now competitive.")
582
+ else:
583
+ print("βœ— PER-PATCH AXIS FEATURES UNDERPERFORM MSE.")
584
+ print(" Even with 256Γ— more spatial data, axes lose to MSE here.")
585
+ print(" Reconstruction error remains the structurally optimal signal")
586
+ print(" for noise discrimination given how the banks were trained.")
587
+
588
+ with open(EXP_DIR / 'results_expJ_perpatch.json', 'w') as f:
589
+ json.dump({
590
+ 'subset_battery_ids': SUBSET_BATTERY_IDS,
591
+ 'subset_phase': SUBSET_PHASE,
592
+ 'n_classes': N_CLASSES,
593
+ 'n_stats': N_STATS,
594
+ 'stat_names': ['max', 'mean', 'std', 'top10_mean', 'entropy'],
595
+ 'codebook_sizes': {bid: codebooks[bid].shape[0]
596
+ for bid in SUBSET_BATTERY_IDS},
597
+ 'codebook_calibration': 'mean+mean (per-patch averaging)',
598
+ 'max_axes_padded_to': MAX_AXES,
599
+ 'per_resolution': {
600
+ str(res): {
601
+ 'accuracy_A': results[res]['accuracy_A'],
602
+ 'accuracy_B': results[res]['accuracy_B'],
603
+ 'per_class_A': results[res]['per_class_A'],
604
+ 'per_class_B': results[res]['per_class_B'],
605
+ }
606
+ for res in RESOLUTIONS
607
+ },
608
+ }, f, indent=2, default=str)
609
+ print(f"\nSaved results_expJ_perpatch.json")