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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
GEOMETRIC BASIN CLASSIFIER - CIFAR-100 [PROPER STRUCTURE]
|
| 3 |
+
----------------------------------------------------------
|
| 4 |
+
Correct directory structure with selective checkpoint uploads.
|
| 5 |
+
|
| 6 |
+
Local structure:
|
| 7 |
+
weights/geo-beatrix/{timestamp}/
|
| 8 |
+
βββ model.pt (best checkpoint)
|
| 9 |
+
βββ model.safetensors (best checkpoint)
|
| 10 |
+
βββ config.json
|
| 11 |
+
βββ training_log.txt
|
| 12 |
+
βββ checkpoints/
|
| 13 |
+
βββ checkpoint_epoch_10.pt
|
| 14 |
+
βββ checkpoint_epoch_10.safetensors
|
| 15 |
+
βββ checkpoint_epoch_20.pt
|
| 16 |
+
βββ checkpoint_epoch_20.safetensors
|
| 17 |
+
|
| 18 |
+
runs/geo-beatrix/{timestamp}/
|
| 19 |
+
βββ events.out.tfevents.*
|
| 20 |
+
βββ metrics.csv
|
| 21 |
+
|
| 22 |
+
HuggingFace uploads:
|
| 23 |
+
- Best model (always)
|
| 24 |
+
- Current epoch checkpoint only (not all accumulated)
|
| 25 |
+
- TensorBoard logs
|
| 26 |
+
- Metrics CSV
|
| 27 |
+
|
| 28 |
+
Author: AbstractPhil + Claude Sonnet 4.5
|
| 29 |
+
License: MIT
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
import torch
|
| 33 |
+
import torch.nn as nn
|
| 34 |
+
import torch.nn.functional as F
|
| 35 |
+
import torch.optim as optim
|
| 36 |
+
from torch.utils.data import DataLoader
|
| 37 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 38 |
+
import torchvision
|
| 39 |
+
import torchvision.transforms as transforms
|
| 40 |
+
from tqdm import tqdm
|
| 41 |
+
import math
|
| 42 |
+
import numpy as np
|
| 43 |
+
import os
|
| 44 |
+
import json
|
| 45 |
+
from datetime import datetime
|
| 46 |
+
from pathlib import Path
|
| 47 |
+
import csv
|
| 48 |
+
|
| 49 |
+
# Hugging Face Hub integration
|
| 50 |
+
try:
|
| 51 |
+
from huggingface_hub import HfApi, create_repo
|
| 52 |
+
HF_AVAILABLE = True
|
| 53 |
+
except ImportError:
|
| 54 |
+
print("β οΈ huggingface_hub not installed. Run: pip install huggingface_hub")
|
| 55 |
+
HF_AVAILABLE = False
|
| 56 |
+
|
| 57 |
+
# Safetensors integration
|
| 58 |
+
try:
|
| 59 |
+
from safetensors.torch import save_file as save_safetensors
|
| 60 |
+
from safetensors.torch import load_file as load_safetensors
|
| 61 |
+
SAFETENSORS_AVAILABLE = True
|
| 62 |
+
except ImportError:
|
| 63 |
+
print("β οΈ safetensors not installed. Run: pip install safetensors")
|
| 64 |
+
SAFETENSORS_AVAILABLE = False
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 68 |
+
# MIXING AUGMENTATIONS
|
| 69 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 70 |
+
|
| 71 |
+
def alphamix_data(x, y, alpha_range=(0.3, 0.7), spatial_ratio=0.25):
|
| 72 |
+
"""AlphaMix: Spatially localized transparent overlay."""
|
| 73 |
+
batch_size = x.size(0)
|
| 74 |
+
index = torch.randperm(batch_size, device=x.device)
|
| 75 |
+
|
| 76 |
+
y_a, y_b = y, y[index]
|
| 77 |
+
|
| 78 |
+
alpha_min, alpha_max = alpha_range
|
| 79 |
+
beta_sample = np.random.beta(2, 2)
|
| 80 |
+
alpha = alpha_min + (alpha_max - alpha_min) * beta_sample
|
| 81 |
+
|
| 82 |
+
_, _, H, W = x.shape
|
| 83 |
+
overlay_ratio = np.sqrt(spatial_ratio)
|
| 84 |
+
overlay_h = int(H * overlay_ratio)
|
| 85 |
+
overlay_w = int(W * overlay_ratio)
|
| 86 |
+
|
| 87 |
+
top = np.random.randint(0, H - overlay_h + 1)
|
| 88 |
+
left = np.random.randint(0, W - overlay_w + 1)
|
| 89 |
+
|
| 90 |
+
composited_x = x.clone()
|
| 91 |
+
overlay_region = alpha * x[:, :, top:top+overlay_h, left:left+overlay_w]
|
| 92 |
+
background_region = (1 - alpha) * x[index, :, top:top+overlay_h, left:left+overlay_w]
|
| 93 |
+
composited_x[:, :, top:top+overlay_h, left:left+overlay_w] = overlay_region + background_region
|
| 94 |
+
|
| 95 |
+
return composited_x, y_a, y_b, alpha
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 99 |
+
# DEVIL'S STAIRCASE PE
|
| 100 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 101 |
+
|
| 102 |
+
class DevilStaircasePE(nn.Module):
|
| 103 |
+
"""Devil's Staircase PE - let alpha float naturally."""
|
| 104 |
+
|
| 105 |
+
def __init__(self, levels=20, features_per_level=4, smooth_tau=0.25, base=3):
|
| 106 |
+
super().__init__()
|
| 107 |
+
self.levels = levels
|
| 108 |
+
self.features_per_level = features_per_level
|
| 109 |
+
self.tau = smooth_tau
|
| 110 |
+
self.base = base
|
| 111 |
+
|
| 112 |
+
self.alpha = nn.Parameter(torch.tensor(0.1))
|
| 113 |
+
|
| 114 |
+
self.base_features = 2
|
| 115 |
+
if features_per_level > 2:
|
| 116 |
+
self.feature_expansion = nn.Linear(self.base_features, features_per_level)
|
| 117 |
+
else:
|
| 118 |
+
self.feature_expansion = None
|
| 119 |
+
|
| 120 |
+
def forward(self, positions, seq_len):
|
| 121 |
+
x = positions.float() / max(1, (seq_len - 1))
|
| 122 |
+
x = x.clamp(1e-6, 1.0 - 1e-6)
|
| 123 |
+
|
| 124 |
+
feats = []
|
| 125 |
+
Cx = torch.zeros_like(x)
|
| 126 |
+
|
| 127 |
+
for k in range(1, self.levels + 1):
|
| 128 |
+
scale = self.base ** k
|
| 129 |
+
y = (x * scale) % self.base
|
| 130 |
+
|
| 131 |
+
centers = torch.tensor([0.5, 1.5, 2.5], device=x.device, dtype=x.dtype)
|
| 132 |
+
d2 = (y.unsqueeze(-1) - centers) ** 2
|
| 133 |
+
logits = -d2 / (self.tau + 1e-8)
|
| 134 |
+
p = F.softmax(logits, dim=-1)
|
| 135 |
+
|
| 136 |
+
bit_k = p[..., 2] + self.alpha * p[..., 1]
|
| 137 |
+
Cx = Cx + bit_k * (0.5 ** k)
|
| 138 |
+
|
| 139 |
+
ent = -(p * p.clamp_min(1e-8).log()).sum(dim=-1)
|
| 140 |
+
pdf_proxy = 1.1 - ent / math.log(3.0)
|
| 141 |
+
|
| 142 |
+
base_feat = torch.stack([bit_k, pdf_proxy], dim=-1)
|
| 143 |
+
|
| 144 |
+
if self.feature_expansion is not None:
|
| 145 |
+
level_feat = self.feature_expansion(base_feat)
|
| 146 |
+
else:
|
| 147 |
+
level_feat = base_feat
|
| 148 |
+
|
| 149 |
+
feats.append(level_feat)
|
| 150 |
+
|
| 151 |
+
pe_levels = torch.stack(feats, dim=1)
|
| 152 |
+
return pe_levels, Cx
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 156 |
+
# RESIDUAL BLOCK
|
| 157 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 158 |
+
|
| 159 |
+
class ResidualBlock(nn.Module):
|
| 160 |
+
"""Basic residual block with skip connection."""
|
| 161 |
+
|
| 162 |
+
def __init__(self, in_channels, out_channels, stride=1):
|
| 163 |
+
super().__init__()
|
| 164 |
+
|
| 165 |
+
self.conv1 = nn.Conv2d(in_channels, out_channels, 3, stride=stride, padding=1, bias=False)
|
| 166 |
+
self.bn1 = nn.BatchNorm2d(out_channels)
|
| 167 |
+
self.conv2 = nn.Conv2d(out_channels, out_channels, 3, stride=1, padding=1, bias=False)
|
| 168 |
+
self.bn2 = nn.BatchNorm2d(out_channels)
|
| 169 |
+
|
| 170 |
+
self.shortcut = nn.Sequential()
|
| 171 |
+
if stride != 1 or in_channels != out_channels:
|
| 172 |
+
self.shortcut = nn.Sequential(
|
| 173 |
+
nn.Conv2d(in_channels, out_channels, 1, stride=stride, bias=False),
|
| 174 |
+
nn.BatchNorm2d(out_channels)
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
def forward(self, x):
|
| 178 |
+
out = F.relu(self.bn1(self.conv1(x)))
|
| 179 |
+
out = self.bn2(self.conv2(out))
|
| 180 |
+
out += self.shortcut(x)
|
| 181 |
+
out = F.relu(out)
|
| 182 |
+
return out
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 186 |
+
# GEOMETRIC BASIN COMPATIBILITY
|
| 187 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 188 |
+
|
| 189 |
+
class GeometricBasinCompatibility(nn.Module):
|
| 190 |
+
"""Compute geometric compatibility scores - FULLY BATCHED."""
|
| 191 |
+
|
| 192 |
+
def __init__(self, num_classes=100, pe_levels=20, features_per_level=4):
|
| 193 |
+
super().__init__()
|
| 194 |
+
|
| 195 |
+
self.num_classes = num_classes
|
| 196 |
+
self.pe_levels = pe_levels
|
| 197 |
+
self.features_per_level = features_per_level
|
| 198 |
+
|
| 199 |
+
self.class_signatures = nn.Parameter(
|
| 200 |
+
torch.randn(num_classes, pe_levels, features_per_level) * 0.1
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
self.cantor_prototypes = nn.Parameter(
|
| 204 |
+
torch.linspace(0.0, 1.0, num_classes)
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
self.level_resonance = nn.Parameter(
|
| 208 |
+
torch.ones(num_classes, pe_levels) / pe_levels
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
def forward(self, pe_levels, cantor_measures):
|
| 212 |
+
B = pe_levels.shape[0]
|
| 213 |
+
|
| 214 |
+
# 1. TRIADIC COMPATIBILITY
|
| 215 |
+
pe_norm = F.normalize(pe_levels, p=2, dim=-1)
|
| 216 |
+
sig_norm = F.normalize(self.class_signatures, p=2, dim=-1)
|
| 217 |
+
|
| 218 |
+
similarities = torch.einsum('blf,clf->bcl', pe_norm, sig_norm)
|
| 219 |
+
similarities = (similarities + 1) / 2
|
| 220 |
+
|
| 221 |
+
resonance = F.softmax(self.level_resonance, dim=-1)
|
| 222 |
+
triadic_compat = (similarities * resonance.unsqueeze(0)).sum(dim=-1)
|
| 223 |
+
|
| 224 |
+
# 2. SELF-SIMILARITY
|
| 225 |
+
level_pairs = []
|
| 226 |
+
for k in range(self.pe_levels - 1):
|
| 227 |
+
level_k = pe_levels[:, k, :]
|
| 228 |
+
level_k1 = pe_levels[:, k+1, :]
|
| 229 |
+
sim = F.cosine_similarity(level_k, level_k1, dim=-1, eps=1e-8)
|
| 230 |
+
sim = (sim + 1) / 2
|
| 231 |
+
level_pairs.append(sim)
|
| 232 |
+
|
| 233 |
+
self_sim_pattern = torch.stack(level_pairs, dim=1)
|
| 234 |
+
|
| 235 |
+
expected_patterns = torch.sigmoid(
|
| 236 |
+
self.level_resonance[:, :-1] - self.level_resonance[:, 1:]
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
pattern_diff = torch.abs(
|
| 240 |
+
self_sim_pattern.unsqueeze(1) - expected_patterns.unsqueeze(0)
|
| 241 |
+
)
|
| 242 |
+
self_sim_compat = 1 - pattern_diff.mean(dim=-1)
|
| 243 |
+
self_sim_compat = torch.clamp(self_sim_compat, 0.0, 1.0)
|
| 244 |
+
|
| 245 |
+
# 3. CANTOR COHERENCE
|
| 246 |
+
distances = torch.abs(
|
| 247 |
+
cantor_measures.unsqueeze(1) - self.cantor_prototypes.unsqueeze(0)
|
| 248 |
+
)
|
| 249 |
+
cantor_compat = torch.exp(-distances ** 2 / 0.1) + 1e-8
|
| 250 |
+
|
| 251 |
+
# 4. HIERARCHICAL CHECK
|
| 252 |
+
split_point = self.pe_levels // 2
|
| 253 |
+
early_levels = pe_levels[:, :split_point, :].mean(dim=1)
|
| 254 |
+
late_levels = pe_levels[:, split_point:, :].mean(dim=1)
|
| 255 |
+
|
| 256 |
+
early_targets = self.class_signatures[:, :split_point, :].mean(dim=1)
|
| 257 |
+
late_targets = self.class_signatures[:, split_point:, :].mean(dim=1)
|
| 258 |
+
|
| 259 |
+
early_levels_norm = F.normalize(early_levels, p=2, dim=-1)
|
| 260 |
+
late_levels_norm = F.normalize(late_levels, p=2, dim=-1)
|
| 261 |
+
early_targets_norm = F.normalize(early_targets, p=2, dim=-1)
|
| 262 |
+
late_targets_norm = F.normalize(late_targets, p=2, dim=-1)
|
| 263 |
+
|
| 264 |
+
early_compat = torch.matmul(early_levels_norm, early_targets_norm.t())
|
| 265 |
+
late_compat = torch.matmul(late_levels_norm, late_targets_norm.t())
|
| 266 |
+
|
| 267 |
+
early_compat = (early_compat + 1) / 2
|
| 268 |
+
late_compat = (late_compat + 1) / 2
|
| 269 |
+
hier_compat = (early_compat + late_compat) / 2
|
| 270 |
+
|
| 271 |
+
# 5. COMBINE
|
| 272 |
+
eps = 1e-6
|
| 273 |
+
triadic_compat = torch.clamp(triadic_compat, eps, 1.0)
|
| 274 |
+
self_sim_compat = torch.clamp(self_sim_compat, eps, 1.0)
|
| 275 |
+
cantor_compat = torch.clamp(cantor_compat, eps, 1.0)
|
| 276 |
+
hier_compat = torch.clamp(hier_compat, eps, 1.0)
|
| 277 |
+
|
| 278 |
+
compatibility_scores = (
|
| 279 |
+
triadic_compat *
|
| 280 |
+
self_sim_compat *
|
| 281 |
+
cantor_compat *
|
| 282 |
+
hier_compat
|
| 283 |
+
) ** 0.25
|
| 284 |
+
|
| 285 |
+
return compatibility_scores
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 289 |
+
# GEOMETRIC BASIN LOSS
|
| 290 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 291 |
+
|
| 292 |
+
class GeometricBasinLoss(nn.Module):
|
| 293 |
+
"""Loss based on geometric basin compatibility."""
|
| 294 |
+
|
| 295 |
+
def __init__(self, temperature=0.1):
|
| 296 |
+
super().__init__()
|
| 297 |
+
self.temperature = temperature
|
| 298 |
+
|
| 299 |
+
def forward(self, compatibility_scores, labels, mixed_labels=None, lam=None):
|
| 300 |
+
batch_size = compatibility_scores.shape[0]
|
| 301 |
+
|
| 302 |
+
if mixed_labels is not None and lam is not None:
|
| 303 |
+
primary_compat = compatibility_scores[torch.arange(batch_size), labels]
|
| 304 |
+
secondary_compat = compatibility_scores[torch.arange(batch_size), mixed_labels]
|
| 305 |
+
|
| 306 |
+
primary_loss = F.mse_loss(primary_compat, torch.full_like(primary_compat, lam))
|
| 307 |
+
secondary_loss = F.mse_loss(secondary_compat, torch.full_like(secondary_compat, 1 - lam))
|
| 308 |
+
|
| 309 |
+
soft_targets = torch.zeros_like(compatibility_scores)
|
| 310 |
+
soft_targets[torch.arange(batch_size), labels] = lam
|
| 311 |
+
soft_targets[torch.arange(batch_size), mixed_labels] = 1 - lam
|
| 312 |
+
|
| 313 |
+
compat_normalized = compatibility_scores / (compatibility_scores.sum(dim=1, keepdim=True) + 1e-8)
|
| 314 |
+
kl_loss = F.kl_div(
|
| 315 |
+
compat_normalized.log(),
|
| 316 |
+
soft_targets,
|
| 317 |
+
reduction='batchmean'
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
total_loss = primary_loss + secondary_loss + 0.1 * kl_loss
|
| 321 |
+
|
| 322 |
+
else:
|
| 323 |
+
correct_compat = compatibility_scores[torch.arange(batch_size), labels]
|
| 324 |
+
correct_loss = -torch.log(correct_compat + 1e-8).mean()
|
| 325 |
+
|
| 326 |
+
mask = torch.ones_like(compatibility_scores)
|
| 327 |
+
mask[torch.arange(batch_size), labels] = 0
|
| 328 |
+
|
| 329 |
+
incorrect_compat = compatibility_scores * mask
|
| 330 |
+
incorrect_loss = torch.log(1 - incorrect_compat + 1e-8).mean()
|
| 331 |
+
incorrect_loss = -incorrect_loss
|
| 332 |
+
|
| 333 |
+
scaled_scores = compatibility_scores / self.temperature
|
| 334 |
+
log_probs = F.log_softmax(scaled_scores, dim=1)
|
| 335 |
+
contrastive_loss = F.nll_loss(log_probs, labels)
|
| 336 |
+
|
| 337 |
+
total_loss = correct_loss + 0.5 * incorrect_loss + 0.5 * contrastive_loss
|
| 338 |
+
|
| 339 |
+
return total_loss
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 343 |
+
# GEOMETRIC BASIN CLASSIFIER
|
| 344 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 345 |
+
|
| 346 |
+
class GeometricBasinClassifier(nn.Module):
|
| 347 |
+
"""BIGGER classifier with deeper ResNet-style backbone."""
|
| 348 |
+
|
| 349 |
+
def __init__(self, num_classes=100, pe_levels=20, pe_features_per_level=4, dropout=0.1):
|
| 350 |
+
super().__init__()
|
| 351 |
+
|
| 352 |
+
self.num_classes = num_classes
|
| 353 |
+
self.pe_levels = pe_levels
|
| 354 |
+
self.pe_features_per_level = pe_features_per_level
|
| 355 |
+
|
| 356 |
+
# Initial conv
|
| 357 |
+
self.conv1 = nn.Conv2d(3, 64, 3, padding=1, bias=False)
|
| 358 |
+
self.bn1 = nn.BatchNorm2d(64)
|
| 359 |
+
|
| 360 |
+
# Residual blocks
|
| 361 |
+
self.layer1 = self._make_layer(64, 128, num_blocks=2, stride=2)
|
| 362 |
+
self.layer2 = self._make_layer(128, 256, num_blocks=2, stride=2)
|
| 363 |
+
self.layer3 = self._make_layer(256, 512, num_blocks=2, stride=2)
|
| 364 |
+
self.layer4 = self._make_layer(512, 1024, num_blocks=2, stride=2)
|
| 365 |
+
|
| 366 |
+
self.global_pool = nn.AdaptiveAvgPool2d(1)
|
| 367 |
+
self.dropout = nn.Dropout(dropout)
|
| 368 |
+
|
| 369 |
+
# Devil's Staircase PE
|
| 370 |
+
self.pe = DevilStaircasePE(pe_levels, pe_features_per_level)
|
| 371 |
+
|
| 372 |
+
# PE modulator
|
| 373 |
+
self.pe_modulator = nn.Sequential(
|
| 374 |
+
nn.Linear(1024, 512),
|
| 375 |
+
nn.ReLU(),
|
| 376 |
+
nn.Dropout(dropout),
|
| 377 |
+
nn.Linear(512, pe_levels * pe_features_per_level)
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
# Geometric basin
|
| 381 |
+
self.basin = GeometricBasinCompatibility(
|
| 382 |
+
num_classes,
|
| 383 |
+
pe_levels,
|
| 384 |
+
pe_features_per_level
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
def _make_layer(self, in_channels, out_channels, num_blocks, stride):
|
| 388 |
+
layers = []
|
| 389 |
+
layers.append(ResidualBlock(in_channels, out_channels, stride))
|
| 390 |
+
for _ in range(1, num_blocks):
|
| 391 |
+
layers.append(ResidualBlock(out_channels, out_channels, stride=1))
|
| 392 |
+
return nn.Sequential(*layers)
|
| 393 |
+
|
| 394 |
+
def forward(self, x, return_details=False):
|
| 395 |
+
batch_size = x.shape[0]
|
| 396 |
+
|
| 397 |
+
# CNN backbone
|
| 398 |
+
x = F.relu(self.bn1(self.conv1(x)))
|
| 399 |
+
|
| 400 |
+
x = self.layer1(x)
|
| 401 |
+
x = self.layer2(x)
|
| 402 |
+
x = self.layer3(x)
|
| 403 |
+
x = self.layer4(x)
|
| 404 |
+
|
| 405 |
+
cnn_features = self.global_pool(x).flatten(1)
|
| 406 |
+
cnn_features = self.dropout(cnn_features)
|
| 407 |
+
|
| 408 |
+
# Generate PE
|
| 409 |
+
positions = torch.arange(batch_size, device=x.device)
|
| 410 |
+
pe_levels, cantor_measures = self.pe(positions, seq_len=batch_size)
|
| 411 |
+
|
| 412 |
+
# Modulate PE with CNN features
|
| 413 |
+
modulation = self.pe_modulator(cnn_features)
|
| 414 |
+
modulation = modulation.view(batch_size, self.pe_levels, self.pe_features_per_level)
|
| 415 |
+
pe_levels = pe_levels + 0.1 * modulation
|
| 416 |
+
|
| 417 |
+
# Geometric basin compatibility
|
| 418 |
+
compatibility_scores = self.basin(pe_levels, cantor_measures)
|
| 419 |
+
|
| 420 |
+
if return_details:
|
| 421 |
+
return {
|
| 422 |
+
'compatibility_scores': compatibility_scores,
|
| 423 |
+
'pe_levels': pe_levels,
|
| 424 |
+
'cantor_measures': cantor_measures,
|
| 425 |
+
'cnn_features': cnn_features
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
return compatibility_scores
|