AbstractPhil commited on
Commit
f5ff727
Β·
verified Β·
1 Parent(s): 490ac4d

Create modeling_trainer_v2.py

Browse files
Files changed (1) hide show
  1. modeling_trainer_v2.py +548 -0
modeling_trainer_v2.py ADDED
@@ -0,0 +1,548 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Constellation Diffusion
4
+ ========================
5
+ Everything through the sphere. No skip projection. No attention.
6
+ The constellation IS the model's information bottleneck.
7
+
8
+ 16384d encoder output β†’ 256d sphere β†’ 768d triangulation
9
+ β†’ conditioned patchwork β†’ 16384d reconstruction
10
+
11
+ The patchwork must carry ALL information through 768 geometric
12
+ measurements. If it works, diffusion is solved through triangulation.
13
+ """
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ import numpy as np
19
+ import math
20
+ import os
21
+ import time
22
+ from tqdm import tqdm
23
+ from torchvision import datasets, transforms
24
+ from torchvision.utils import save_image, make_grid
25
+
26
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
27
+ torch.backends.cuda.matmul.allow_tf32 = True
28
+ torch.backends.cudnn.allow_tf32 = True
29
+
30
+
31
+ # ══════════════════════════════════════════════════════════════════
32
+ # CONSTELLATION BOTTLENECK β€” NO SKIP
33
+ # ══════════════════════════════════════════════════════════════════
34
+
35
+ class ConstellationBottleneck(nn.Module):
36
+ """
37
+ Pure constellation bottleneck. No skip path.
38
+ All information passes through S^15 triangulation.
39
+
40
+ Flow:
41
+ (B, spatial) β†’ proj_in(spatial, embed) β†’ LN β†’ reshape β†’ L2 norm
42
+ β†’ triangulate: P patches Γ— A anchors Γ— n_phases = tri_dim
43
+ β†’ concat(tri, cond)
44
+ β†’ deep patchwork with residual blocks
45
+ β†’ proj_out(hidden, spatial)
46
+ """
47
+ def __init__(
48
+ self,
49
+ spatial_dim, # C*H*W from encoder
50
+ embed_dim=256,
51
+ patch_dim=16,
52
+ n_anchors=16,
53
+ n_phases=3,
54
+ cond_dim=256,
55
+ pw_hidden=1024,
56
+ pw_depth=4, # number of residual blocks in patchwork
57
+ ):
58
+ super().__init__()
59
+ self.spatial_dim = spatial_dim
60
+ self.embed_dim = embed_dim
61
+ self.patch_dim = patch_dim
62
+ self.n_patches = embed_dim // patch_dim
63
+ self.n_anchors = n_anchors
64
+ self.n_phases = n_phases
65
+
66
+ P, A, d = self.n_patches, n_anchors, patch_dim
67
+
68
+ # Encoder projection β†’ sphere
69
+ self.proj_in = nn.Sequential(
70
+ nn.Linear(spatial_dim, embed_dim),
71
+ nn.LayerNorm(embed_dim),
72
+ )
73
+
74
+ # Constellation anchors β€” home + learnable
75
+ home = torch.empty(P, A, d)
76
+ nn.init.xavier_normal_(home.view(P * A, d))
77
+ home = F.normalize(home.view(P, A, d), dim=-1)
78
+ self.register_buffer('home', home)
79
+ self.anchors = nn.Parameter(home.clone())
80
+
81
+ # Triangulation dimensions
82
+ tri_dim = P * A * n_phases # 16 * 16 * 3 = 768
83
+
84
+ # Conditioning projection β€” align cond to patchwork input space
85
+ pw_input = tri_dim + cond_dim
86
+ self.input_proj = nn.Sequential(
87
+ nn.Linear(pw_input, pw_hidden),
88
+ nn.GELU(),
89
+ nn.LayerNorm(pw_hidden),
90
+ )
91
+
92
+ # Deep patchwork β€” residual MLP blocks
93
+ # This must carry ALL information. Make it deep enough.
94
+ self.pw_blocks = nn.ModuleList()
95
+ for _ in range(pw_depth):
96
+ self.pw_blocks.append(nn.Sequential(
97
+ nn.Linear(pw_hidden, pw_hidden),
98
+ nn.GELU(),
99
+ nn.LayerNorm(pw_hidden),
100
+ nn.Linear(pw_hidden, pw_hidden),
101
+ nn.GELU(),
102
+ nn.LayerNorm(pw_hidden),
103
+ ))
104
+
105
+ # Reconstruction head
106
+ self.proj_out = nn.Sequential(
107
+ nn.Linear(pw_hidden, pw_hidden),
108
+ nn.GELU(),
109
+ nn.Linear(pw_hidden, spatial_dim),
110
+ )
111
+
112
+ def drift(self):
113
+ h, c = F.normalize(self.home, dim=-1), F.normalize(self.anchors, dim=-1)
114
+ return torch.acos((h * c).sum(-1).clamp(-1 + 1e-7, 1 - 1e-7))
115
+
116
+ def at_phase(self, t):
117
+ h, c = F.normalize(self.home, dim=-1), F.normalize(self.anchors, dim=-1)
118
+ omega = self.drift().unsqueeze(-1)
119
+ so = omega.sin().clamp(min=1e-7)
120
+ return torch.sin((1-t)*omega)/so * h + torch.sin(t*omega)/so * c
121
+
122
+ def triangulate(self, patches_n):
123
+ """
124
+ patches_n: (B, P, d) normalized on S^(d-1)
125
+ Returns: (B, P*A*n_phases) full triangulation profile
126
+ """
127
+ phases = torch.linspace(0, 1, self.n_phases, device=patches_n.device).tolist()
128
+ tris = []
129
+ for t in phases:
130
+ anchors_t = F.normalize(self.at_phase(t), dim=-1)
131
+ cos = torch.einsum('bpd,pad->bpa', patches_n, anchors_t)
132
+ tris.append(1.0 - cos)
133
+ return torch.cat(tris, dim=-1).reshape(patches_n.shape[0], -1)
134
+
135
+ def forward(self, x_flat, cond):
136
+ """
137
+ x_flat: (B, spatial_dim)
138
+ cond: (B, cond_dim)
139
+ Returns: (B, spatial_dim)
140
+ """
141
+ # Project to sphere
142
+ emb = self.proj_in(x_flat) # (B, embed_dim)
143
+ B = emb.shape[0]
144
+ patches = emb.reshape(B, self.n_patches, self.patch_dim)
145
+ patches_n = F.normalize(patches, dim=-1) # on S^(d-1)
146
+
147
+ # Triangulate β€” the geometric encoding
148
+ tri = self.triangulate(patches_n) # (B, tri_dim)
149
+
150
+ # Inject conditioning
151
+ pw_in = torch.cat([tri, cond], dim=-1) # (B, tri_dim + cond_dim)
152
+
153
+ # Deep patchwork with residual connections
154
+ h = self.input_proj(pw_in)
155
+ for block in self.pw_blocks:
156
+ h = h + block(h) # residual
157
+
158
+ # Reconstruct spatial features
159
+ return self.proj_out(h)
160
+
161
+
162
+ # ══════════════════════════════════════════════════════════════════
163
+ # UNET BUILDING BLOCKS
164
+ # ══════════════════════════════════════════════════════════════════
165
+
166
+ class SinusoidalPosEmb(nn.Module):
167
+ def __init__(self, dim):
168
+ super().__init__()
169
+ self.dim = dim
170
+
171
+ def forward(self, t):
172
+ half = self.dim // 2
173
+ emb = math.log(10000) / (half - 1)
174
+ emb = torch.exp(torch.arange(half, device=t.device, dtype=t.dtype) * -emb)
175
+ emb = t.unsqueeze(-1) * emb.unsqueeze(0)
176
+ return torch.cat([emb.sin(), emb.cos()], dim=-1)
177
+
178
+
179
+ class AdaGroupNorm(nn.Module):
180
+ def __init__(self, channels, cond_dim, n_groups=8):
181
+ super().__init__()
182
+ self.gn = nn.GroupNorm(min(n_groups, channels), channels, affine=False)
183
+ self.proj = nn.Linear(cond_dim, channels * 2)
184
+ nn.init.zeros_(self.proj.weight)
185
+ nn.init.zeros_(self.proj.bias)
186
+
187
+ def forward(self, x, cond):
188
+ x = self.gn(x)
189
+ s, sh = self.proj(cond).unsqueeze(-1).unsqueeze(-1).chunk(2, dim=1)
190
+ return x * (1 + s) + sh
191
+
192
+
193
+ class ConvBlock(nn.Module):
194
+ def __init__(self, channels, cond_dim):
195
+ super().__init__()
196
+ self.dw = nn.Conv2d(channels, channels, 7, padding=3, groups=channels)
197
+ self.norm = AdaGroupNorm(channels, cond_dim)
198
+ self.pw1 = nn.Conv2d(channels, channels * 4, 1)
199
+ self.pw2 = nn.Conv2d(channels * 4, channels, 1)
200
+ self.act = nn.GELU()
201
+
202
+ def forward(self, x, cond):
203
+ r = x
204
+ x = self.dw(x)
205
+ x = self.norm(x, cond)
206
+ x = self.act(self.pw1(x))
207
+ return r + self.pw2(x)
208
+
209
+
210
+ class Downsample(nn.Module):
211
+ def __init__(self, ch):
212
+ super().__init__()
213
+ self.conv = nn.Conv2d(ch, ch, 3, stride=2, padding=1)
214
+ def forward(self, x): return self.conv(x)
215
+
216
+
217
+ class Upsample(nn.Module):
218
+ def __init__(self, ch):
219
+ super().__init__()
220
+ self.conv = nn.Conv2d(ch, ch, 3, padding=1)
221
+ def forward(self, x):
222
+ return self.conv(F.interpolate(x, scale_factor=2, mode='nearest'))
223
+
224
+
225
+ # ══════════════════════════════════════════════════════════════════
226
+ # CONSTELLATION DIFFUSION UNET
227
+ # ══════════════════════════════════════════════════════════════════
228
+
229
+ class ConstellationDiffusionUNet(nn.Module):
230
+ """
231
+ UNet where the middle block IS the constellation.
232
+ No attention. No skip projection. Pure geometric bottleneck.
233
+ """
234
+ def __init__(
235
+ self,
236
+ in_ch=3,
237
+ base_ch=64,
238
+ ch_mults=(1, 2, 4),
239
+ n_classes=10,
240
+ cond_dim=256,
241
+ embed_dim=256,
242
+ n_anchors=16,
243
+ n_phases=3,
244
+ pw_hidden=1024,
245
+ pw_depth=4,
246
+ ):
247
+ super().__init__()
248
+ self.ch_mults = ch_mults
249
+
250
+ # Conditioning
251
+ self.time_emb = nn.Sequential(
252
+ SinusoidalPosEmb(cond_dim),
253
+ nn.Linear(cond_dim, cond_dim), nn.GELU(),
254
+ nn.Linear(cond_dim, cond_dim))
255
+ self.class_emb = nn.Embedding(n_classes, cond_dim)
256
+
257
+ self.in_conv = nn.Conv2d(in_ch, base_ch, 3, padding=1)
258
+
259
+ # Encoder
260
+ self.enc = nn.ModuleList()
261
+ self.enc_down = nn.ModuleList()
262
+ ch = base_ch
263
+ enc_channels = [base_ch]
264
+
265
+ for i, m in enumerate(ch_mults):
266
+ ch_out = base_ch * m
267
+ self.enc.append(nn.ModuleList([
268
+ ConvBlock(ch, cond_dim) if ch == ch_out
269
+ else nn.Sequential(nn.Conv2d(ch, ch_out, 1), ConvBlock(ch_out, cond_dim)),
270
+ ConvBlock(ch_out, cond_dim),
271
+ ]))
272
+ ch = ch_out
273
+ enc_channels.append(ch)
274
+ if i < len(ch_mults) - 1:
275
+ self.enc_down.append(Downsample(ch))
276
+
277
+ # Constellation bottleneck β€” NO SKIP
278
+ mid_ch = ch
279
+ H_mid = 32 // (2 ** (len(ch_mults) - 1)) # spatial size at bottleneck
280
+ spatial_dim = mid_ch * H_mid * H_mid
281
+ self.mid_spatial = (mid_ch, H_mid, H_mid)
282
+
283
+ self.bottleneck = ConstellationBottleneck(
284
+ spatial_dim=spatial_dim,
285
+ embed_dim=embed_dim,
286
+ patch_dim=16,
287
+ n_anchors=n_anchors,
288
+ n_phases=n_phases,
289
+ cond_dim=cond_dim,
290
+ pw_hidden=pw_hidden,
291
+ pw_depth=pw_depth,
292
+ )
293
+
294
+ # Decoder
295
+ self.dec_up = nn.ModuleList()
296
+ self.dec_skip_proj = nn.ModuleList()
297
+ self.dec = nn.ModuleList()
298
+
299
+ for i in range(len(ch_mults) - 1, -1, -1):
300
+ ch_out = base_ch * ch_mults[i]
301
+ skip_ch = enc_channels.pop()
302
+ self.dec_skip_proj.append(nn.Conv2d(ch + skip_ch, ch_out, 1))
303
+ self.dec.append(nn.ModuleList([
304
+ ConvBlock(ch_out, cond_dim),
305
+ ConvBlock(ch_out, cond_dim),
306
+ ]))
307
+ ch = ch_out
308
+ if i > 0:
309
+ self.dec_up.append(Upsample(ch))
310
+
311
+ self.out_norm = nn.GroupNorm(8, ch)
312
+ self.out_conv = nn.Conv2d(ch, in_ch, 3, padding=1)
313
+ nn.init.zeros_(self.out_conv.weight)
314
+ nn.init.zeros_(self.out_conv.bias)
315
+
316
+ def forward(self, x, t, class_labels):
317
+ cond = self.time_emb(t) + self.class_emb(class_labels)
318
+ h = self.in_conv(x)
319
+ skips = [h]
320
+
321
+ # Encoder
322
+ for i in range(len(self.ch_mults)):
323
+ for block in self.enc[i]:
324
+ if isinstance(block, ConvBlock):
325
+ h = block(h, cond)
326
+ elif isinstance(block, nn.Sequential):
327
+ h = block[0](h); h = block[1](h, cond)
328
+ skips.append(h)
329
+ if i < len(self.enc_down):
330
+ h = self.enc_down[i](h)
331
+
332
+ # β˜… CONSTELLATION BOTTLENECK β€” everything through S^15 β˜…
333
+ B = h.shape[0]
334
+ h = self.bottleneck(h.reshape(B, -1), cond)
335
+ h = h.reshape(B, *self.mid_spatial)
336
+
337
+ # Decoder
338
+ for i in range(len(self.ch_mults)):
339
+ skip = skips.pop()
340
+ if i > 0:
341
+ h = self.dec_up[i - 1](h)
342
+ h = torch.cat([h, skip], dim=1)
343
+ h = self.dec_skip_proj[i](h)
344
+ for block in self.dec[i]:
345
+ h = block(h, cond)
346
+
347
+ return self.out_conv(F.silu(self.out_norm(h)))
348
+
349
+
350
+ # ══════════════════════════════════════════════════════════════════
351
+ # SAMPLING
352
+ # ══════════════════════════════════════════════════════════════════
353
+
354
+ @torch.no_grad()
355
+ def sample(model, n=64, steps=50, cls=None, n_cls=10):
356
+ model.eval()
357
+ x = torch.randn(n, 3, 32, 32, device=DEVICE)
358
+ labels = (torch.full((n,), cls, dtype=torch.long, device=DEVICE)
359
+ if cls is not None else torch.randint(0, n_cls, (n,), device=DEVICE))
360
+ dt = 1.0 / steps
361
+ for s in range(steps):
362
+ t = torch.full((n,), 1.0 - s * dt, device=DEVICE)
363
+ with torch.amp.autocast("cuda", dtype=torch.bfloat16):
364
+ v = model(x, t, labels)
365
+ x = x - v.float() * dt
366
+ return x.clamp(-1, 1), labels
367
+
368
+
369
+ # ══════════════════════════════════════════════════════════════════
370
+ # TRAINING
371
+ # ══════════════════════════════════════════════════════════════════
372
+
373
+ BATCH = 128
374
+ EPOCHS = 80
375
+ LR = 3e-4
376
+ SAMPLE_EVERY = 5
377
+
378
+ print("=" * 70)
379
+ print("CONSTELLATION DIFFUSION β€” PURE GEOMETRIC BOTTLENECK")
380
+ print(f" No attention. No skip. Everything through S^15.")
381
+ print(f" Device: {DEVICE}")
382
+ print("=" * 70)
383
+
384
+ transform = transforms.Compose([
385
+ transforms.RandomHorizontalFlip(),
386
+ transforms.ToTensor(),
387
+ transforms.Normalize((0.5,)*3, (0.5,)*3),
388
+ ])
389
+ train_ds = datasets.CIFAR10('./data', train=True, download=True, transform=transform)
390
+ train_loader = torch.utils.data.DataLoader(
391
+ train_ds, batch_size=BATCH, shuffle=True,
392
+ num_workers=4, pin_memory=True, drop_last=True)
393
+
394
+ model = ConstellationDiffusionUNet(
395
+ in_ch=3, base_ch=64, ch_mults=(1, 2, 4),
396
+ n_classes=10, cond_dim=256, embed_dim=256,
397
+ n_anchors=16, n_phases=3, pw_hidden=1024, pw_depth=4,
398
+ ).to(DEVICE)
399
+
400
+ n_params = sum(p.numel() for p in model.parameters())
401
+ n_bn = sum(p.numel() for p in model.bottleneck.parameters())
402
+ n_enc = sum(p.numel() for n, p in model.named_parameters()
403
+ if 'enc' in n or 'in_conv' in n)
404
+ n_dec = sum(p.numel() for n, p in model.named_parameters()
405
+ if 'dec' in n or 'out' in n)
406
+ n_anchor = sum(p.numel() for n, p in model.named_parameters() if 'anchor' in n)
407
+
408
+ print(f" Total: {n_params:,}")
409
+ print(f" Encoder: {n_enc:,}")
410
+ print(f" Bottleneck: {n_bn:,} ({100*n_bn/n_params:.1f}%)")
411
+ print(f" Anchors: {n_anchor:,}")
412
+ print(f" Decoder: {n_dec:,}")
413
+ print(f" Train: {len(train_ds):,} images")
414
+
415
+ # Shape check
416
+ with torch.no_grad():
417
+ d = torch.randn(2, 3, 32, 32, device=DEVICE)
418
+ o = model(d, torch.rand(2, device=DEVICE), torch.randint(0, 10, (2,), device=DEVICE))
419
+ print(f" Shape: {d.shape} β†’ {o.shape} βœ“")
420
+ bn = model.bottleneck
421
+ print(f" Bottleneck: {bn.spatial_dim}d β†’ {bn.embed_dim}d sphere β†’ "
422
+ f"{bn.n_patches}pΓ—{bn.patch_dim}d β†’ "
423
+ f"{bn.n_patches * bn.n_anchors * bn.n_phases} tri dims")
424
+ print(f" Patchwork: {len(bn.pw_blocks)} residual blocks Γ— {1024}d")
425
+ print(f" Compression: {bn.spatial_dim} β†’ {bn.n_patches * bn.n_anchors * bn.n_phases} "
426
+ f"({bn.spatial_dim / (bn.n_patches * bn.n_anchors * bn.n_phases):.1f}Γ— ratio)")
427
+
428
+ optimizer = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=0.01)
429
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
430
+ optimizer, T_max=EPOCHS * len(train_loader), eta_min=1e-6)
431
+ scaler = torch.amp.GradScaler("cuda")
432
+
433
+ os.makedirs("samples_cd", exist_ok=True)
434
+ os.makedirs("checkpoints", exist_ok=True)
435
+
436
+ print(f"\n{'='*70}")
437
+ print(f"TRAINING β€” {EPOCHS} epochs, pure constellation diffusion")
438
+ print(f"{'='*70}")
439
+
440
+ best_loss = float('inf')
441
+
442
+ for epoch in range(EPOCHS):
443
+ model.train()
444
+ t0 = time.time()
445
+ total_loss = 0
446
+ n = 0
447
+
448
+ pbar = tqdm(train_loader, desc=f"E{epoch+1:3d}/{EPOCHS}", unit="b")
449
+ for images, labels in pbar:
450
+ images = images.to(DEVICE, non_blocking=True)
451
+ labels = labels.to(DEVICE, non_blocking=True)
452
+ B = images.shape[0]
453
+
454
+ t = torch.rand(B, device=DEVICE)
455
+ eps = torch.randn_like(images)
456
+ t_b = t.view(B, 1, 1, 1)
457
+ x_t = (1 - t_b) * images + t_b * eps
458
+ v_target = eps - images
459
+
460
+ with torch.amp.autocast("cuda", dtype=torch.bfloat16):
461
+ v_pred = model(x_t, t, labels)
462
+ loss = F.mse_loss(v_pred, v_target)
463
+
464
+ optimizer.zero_grad(set_to_none=True)
465
+ scaler.scale(loss).backward()
466
+ scaler.unscale_(optimizer)
467
+ nn.utils.clip_grad_norm_(model.parameters(), 1.0)
468
+ scaler.step(optimizer)
469
+ scaler.update()
470
+ scheduler.step()
471
+
472
+ total_loss += loss.item()
473
+ n += 1
474
+ if n % 20 == 0:
475
+ pbar.set_postfix(loss=f"{total_loss/n:.4f}", lr=f"{scheduler.get_last_lr()[0]:.1e}")
476
+
477
+ elapsed = time.time() - t0
478
+ avg_loss = total_loss / n
479
+
480
+ mk = ""
481
+ if avg_loss < best_loss:
482
+ best_loss = avg_loss
483
+ torch.save({
484
+ 'state_dict': model.state_dict(),
485
+ 'epoch': epoch + 1,
486
+ 'loss': avg_loss,
487
+ }, 'checkpoints/constellation_diffusion_best.pt')
488
+ mk = " β˜…"
489
+
490
+ print(f" E{epoch+1:3d}: loss={avg_loss:.4f} lr={scheduler.get_last_lr()[0]:.1e} "
491
+ f"({elapsed:.0f}s){mk}")
492
+
493
+ # Diagnostics
494
+ if (epoch + 1) % 10 == 0:
495
+ with torch.no_grad():
496
+ drift = bn.drift().detach()
497
+ near_029 = (drift - 0.29154).abs().lt(0.05).float().mean().item()
498
+ print(f" β˜… drift: mean={drift.mean():.4f}rad ({math.degrees(drift.mean().item()):.1f}Β°) "
499
+ f"max={drift.max():.4f}rad ({math.degrees(drift.max().item()):.1f}Β°) "
500
+ f"near_0.29: {near_029:.1%}")
501
+
502
+ # Anchor utilization quick check
503
+ test_imgs = torch.randn(64, 3, 32, 32, device=DEVICE)
504
+ t_test = torch.full((64,), 0.5, device=DEVICE)
505
+ c_test = torch.randint(0, 10, (64,), device=DEVICE)
506
+ cond = model.time_emb(t_test) + model.class_emb(c_test)
507
+ h = model.in_conv(test_imgs)
508
+ for i in range(len(model.ch_mults)):
509
+ for block in model.enc[i]:
510
+ if isinstance(block, ConvBlock): h = block(h, cond)
511
+ elif isinstance(block, nn.Sequential): h = block[0](h); h = block[1](h, cond)
512
+ if i < len(model.enc_down): h = model.enc_down[i](h)
513
+
514
+ emb = bn.proj_in(h.reshape(64, -1))
515
+ patches = F.normalize(emb.reshape(64, bn.n_patches, bn.patch_dim), dim=-1)
516
+ anchors_n = F.normalize(bn.anchors, dim=-1)
517
+ cos = torch.einsum('bpd,pad->bpa', patches, anchors_n)
518
+ nearest = cos.argmax(dim=-1) # (64, P)
519
+ # Count unique anchors used across all patches
520
+ unique = nearest.unique().numel()
521
+ total = bn.n_patches * bn.n_anchors
522
+ print(f" β˜… anchors: {unique}/{total} unique assignments "
523
+ f"({100*unique/total:.0f}% utilization)")
524
+
525
+ # Sample
526
+ if (epoch + 1) % SAMPLE_EVERY == 0 or epoch == 0:
527
+ imgs, _ = sample(model, 64, 50)
528
+ save_image(make_grid((imgs + 1) / 2, nrow=8), f'samples_cd/epoch_{epoch+1:03d}.png')
529
+ print(f" β†’ samples_cd/epoch_{epoch+1:03d}.png")
530
+
531
+ if (epoch + 1) % 20 == 0:
532
+ names = ['plane','auto','bird','cat','deer','dog','frog','horse','ship','truck']
533
+ for c in range(10):
534
+ cs, _ = sample(model, 8, 50, cls=c)
535
+ save_image(make_grid((cs+1)/2, nrow=8),
536
+ f'samples_cd/epoch_{epoch+1:03d}_{names[c]}.png')
537
+ print(f" β†’ per-class samples saved")
538
+
539
+
540
+ print(f"\n{'='*70}")
541
+ print(f"CONSTELLATION DIFFUSION β€” COMPLETE")
542
+ print(f" Best loss: {best_loss:.4f}")
543
+ print(f" Params: {n_params:,} (bottleneck: {n_bn:,})")
544
+ with torch.no_grad():
545
+ drift = bn.drift().detach()
546
+ print(f" Final drift: mean={drift.mean():.4f} max={drift.max():.4f}")
547
+ print(f" Near 0.29154: {(drift - 0.29154).abs().lt(0.05).float().mean().item():.1%}")
548
+ print(f"{'='*70}")