AbstractPhil commited on
Commit
3c5907a
·
verified ·
1 Parent(s): 4dea171

Create make_chart_1.py

Browse files
Files changed (1) hide show
  1. make_chart_1.py +420 -0
make_chart_1.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #@title MobiusNet Aggregate Analysis - 1024 Samples
2
+ !pip install -q datasets safetensors huggingface_hub
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from torch.utils.data import DataLoader
8
+ from datasets import load_dataset
9
+ from huggingface_hub import hf_hub_download
10
+ from safetensors.torch import load_file as load_safetensors
11
+ import matplotlib.pyplot as plt
12
+ import numpy as np
13
+ from sklearn.decomposition import PCA
14
+ from typing import Tuple
15
+ from collections import defaultdict
16
+ import math
17
+ import json
18
+
19
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
20
+
21
+ # ============================================================================
22
+ # MOBIUSNET (compact)
23
+ # ============================================================================
24
+
25
+ class MobiusLens(nn.Module):
26
+ def __init__(self, dim, layer_idx, total_layers, scale_range=(1.0, 9.0)):
27
+ super().__init__()
28
+ self.t = layer_idx / max(total_layers - 1, 1)
29
+ scale_span = scale_range[1] - scale_range[0]
30
+ step = scale_span / max(total_layers, 1)
31
+ self.register_buffer('scales', torch.tensor([scale_range[0] + self.t * scale_span,
32
+ scale_range[0] + self.t * scale_span + step]))
33
+ self.twist_in_angle = nn.Parameter(torch.tensor(self.t * math.pi))
34
+ self.twist_in_proj = nn.Linear(dim, dim, bias=False)
35
+ self.omega = nn.Parameter(torch.tensor(math.pi))
36
+ self.alpha = nn.Parameter(torch.tensor(1.5))
37
+ self.phase_l, self.drift_l = nn.Parameter(torch.zeros(2)), nn.Parameter(torch.ones(2))
38
+ self.phase_m, self.drift_m = nn.Parameter(torch.zeros(2)), nn.Parameter(torch.zeros(2))
39
+ self.phase_r, self.drift_r = nn.Parameter(torch.zeros(2)), nn.Parameter(-torch.ones(2))
40
+ self.accum_weights = nn.Parameter(torch.tensor([0.4, 0.2, 0.4]))
41
+ self.xor_weight = nn.Parameter(torch.tensor(0.7))
42
+ self.gate_norm = nn.LayerNorm(dim)
43
+ self.twist_out_angle = nn.Parameter(torch.tensor(-self.t * math.pi))
44
+ self.twist_out_proj = nn.Linear(dim, dim, bias=False)
45
+
46
+ def forward(self, x):
47
+ cos_t, sin_t = torch.cos(self.twist_in_angle), torch.sin(self.twist_in_angle)
48
+ x = x * cos_t + self.twist_in_proj(x) * sin_t
49
+ x_norm = torch.tanh(x)
50
+ t = x_norm.abs().mean(dim=-1, keepdim=True).unsqueeze(-2)
51
+ x_exp = x_norm.unsqueeze(-2)
52
+ s = self.scales.view(-1, 1)
53
+ def wave(phase, drift):
54
+ a = self.alpha.abs() + 0.1
55
+ pos = s * self.omega * (x_exp + drift.view(-1, 1) * t) + phase.view(-1, 1)
56
+ return torch.exp(-a * torch.sin(pos).pow(2)).prod(dim=-2)
57
+ L, M, R = wave(self.phase_l, self.drift_l), wave(self.phase_m, self.drift_m), wave(self.phase_r, self.drift_r)
58
+ w = torch.softmax(self.accum_weights, dim=0)
59
+ xor_w = torch.sigmoid(self.xor_weight)
60
+ lr = xor_w * (L + R - 2*L*R).abs() + (1 - xor_w) * L * R
61
+ gate = torch.sigmoid(self.gate_norm((w[0]*L + w[1]*M + w[2]*R) * (0.5 + 0.5*lr)))
62
+ x = x * gate
63
+ cos_t, sin_t = torch.cos(self.twist_out_angle), torch.sin(self.twist_out_angle)
64
+ return x * cos_t + self.twist_out_proj(x) * sin_t, gate
65
+
66
+ class MobiusConvBlock(nn.Module):
67
+ def __init__(self, channels, layer_idx, total_layers, scale_range=(1.0, 9.0), reduction=0.5):
68
+ super().__init__()
69
+ self.conv = nn.Sequential(nn.Conv2d(channels, channels, 3, padding=1, groups=channels, bias=False),
70
+ nn.Conv2d(channels, channels, 1, bias=False), nn.BatchNorm2d(channels))
71
+ self.lens = MobiusLens(channels, layer_idx, total_layers, scale_range)
72
+ third = channels // 3
73
+ which_third = layer_idx % 3
74
+ mask = torch.ones(channels)
75
+ mask[which_third*third : which_third*third + third + (channels%3 if which_third==2 else 0)] = reduction
76
+ self.register_buffer('thirds_mask', mask.view(1, -1, 1, 1))
77
+ self.residual_weight = nn.Parameter(torch.tensor(0.9))
78
+
79
+ def forward(self, x):
80
+ identity = x
81
+ h = self.conv(x).permute(0, 2, 3, 1)
82
+ h, gate = self.lens(h)
83
+ h = h.permute(0, 3, 1, 2) * self.thirds_mask
84
+ rw = torch.sigmoid(self.residual_weight)
85
+ return rw * identity + (1 - rw) * h, gate
86
+
87
+ class MobiusNet(nn.Module):
88
+ def __init__(self, in_chans=1, num_classes=1000, channels=(64,128,256),
89
+ depths=(2,2,2), scale_range=(0.5,2.5), use_integrator=True):
90
+ super().__init__()
91
+ total_layers = sum(depths)
92
+ channels = list(channels)
93
+ self.stem = nn.Sequential(nn.Conv2d(in_chans, channels[0], 3, padding=1, bias=False), nn.BatchNorm2d(channels[0]))
94
+ self.stages = nn.ModuleList()
95
+ self.downsamples = nn.ModuleList()
96
+ layer_idx = 0
97
+ for si, d in enumerate(depths):
98
+ self.stages.append(nn.ModuleList([MobiusConvBlock(channels[si], layer_idx+i, total_layers, scale_range) for i in range(d)]))
99
+ layer_idx += d
100
+ if si < len(depths)-1:
101
+ self.downsamples.append(nn.Sequential(nn.Conv2d(channels[si], channels[si+1], 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(channels[si+1])))
102
+ self.integrator = nn.Sequential(nn.Conv2d(channels[-1], channels[-1], 3, padding=1, bias=False), nn.BatchNorm2d(channels[-1]), nn.GELU()) if use_integrator else nn.Identity()
103
+ self.pool = nn.AdaptiveAvgPool2d(1)
104
+ self.head = nn.Linear(channels[-1], num_classes)
105
+
106
+ def forward_with_intermediates(self, x):
107
+ out = {'input': x, 'stem': None, 'stages': [], 'gates': [], 'final': None}
108
+ x = self.stem(x)
109
+ out['stem'] = x
110
+ for i, stage in enumerate(self.stages):
111
+ acts, gates = [], []
112
+ for block in stage:
113
+ x, g = block(x)
114
+ acts.append(x)
115
+ gates.append(g)
116
+ out['stages'].append(acts)
117
+ out['gates'].append(gates)
118
+ if i < len(self.downsamples):
119
+ x = self.downsamples[i](x)
120
+ x = self.integrator(x)
121
+ out['final'] = x
122
+ return self.head(self.pool(x).flatten(1)), out
123
+
124
+ # ============================================================================
125
+ # LOAD MODEL
126
+ # ============================================================================
127
+
128
+ print("Loading model...")
129
+ config_path = hf_hub_download("AbstractPhil/mobiusnet-distillations",
130
+ "checkpoints/mobius_tiny_s_imagenet_clip_vit_l14/20260111_000512/config.json")
131
+ with open(config_path) as f:
132
+ config = json.load(f)
133
+ model_path = hf_hub_download("AbstractPhil/mobiusnet-distillations",
134
+ "checkpoints/mobius_tiny_s_imagenet_clip_vit_l14/20260111_000512/checkpoints/best_model.safetensors")
135
+
136
+ cfg = config['model']
137
+ model = MobiusNet(cfg['in_chans'], cfg['num_classes'], tuple(cfg['channels']),
138
+ tuple(cfg['depths']), tuple(cfg['scale_range']), cfg['use_integrator']).to(device)
139
+ model.load_state_dict(load_safetensors(model_path))
140
+ model.eval()
141
+ print(f"✓ Loaded MobiusNet")
142
+
143
+ # ============================================================================
144
+ # AGGREGATE OVER 1024 SAMPLES
145
+ # ============================================================================
146
+
147
+ print("\nProcessing 1024 samples...")
148
+ ds = load_dataset("AbstractPhil/imagenet-clip-features-orderly", "clip_vit_l14",
149
+ split="validation", streaming=True).with_format("torch")
150
+ loader = DataLoader(ds, batch_size=64)
151
+
152
+ # Accumulators
153
+ n_samples = 0
154
+ total_correct = 0
155
+ agg = {
156
+ 'input': {'sum': None, 'sum_sq': None},
157
+ 'stem': {'sum': None, 'sum_sq': None},
158
+ 'final': {'sum': None, 'sum_sq': None},
159
+ }
160
+ gate_stats = defaultdict(lambda: {'sum': 0, 'sum_sq': 0, 'min': float('inf'), 'max': float('-inf'), 'count': 0})
161
+ stage_stats = defaultdict(lambda: {'sum': None, 'sum_sq': None})
162
+
163
+ # Class-wise gate means
164
+ class_gate_means = defaultdict(lambda: defaultdict(list))
165
+
166
+ for batch_idx, batch in enumerate(loader):
167
+ if n_samples >= 1024:
168
+ break
169
+
170
+ features = batch['clip_features'].view(-1, 1, 24, 32).to(device)
171
+ labels = batch['label'].to(device)
172
+ bs = features.shape[0]
173
+
174
+ with torch.no_grad():
175
+ logits, intermediates = model.forward_with_intermediates(features)
176
+ preds = logits.argmax(dim=-1)
177
+ total_correct += (preds == labels).sum().item()
178
+
179
+ # Aggregate inputs, stem, final
180
+ for key in ['input', 'stem', 'final']:
181
+ tensor = intermediates[key].detach()
182
+ if agg[key]['sum'] is None:
183
+ agg[key]['sum'] = tensor.sum(dim=0)
184
+ agg[key]['sum_sq'] = (tensor ** 2).sum(dim=0)
185
+ else:
186
+ agg[key]['sum'] += tensor.sum(dim=0)
187
+ agg[key]['sum_sq'] += (tensor ** 2).sum(dim=0)
188
+
189
+ # Aggregate gates and stages
190
+ for si, (acts, gates) in enumerate(zip(intermediates['stages'], intermediates['gates'])):
191
+ for bi, (act, gate) in enumerate(zip(acts, gates)):
192
+ key = f"S{si}B{bi}"
193
+
194
+ # Gate stats
195
+ g = gate.detach()
196
+ gate_stats[key]['sum'] += g.mean().item() * bs
197
+ gate_stats[key]['sum_sq'] += (g.mean(dim=(1,2,3)) ** 2).sum().item()
198
+ gate_stats[key]['min'] = min(gate_stats[key]['min'], g.min().item())
199
+ gate_stats[key]['max'] = max(gate_stats[key]['max'], g.max().item())
200
+ gate_stats[key]['count'] += bs
201
+
202
+ # Stage activation stats
203
+ a = act.detach()
204
+ if stage_stats[key]['sum'] is None:
205
+ stage_stats[key]['sum'] = a.sum(dim=0)
206
+ stage_stats[key]['sum_sq'] = (a ** 2).sum(dim=0)
207
+ else:
208
+ stage_stats[key]['sum'] += a.sum(dim=0)
209
+ stage_stats[key]['sum_sq'] += (a ** 2).sum(dim=0)
210
+
211
+ # Per-class gate means
212
+ for i in range(bs):
213
+ lbl = labels[i].item()
214
+ class_gate_means[key][lbl].append(g[i].mean().item())
215
+
216
+ n_samples += bs
217
+ if (batch_idx + 1) % 4 == 0:
218
+ print(f" Processed {n_samples} samples...")
219
+
220
+ print(f"\n✓ Processed {n_samples} samples")
221
+ print(f"✓ Overall accuracy: {total_correct / n_samples:.2%}")
222
+
223
+ # ============================================================================
224
+ # COMPUTE MEANS AND STDS
225
+ # ============================================================================
226
+
227
+ def compute_mean_std(agg_dict, n):
228
+ mean = agg_dict['sum'] / n
229
+ std = torch.sqrt(agg_dict['sum_sq'] / n - mean ** 2 + 1e-8)
230
+ return mean.cpu().numpy(), std.cpu().numpy()
231
+
232
+ input_mean, input_std = compute_mean_std(agg['input'], n_samples)
233
+ stem_mean, stem_std = compute_mean_std(agg['stem'], n_samples)
234
+ final_mean, final_std = compute_mean_std(agg['final'], n_samples)
235
+
236
+ stage_means, stage_stds = {}, {}
237
+ for key in stage_stats:
238
+ stage_means[key], stage_stds[key] = compute_mean_std(stage_stats[key], n_samples)
239
+
240
+ # ============================================================================
241
+ # VISUALIZATION
242
+ # ============================================================================
243
+
244
+ fig = plt.figure(figsize=(24, 18))
245
+
246
+ # Row 1: Input/Stem aggregates
247
+ ax = fig.add_subplot(4, 6, 1)
248
+ ax.imshow(input_mean[0], cmap='viridis', aspect='auto')
249
+ ax.set_title(f"Input Mean\n[1×24×32]", fontsize=10)
250
+ ax.axis('off')
251
+
252
+ ax = fig.add_subplot(4, 6, 2)
253
+ ax.imshow(input_std[0], cmap='magma', aspect='auto')
254
+ ax.set_title(f"Input Std\nσ={input_std.mean():.4f}", fontsize=10)
255
+ ax.axis('off')
256
+
257
+ ax = fig.add_subplot(4, 6, 3)
258
+ pca = PCA(n_components=3)
259
+ stem_pca = pca.fit_transform(stem_mean.reshape(64, -1).T).reshape(24, 32, 3)
260
+ stem_pca = (stem_pca - stem_pca.min()) / (stem_pca.max() - stem_pca.min() + 1e-8)
261
+ ax.imshow(stem_pca, aspect='auto')
262
+ ax.set_title(f"Stem Mean PCA\n({pca.explained_variance_ratio_.sum()*100:.1f}%)", fontsize=10)
263
+ ax.axis('off')
264
+
265
+ ax = fig.add_subplot(4, 6, 4)
266
+ ax.imshow(stem_std.mean(axis=0), cmap='magma', aspect='auto')
267
+ ax.set_title(f"Stem Std (avg ch)\nσ={stem_std.mean():.4f}", fontsize=10)
268
+ ax.axis('off')
269
+
270
+ ax = fig.add_subplot(4, 6, 5)
271
+ pca = PCA(n_components=3)
272
+ final_pca = pca.fit_transform(final_mean.reshape(256, -1).T).reshape(6, 8, 3)
273
+ final_pca = (final_pca - final_pca.min()) / (final_pca.max() - final_pca.min() + 1e-8)
274
+ ax.imshow(final_pca, aspect='auto')
275
+ ax.set_title(f"Final Mean PCA\n({pca.explained_variance_ratio_.sum()*100:.1f}%)", fontsize=10)
276
+ ax.axis('off')
277
+
278
+ ax = fig.add_subplot(4, 6, 6)
279
+ ax.imshow(np.linalg.norm(final_mean, axis=0), cmap='hot', aspect='auto')
280
+ ax.set_title(f"Final Mean L2\nμ={np.linalg.norm(final_mean, axis=0).mean():.2f}", fontsize=10)
281
+ ax.axis('off')
282
+
283
+ # Row 2: Stage means
284
+ for i, key in enumerate(['S0B0', 'S0B1', 'S1B0', 'S1B1', 'S2B0', 'S2B1']):
285
+ ax = fig.add_subplot(4, 6, 7 + i)
286
+ m = stage_means[key]
287
+ pca = PCA(n_components=3)
288
+ m_pca = pca.fit_transform(m.reshape(m.shape[0], -1).T).reshape(m.shape[1], m.shape[2], 3)
289
+ m_pca = (m_pca - m_pca.min()) / (m_pca.max() - m_pca.min() + 1e-8)
290
+ ax.imshow(m_pca, aspect='auto')
291
+ ax.set_title(f"{key} Mean\n[{m.shape[0]}×{m.shape[1]}×{m.shape[2]}]", fontsize=10)
292
+ ax.axis('off')
293
+
294
+ # Row 3: Stage stds + Gate summary
295
+ for i, key in enumerate(['S0B0', 'S0B1', 'S1B0', 'S1B1', 'S2B0', 'S2B1']):
296
+ ax = fig.add_subplot(4, 6, 13 + i)
297
+ s = stage_stds[key]
298
+ ax.imshow(s.mean(axis=0), cmap='magma', aspect='auto')
299
+ gs = gate_stats[key]
300
+ gate_mean = gs['sum'] / gs['count']
301
+ ax.set_title(f"{key} Std | Gate μ={gate_mean:.3f}\nrange=[{gs['min']:.2f}, {gs['max']:.2f}]", fontsize=9)
302
+ ax.axis('off')
303
+
304
+ # Row 4: Analysis plots
305
+ ax = fig.add_subplot(4, 6, 19)
306
+ keys = ['S0B0', 'S0B1', 'S1B0', 'S1B1', 'S2B0', 'S2B1']
307
+ gate_means_plot = [gate_stats[k]['sum'] / gate_stats[k]['count'] for k in keys]
308
+ gate_mins = [gate_stats[k]['min'] for k in keys]
309
+ gate_maxs = [gate_stats[k]['max'] for k in keys]
310
+ x = np.arange(len(keys))
311
+ ax.bar(x, gate_means_plot, color='steelblue', alpha=0.7)
312
+ ax.errorbar(x, gate_means_plot, yerr=[np.array(gate_means_plot) - gate_mins, np.array(gate_maxs) - gate_means_plot],
313
+ fmt='none', color='black', capsize=3)
314
+ ax.set_xticks(x)
315
+ ax.set_xticklabels(keys, fontsize=9)
316
+ ax.set_ylabel('Gate Activation')
317
+ ax.set_title('Gate Means (± range)', fontsize=10)
318
+ ax.set_ylim(0, 1)
319
+
320
+ # Lens parameters
321
+ ax = fig.add_subplot(4, 6, 20)
322
+ lens_data = []
323
+ for si, stage in enumerate(model.stages):
324
+ for bi, block in enumerate(stage):
325
+ L = block.lens
326
+ lens_data.append({
327
+ 'name': f"S{si}B{bi}",
328
+ 'omega': L.omega.item(),
329
+ 'alpha': L.alpha.item(),
330
+ 'xor': torch.sigmoid(L.xor_weight).item()
331
+ })
332
+ omegas = [d['omega'] for d in lens_data]
333
+ alphas = [d['alpha'] for d in lens_data]
334
+ xors = [d['xor'] for d in lens_data]
335
+ x = np.arange(len(lens_data))
336
+ width = 0.25
337
+ ax.bar(x - width, omegas, width, label='ω', alpha=0.7)
338
+ ax.bar(x, alphas, width, label='α', alpha=0.7)
339
+ ax.bar(x + width, xors, width, label='xor', alpha=0.7)
340
+ ax.set_xticks(x)
341
+ ax.set_xticklabels([d['name'] for d in lens_data], fontsize=9)
342
+ ax.legend(fontsize=8)
343
+ ax.set_title('Lens Parameters', fontsize=10)
344
+
345
+ # Distribution flow
346
+ ax = fig.add_subplot(4, 6, 21)
347
+ flow_labels = ['Input', 'Stem'] + keys + ['Final']
348
+ flow_stds = [input_std.std(), stem_std.std()] + [stage_stds[k].std() for k in keys] + [final_std.std()]
349
+ ax.plot(flow_labels, flow_stds, 'o-', color='purple', linewidth=2, markersize=8)
350
+ ax.set_ylabel('Std of Std')
351
+ ax.set_title('Activation Variance Flow', fontsize=10)
352
+ ax.tick_params(axis='x', rotation=45)
353
+
354
+ # Per-class gate variance (are gates class-specific?)
355
+ ax = fig.add_subplot(4, 6, 22)
356
+ class_variance = []
357
+ for key in keys:
358
+ per_class = class_gate_means[key]
359
+ class_means = [np.mean(v) for v in per_class.values() if len(v) > 0]
360
+ class_variance.append(np.std(class_means) if len(class_means) > 1 else 0)
361
+ ax.bar(keys, class_variance, color='coral', alpha=0.7)
362
+ ax.set_ylabel('Std of Class Gate Means')
363
+ ax.set_title('Gate Class-Specificity', fontsize=10)
364
+ ax.tick_params(axis='x', rotation=45)
365
+
366
+ # Accuracy bar
367
+ ax = fig.add_subplot(4, 6, 23)
368
+ ax.bar(['Accuracy'], [total_correct / n_samples], color='green', alpha=0.7)
369
+ ax.set_ylim(0, 1)
370
+ ax.set_title(f'Overall: {total_correct / n_samples:.1%}\n({total_correct}/{n_samples})', fontsize=10)
371
+
372
+ # Summary text
373
+ ax = fig.add_subplot(4, 6, 24)
374
+ summary = f"""AGGREGATE STATS (n={n_samples})
375
+
376
+ Input: μ={input_mean.mean():.6f}, σ={input_std.mean():.6f}
377
+ Stem: μ={stem_mean.mean():.6f}, σ={stem_std.mean():.4f}
378
+ Final: μ={final_mean.mean():.4f}, σ={final_std.mean():.4f}
379
+
380
+ Gate Progression:
381
+ S0: {gate_means_plot[0]:.3f} → {gate_means_plot[1]:.3f}
382
+ S1: {gate_means_plot[2]:.3f} → {gate_means_plot[3]:.3f}
383
+ S2: {gate_means_plot[4]:.3f} → {gate_means_plot[5]:.3f}
384
+
385
+ Accuracy: {total_correct / n_samples:.2%}
386
+ """
387
+ ax.text(0.05, 0.95, summary, transform=ax.transAxes, fontsize=9,
388
+ va='top', family='monospace')
389
+ ax.set_title('Summary', fontsize=10)
390
+ ax.axis('off')
391
+
392
+ plt.suptitle(f'MobiusNet Aggregate Analysis: {n_samples} Samples from CLIP-ViT-L14 Features', fontsize=14, fontweight='bold')
393
+ plt.tight_layout()
394
+ plt.savefig("mobiusnet_aggregate_1024.png", dpi=150, bbox_inches="tight")
395
+ plt.show()
396
+
397
+ # ============================================================================
398
+ # PRINT DETAILED STATS
399
+ # ============================================================================
400
+
401
+ print(f"\n{'='*70}")
402
+ print(f"AGGREGATE STATISTICS ({n_samples} samples)")
403
+ print(f"{'='*70}")
404
+
405
+ print(f"\nActivation Flow:")
406
+ print(f" Input: μ={input_mean.mean():.6f}, σ={input_std.mean():.6f}")
407
+ print(f" Stem: μ={stem_mean.mean():.6f}, σ={stem_std.mean():.6f}")
408
+ for key in keys:
409
+ m, s = stage_means[key], stage_stds[key]
410
+ print(f" {key}: μ={m.mean():.6f}, σ={s.mean():.6f}")
411
+ print(f" Final: μ={final_mean.mean():.6f}, σ={final_std.mean():.6f}")
412
+
413
+ print(f"\nGate Statistics:")
414
+ for key in keys:
415
+ gs = gate_stats[key]
416
+ print(f" {key}: μ={gs['sum']/gs['count']:.4f}, range=[{gs['min']:.3f}, {gs['max']:.3f}]")
417
+
418
+ print(f"\nClass-Specificity (std of per-class gate means):")
419
+ for i, key in enumerate(keys):
420
+ print(f" {key}: {class_variance[i]:.6f}")