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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Constellation Diffusion β Analysis
|
| 3 |
+
=====================================
|
| 4 |
+
Paste after training. Uses `model` and `bn` from memory.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
import numpy as np
|
| 11 |
+
import math
|
| 12 |
+
import os
|
| 13 |
+
from torchvision import datasets, transforms
|
| 14 |
+
from torchvision.utils import save_image, make_grid
|
| 15 |
+
|
| 16 |
+
DEVICE = "cuda"
|
| 17 |
+
os.makedirs("analysis_cd", exist_ok=True)
|
| 18 |
+
|
| 19 |
+
def compute_cv(points, n_samples=1500, n_points=5):
|
| 20 |
+
N = points.shape[0]
|
| 21 |
+
if N < n_points: return float('nan')
|
| 22 |
+
points = F.normalize(points.to(DEVICE).float(), dim=-1)
|
| 23 |
+
vols = []
|
| 24 |
+
for _ in range(n_samples):
|
| 25 |
+
idx = torch.randperm(min(N, 5000), device=DEVICE)[:n_points]
|
| 26 |
+
pts = points[idx].unsqueeze(0)
|
| 27 |
+
gram = torch.bmm(pts, pts.transpose(1, 2))
|
| 28 |
+
norms = torch.diagonal(gram, dim1=1, dim2=2)
|
| 29 |
+
d2 = norms.unsqueeze(2) + norms.unsqueeze(1) - 2 * gram
|
| 30 |
+
d2 = F.relu(d2)
|
| 31 |
+
cm = torch.zeros(1, 6, 6, device=DEVICE, dtype=torch.float32)
|
| 32 |
+
cm[:, 0, 1:] = 1; cm[:, 1:, 0] = 1; cm[:, 1:, 1:] = d2
|
| 33 |
+
v2 = -torch.linalg.det(cm) / 9216
|
| 34 |
+
if v2[0].item() > 1e-20:
|
| 35 |
+
vols.append(v2[0].sqrt().cpu())
|
| 36 |
+
if len(vols) < 50: return float('nan')
|
| 37 |
+
vt = torch.stack(vols)
|
| 38 |
+
return (vt.std() / (vt.mean() + 1e-8)).item()
|
| 39 |
+
|
| 40 |
+
def eff_dim(x):
|
| 41 |
+
x_c = x - x.mean(0, keepdim=True)
|
| 42 |
+
n = min(512, x.shape[0])
|
| 43 |
+
_, S, _ = torch.linalg.svd(x_c[:n].float(), full_matrices=False)
|
| 44 |
+
p = S / S.sum()
|
| 45 |
+
return p.pow(2).sum().reciprocal().item()
|
| 46 |
+
|
| 47 |
+
CLASS_NAMES = ['plane','auto','bird','cat','deer','dog','frog','horse','ship','truck']
|
| 48 |
+
|
| 49 |
+
model.eval()
|
| 50 |
+
bn = model.bottleneck
|
| 51 |
+
|
| 52 |
+
print("=" * 80)
|
| 53 |
+
print("CONSTELLATION DIFFUSION β PURE BOTTLENECK ANALYSIS")
|
| 54 |
+
n_params = sum(p.numel() for p in model.parameters())
|
| 55 |
+
n_bn = sum(p.numel() for p in bn.parameters())
|
| 56 |
+
print(f" Total: {n_params:,} Bottleneck: {n_bn:,} ({100*n_bn/n_params:.1f}%)")
|
| 57 |
+
print(f" Compression: {bn.spatial_dim} β {bn.n_patches * bn.n_anchors * bn.n_phases} "
|
| 58 |
+
f"({bn.spatial_dim / (bn.n_patches * bn.n_anchors * bn.n_phases):.1f}Γ)")
|
| 59 |
+
print("=" * 80)
|
| 60 |
+
|
| 61 |
+
# Test data
|
| 62 |
+
transform = transforms.Compose([
|
| 63 |
+
transforms.ToTensor(), transforms.Normalize((0.5,)*3, (0.5,)*3)])
|
| 64 |
+
test_ds = datasets.CIFAR10('./data', train=False, download=True, transform=transform)
|
| 65 |
+
test_loader = torch.utils.data.DataLoader(test_ds, batch_size=256, shuffle=False)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# Helper: run encoder to get sphere embeddings
|
| 69 |
+
@torch.no_grad()
|
| 70 |
+
def get_sphere_embeddings(images, labels, t_val=0.0):
|
| 71 |
+
"""Run encoder + projection, return patches on S^15 and tri profiles."""
|
| 72 |
+
B = images.shape[0]
|
| 73 |
+
t = torch.full((B,), t_val, device=DEVICE)
|
| 74 |
+
eps = torch.randn_like(images)
|
| 75 |
+
t_b = t.view(B, 1, 1, 1)
|
| 76 |
+
x_t = (1 - t_b) * images + t_b * eps
|
| 77 |
+
|
| 78 |
+
cond = model.time_emb(t) + model.class_emb(labels)
|
| 79 |
+
h = model.in_conv(x_t)
|
| 80 |
+
for i in range(len(model.ch_mults)):
|
| 81 |
+
for block in model.enc[i]:
|
| 82 |
+
if isinstance(block, nn.Sequential):
|
| 83 |
+
h = block[0](h); h = block[1](h, cond)
|
| 84 |
+
else:
|
| 85 |
+
h = block(h, cond)
|
| 86 |
+
if i < len(model.enc_down):
|
| 87 |
+
h = model.enc_down[i](h)
|
| 88 |
+
|
| 89 |
+
h_flat = h.reshape(B, -1)
|
| 90 |
+
emb = bn.proj_in(h_flat)
|
| 91 |
+
patches = emb.reshape(B, bn.n_patches, bn.patch_dim)
|
| 92 |
+
patches_n = F.normalize(patches, dim=-1)
|
| 93 |
+
tri = bn.triangulate(patches_n)
|
| 94 |
+
return patches_n, tri, h_flat
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 98 |
+
# TEST 1: DRIFT & ANCHOR DIAGNOSTICS
|
| 99 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 100 |
+
|
| 101 |
+
print(f"\n{'β'*80}")
|
| 102 |
+
print("TEST 1: Drift & Anchor Diagnostics")
|
| 103 |
+
print(f"{'β'*80}")
|
| 104 |
+
|
| 105 |
+
with torch.no_grad():
|
| 106 |
+
drift = bn.drift().detach()
|
| 107 |
+
home = F.normalize(bn.home, dim=-1).detach()
|
| 108 |
+
curr = F.normalize(bn.anchors, dim=-1).detach()
|
| 109 |
+
P, A, d = home.shape
|
| 110 |
+
|
| 111 |
+
print(f" Drift: mean={drift.mean():.6f} rad ({math.degrees(drift.mean().item()):.2f}Β°)")
|
| 112 |
+
print(f" max={drift.max():.6f} rad ({math.degrees(drift.max().item()):.2f}Β°)")
|
| 113 |
+
print(f" Near 0.29154: {(drift - 0.29154).abs().lt(0.05).float().mean().item():.1%}")
|
| 114 |
+
print(f" Near 0.29154 (Β±0.03): {(drift - 0.29154).abs().lt(0.03).float().mean().item():.1%}")
|
| 115 |
+
|
| 116 |
+
# Drift distribution
|
| 117 |
+
all_d = drift.flatten().cpu().numpy()
|
| 118 |
+
print(f"\n Drift distribution ({len(all_d)} anchors):")
|
| 119 |
+
bins = [0.0, 0.05, 0.10, 0.15, 0.20, 0.25, 0.29154, 0.35, 0.40, 0.50]
|
| 120 |
+
hist, _ = np.histogram(all_d, bins=bins)
|
| 121 |
+
for i in range(len(bins)-1):
|
| 122 |
+
bar = "β" * (hist[i] // 2 + (1 if hist[i] > 0 else 0))
|
| 123 |
+
label = " β BINDING" if bins[i+1] == 0.29154 else ""
|
| 124 |
+
print(f" {bins[i]:.3f}-{bins[i+1]:.3f}: {hist[i]:3d} {bar}{label}")
|
| 125 |
+
|
| 126 |
+
# Per-patch summary
|
| 127 |
+
print(f"\n Per-patch drift summary:")
|
| 128 |
+
for p in range(P):
|
| 129 |
+
d_mean = drift[p].mean().item()
|
| 130 |
+
d_max = drift[p].max().item()
|
| 131 |
+
n_near = (drift[p] - 0.29154).abs().lt(0.05).sum().item()
|
| 132 |
+
flags = []
|
| 133 |
+
if abs(d_mean - 0.29154) < 0.05: flags.append("MEANβ0.29")
|
| 134 |
+
if abs(d_max - 0.29154) < 0.05: flags.append("MAXβ0.29")
|
| 135 |
+
if d_max > 0.29154: flags.append("CROSSED")
|
| 136 |
+
flag_str = " β " + ", ".join(flags) if flags else ""
|
| 137 |
+
print(f" P{p:2d}: mean={d_mean:.4f} max={d_max:.4f} near={n_near}/{A}{flag_str}")
|
| 138 |
+
|
| 139 |
+
# Anchor spread
|
| 140 |
+
print(f"\n Anchor effective dimensionality:")
|
| 141 |
+
for p in range(P):
|
| 142 |
+
_, S, _ = torch.linalg.svd(curr[p].float(), full_matrices=False)
|
| 143 |
+
pr = S / S.sum()
|
| 144 |
+
ed = pr.pow(2).sum().reciprocal().item()
|
| 145 |
+
print(f" P{p:2d}: {ed:.1f} / {A}")
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 149 |
+
# TEST 2: SPHERE GEOMETRY β CV ON S^15
|
| 150 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 151 |
+
|
| 152 |
+
print(f"\n{'β'*80}")
|
| 153 |
+
print("TEST 2: Sphere Geometry β per-patch CV across timesteps")
|
| 154 |
+
print(f"{'β'*80}")
|
| 155 |
+
|
| 156 |
+
images_t, labels_t = next(iter(test_loader))
|
| 157 |
+
images_t, labels_t = images_t.to(DEVICE), labels_t.to(DEVICE)
|
| 158 |
+
|
| 159 |
+
# Per-patch CV at t=0
|
| 160 |
+
patches_n, tri, _ = get_sphere_embeddings(images_t, labels_t, 0.0)
|
| 161 |
+
print(f"\n Per-patch CV at t=0.0 (natural S^15 = 0.20):")
|
| 162 |
+
for p in range(P):
|
| 163 |
+
cv_p = compute_cv(patches_n[:, p, :], 1000)
|
| 164 |
+
print(f" P{p:2d}: CV={cv_p:.4f}")
|
| 165 |
+
|
| 166 |
+
# Across timesteps
|
| 167 |
+
print(f"\n {'t':>6} {'CV_sphere':>10} {'CV_tri':>10} {'eff_d_sph':>10} {'eff_d_tri':>10}")
|
| 168 |
+
for t_val in [0.0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0]:
|
| 169 |
+
pn, tr, _ = get_sphere_embeddings(images_t, labels_t, t_val)
|
| 170 |
+
sph_flat = pn.reshape(pn.shape[0], -1)
|
| 171 |
+
cv_s = compute_cv(sph_flat, 1000)
|
| 172 |
+
cv_t = compute_cv(tr, 1000)
|
| 173 |
+
ed_s = eff_dim(sph_flat)
|
| 174 |
+
ed_t = eff_dim(tr)
|
| 175 |
+
print(f" {t_val:>6.2f} {cv_s:>10.4f} {cv_t:>10.4f} {ed_s:>10.1f} {ed_t:>10.1f}")
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 179 |
+
# TEST 3: PER-CLASS ANCHOR ROUTING β ALL PATCHES
|
| 180 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 181 |
+
|
| 182 |
+
print(f"\n{'β'*80}")
|
| 183 |
+
print("TEST 3: Per-Class Anchor Routing")
|
| 184 |
+
print(f"{'β'*80}")
|
| 185 |
+
|
| 186 |
+
class_nearest = {c: [] for c in range(10)}
|
| 187 |
+
anchors_n = F.normalize(bn.anchors.detach(), dim=-1)
|
| 188 |
+
|
| 189 |
+
for imgs_b, labs_b in test_loader:
|
| 190 |
+
imgs_b, labs_b = imgs_b.to(DEVICE), labs_b.to(DEVICE)
|
| 191 |
+
pn, _, _ = get_sphere_embeddings(imgs_b, labs_b, 0.0)
|
| 192 |
+
cos = torch.einsum('bpd,pad->bpa', pn, anchors_n)
|
| 193 |
+
nearest = cos.argmax(dim=-1).cpu()
|
| 194 |
+
for i in range(imgs_b.shape[0]):
|
| 195 |
+
class_nearest[labs_b[i].item()].append(nearest[i])
|
| 196 |
+
if sum(len(v) for v in class_nearest.values()) > 8000:
|
| 197 |
+
break
|
| 198 |
+
|
| 199 |
+
# Show top 4 patches
|
| 200 |
+
for p_idx in range(min(4, P)):
|
| 201 |
+
print(f"\n Patch {p_idx}:")
|
| 202 |
+
print(f" {'class':>8}", end="")
|
| 203 |
+
for a in range(A):
|
| 204 |
+
print(f" {a:>4}", end="")
|
| 205 |
+
print(" entropy")
|
| 206 |
+
|
| 207 |
+
for c in range(10):
|
| 208 |
+
if not class_nearest[c]: continue
|
| 209 |
+
nearest_all = torch.stack(class_nearest[c])
|
| 210 |
+
counts = torch.bincount(nearest_all[:, p_idx], minlength=A).float()
|
| 211 |
+
counts = counts / counts.sum()
|
| 212 |
+
entropy = -(counts * (counts + 1e-8).log()).sum().item()
|
| 213 |
+
|
| 214 |
+
row = f" {CLASS_NAMES[c]:>8}"
|
| 215 |
+
for a in range(A):
|
| 216 |
+
pct = counts[a].item()
|
| 217 |
+
if pct > 0.15: row += f" {pct:>3.0%}β"
|
| 218 |
+
elif pct > 0.08: row += f" {pct:>3.0%}β"
|
| 219 |
+
elif pct > 0.02: row += f" {pct:>3.0%} "
|
| 220 |
+
else: row += f" ."
|
| 221 |
+
row += f" {entropy:.2f}"
|
| 222 |
+
print(row)
|
| 223 |
+
|
| 224 |
+
# Global utilization
|
| 225 |
+
all_nearest = torch.cat([torch.stack(v) for v in class_nearest.values() if v])
|
| 226 |
+
unique_per_patch = []
|
| 227 |
+
for p_idx in range(P):
|
| 228 |
+
unique_per_patch.append(all_nearest[:, p_idx].unique().numel())
|
| 229 |
+
print(f"\n Unique anchors per patch: {unique_per_patch}")
|
| 230 |
+
print(f" Mean utilization: {np.mean(unique_per_patch):.1f}/{A} "
|
| 231 |
+
f"({100*np.mean(unique_per_patch)/A:.0f}%)")
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 235 |
+
# TEST 4: RECONSTRUCTION FIDELITY β THROUGH THE BOTTLENECK
|
| 236 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 237 |
+
|
| 238 |
+
print(f"\n{'β'*80}")
|
| 239 |
+
print("TEST 4: Reconstruction Fidelity β what survives 768 dims?")
|
| 240 |
+
print(f"{'β'*80}")
|
| 241 |
+
|
| 242 |
+
print(f" {'t':>6} {'input_norm':>12} {'output_norm':>12} {'cos_sim':>10} "
|
| 243 |
+
f"{'rel_error':>10} {'mse':>10}")
|
| 244 |
+
|
| 245 |
+
for t_val in [0.0, 0.25, 0.5, 0.75, 1.0]:
|
| 246 |
+
B = images_t.shape[0]
|
| 247 |
+
t = torch.full((B,), t_val, device=DEVICE)
|
| 248 |
+
eps = torch.randn_like(images_t)
|
| 249 |
+
t_b = t.view(B, 1, 1, 1)
|
| 250 |
+
x_t = (1 - t_b) * images_t + t_b * eps
|
| 251 |
+
cond = model.time_emb(t) + model.class_emb(labels_t)
|
| 252 |
+
|
| 253 |
+
with torch.no_grad():
|
| 254 |
+
# Run encoder
|
| 255 |
+
h = model.in_conv(x_t)
|
| 256 |
+
for i in range(len(model.ch_mults)):
|
| 257 |
+
for block in model.enc[i]:
|
| 258 |
+
if isinstance(block, nn.Sequential):
|
| 259 |
+
h = block[0](h); h = block[1](h, cond)
|
| 260 |
+
else: h = block(h, cond)
|
| 261 |
+
if i < len(model.enc_down): h = model.enc_down[i](h)
|
| 262 |
+
|
| 263 |
+
h_flat = h.reshape(B, -1)
|
| 264 |
+
h_reconstructed = bn(h_flat, cond)
|
| 265 |
+
|
| 266 |
+
in_norm = h_flat.norm(dim=-1).mean().item()
|
| 267 |
+
out_norm = h_reconstructed.norm(dim=-1).mean().item()
|
| 268 |
+
cos = F.cosine_similarity(h_flat, h_reconstructed).mean().item()
|
| 269 |
+
rel_err = (h_flat - h_reconstructed).norm(dim=-1).mean().item() / (in_norm + 1e-8)
|
| 270 |
+
mse = F.mse_loss(h_flat, h_reconstructed).item()
|
| 271 |
+
|
| 272 |
+
print(f" {t_val:>6.2f} {in_norm:>12.2f} {out_norm:>12.2f} {cos:>10.6f} "
|
| 273 |
+
f"{rel_err:>10.4f} {mse:>10.2f}")
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 277 |
+
# TEST 5: GENERATION QUALITY
|
| 278 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 279 |
+
|
| 280 |
+
print(f"\n{'β'*80}")
|
| 281 |
+
print("TEST 5: Generation Quality β per class")
|
| 282 |
+
print(f"{'β'*80}")
|
| 283 |
+
|
| 284 |
+
print(f" {'class':>8} {'intra_cos':>10} {'std':>8} {'CV':>8} {'norm':>8}")
|
| 285 |
+
|
| 286 |
+
all_gen = []
|
| 287 |
+
for c in range(10):
|
| 288 |
+
with torch.no_grad():
|
| 289 |
+
imgs, _ = sample(model, 64, 50, cls=c)
|
| 290 |
+
imgs = (imgs + 1) / 2
|
| 291 |
+
all_gen.append(imgs)
|
| 292 |
+
|
| 293 |
+
flat = imgs.reshape(64, -1)
|
| 294 |
+
flat_n = F.normalize(flat, dim=-1)
|
| 295 |
+
sim = flat_n @ flat_n.T
|
| 296 |
+
mask = ~torch.eye(64, device=DEVICE, dtype=torch.bool)
|
| 297 |
+
print(f" {CLASS_NAMES[c]:>8} {sim[mask].mean().item():>10.4f} "
|
| 298 |
+
f"{sim[mask].std().item():>8.4f} {compute_cv(flat, 500):>8.4f} "
|
| 299 |
+
f"{flat.norm(dim=-1).mean().item():>8.2f}")
|
| 300 |
+
|
| 301 |
+
save_image(make_grid(imgs[:16], nrow=4), f"analysis_cd/class_{CLASS_NAMES[c]}.png")
|
| 302 |
+
|
| 303 |
+
all_grid = torch.cat([g[:4] for g in all_gen])
|
| 304 |
+
save_image(make_grid(all_grid, nrow=10), "analysis_cd/all_classes.png")
|
| 305 |
+
print(f" β Saved to analysis_cd/")
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 309 |
+
# TEST 6: VELOCITY FIELD
|
| 310 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 311 |
+
|
| 312 |
+
print(f"\n{'β'*80}")
|
| 313 |
+
print("TEST 6: Velocity Field Quality")
|
| 314 |
+
print(f"{'β'*80}")
|
| 315 |
+
|
| 316 |
+
print(f" {'t':>6} {'v_norm':>10} {'vΒ·target':>10} {'mse':>10}")
|
| 317 |
+
|
| 318 |
+
for t_val in [0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95]:
|
| 319 |
+
B = 128
|
| 320 |
+
imgs_v = images_t[:B]
|
| 321 |
+
labs_v = labels_t[:B]
|
| 322 |
+
t = torch.full((B,), t_val, device=DEVICE)
|
| 323 |
+
eps = torch.randn_like(imgs_v)
|
| 324 |
+
t_b = t.view(B, 1, 1, 1)
|
| 325 |
+
x_t = (1 - t_b) * imgs_v + t_b * eps
|
| 326 |
+
v_target = eps - imgs_v
|
| 327 |
+
|
| 328 |
+
with torch.no_grad():
|
| 329 |
+
v_pred = model(x_t, t, labs_v)
|
| 330 |
+
v_cos = F.cosine_similarity(
|
| 331 |
+
v_pred.reshape(B, -1), v_target.reshape(B, -1)).mean().item()
|
| 332 |
+
mse = F.mse_loss(v_pred, v_target).item()
|
| 333 |
+
v_norm = v_pred.reshape(B, -1).norm(dim=-1).mean().item()
|
| 334 |
+
print(f" {t_val:>6.2f} {v_norm:>10.2f} {v_cos:>10.4f} {mse:>10.4f}")
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 338 |
+
# TEST 7: ODE TRAJECTORY
|
| 339 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 340 |
+
|
| 341 |
+
print(f"\n{'β'*80}")
|
| 342 |
+
print("TEST 7: ODE Trajectory β geometry through generation")
|
| 343 |
+
print(f"{'β'*80}")
|
| 344 |
+
|
| 345 |
+
B_traj = 256
|
| 346 |
+
x = torch.randn(B_traj, 3, 32, 32, device=DEVICE)
|
| 347 |
+
labs_traj = torch.randint(0, 10, (B_traj,), device=DEVICE)
|
| 348 |
+
dt = 1.0 / 50
|
| 349 |
+
|
| 350 |
+
print(f" {'step':>6} {'t':>6} {'norm':>10} {'std':>10} {'CV':>8}")
|
| 351 |
+
for step in range(50):
|
| 352 |
+
t = torch.full((B_traj,), 1.0 - step * dt, device=DEVICE)
|
| 353 |
+
with torch.no_grad(), torch.amp.autocast("cuda", dtype=torch.bfloat16):
|
| 354 |
+
v = model(x, t, labs_traj)
|
| 355 |
+
x = x - v.float() * dt
|
| 356 |
+
if step in [0, 1, 5, 10, 20, 30, 40, 49]:
|
| 357 |
+
xf = x.reshape(B_traj, -1)
|
| 358 |
+
print(f" {step:>6} {1.0-step*dt:>6.2f} {xf.norm(dim=-1).mean().item():>10.2f} "
|
| 359 |
+
f"{x.std().item():>10.4f} {compute_cv(xf, 500):>8.4f}")
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 363 |
+
# TEST 8: INTER vs INTRA CLASS
|
| 364 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 365 |
+
|
| 366 |
+
print(f"\n{'β'*80}")
|
| 367 |
+
print("TEST 8: Class Separation")
|
| 368 |
+
print(f"{'β'*80}")
|
| 369 |
+
|
| 370 |
+
intra, inter = [], []
|
| 371 |
+
for c in range(10):
|
| 372 |
+
f = F.normalize(all_gen[c].reshape(64, -1), dim=-1)
|
| 373 |
+
s = f @ f.T
|
| 374 |
+
m = ~torch.eye(64, device=DEVICE, dtype=torch.bool)
|
| 375 |
+
intra.append(s[m].mean().item())
|
| 376 |
+
|
| 377 |
+
for i in range(10):
|
| 378 |
+
for j in range(i+1, 10):
|
| 379 |
+
fi = F.normalize(all_gen[i].reshape(64, -1), dim=-1)
|
| 380 |
+
fj = F.normalize(all_gen[j].reshape(64, -1), dim=-1)
|
| 381 |
+
inter.append((fi @ fj.T).mean().item())
|
| 382 |
+
|
| 383 |
+
print(f" Intra-class cos: {np.mean(intra):.4f} Β± {np.std(intra):.4f}")
|
| 384 |
+
print(f" Inter-class cos: {np.mean(inter):.4f} Β± {np.std(inter):.4f}")
|
| 385 |
+
print(f" Separation ratio: {np.mean(intra) / (np.mean(inter) + 1e-8):.3f}Γ")
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 389 |
+
# TEST 9: COMPARISON WITH PREVIOUS VERSIONS
|
| 390 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 391 |
+
|
| 392 |
+
print(f"\n{'β'*80}")
|
| 393 |
+
print("TEST 9: Comparison Summary")
|
| 394 |
+
print(f"{'β'*80}")
|
| 395 |
+
|
| 396 |
+
print(f"""
|
| 397 |
+
{'':>25} {'Regulator':>12} {'Skip BN':>12} {'Pure BN':>12}
|
| 398 |
+
{'':>25} {'(v1)':>12} {'(v2)':>12} {'(v3)':>12}
|
| 399 |
+
{'β'*73}
|
| 400 |
+
{'Relay/BN params':>25} {'76K':>12} {'281M':>12} {f'{n_bn:,}':>12}
|
| 401 |
+
{'Total params':>25} {'6.1M':>12} {'287M':>12} {f'{n_params:,}':>12}
|
| 402 |
+
{'Best loss':>25} {'0.1900':>12} {'0.1757':>12} {f'{best_loss:.4f}':>12}
|
| 403 |
+
{'Constellation signal':>25} {'6%':>12} {'88%':>12} {'100%':>12}
|
| 404 |
+
{'Skip params':>25} {'0':>12} {'268M':>12} {'0':>12}
|
| 405 |
+
{'Anchor routing':>25} {'2 active':>12} {'class-spec':>12} {'(see T3)':>12}
|
| 406 |
+
""")
|
| 407 |
+
|
| 408 |
+
# Final drift
|
| 409 |
+
with torch.no_grad():
|
| 410 |
+
drift = bn.drift().detach()
|
| 411 |
+
near = (drift - 0.29154).abs().lt(0.05).float().mean().item()
|
| 412 |
+
near_tight = (drift - 0.29154).abs().lt(0.03).float().mean().item()
|
| 413 |
+
crossed = (drift > 0.29154).float().mean().item()
|
| 414 |
+
|
| 415 |
+
print(f" Final drift stats:")
|
| 416 |
+
print(f" Mean: {drift.mean():.6f} rad ({math.degrees(drift.mean().item()):.2f}Β°)")
|
| 417 |
+
print(f" Max: {drift.max():.6f} rad ({math.degrees(drift.max().item()):.2f}Β°)")
|
| 418 |
+
print(f" Near 0.29154: {near:.1%} (Β±0.05) {near_tight:.1%} (Β±0.03)")
|
| 419 |
+
print(f" Crossed 0.29: {crossed:.1%}")
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
print(f"\n{'='*80}")
|
| 423 |
+
print("ANALYSIS COMPLETE")
|
| 424 |
+
print(f"{'='*80}")
|