AbstractPhil commited on
Commit
6288b7c
Β·
verified Β·
1 Parent(s): a68a927

Create trainer.py

Browse files
Files changed (1) hide show
  1. v18_johanna_curriculum/trainer.py +579 -0
v18_johanna_curriculum/trainer.py ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Johanna-Tiny Curriculum β€” Tiered Noise Introduction
3
+ =====================================================
4
+ Start with Gaussian. Introduce harder noise types only when the
5
+ current tier converges. Track per-type MSE to identify which
6
+ distributions break the geometry.
7
+
8
+ Tiers:
9
+ 0: Gaussian (foundation)
10
+ 1: + Pink, Brown, Block-structured, Gradient (correlated)
11
+ 2: + Uniform, Scaled uniform, Checkerboard, Mixed (bounded)
12
+ 3: + Poisson, Exponential, Laplace, Sparse (adversarial)
13
+ 4: + Cauchy, Salt-and-pepper, Structural inconsist. (hostile)
14
+
15
+ Promotion: when tier MSE improvement < 1% over 10 epochs, unlock next tier.
16
+ """
17
+
18
+ import os
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+ import math
23
+ import time
24
+ import numpy as np
25
+ from tqdm import tqdm
26
+
27
+ try:
28
+ from google.colab import userdata
29
+ os.environ["HF_TOKEN"] = userdata.get('HF_TOKEN')
30
+ from huggingface_hub import login
31
+ login(token=os.environ["HF_TOKEN"])
32
+ except Exception:
33
+ pass
34
+
35
+ # ── SVD Backend ──────────────────────────────────────────────────
36
+
37
+ try:
38
+ from geolip_core.linalg.eigh import FLEigh, _FL_MAX_N
39
+ HAS_FL = True
40
+ except ImportError:
41
+ HAS_FL = False
42
+
43
+
44
+ def gram_eigh_svd_fp64(A):
45
+ orig_dtype = A.dtype
46
+ with torch.amp.autocast('cuda', enabled=False):
47
+ A_d = A.double()
48
+ G = torch.bmm(A_d.transpose(1, 2), A_d)
49
+ G.diagonal(dim1=-2, dim2=-1).add_(1e-12)
50
+ eigenvalues, V = torch.linalg.eigh(G)
51
+ eigenvalues = eigenvalues.flip(-1)
52
+ V = V.flip(-1)
53
+ S = torch.sqrt(eigenvalues.clamp(min=1e-24))
54
+ U = torch.bmm(A_d, V) / S.unsqueeze(1).clamp(min=1e-16)
55
+ Vh = V.transpose(-2, -1).contiguous()
56
+ return U.to(orig_dtype), S.to(orig_dtype), Vh.to(orig_dtype)
57
+
58
+
59
+ def svd_fp64(A):
60
+ B, M, N = A.shape
61
+ if HAS_FL and N <= _FL_MAX_N and A.is_cuda:
62
+ orig_dtype = A.dtype
63
+ with torch.amp.autocast('cuda', enabled=False):
64
+ A_d = A.double()
65
+ G = torch.bmm(A_d.transpose(1, 2), A_d)
66
+ eigenvalues, V = FLEigh()(G.float())
67
+ eigenvalues = eigenvalues.double().flip(-1)
68
+ V = V.double().flip(-1)
69
+ S = torch.sqrt(eigenvalues.clamp(min=1e-24))
70
+ U = torch.bmm(A_d, V) / S.unsqueeze(1).clamp(min=1e-16)
71
+ Vh = V.transpose(-2, -1).contiguous()
72
+ return U.to(orig_dtype), S.to(orig_dtype), Vh.to(orig_dtype)
73
+ else:
74
+ return gram_eigh_svd_fp64(A)
75
+
76
+
77
+ def cayley_menger_vol2(points):
78
+ B, N, D = points.shape
79
+ pts = points.double()
80
+ gram = torch.bmm(pts, pts.transpose(1, 2))
81
+ norms = torch.diagonal(gram, dim1=1, dim2=2)
82
+ d2 = F.relu(norms.unsqueeze(2) + norms.unsqueeze(1) - 2 * gram)
83
+ cm = torch.zeros(B, N + 1, N + 1, device=points.device, dtype=torch.float64)
84
+ cm[:, 0, 1:] = 1.0
85
+ cm[:, 1:, 0] = 1.0
86
+ cm[:, 1:, 1:] = d2
87
+ k = N - 1
88
+ sign = (-1.0) ** (k + 1)
89
+ fact = math.factorial(k)
90
+ return sign * torch.linalg.det(cm) / ((2 ** k) * (fact ** 2))
91
+
92
+
93
+ def cv_of(emb, n_samples=200):
94
+ if emb.dim() != 2 or emb.shape[0] < 5:
95
+ return 0.0
96
+ N, D = emb.shape
97
+ pool = min(N, 512)
98
+ indices = torch.stack([torch.randperm(pool, device=emb.device)[:5] for _ in range(n_samples)])
99
+ vol2 = cayley_menger_vol2(emb[:pool][indices])
100
+ valid = vol2 > 1e-20
101
+ if valid.sum() < 10:
102
+ return 0.0
103
+ vols = vol2[valid].sqrt()
104
+ return (vols.std() / (vols.mean() + 1e-8)).item()
105
+
106
+
107
+ # ── Noise Type Registry ─────────────────────────────────────────
108
+
109
+ NOISE_NAMES = {
110
+ 0: 'gaussian', 1: 'uniform', 2: 'uniform_scaled', 3: 'poisson',
111
+ 4: 'pink', 5: 'brown', 6: 'salt_pepper', 7: 'sparse',
112
+ 8: 'block', 9: 'gradient', 10: 'checkerboard', 11: 'mixed',
113
+ 12: 'structural', 13: 'cauchy', 14: 'exponential', 15: 'laplace',
114
+ }
115
+
116
+ TIERS = {
117
+ 0: [0], # Gaussian (foundation)
118
+ 1: [4, 5, 8, 9], # Pink, Brown, Block, Gradient (correlated)
119
+ 2: [1, 2, 10, 11], # Uniform, Scaled, Checkerboard, Mixed (bounded)
120
+ 3: [3, 14, 15, 7], # Poisson, Exponential, Laplace, Sparse (adversarial)
121
+ 4: [13, 6, 12], # Cauchy, Salt-pepper, Structural (hostile)
122
+ }
123
+
124
+
125
+ # ── Curriculum Noise Dataset ─────────────────────────────────────
126
+
127
+ class CurriculumNoiseDataset(torch.utils.data.Dataset):
128
+ """Noise dataset with tier-based type activation.
129
+
130
+ Only generates noise types that are currently unlocked.
131
+ Types are activated by tier β€” call unlock_tier(n) to enable.
132
+ """
133
+
134
+ def __init__(self, size=500000, img_size=64, seed_rotate_every=1000):
135
+ self.size = size
136
+ self.img_size = img_size
137
+ self.seed_rotate_every = seed_rotate_every
138
+ self._rng = np.random.RandomState(42)
139
+ self._call_count = 0
140
+ self.active_types = list(TIERS[0]) # start with Gaussian only
141
+ self.current_tier = 0
142
+
143
+ def unlock_tier(self, tier):
144
+ """Unlock a tier of noise types."""
145
+ if tier in TIERS:
146
+ for t in TIERS[tier]:
147
+ if t not in self.active_types:
148
+ self.active_types.append(t)
149
+ self.current_tier = tier
150
+
151
+ def __len__(self):
152
+ return self.size
153
+
154
+ def _rotate_seed(self):
155
+ self._call_count += 1
156
+ if self._call_count % self.seed_rotate_every == 0:
157
+ new_seed = int.from_bytes(os.urandom(4), 'big')
158
+ self._rng = np.random.RandomState(new_seed)
159
+ torch.manual_seed(new_seed)
160
+
161
+ def _pink_noise(self, shape):
162
+ white = torch.randn(shape)
163
+ S = torch.fft.rfft2(white)
164
+ h, w = shape[-2], shape[-1]
165
+ fy = torch.fft.fftfreq(h).unsqueeze(-1).expand(-1, w // 2 + 1)
166
+ fx = torch.fft.rfftfreq(w).unsqueeze(0).expand(h, -1)
167
+ f = torch.sqrt(fx**2 + fy**2).clamp(min=1e-8)
168
+ return torch.fft.irfft2(S / f, s=(h, w))
169
+
170
+ def _brown_noise(self, shape):
171
+ white = torch.randn(shape)
172
+ S = torch.fft.rfft2(white)
173
+ h, w = shape[-2], shape[-1]
174
+ fy = torch.fft.fftfreq(h).unsqueeze(-1).expand(-1, w // 2 + 1)
175
+ fx = torch.fft.rfftfreq(w).unsqueeze(0).expand(h, -1)
176
+ f = (fx**2 + fy**2).clamp(min=1e-8)
177
+ return torch.fft.irfft2(S / f, s=(h, w))
178
+
179
+ def _generate(self, noise_type):
180
+ s = self.img_size
181
+ if noise_type == 0: return torch.randn(3, s, s)
182
+ elif noise_type == 1: return torch.rand(3, s, s) * 2 - 1
183
+ elif noise_type == 2: return (torch.rand(3, s, s) - 0.5) * 4
184
+ elif noise_type == 3:
185
+ lam = self._rng.uniform(0.5, 20.0)
186
+ return torch.poisson(torch.full((3, s, s), lam)) / lam - 1.0
187
+ elif noise_type == 4:
188
+ img = self._pink_noise((3, s, s)); return img / (img.std() + 1e-8)
189
+ elif noise_type == 5:
190
+ img = self._brown_noise((3, s, s)); return img / (img.std() + 1e-8)
191
+ elif noise_type == 6:
192
+ img = torch.where(torch.rand(3,s,s)>0.5, torch.ones(3,s,s)*2, -torch.ones(3,s,s)*2)
193
+ return img + torch.randn(3, s, s) * 0.1
194
+ elif noise_type == 7:
195
+ return torch.randn(3,s,s) * (torch.rand(3,s,s) > 0.9).float() * 3
196
+ elif noise_type == 8:
197
+ b = self._rng.randint(2, 16)
198
+ small = torch.randn(3, s//b+1, s//b+1)
199
+ return F.interpolate(small.unsqueeze(0), size=s, mode='nearest').squeeze(0)
200
+ elif noise_type == 9:
201
+ gy = torch.linspace(-2,2,s).unsqueeze(1).expand(s,s)
202
+ gx = torch.linspace(-2,2,s).unsqueeze(0).expand(s,s)
203
+ a = self._rng.uniform(0, 2*math.pi)
204
+ return (math.cos(a)*gx + math.sin(a)*gy).unsqueeze(0).expand(3,-1,-1) + torch.randn(3,s,s)*0.5
205
+ elif noise_type == 10:
206
+ cs = self._rng.randint(2, 16)
207
+ cy = torch.arange(s)//cs; cx = torch.arange(s)//cs
208
+ checker = ((cy.unsqueeze(1)+cx.unsqueeze(0))%2).float()*2-1
209
+ return checker.unsqueeze(0).expand(3,-1,-1) + torch.randn(3,s,s)*0.3
210
+ elif noise_type == 11:
211
+ alpha = self._rng.uniform(0.2, 0.8)
212
+ return alpha*torch.randn(3,s,s) + (1-alpha)*(torch.rand(3,s,s)*2-1)
213
+ elif noise_type == 12:
214
+ img = torch.zeros(3,s,s); h2 = s//2
215
+ img[:,:h2,:h2] = torch.randn(3,h2,h2)
216
+ img[:,:h2,h2:] = torch.rand(3,h2,h2)*2-1
217
+ img[:,h2:,:h2] = self._pink_noise((3,h2,h2))/2
218
+ img[:,h2:,h2:] = torch.where(torch.rand(3,h2,h2)>0.5, torch.ones(3,h2,h2), -torch.ones(3,h2,h2))
219
+ return img
220
+ elif noise_type == 13:
221
+ return torch.tan(math.pi*(torch.rand(3,s,s)-0.5)).clamp(-3,3)
222
+ elif noise_type == 14:
223
+ return torch.empty(3,s,s).exponential_(1.0) - 1.0
224
+ elif noise_type == 15:
225
+ u = torch.rand(3,s,s)-0.5; return -torch.sign(u)*torch.log1p(-2*u.abs())
226
+ return torch.randn(3, s, s)
227
+
228
+ def __getitem__(self, idx):
229
+ self._rotate_seed()
230
+ noise_type = self.active_types[idx % len(self.active_types)]
231
+ img = self._generate(noise_type).clamp(-4, 4)
232
+ return img.float(), noise_type
233
+
234
+
235
+ # ── Model (identical to proven architecture) ─────────────────────
236
+
237
+ def extract_patches(images, patch_size=16):
238
+ B, C, H, W = images.shape
239
+ gh, gw = H // patch_size, W // patch_size
240
+ p = images.reshape(B, C, gh, patch_size, gw, patch_size)
241
+ return p.permute(0,2,4,1,3,5).reshape(B, gh*gw, C*patch_size*patch_size), gh, gw
242
+
243
+ def stitch_patches(patches, gh, gw, patch_size=16):
244
+ B = patches.shape[0]
245
+ p = patches.reshape(B, gh, gw, 3, patch_size, patch_size)
246
+ return p.permute(0,3,1,4,2,5).reshape(B, 3, gh*patch_size, gw*patch_size)
247
+
248
+ class BoundarySmooth(nn.Module):
249
+ def __init__(self, channels=3, mid=16):
250
+ super().__init__()
251
+ self.net = nn.Sequential(nn.Conv2d(channels, mid, 3, padding=1), nn.GELU(),
252
+ nn.Conv2d(mid, channels, 3, padding=1))
253
+ nn.init.zeros_(self.net[-1].weight); nn.init.zeros_(self.net[-1].bias)
254
+ def forward(self, x): return x + self.net(x)
255
+
256
+ class SpectralCrossAttention(nn.Module):
257
+ def __init__(self, D, n_heads=4, max_alpha=0.2, alpha_init=-2.0):
258
+ super().__init__()
259
+ self.n_heads = n_heads; self.head_dim = D // n_heads
260
+ self.max_alpha = max_alpha; assert D % n_heads == 0
261
+ self.qkv = nn.Linear(D, 3*D); self.out_proj = nn.Linear(D, D)
262
+ self.norm = nn.LayerNorm(D); self.scale = self.head_dim**-0.5
263
+ self.alpha_logits = nn.Parameter(torch.full((D,), alpha_init))
264
+ @property
265
+ def alpha(self): return self.max_alpha * torch.sigmoid(self.alpha_logits)
266
+ def forward(self, S):
267
+ B, N, D = S.shape; S_n = self.norm(S)
268
+ qkv = self.qkv(S_n).reshape(B,N,3,self.n_heads,self.head_dim).permute(2,0,3,1,4)
269
+ q, k, v = qkv[0], qkv[1], qkv[2]
270
+ out = (((q @ k.transpose(-2,-1))*self.scale).softmax(-1) @ v).transpose(1,2).reshape(B,N,D)
271
+ return S * (1.0 + self.alpha.unsqueeze(0).unsqueeze(0) * torch.tanh(self.out_proj(out)))
272
+
273
+ class PatchSVAE(nn.Module):
274
+ def __init__(self, matrix_v=256, D=16, patch_size=16, hidden=768, depth=4, n_cross_layers=2):
275
+ super().__init__()
276
+ self.matrix_v, self.D, self.patch_size = matrix_v, D, patch_size
277
+ self.patch_dim = 3*patch_size*patch_size; self.mat_dim = matrix_v*D
278
+ self.enc_in = nn.Linear(self.patch_dim, hidden)
279
+ self.enc_blocks = nn.ModuleList([nn.Sequential(
280
+ nn.LayerNorm(hidden), nn.Linear(hidden, hidden),
281
+ nn.GELU(), nn.Linear(hidden, hidden)) for _ in range(depth)])
282
+ self.enc_out = nn.Linear(hidden, self.mat_dim)
283
+ self.dec_in = nn.Linear(self.mat_dim, hidden)
284
+ self.dec_blocks = nn.ModuleList([nn.Sequential(
285
+ nn.LayerNorm(hidden), nn.Linear(hidden, hidden),
286
+ nn.GELU(), nn.Linear(hidden, hidden)) for _ in range(depth)])
287
+ self.dec_out = nn.Linear(hidden, self.patch_dim)
288
+ nn.init.orthogonal_(self.enc_out.weight)
289
+ self.cross_attn = nn.ModuleList([
290
+ SpectralCrossAttention(D, n_heads=min(4,D)) for _ in range(n_cross_layers)])
291
+ self.boundary_smooth = BoundarySmooth(channels=3, mid=16)
292
+
293
+ def encode_patches(self, patches):
294
+ B, N, _ = patches.shape
295
+ h = F.gelu(self.enc_in(patches.reshape(B*N,-1)))
296
+ for block in self.enc_blocks: h = h + block(h)
297
+ M = F.normalize(self.enc_out(h).reshape(B*N, self.matrix_v, self.D), dim=-1)
298
+ U, S, Vt = svd_fp64(M)
299
+ U = U.reshape(B,N,self.matrix_v,self.D); S = S.reshape(B,N,self.D)
300
+ Vt = Vt.reshape(B,N,self.D,self.D); M = M.reshape(B,N,self.matrix_v,self.D)
301
+ S_c = S
302
+ for layer in self.cross_attn: S_c = layer(S_c)
303
+ return {'U':U, 'S_orig':S, 'S':S_c, 'Vt':Vt, 'M':M}
304
+
305
+ def decode_patches(self, U, S, Vt):
306
+ B, N, V, D = U.shape
307
+ M_hat = torch.bmm(U.reshape(B*N,V,D)*S.reshape(B*N,D).unsqueeze(1), Vt.reshape(B*N,D,D))
308
+ h = F.gelu(self.dec_in(M_hat.reshape(B*N,-1)))
309
+ for block in self.dec_blocks: h = h + block(h)
310
+ return self.dec_out(h).reshape(B, N, -1)
311
+
312
+ def forward(self, images):
313
+ patches, gh, gw = extract_patches(images, self.patch_size)
314
+ svd = self.encode_patches(patches)
315
+ recon = stitch_patches(self.decode_patches(svd['U'], svd['S'], svd['Vt']), gh, gw, self.patch_size)
316
+ return {'recon': self.boundary_smooth(recon), 'svd': svd}
317
+
318
+ @staticmethod
319
+ def effective_rank(S):
320
+ p = S / (S.sum(-1, keepdim=True)+1e-8); p = p.clamp(min=1e-8)
321
+ return (-(p * p.log()).sum(-1)).exp()
322
+
323
+
324
+ # ── Per-Type MSE Evaluation ──────────────────────────────────────
325
+
326
+ def eval_per_type(model, dataset, device, n_per_type=64):
327
+ """Evaluate MSE for each active noise type independently."""
328
+ model.eval()
329
+ type_mse = {}
330
+ with torch.no_grad():
331
+ for t in dataset.active_types:
332
+ imgs = torch.stack([dataset._generate(t).clamp(-4, 4) for _ in range(n_per_type)]).to(device)
333
+ out = model(imgs)
334
+ type_mse[t] = F.mse_loss(out['recon'], imgs).item()
335
+ return type_mse
336
+
337
+
338
+ # ── Training ─────────────────────────────────────────────────────
339
+
340
+ def train():
341
+ V, D, patch_size = 256, 16, 16
342
+ hidden, depth = 768, 4
343
+ n_cross_layers = 2
344
+ batch_size = 512
345
+ lr = 3e-4
346
+ epochs = 300
347
+ target_cv = 0.125
348
+ cv_weight, boost, sigma = 0.3, 0.5, 0.15
349
+ img_size = 64
350
+
351
+ # Curriculum config
352
+ promote_patience = 10 # epochs of <1% improvement before promoting
353
+ promote_threshold = 0.01 # relative improvement threshold
354
+
355
+ save_dir = '/content/checkpoints'
356
+ save_every = 25
357
+ hf_repo = 'AbstractPhil/geolip-SVAE'
358
+ hf_version = 'v18_johanna_curriculum'
359
+ tb_dir = '/content/runs'
360
+
361
+ os.makedirs(save_dir, exist_ok=True)
362
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
363
+
364
+ from torch.utils.tensorboard import SummaryWriter
365
+ run_name = f"johanna_tiny_curriculum_64x64_h{hidden}_d{depth}_lr{lr}"
366
+ tb_path = os.path.join(tb_dir, run_name)
367
+ writer = SummaryWriter(tb_path)
368
+ print(f" TensorBoard: {tb_path}")
369
+
370
+ hf_enabled = False
371
+ try:
372
+ from huggingface_hub import HfApi
373
+ api = HfApi(); api.whoami(); hf_enabled = True
374
+ hf_prefix = f"{hf_version}/checkpoints"
375
+ print(f" HuggingFace: {hf_repo}/{hf_prefix}")
376
+ except Exception as e:
377
+ print(f" HuggingFace: disabled ({e})")
378
+
379
+ def upload_to_hf(local_path, remote_name):
380
+ if not hf_enabled: return
381
+ try:
382
+ api.upload_file(path_or_fileobj=local_path,
383
+ path_in_repo=f"{hf_prefix}/{remote_name}",
384
+ repo_id=hf_repo, repo_type="model")
385
+ print(f" ☁️ Uploaded: {hf_repo}/{hf_prefix}/{remote_name}")
386
+ except Exception as e:
387
+ print(f" ⚠️ HF upload: {e}")
388
+
389
+ # ── Data: Curriculum noise ──
390
+ train_ds = CurriculumNoiseDataset(size=500000, img_size=img_size)
391
+ val_ds = CurriculumNoiseDataset(size=10000, img_size=img_size)
392
+ train_loader = torch.utils.data.DataLoader(
393
+ train_ds, batch_size=batch_size, shuffle=True,
394
+ num_workers=4, pin_memory=True, drop_last=True)
395
+ test_loader = torch.utils.data.DataLoader(
396
+ val_ds, batch_size=batch_size, shuffle=False,
397
+ num_workers=4, pin_memory=True)
398
+
399
+ # ── Model: fresh init ──
400
+ model = PatchSVAE(matrix_v=V, D=D, patch_size=patch_size,
401
+ hidden=hidden, depth=depth,
402
+ n_cross_layers=n_cross_layers).to(device)
403
+ opt = torch.optim.Adam(model.parameters(), lr=lr)
404
+ sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=epochs)
405
+
406
+ total_params = sum(p.numel() for p in model.parameters())
407
+
408
+ print(f"\n JOHANNA-TINY CURRICULUM TRAINER")
409
+ print(f" {img_size}Γ—{img_size}, 16 patches, ({V},{D}), {total_params:,} params")
410
+ print(f" Batch={batch_size}, lr={lr}, epochs={epochs}")
411
+ print(f" Tiers: {len(TIERS)} tiers, promote after {promote_patience} epochs of <{promote_threshold*100:.0f}% improvement")
412
+ for tier_id, types in sorted(TIERS.items()):
413
+ names = [NOISE_NAMES[t] for t in types]
414
+ print(f" Tier {tier_id}: {', '.join(names)}")
415
+ print("=" * 110)
416
+ print(f" {'ep':>3} {'tier':>4} {'types':>5} | {'loss':>7} {'recon':>7} | "
417
+ f"{'S0':>6} {'SD':>6} {'ratio':>5} {'erank':>5} | "
418
+ f"{'row_cv':>7} {'prox':>5} | {'per-type MSE':>40}")
419
+ print("-" * 110)
420
+
421
+ best_recon = float('inf')
422
+ tier_best_mse = float('inf')
423
+ stale_epochs = 0
424
+
425
+ def save_checkpoint(path, epoch, test_mse, extra=None, upload=True):
426
+ ckpt = {
427
+ 'epoch': epoch, 'test_mse': test_mse,
428
+ 'current_tier': train_ds.current_tier,
429
+ 'active_types': train_ds.active_types,
430
+ 'model_state_dict': model.state_dict(),
431
+ 'optimizer_state_dict': opt.state_dict(),
432
+ 'scheduler_state_dict': sched.state_dict(),
433
+ 'config': {
434
+ 'V': V, 'D': D, 'patch_size': patch_size,
435
+ 'hidden': hidden, 'depth': depth,
436
+ 'n_cross_layers': n_cross_layers,
437
+ 'target_cv': target_cv, 'dataset': 'curriculum_noise',
438
+ 'img_size': img_size, 'lr': lr,
439
+ },
440
+ }
441
+ if extra: ckpt.update(extra)
442
+ torch.save(ckpt, path)
443
+ size_mb = os.path.getsize(path) / (1024 * 1024)
444
+ print(f" πŸ’Ύ Saved: {path} ({size_mb:.1f}MB, ep{epoch}, tier{train_ds.current_tier}, MSE={test_mse:.6f})")
445
+ if upload: upload_to_hf(path, os.path.basename(path))
446
+
447
+ for epoch in range(1, epochs + 1):
448
+ model.train()
449
+ total_loss, total_recon, n = 0, 0, 0
450
+ last_cv, last_prox = target_cv, 1.0
451
+ t0 = time.time()
452
+
453
+ pbar = tqdm(train_loader, desc=f"Ep {epoch} T{train_ds.current_tier}({len(train_ds.active_types)})",
454
+ bar_format='{l_bar}{bar:20}{r_bar}')
455
+ for batch_idx, (images, noise_types) in enumerate(pbar):
456
+ images = images.to(device)
457
+ opt.zero_grad()
458
+ out = model(images)
459
+ recon_loss = F.mse_loss(out['recon'], images)
460
+
461
+ with torch.no_grad():
462
+ if batch_idx % 50 == 0:
463
+ current_cv = cv_of(out['svd']['M'][0, 0])
464
+ if current_cv > 0: last_cv = current_cv
465
+ delta = last_cv - target_cv
466
+ last_prox = math.exp(-delta**2 / (2*sigma**2))
467
+
468
+ recon_w = 1.0 + boost * last_prox
469
+ cv_pen = cv_weight * (1.0 - last_prox)
470
+ loss = recon_w * recon_loss + cv_pen * (last_cv - target_cv)**2
471
+ loss.backward()
472
+
473
+ torch.nn.utils.clip_grad_norm_(model.cross_attn.parameters(), max_norm=0.5)
474
+ opt.step()
475
+
476
+ total_loss += loss.item() * len(images)
477
+ total_recon += recon_loss.item() * len(images)
478
+ n += len(images)
479
+ pbar.set_postfix_str(f"mse={recon_loss.item():.4f} cv={last_cv:.3f} prox={last_prox:.2f}")
480
+
481
+ pbar.close()
482
+ sched.step()
483
+ epoch_time = time.time() - t0
484
+
485
+ # ── Evaluation: overall + per-type ──
486
+ model.eval()
487
+ test_mse_total, test_n = 0, 0
488
+ with torch.no_grad():
489
+ for imgs, _ in test_loader:
490
+ imgs = imgs.to(device)
491
+ out = model(imgs)
492
+ test_mse_total += F.mse_loss(out['recon'], imgs).item() * len(imgs)
493
+ test_n += len(imgs)
494
+ test_mse = test_mse_total / test_n
495
+
496
+ # Per-type MSE
497
+ type_mse = eval_per_type(model, train_ds, device, n_per_type=64)
498
+ type_str = " ".join([f"{NOISE_NAMES[t][:4]}={v:.3f}" for t, v in sorted(type_mse.items())])
499
+
500
+ # Geometry
501
+ with torch.no_grad():
502
+ sample, _ = next(iter(test_loader))
503
+ sample = sample[:64].to(device)
504
+ out = model(sample)
505
+ S_mean = out['svd']['S'].mean(dim=(0,1))
506
+ ratio = (S_mean[0] / (S_mean[-1]+1e-8)).item()
507
+ erank = model.effective_rank(out['svd']['S'].reshape(-1, D)).mean().item()
508
+
509
+ # TB logging
510
+ writer.add_scalar('train/recon', total_recon/n, epoch)
511
+ writer.add_scalar('test/mse', test_mse, epoch)
512
+ writer.add_scalar('curriculum/tier', train_ds.current_tier, epoch)
513
+ writer.add_scalar('curriculum/n_types', len(train_ds.active_types), epoch)
514
+ writer.add_scalar('geo/cv', last_cv, epoch)
515
+ writer.add_scalar('geo/S0', S_mean[0].item(), epoch)
516
+ writer.add_scalar('geo/ratio', ratio, epoch)
517
+ for t, mse in type_mse.items():
518
+ writer.add_scalar(f'per_type/{NOISE_NAMES[t]}', mse, epoch)
519
+
520
+ print(f" {epoch:3d} T{train_ds.current_tier:>2} {len(train_ds.active_types):>3}t | "
521
+ f"{total_loss/n:7.4f} {total_recon/n:7.4f} | "
522
+ f"{S_mean[0]:6.3f} {S_mean[-1]:6.3f} {ratio:5.2f} {erank:5.2f} | "
523
+ f"{last_cv:7.4f} {last_prox:5.3f} | {type_str}")
524
+
525
+ # ── Tier promotion logic ──
526
+ improvement = (tier_best_mse - test_mse) / (tier_best_mse + 1e-8)
527
+ if test_mse < tier_best_mse:
528
+ tier_best_mse = test_mse
529
+ if improvement < promote_threshold:
530
+ stale_epochs += 1
531
+ else:
532
+ stale_epochs = 0
533
+
534
+ if stale_epochs >= promote_patience and train_ds.current_tier < max(TIERS.keys()):
535
+ next_tier = train_ds.current_tier + 1
536
+ train_ds.unlock_tier(next_tier)
537
+ val_ds.unlock_tier(next_tier)
538
+ new_names = [NOISE_NAMES[t] for t in TIERS[next_tier]]
539
+ print(f"\n β˜… PROMOTED TO TIER {next_tier}: +{', '.join(new_names)}")
540
+ print(f" Active types: {[NOISE_NAMES[t] for t in train_ds.active_types]}")
541
+ print(f" Tier MSE was: {tier_best_mse:.6f}\n")
542
+ tier_best_mse = test_mse # reset for new tier
543
+ stale_epochs = 0
544
+
545
+ # Save promotion checkpoint
546
+ save_checkpoint(os.path.join(save_dir, f'tier{next_tier}_start.pt'),
547
+ epoch, test_mse, upload=True)
548
+
549
+ # ── Checkpoints ──
550
+ if test_mse < best_recon:
551
+ best_recon = test_mse
552
+ save_checkpoint(os.path.join(save_dir, 'best.pt'),
553
+ epoch, test_mse, upload=False)
554
+
555
+ if epoch % save_every == 0:
556
+ save_checkpoint(os.path.join(save_dir, f'epoch_{epoch:04d}.pt'),
557
+ epoch, test_mse)
558
+ best_path = os.path.join(save_dir, 'best.pt')
559
+ if os.path.exists(best_path):
560
+ upload_to_hf(best_path, 'best.pt')
561
+ writer.flush()
562
+ if hf_enabled:
563
+ try:
564
+ api.upload_folder(folder_path=tb_path,
565
+ path_in_repo=f"{hf_version}/tensorboard/{run_name}",
566
+ repo_id=hf_repo, repo_type="model")
567
+ print(f" ☁️ TB synced")
568
+ except: pass
569
+
570
+ writer.close()
571
+ print(f"\n CURRICULUM TRAINING COMPLETE")
572
+ print(f" Final tier: {train_ds.current_tier}")
573
+ print(f" Active types: {[NOISE_NAMES[t] for t in train_ds.active_types]}")
574
+ print(f" Best MSE: {best_recon:.6f}")
575
+
576
+
577
+ if __name__ == "__main__":
578
+ torch.set_float32_matmul_precision('high')
579
+ train()