AbstractPhil commited on
Commit
3d6538d
Β·
verified Β·
1 Parent(s): 30e35e9

Create model_code.py

Browse files
Files changed (1) hide show
  1. model_code.py +416 -0
model_code.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
2
+ # MIXING AUGMENTATIONS
3
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
4
+
5
+ def alphamix_data(x, y, alpha_range=(0.3, 0.7), spatial_ratio=0.25):
6
+ """
7
+ Standard AlphaMix: Single spatially localized transparent overlay.
8
+ """
9
+ batch_size = x.size(0)
10
+ index = torch.randperm(batch_size, device=x.device)
11
+
12
+ y_a, y_b = y, y[index]
13
+
14
+ # Sample alpha from Beta distribution
15
+ alpha_min, alpha_max = alpha_range
16
+ beta_sample = torch.distributions.Beta(2.0, 2.0).sample().item()
17
+ alpha = alpha_min + (alpha_max - alpha_min) * beta_sample
18
+
19
+ # Compute overlay region
20
+ _, _, H, W = x.shape
21
+ overlay_ratio = torch.sqrt(torch.tensor(spatial_ratio)).item()
22
+ overlay_h = int(H * overlay_ratio)
23
+ overlay_w = int(W * overlay_ratio)
24
+
25
+ top = torch.randint(0, H - overlay_h + 1, (1,), device=x.device).item()
26
+ left = torch.randint(0, W - overlay_w + 1, (1,), device=x.device).item()
27
+
28
+ # Blend
29
+ composited_x = x.clone()
30
+ overlay_region = alpha * x[:, :, top:top+overlay_h, left:left+overlay_w]
31
+ background_region = (1 - alpha) * x[index, :, top:top+overlay_h, left:left+overlay_w]
32
+ composited_x[:, :, top:top+overlay_h, left:left+overlay_w] = overlay_region + background_region
33
+
34
+ return composited_x, y_a, y_b, alpha
35
+
36
+
37
+ def alphamix_fractal(
38
+ x: torch.Tensor,
39
+ y: torch.Tensor,
40
+ alpha_range=(0.3, 0.7),
41
+ steps_range=(1, 3),
42
+ triad_scales=(1/3, 1/9, 1/27),
43
+ beta_shape=(2.0, 2.0),
44
+ seed: int | None = None,
45
+ ):
46
+ """
47
+ Fractal AlphaMix: Triadic multi-patch overlays aligned to Cantor geometry.
48
+ Pure torch, GPU-compatible.
49
+ """
50
+ if seed is not None:
51
+ torch.manual_seed(seed)
52
+
53
+ B, C, H, W = x.shape
54
+ device = x.device
55
+
56
+ # Permutation for mixing
57
+ idx = torch.randperm(B, device=device)
58
+ y_a, y_b = y, y[idx]
59
+
60
+ x_mix = x.clone()
61
+ total_area = H * W
62
+
63
+ # Beta distribution for transparency sampling
64
+ k1, k2 = beta_shape
65
+ beta_dist = torch.distributions.Beta(k1, k2)
66
+ alpha_min, alpha_max = alpha_range
67
+
68
+ # Storage for effective alpha calculation
69
+ alpha_elems = []
70
+ area_weights = []
71
+
72
+ # Sample number of patches (same for all images in batch)
73
+ steps = torch.randint(steps_range[0], steps_range[1] + 1, (1,), device=device).item()
74
+
75
+ for _ in range(steps):
76
+ # Choose triadic scale
77
+ scale_idx = torch.randint(0, len(triad_scales), (1,), device=device).item()
78
+ scale = triad_scales[scale_idx]
79
+
80
+ # Compute patch dimensions (triadic area)
81
+ patch_area = max(1, int(total_area * scale))
82
+ side = int(torch.sqrt(torch.tensor(patch_area, dtype=torch.float32)).item())
83
+ h = max(1, min(H, side))
84
+ w = max(1, min(W, side))
85
+
86
+ # Random position
87
+ top = torch.randint(0, H - h + 1, (1,), device=device).item()
88
+ left = torch.randint(0, W - w + 1, (1,), device=device).item()
89
+
90
+ # Sample transparency from Beta distribution
91
+ alpha_raw = beta_dist.sample().item()
92
+ alpha = alpha_min + (alpha_max - alpha_min) * alpha_raw
93
+
94
+ # Track for effective alpha
95
+ alpha_elems.append(alpha)
96
+ area_weights.append(h * w)
97
+
98
+ # Blend patches
99
+ fg = alpha * x[:, :, top:top + h, left:left + w]
100
+ bg = (1 - alpha) * x[idx, :, top:top + h, left:left + w]
101
+ x_mix[:, :, top:top + h, left:left + w] = fg + bg
102
+
103
+ # Compute area-weighted effective alpha
104
+ alpha_t = torch.tensor(alpha_elems, dtype=torch.float32, device=device)
105
+ area_t = torch.tensor(area_weights, dtype=torch.float32, device=device)
106
+ alpha_eff = (alpha_t * area_t).sum() / (area_t.sum() + 1e-12)
107
+ alpha_eff = alpha_eff.item()
108
+
109
+ return x_mix, y_a, y_b, alpha_eff
110
+
111
+
112
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
113
+ # DEVIL'S STAIRCASE PE
114
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
115
+
116
+ class DevilStaircasePE(nn.Module):
117
+ """Devil's Staircase PE - VECTORIZED for GPU."""
118
+
119
+ def __init__(self, levels=20, features_per_level=4, smooth_tau=0.25, base=3):
120
+ super().__init__()
121
+ self.levels = levels
122
+ self.features_per_level = features_per_level
123
+ self.tau = smooth_tau
124
+ self.base = base
125
+
126
+ self.alpha = nn.Parameter(torch.tensor(0.1))
127
+
128
+ # Precompute level scales and powers
129
+ self.register_buffer('k_range', torch.arange(1, levels + 1, dtype=torch.float32))
130
+ self.register_buffer('cantor_powers', 0.5 ** self.k_range)
131
+
132
+ self.base_features = 2
133
+ if features_per_level > 2:
134
+ self.feature_expansion = nn.Linear(self.base_features, features_per_level)
135
+ else:
136
+ self.feature_expansion = None
137
+
138
+ def forward(self, positions, seq_len):
139
+ B = positions.shape[0]
140
+ device = positions.device
141
+
142
+ x = positions.float() / max(1, (seq_len - 1))
143
+ x = x.clamp(1e-6, 1.0 - 1e-6) # [B]
144
+
145
+ # VECTORIZED: Compute all levels at once
146
+ scales = self.base ** self.k_range.to(device) # [levels]
147
+ y = (x.unsqueeze(1) * scales.unsqueeze(0)) % self.base # [B, levels]
148
+
149
+ # VECTORIZED: Triadic softmax for all levels
150
+ centers = torch.tensor([0.5, 1.5, 2.5], device=device, dtype=x.dtype)
151
+ d2 = (y.unsqueeze(-1) - centers) ** 2 # [B, levels, 3]
152
+ logits = -d2 / (self.tau + 1e-8)
153
+ p = F.softmax(logits, dim=-1) # [B, levels, 3]
154
+
155
+ # VECTORIZED: Cantor bits
156
+ bit_k = p[..., 2] + self.alpha * p[..., 1] # [B, levels]
157
+
158
+ # VECTORIZED: Cantor sum (single matmul instead of loop)
159
+ Cx = (bit_k * self.cantor_powers.to(device).unsqueeze(0)).sum(dim=1) # [B]
160
+
161
+ # VECTORIZED: Entropy and PDF
162
+ ent = -(p * p.clamp_min(1e-8).log()).sum(dim=-1) # [B, levels]
163
+ pdf_proxy = 1.1 - ent / math.log(3.0) # [B, levels]
164
+
165
+ # Stack features
166
+ base_feat = torch.stack([bit_k, pdf_proxy], dim=-1) # [B, levels, 2]
167
+
168
+ if self.feature_expansion is not None:
169
+ # [B, levels, 2] -> [B, levels, features_per_level]
170
+ pe_levels = self.feature_expansion(base_feat)
171
+ else:
172
+ pe_levels = base_feat
173
+
174
+ return pe_levels, Cx
175
+
176
+
177
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
178
+ # GEOMETRIC BASIN COMPATIBILITY
179
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
180
+
181
+ class GeometricBasinCompatibility(nn.Module):
182
+ """Compute geometric compatibility scores - 4-factor product."""
183
+
184
+ def __init__(self, num_classes=100, pe_levels=20, features_per_level=4):
185
+ super().__init__()
186
+
187
+ self.num_classes = num_classes
188
+ self.pe_levels = pe_levels
189
+ self.features_per_level = features_per_level
190
+
191
+ self.class_signatures = nn.Parameter(
192
+ torch.randn(num_classes, pe_levels, features_per_level) * 0.1
193
+ )
194
+
195
+ self.cantor_prototypes = nn.Parameter(
196
+ torch.linspace(0.0, 1.0, num_classes)
197
+ )
198
+
199
+ self.level_resonance = nn.Parameter(
200
+ torch.ones(num_classes, pe_levels) / pe_levels
201
+ )
202
+
203
+ def forward(self, pe_levels, cantor_measures):
204
+ B = pe_levels.shape[0]
205
+
206
+ # 1. TRIADIC COMPATIBILITY
207
+ pe_norm = F.normalize(pe_levels, p=2, dim=-1)
208
+ sig_norm = F.normalize(self.class_signatures, p=2, dim=-1)
209
+
210
+ similarities = torch.einsum('blf,clf->bcl', pe_norm, sig_norm)
211
+ similarities = (similarities + 1) / 2
212
+
213
+ resonance = F.softmax(self.level_resonance, dim=-1)
214
+ triadic_compat = (similarities * resonance.unsqueeze(0)).sum(dim=-1)
215
+
216
+ # 2. SELF-SIMILARITY - VECTORIZED
217
+ level_k = pe_levels[:, :-1, :] # [B, 19, features] - all levels except last
218
+ level_k1 = pe_levels[:, 1:, :] # [B, 19, features] - all levels except first
219
+
220
+ # Compute all pairwise similarities at once
221
+ sim = F.cosine_similarity(level_k, level_k1, dim=-1, eps=1e-8) # [B, 19]
222
+ sim = (sim + 1) / 2
223
+ self_sim_pattern = sim # No stack needed, already [B, levels-1]
224
+
225
+ expected_patterns = torch.sigmoid(
226
+ self.level_resonance[:, :-1] - self.level_resonance[:, 1:]
227
+ )
228
+
229
+ pattern_diff = torch.abs(
230
+ self_sim_pattern.unsqueeze(1) - expected_patterns.unsqueeze(0)
231
+ )
232
+ self_sim_compat = 1 - pattern_diff.mean(dim=-1)
233
+ self_sim_compat = torch.clamp(self_sim_compat, 0.0, 1.0)
234
+
235
+ # 3. CANTOR COHERENCE
236
+ distances = torch.abs(
237
+ cantor_measures.unsqueeze(1) - self.cantor_prototypes.unsqueeze(0)
238
+ )
239
+ cantor_compat = torch.exp(-distances ** 2 / 0.1) + 1e-8
240
+
241
+ # 4. HIERARCHICAL CHECK
242
+ split_point = self.pe_levels // 2
243
+ early_levels = pe_levels[:, :split_point, :].mean(dim=1)
244
+ late_levels = pe_levels[:, split_point:, :].mean(dim=1)
245
+
246
+ early_targets = self.class_signatures[:, :split_point, :].mean(dim=1)
247
+ late_targets = self.class_signatures[:, split_point:, :].mean(dim=1)
248
+
249
+ early_levels_norm = F.normalize(early_levels, p=2, dim=-1)
250
+ late_levels_norm = F.normalize(late_levels, p=2, dim=-1)
251
+ early_targets_norm = F.normalize(early_targets, p=2, dim=-1)
252
+ late_targets_norm = F.normalize(late_targets, p=2, dim=-1)
253
+
254
+ early_compat = torch.matmul(early_levels_norm, early_targets_norm.t())
255
+ late_compat = torch.matmul(late_levels_norm, late_targets_norm.t())
256
+
257
+ early_compat = (early_compat + 1) / 2
258
+ late_compat = (late_compat + 1) / 2
259
+ hier_compat = (early_compat + late_compat) / 2
260
+
261
+ # 5. COMBINE (geometric mean)
262
+ eps = 1e-6
263
+ triadic_compat = torch.clamp(triadic_compat, eps, 1.0)
264
+ self_sim_compat = torch.clamp(self_sim_compat, eps, 1.0)
265
+ cantor_compat = torch.clamp(cantor_compat, eps, 1.0)
266
+ hier_compat = torch.clamp(hier_compat, eps, 1.0)
267
+
268
+ compatibility_scores = (
269
+ triadic_compat *
270
+ self_sim_compat *
271
+ cantor_compat *
272
+ hier_compat
273
+ ) ** 0.25
274
+
275
+ return compatibility_scores
276
+
277
+
278
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
279
+ # GEOMETRIC BASIN LOSS
280
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
281
+
282
+ class GeometricBasinLoss(nn.Module):
283
+ """Loss supervising geometric basin stability field."""
284
+
285
+ def __init__(self, temperature=0.1):
286
+ super().__init__()
287
+ self.temperature = temperature
288
+
289
+ def forward(self, compatibility_scores, labels, mixed_labels=None, lam=None):
290
+ batch_size = compatibility_scores.shape[0]
291
+
292
+ if mixed_labels is not None and lam is not None:
293
+ primary_compat = compatibility_scores[torch.arange(batch_size), labels]
294
+ secondary_compat = compatibility_scores[torch.arange(batch_size), mixed_labels]
295
+
296
+ primary_loss = F.mse_loss(primary_compat, torch.full_like(primary_compat, lam))
297
+ secondary_loss = F.mse_loss(secondary_compat, torch.full_like(secondary_compat, 1 - lam))
298
+
299
+ soft_targets = torch.zeros_like(compatibility_scores)
300
+ soft_targets[torch.arange(batch_size), labels] = lam
301
+ soft_targets[torch.arange(batch_size), mixed_labels] = 1 - lam
302
+
303
+ compat_normalized = compatibility_scores / (compatibility_scores.sum(dim=1, keepdim=True) + 1e-8)
304
+ kl_loss = F.kl_div(
305
+ compat_normalized.log(),
306
+ soft_targets,
307
+ reduction='batchmean'
308
+ )
309
+
310
+ total_loss = primary_loss + secondary_loss + 0.1 * kl_loss
311
+
312
+ else:
313
+ correct_compat = compatibility_scores[torch.arange(batch_size), labels]
314
+ correct_loss = -torch.log(correct_compat + 1e-8).mean()
315
+
316
+ mask = torch.ones_like(compatibility_scores)
317
+ mask[torch.arange(batch_size), labels] = 0
318
+
319
+ incorrect_compat = compatibility_scores * mask
320
+ incorrect_loss = torch.log(1 - incorrect_compat + 1e-8).mean()
321
+ incorrect_loss = -incorrect_loss
322
+
323
+ scaled_scores = compatibility_scores / self.temperature
324
+ log_probs = F.log_softmax(scaled_scores, dim=1)
325
+ contrastive_loss = F.nll_loss(log_probs, labels)
326
+
327
+ total_loss = correct_loss + 0.5 * incorrect_loss + 0.5 * contrastive_loss
328
+
329
+ return total_loss
330
+
331
+
332
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
333
+ # GEOMETRIC BASIN CLASSIFIER
334
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
335
+
336
+ class GeometricBasinClassifier(nn.Module):
337
+ """Geometric basin classifier with ResNet18 backbone + Cantor PE."""
338
+
339
+ def __init__(self, num_classes=100, pe_levels=20, pe_features_per_level=4, dropout=0.1, pretrained=False):
340
+ super().__init__()
341
+
342
+ self.num_classes = num_classes
343
+ self.pe_levels = pe_levels
344
+ self.pe_features_per_level = pe_features_per_level
345
+
346
+ # ResNet18 backbone from torchvision
347
+ from torchvision.models import resnet18, ResNet18_Weights
348
+ if pretrained:
349
+ resnet = resnet18(weights=ResNet18_Weights.IMAGENET1K_V1)
350
+ else:
351
+ resnet = resnet18(weights=None)
352
+
353
+ # Extract feature extractor (everything except fc layer)
354
+ self.backbone = nn.Sequential(
355
+ resnet.conv1,
356
+ resnet.bn1,
357
+ resnet.relu,
358
+ resnet.maxpool,
359
+ resnet.layer1,
360
+ resnet.layer2,
361
+ resnet.layer3,
362
+ resnet.layer4,
363
+ resnet.avgpool
364
+ )
365
+
366
+ # ResNet18 outputs 512 features
367
+ self.feature_dim = 512
368
+ self.dropout = nn.Dropout(dropout)
369
+
370
+ # Devil's Staircase PE
371
+ self.pe = DevilStaircasePE(pe_levels, pe_features_per_level)
372
+
373
+ # PE modulator (adjusted for ResNet18's 512 features)
374
+ self.pe_modulator = nn.Sequential(
375
+ nn.Linear(self.feature_dim, 256),
376
+ nn.ReLU(),
377
+ nn.Dropout(dropout),
378
+ nn.Linear(256, pe_levels * pe_features_per_level)
379
+ )
380
+
381
+ # Geometric basin
382
+ self.basin = GeometricBasinCompatibility(
383
+ num_classes,
384
+ pe_levels,
385
+ pe_features_per_level
386
+ )
387
+
388
+ def forward(self, x, return_details=False):
389
+ batch_size = x.shape[0]
390
+
391
+ # ResNet18 backbone
392
+ cnn_features = self.backbone(x)
393
+ cnn_features = torch.flatten(cnn_features, 1)
394
+ cnn_features = self.dropout(cnn_features)
395
+
396
+ # Generate PE
397
+ positions = torch.arange(batch_size, device=x.device)
398
+ pe_levels, cantor_measures = self.pe(positions, seq_len=batch_size)
399
+
400
+ # Modulate PE with CNN features
401
+ modulation = self.pe_modulator(cnn_features)
402
+ modulation = modulation.view(batch_size, self.pe_levels, self.pe_features_per_level)
403
+ pe_levels = pe_levels + 0.1 * modulation
404
+
405
+ # Geometric basin compatibility
406
+ compatibility_scores = self.basin(pe_levels, cantor_measures)
407
+
408
+ if return_details:
409
+ return {
410
+ 'compatibility_scores': compatibility_scores,
411
+ 'pe_levels': pe_levels,
412
+ 'cantor_measures': cantor_measures,
413
+ 'cnn_features': cnn_features
414
+ }
415
+
416
+ return compatibility_scores