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FAR-100 (Dynamic Stages)
3
+ ======================================
4
+ Properly handles variable stage counts.
5
+
6
+ Author: AbstractPhil
7
+ https://huggingface.co/AbstractPhil/mobiusnet
8
+ License: Apache 2.0
9
+ """
10
+
11
+ import math
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ from torch import Tensor
16
+ from typing import Tuple
17
+ from torchvision import datasets, transforms
18
+ from torch.utils.data import DataLoader
19
+ from tqdm.auto import tqdm
20
+
21
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
22
+ print(f"Device: {device}")
23
+
24
+
25
+ # ============================================================================
26
+ # MÖBIUS LENS
27
+ # ============================================================================
28
+
29
+ class MobiusLens(nn.Module):
30
+ def __init__(
31
+ self,
32
+ dim: int,
33
+ layer_idx: int,
34
+ total_layers: int,
35
+ scale_range: Tuple[float, float] = (1.0, 9.0),
36
+ ):
37
+ super().__init__()
38
+
39
+ self.t = layer_idx / max(total_layers - 1, 1)
40
+
41
+ scale_span = scale_range[1] - scale_range[0]
42
+ step = scale_span / max(total_layers, 1)
43
+ scale_low = scale_range[0] + self.t * scale_span
44
+ scale_high = scale_low + step
45
+
46
+ self.register_buffer('scales', torch.tensor([scale_low, scale_high]))
47
+
48
+ # TWIST IN
49
+ self.twist_in_angle = nn.Parameter(torch.tensor(self.t * math.pi))
50
+ self.twist_in_proj = nn.Linear(dim, dim, bias=False)
51
+ nn.init.orthogonal_(self.twist_in_proj.weight)
52
+
53
+ # CENTER LENS
54
+ self.omega = nn.Parameter(torch.tensor(math.pi))
55
+ self.alpha = nn.Parameter(torch.tensor(1.5))
56
+
57
+ self.phase_l = nn.Parameter(torch.zeros(2))
58
+ self.drift_l = nn.Parameter(torch.ones(2))
59
+ self.phase_m = nn.Parameter(torch.zeros(2))
60
+ self.drift_m = nn.Parameter(torch.zeros(2))
61
+ self.phase_r = nn.Parameter(torch.zeros(2))
62
+ self.drift_r = nn.Parameter(-torch.ones(2))
63
+
64
+ self.accum_weights = nn.Parameter(torch.tensor([0.4, 0.2, 0.4]))
65
+ self.xor_weight = nn.Parameter(torch.tensor(0.7))
66
+
67
+ # TWIST OUT
68
+ self.twist_out_angle = nn.Parameter(torch.tensor(-self.t * math.pi))
69
+ self.twist_out_proj = nn.Linear(dim, dim, bias=False)
70
+ nn.init.orthogonal_(self.twist_out_proj.weight)
71
+
72
+ def _twist_in(self, x: Tensor) -> Tensor:
73
+ cos_t = torch.cos(self.twist_in_angle)
74
+ sin_t = torch.sin(self.twist_in_angle)
75
+ return x * cos_t + self.twist_in_proj(x) * sin_t
76
+
77
+ def _center_lens(self, x: Tensor) -> Tensor:
78
+ x_norm = torch.tanh(x)
79
+ t = x_norm.abs().mean(dim=-1, keepdim=True).unsqueeze(-2)
80
+
81
+ x_exp = x_norm.unsqueeze(-2)
82
+ s = self.scales.view(-1, 1)
83
+
84
+ def wave(phase, drift):
85
+ a = self.alpha.abs() + 0.1
86
+ pos = s * self.omega * (x_exp + drift.view(-1, 1) * t) + phase.view(-1, 1)
87
+ return torch.exp(-a * torch.sin(pos).pow(2)).prod(dim=-2)
88
+
89
+ L = wave(self.phase_l, self.drift_l)
90
+ M = wave(self.phase_m, self.drift_m)
91
+ R = wave(self.phase_r, self.drift_r)
92
+
93
+ w = torch.softmax(self.accum_weights, dim=0)
94
+ xor_w = torch.sigmoid(self.xor_weight)
95
+
96
+ xor_comp = (L + R - 2 * L * R).abs()
97
+ and_comp = L * R
98
+ lr = xor_w * xor_comp + (1 - xor_w) * and_comp
99
+
100
+ gate = w[0] * L + w[1] * M + w[2] * R
101
+ gate = gate * (0.5 + 0.5 * lr)
102
+ gate = gate / (gate.mean() + 1e-6) * 0.5
103
+
104
+ return x * gate.clamp(0, 1)
105
+
106
+ def _twist_out(self, x: Tensor) -> Tensor:
107
+ cos_t = torch.cos(self.twist_out_angle)
108
+ sin_t = torch.sin(self.twist_out_angle)
109
+ return x * cos_t + self.twist_out_proj(x) * sin_t
110
+
111
+ def forward(self, x: Tensor) -> Tensor:
112
+ return self._twist_out(self._center_lens(self._twist_in(x)))
113
+
114
+
115
+ # ============================================================================
116
+ # MÖBIUS CONV BLOCK
117
+ # ============================================================================
118
+
119
+ class MobiusConvBlock(nn.Module):
120
+ def __init__(
121
+ self,
122
+ channels: int,
123
+ layer_idx: int,
124
+ total_layers: int,
125
+ scale_range: Tuple[float, float] = (1.0, 9.0),
126
+ reduction: float = 0.5,
127
+ ):
128
+ super().__init__()
129
+
130
+ self.conv = nn.Sequential(
131
+ nn.Conv2d(channels, channels, 3, padding=1, groups=channels, bias=False),
132
+ nn.Conv2d(channels, channels, 1, bias=False),
133
+ nn.BatchNorm2d(channels),
134
+ )
135
+
136
+ self.lens = MobiusLens(channels, layer_idx, total_layers, scale_range)
137
+
138
+ third = channels // 3
139
+ which_third = layer_idx % 3
140
+ mask = torch.ones(channels)
141
+ start = which_third * third
142
+ end = start + third + (channels % 3 if which_third == 2 else 0)
143
+ mask[start:end] = reduction
144
+ self.register_buffer('thirds_mask', mask.view(1, -1, 1, 1))
145
+
146
+ self.residual_weight = nn.Parameter(torch.tensor(0.9))
147
+
148
+ def forward(self, x: Tensor) -> Tensor:
149
+ identity = x
150
+
151
+ h = self.conv(x)
152
+ B, D, H, W = h.shape
153
+ h = h.permute(0, 2, 3, 1)
154
+ h = self.lens(h)
155
+ h = h.permute(0, 3, 1, 2)
156
+ h = h * self.thirds_mask
157
+
158
+ rw = torch.sigmoid(self.residual_weight)
159
+ return rw * identity + (1 - rw) * h
160
+
161
+
162
+ # ============================================================================
163
+ # MÖBIUS NET - DYNAMIC STAGES
164
+ # ============================================================================
165
+
166
+ class MobiusNet(nn.Module):
167
+ """
168
+ Pure conv with Möbius topology.
169
+ Dynamic number of stages based on len(depths).
170
+ """
171
+
172
+ def __init__(
173
+ self,
174
+ in_chans: int = 3,
175
+ num_classes: int = 100,
176
+ channels: Tuple[int, ...] = (64, 64, 128, 128),
177
+ depths: Tuple[int, ...] = (8, 4, 2),
178
+ scale_range: Tuple[float, float] = (0.5, 2.5),
179
+ ):
180
+ super().__init__()
181
+
182
+ num_stages = len(depths)
183
+ total_layers = sum(depths)
184
+
185
+ self.total_layers = total_layers
186
+ self.scale_range = scale_range
187
+ self.channels = channels
188
+ self.depths = depths
189
+ self.num_stages = num_stages
190
+
191
+ # Ensure we have enough channel specs
192
+ channels = list(channels)
193
+ while len(channels) < num_stages:
194
+ channels.append(channels[-1])
195
+
196
+ # Stem
197
+ self.stem = nn.Sequential(
198
+ nn.Conv2d(in_chans, channels[0], 3, padding=1, bias=False),
199
+ nn.BatchNorm2d(channels[0]),
200
+ )
201
+
202
+ # Build stages dynamically
203
+ layer_idx = 0
204
+ self.stages = nn.ModuleList()
205
+ self.downsamples = nn.ModuleList()
206
+
207
+ for stage_idx in range(num_stages):
208
+ ch = channels[stage_idx]
209
+
210
+ # Stage blocks
211
+ stage = nn.ModuleList()
212
+ for _ in range(depths[stage_idx]):
213
+ stage.append(MobiusConvBlock(
214
+ ch, layer_idx, total_layers, scale_range
215
+ ))
216
+ layer_idx += 1
217
+ self.stages.append(stage)
218
+
219
+ # Downsample between stages (not after last)
220
+ if stage_idx < num_stages - 1:
221
+ ch_next = channels[stage_idx + 1]
222
+ self.downsamples.append(nn.Sequential(
223
+ nn.Conv2d(ch, ch_next, 3, stride=2, padding=1, bias=False),
224
+ nn.BatchNorm2d(ch_next),
225
+ ))
226
+
227
+ # Head
228
+ self.pool = nn.AdaptiveAvgPool2d(1)
229
+ self.head = nn.Linear(channels[num_stages - 1], num_classes)
230
+
231
+ def forward(self, x: Tensor) -> Tensor:
232
+ x = self.stem(x)
233
+
234
+ for i, stage in enumerate(self.stages):
235
+ for block in stage:
236
+ x = block(x)
237
+ if i < len(self.downsamples):
238
+ x = self.downsamples[i](x)
239
+
240
+ return self.head(self.pool(x).flatten(1))
241
+
242
+ def get_info(self) -> str:
243
+ return (
244
+ f"MobiusNet: channels={self.channels}, depths={self.depths}, "
245
+ f"total_layers={self.total_layers}, scale_range={self.scale_range}"
246
+ )
247
+
248
+ def get_topology_info(self) -> str:
249
+ lines = ["Möbius Ribbon Topology:"]
250
+ lines.append("=" * 60)
251
+
252
+ scale_span = self.scale_range[1] - self.scale_range[0]
253
+ layer_idx = 0
254
+
255
+ for stage_idx, depth in enumerate(self.depths):
256
+ ch = self.channels[stage_idx] if stage_idx < len(self.channels) else self.channels[-1]
257
+ for local_idx in range(depth):
258
+ t = layer_idx / max(self.total_layers - 1, 1)
259
+ scale_low = self.scale_range[0] + t * scale_span
260
+ scale_high = scale_low + scale_span / self.total_layers
261
+
262
+ lines.append(
263
+ f"Layer {layer_idx:2d} (Stage {stage_idx+1}, ch={ch:3d}): "
264
+ f"t={t:.3f}, scales=[{scale_low:.3f}, {scale_high:.3f}]"
265
+ )
266
+ layer_idx += 1
267
+
268
+ if stage_idx < self.num_stages - 1:
269
+ ch_next = self.channels[stage_idx + 1] if stage_idx + 1 < len(self.channels) else self.channels[-1]
270
+ lines.append(f" ↓ Downsample {ch} → {ch_next}")
271
+
272
+ lines.append("=" * 60)
273
+ return "\n".join(lines)
274
+
275
+
276
+ # ============================================================================
277
+ # PRESETS
278
+ # ============================================================================
279
+
280
+ PRESETS = {
281
+ 'mobius_xs': {
282
+ 'channels': (64, 64, 128),
283
+ 'depths': (4, 2, 2),
284
+ 'scale_range': (0.5, 2.5),
285
+ },
286
+ 'mobius_stretched': {
287
+ 'channels': (32, 64, 96, 128, 192, 256, 320, 384, 448),
288
+ 'depths': (4, 4, 4, 3, 3, 3, 2, 2, 2),
289
+ 'scale_range': (0.2915, 2.85),
290
+ },
291
+ 'mobius_m': {
292
+ 'channels': (64, 128, 256, 256),
293
+ 'depths': (8, 4, 2),
294
+ 'scale_range': (0.5, 3.0),
295
+ },
296
+ 'mobius_deep': {
297
+ 'channels': (64, 64, 128, 128),
298
+ 'depths': (12, 6, 4),
299
+ 'scale_range': (0.5, 3.5),
300
+ },
301
+ 'mobius_wide': {
302
+ 'channels': (96, 96, 192, 192),
303
+ 'depths': (8, 4, 2),
304
+ 'scale_range': (0.5, 2.5),
305
+ },
306
+ }
307
+
308
+
309
+ # ============================================================================
310
+ # TRAINING
311
+ # ============================================================================
312
+
313
+ def train_mobius_cifar100(
314
+ preset: str = 'mobius_s',
315
+ epochs: int = 100,
316
+ lr: float = 1e-3,
317
+ batch_size: int = 128,
318
+ use_autoaugment: bool = True,
319
+ ):
320
+ config = PRESETS[preset]
321
+
322
+ print("=" * 70)
323
+ print(f"MÖBIUS NET - {preset.upper()} - CIFAR-100")
324
+ print("=" * 70)
325
+ print(f"Device: {device}")
326
+ print(f"Channels: {config['channels']}")
327
+ print(f"Depths: {config['depths']}")
328
+ print(f"Scale range: {config['scale_range']}")
329
+ print(f"AutoAugment: {use_autoaugment}")
330
+ print()
331
+
332
+ # CIFAR-100 normalization
333
+ mean = (0.5071, 0.4867, 0.4408)
334
+ std = (0.2675, 0.2565, 0.2761)
335
+
336
+ train_transforms = [
337
+ transforms.RandomCrop(32, padding=4),
338
+ transforms.RandomHorizontalFlip(),
339
+ ]
340
+ if use_autoaugment:
341
+ train_transforms.append(transforms.AutoAugment(transforms.AutoAugmentPolicy.CIFAR10))
342
+ train_transforms.extend([
343
+ transforms.ToTensor(),
344
+ transforms.Normalize(mean, std),
345
+ ])
346
+
347
+ train_tf = transforms.Compose(train_transforms)
348
+ test_tf = transforms.Compose([
349
+ transforms.ToTensor(),
350
+ transforms.Normalize(mean, std),
351
+ ])
352
+
353
+ train_ds = datasets.CIFAR100('./data', train=True, download=True, transform=train_tf)
354
+ test_ds = datasets.CIFAR100('./data', train=False, download=True, transform=test_tf)
355
+
356
+ train_loader = DataLoader(
357
+ train_ds, batch_size=batch_size, shuffle=True,
358
+ num_workers=8, pin_memory=True, persistent_workers=True
359
+ )
360
+ test_loader = DataLoader(
361
+ test_ds, batch_size=256, num_workers=2, pin_memory=True, persistent_workers=True,
362
+ )
363
+
364
+ model = MobiusNet(
365
+ in_chans=3,
366
+ num_classes=100,
367
+ **config
368
+ ).to(device)
369
+
370
+ print(model.get_info())
371
+ print()
372
+ print(model.get_topology_info())
373
+ print()
374
+
375
+ model.compile(mode='reduce-overhead')
376
+
377
+ total_params = sum(p.numel() for p in model.parameters())
378
+ print(f"Total params: {total_params:,}")
379
+ print()
380
+
381
+ optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.05)
382
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs)
383
+
384
+ best_acc = 0.0
385
+
386
+ for epoch in range(1, epochs + 1):
387
+ model.train()
388
+ train_loss, train_correct, train_total = 0, 0, 0
389
+
390
+ pbar = tqdm(train_loader, desc=f"Epoch {epoch:3d}")
391
+ for x, y in pbar:
392
+ x, y = x.to(device), y.to(device)
393
+
394
+ optimizer.zero_grad()
395
+ logits = model(x)
396
+ loss = F.cross_entropy(logits, y)
397
+ loss.backward()
398
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
399
+ optimizer.step()
400
+
401
+ train_loss += loss.item() * x.size(0)
402
+ train_correct += (logits.argmax(1) == y).sum().item()
403
+ train_total += x.size(0)
404
+
405
+ pbar.set_postfix(loss=f"{loss.item():.4f}")
406
+
407
+ scheduler.step()
408
+
409
+ model.eval()
410
+ val_correct, val_total = 0, 0
411
+ with torch.no_grad():
412
+ for x, y in test_loader:
413
+ x, y = x.to(device), y.to(device)
414
+ logits = model(x)
415
+ val_correct += (logits.argmax(1) == y).sum().item()
416
+ val_total += x.size(0)
417
+
418
+ train_acc = train_correct / train_total
419
+ val_acc = val_correct / val_total
420
+ best_acc = max(best_acc, val_acc)
421
+ marker = " ★" if val_acc >= best_acc else ""
422
+
423
+ print(f"Epoch {epoch:3d} | Loss: {train_loss/train_total:.4f} | "
424
+ f"Train: {train_acc:.4f} | Val: {val_acc:.4f} | Best: {best_acc:.4f}{marker}")
425
+
426
+ print()
427
+ print("=" * 70)
428
+ print("FINAL RESULTS")
429
+ print("=" * 70)
430
+ print(model.get_info())
431
+ print(f"Best accuracy: {best_acc:.4f}")
432
+ print(f"Total params: {total_params:,}")
433
+ print("=" * 70)
434
+
435
+ return model, best_acc
436
+
437
+
438
+ # ============================================================================
439
+ # RUN
440
+ # ============================================================================
441
+
442
+ if __name__ == '__main__':
443
+ model, best_acc = train_mobius_cifar100(
444
+ preset='mobius_stretched', # channels=(64, 64, 128, 128), depths=(8, 4, 2)
445
+ epochs=100,
446
+ lr=1e-3,
447
+ use_autoaugment=True,
448
+ )