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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Cell 5: Multi-VAE Geometric Comparison
|
| 3 |
+
========================================
|
| 4 |
+
Run after Cells 1-4. Reuses existing pipeline.
|
| 5 |
+
|
| 6 |
+
Processes 4 VAEs sequentially:
|
| 7 |
+
SD 1.5 β 4ch Γ 64Γ64 (512px input)
|
| 8 |
+
SDXL β 4ch Γ 128Γ128 (1024px input)
|
| 9 |
+
Flux.1 β 16ch Γ 128Γ128 (1024px input)
|
| 10 |
+
Flux.2 β 16ch Γ 128Γ128 (1024px input)
|
| 11 |
+
|
| 12 |
+
Each: load VAE β encode β free β cluster β extract β store
|
| 13 |
+
Then: comparative diagnostics
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import os, time, json, zipfile, math
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn.functional as F
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from tqdm.auto import tqdm
|
| 22 |
+
from collections import Counter
|
| 23 |
+
|
| 24 |
+
# === 0. Images ================================================================
|
| 25 |
+
print("=" * 70)
|
| 26 |
+
print("Multi-VAE Geometric Comparison Pipeline")
|
| 27 |
+
print("=" * 70)
|
| 28 |
+
|
| 29 |
+
IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.webp', '.bmp'}
|
| 30 |
+
HF_REPO = "AbstractPhil/grid-geometric-classifier-sliding-proto"
|
| 31 |
+
HF_ZIP = "mega_liminal_captioned.zip"
|
| 32 |
+
SKIP_DIRS = {'.config', 'sample_data', 'drive', '__pycache__',
|
| 33 |
+
'checkpoints_vae_ca',
|
| 34 |
+
'latent_cache_sd15', 'latent_cache_sdxl',
|
| 35 |
+
'latent_cache_flux1', 'latent_cache_flux2',
|
| 36 |
+
'latent_cache_mega_sd15', 'latent_cache_mega_sdxl',
|
| 37 |
+
'latent_cache_mega_flux1', 'latent_cache_mega_flux2'}
|
| 38 |
+
|
| 39 |
+
def find_images(directory):
|
| 40 |
+
return sorted([
|
| 41 |
+
os.path.join(r, f) for r, _, fs in os.walk(directory)
|
| 42 |
+
for f in fs if Path(f).suffix.lower() in IMAGE_EXTENSIONS
|
| 43 |
+
]) if os.path.exists(directory) else []
|
| 44 |
+
|
| 45 |
+
def scan_content_for_images(min_count=100):
|
| 46 |
+
"""Scan /content/ for the largest image directory."""
|
| 47 |
+
best_dir, best_imgs = None, []
|
| 48 |
+
for d in sorted(os.listdir('/content/')):
|
| 49 |
+
full = f'/content/{d}'
|
| 50 |
+
if os.path.isdir(full) and d not in SKIP_DIRS:
|
| 51 |
+
found = find_images(full)
|
| 52 |
+
if len(found) > len(best_imgs):
|
| 53 |
+
best_dir, best_imgs = full, found
|
| 54 |
+
if len(best_imgs) >= min_count:
|
| 55 |
+
return best_dir, best_imgs
|
| 56 |
+
return None, []
|
| 57 |
+
|
| 58 |
+
LIMINAL_DIR, image_paths = scan_content_for_images()
|
| 59 |
+
|
| 60 |
+
if LIMINAL_DIR is None:
|
| 61 |
+
try:
|
| 62 |
+
from huggingface_hub import hf_hub_download
|
| 63 |
+
except ImportError:
|
| 64 |
+
os.system('pip install -q huggingface_hub')
|
| 65 |
+
from huggingface_hub import hf_hub_download
|
| 66 |
+
print(f"Downloading {HF_ZIP} from {HF_REPO}...")
|
| 67 |
+
zip_path = hf_hub_download(repo_id=HF_REPO, filename=HF_ZIP)
|
| 68 |
+
with zipfile.ZipFile(zip_path, 'r') as z:
|
| 69 |
+
z.extractall('/content/')
|
| 70 |
+
LIMINAL_DIR, image_paths = scan_content_for_images()
|
| 71 |
+
|
| 72 |
+
assert LIMINAL_DIR and len(image_paths) > 0, "No images found in /content/"
|
| 73 |
+
print(f"Found {len(image_paths)} images in {LIMINAL_DIR}")
|
| 74 |
+
|
| 75 |
+
# === 1. Classifier ============================================================
|
| 76 |
+
print("\n" + "=" * 70)
|
| 77 |
+
print("Step 1: Classifier")
|
| 78 |
+
print("=" * 70)
|
| 79 |
+
|
| 80 |
+
ckpt = '/content/best_vae_ca_classifier.pt'
|
| 81 |
+
if not os.path.exists(ckpt):
|
| 82 |
+
ckpt = '/content/checkpoints_vae_ca/best.pt'
|
| 83 |
+
|
| 84 |
+
model = PatchCrossAttentionClassifier(n_classes=NUM_CLASSES)
|
| 85 |
+
model.load_state_dict(torch.load(ckpt, map_location='cpu', weights_only=True))
|
| 86 |
+
device = torch.device('cuda')
|
| 87 |
+
model = model.to(device).eval()
|
| 88 |
+
print(f"Loaded {sum(p.numel() for p in model.parameters()):,} params")
|
| 89 |
+
|
| 90 |
+
# === 2. VAE Definitions ======================================================
|
| 91 |
+
|
| 92 |
+
try:
|
| 93 |
+
from diffusers import AutoencoderKL
|
| 94 |
+
except ImportError:
|
| 95 |
+
os.system('pip install -q diffusers transformers accelerate')
|
| 96 |
+
from diffusers import AutoencoderKL
|
| 97 |
+
|
| 98 |
+
from torchvision import transforms
|
| 99 |
+
from PIL import Image
|
| 100 |
+
|
| 101 |
+
VAE_CONFIGS = [
|
| 102 |
+
{
|
| 103 |
+
'name': 'SD 1.5',
|
| 104 |
+
'model_id': 'stable-diffusion-v1-5/stable-diffusion-v1-5',
|
| 105 |
+
'subfolder': 'vae',
|
| 106 |
+
'input_res': 512,
|
| 107 |
+
'dtype': torch.float16,
|
| 108 |
+
'cache_dir': '/content/latent_cache_mega_sd15',
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
'name': 'SDXL',
|
| 112 |
+
'model_id': 'madebyollin/sdxl-vae-fp16-fix',
|
| 113 |
+
'subfolder': None,
|
| 114 |
+
'input_res': 1024,
|
| 115 |
+
'dtype': torch.float16,
|
| 116 |
+
'cache_dir': '/content/latent_cache_mega_sdxl',
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
'name': 'Flux.1',
|
| 120 |
+
'model_id': 'black-forest-labs/FLUX.1-dev',
|
| 121 |
+
'subfolder': 'vae',
|
| 122 |
+
'input_res': 1024,
|
| 123 |
+
'dtype': torch.bfloat16,
|
| 124 |
+
'cache_dir': '/content/latent_cache_mega_flux1',
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
'name': 'Flux.2',
|
| 128 |
+
'model_id': 'black-forest-labs/FLUX.2-dev',
|
| 129 |
+
'subfolder': 'vae',
|
| 130 |
+
'input_res': 1024,
|
| 131 |
+
'dtype': torch.bfloat16,
|
| 132 |
+
'cache_dir': '/content/latent_cache_mega_flux2',
|
| 133 |
+
},
|
| 134 |
+
]
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def get_scales_for_latent(C, H, W):
|
| 138 |
+
"""Compute appropriate scales based on actual latent dimensions. No L3 (noise)."""
|
| 139 |
+
scales = []
|
| 140 |
+
# L0: full latent (or capped)
|
| 141 |
+
scales.append((min(C, 16), min(H, 64), min(W, 64)))
|
| 142 |
+
# L1: regional
|
| 143 |
+
scales.append((min(C, 8), min(H, 32), min(W, 32)))
|
| 144 |
+
# L2: native patch (classifier resolution)
|
| 145 |
+
scales.append((min(C, 8), 16, 16))
|
| 146 |
+
return scales
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def encode_dataset(vae, image_paths, cache_dir, input_res, dtype, batch_size=4):
|
| 150 |
+
"""Encode images, return list of cache paths."""
|
| 151 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 152 |
+
|
| 153 |
+
transform = transforms.Compose([
|
| 154 |
+
transforms.Resize((input_res, input_res)),
|
| 155 |
+
transforms.ToTensor(),
|
| 156 |
+
transforms.Normalize([0.5]*3, [0.5]*3),
|
| 157 |
+
])
|
| 158 |
+
|
| 159 |
+
latent_paths = []
|
| 160 |
+
need_encode = []
|
| 161 |
+
|
| 162 |
+
for p in image_paths:
|
| 163 |
+
name = Path(p).stem
|
| 164 |
+
cp = os.path.join(cache_dir, f'{name}.pt')
|
| 165 |
+
latent_paths.append(cp)
|
| 166 |
+
if not os.path.exists(cp):
|
| 167 |
+
need_encode.append((p, cp))
|
| 168 |
+
|
| 169 |
+
if not need_encode:
|
| 170 |
+
return latent_paths
|
| 171 |
+
|
| 172 |
+
for i in tqdm(range(0, len(need_encode), batch_size), desc="Encoding", unit="batch"):
|
| 173 |
+
batch_items = need_encode[i:i+batch_size]
|
| 174 |
+
imgs = []
|
| 175 |
+
for p, cp in batch_items:
|
| 176 |
+
try:
|
| 177 |
+
imgs.append((transform(Image.open(p).convert('RGB')), cp))
|
| 178 |
+
except Exception:
|
| 179 |
+
pass
|
| 180 |
+
|
| 181 |
+
if imgs:
|
| 182 |
+
batch = torch.stack([im[0] for im in imgs]).to(device, dtype=dtype)
|
| 183 |
+
with torch.no_grad():
|
| 184 |
+
latents = vae.encode(batch).latent_dist.mean
|
| 185 |
+
for j, (_, cp) in enumerate(imgs):
|
| 186 |
+
torch.save(latents[j].cpu().float(), cp)
|
| 187 |
+
del batch, latents
|
| 188 |
+
|
| 189 |
+
return latent_paths
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# === 3. Process Each VAE =====================================================
|
| 193 |
+
|
| 194 |
+
all_vae_results = {}
|
| 195 |
+
|
| 196 |
+
for vconf in VAE_CONFIGS:
|
| 197 |
+
vname = vconf['name']
|
| 198 |
+
print("\n" + "=" * 70)
|
| 199 |
+
print(f"Processing: {vname}")
|
| 200 |
+
print(f" Model: {vconf['model_id']}")
|
| 201 |
+
print("=" * 70)
|
| 202 |
+
|
| 203 |
+
# --- Encode ---
|
| 204 |
+
try:
|
| 205 |
+
load_kwargs = dict(torch_dtype=vconf['dtype'])
|
| 206 |
+
if vconf['subfolder']:
|
| 207 |
+
load_kwargs['subfolder'] = vconf['subfolder']
|
| 208 |
+
vae = AutoencoderKL.from_pretrained(
|
| 209 |
+
vconf['model_id'], **load_kwargs
|
| 210 |
+
).to(device).eval()
|
| 211 |
+
except Exception as e:
|
| 212 |
+
print(f" β Failed to load {vname}: {e}")
|
| 213 |
+
print(f" Skipping...")
|
| 214 |
+
continue
|
| 215 |
+
|
| 216 |
+
latent_paths = encode_dataset(
|
| 217 |
+
vae, image_paths, vconf['cache_dir'],
|
| 218 |
+
vconf['input_res'], vconf['dtype'])
|
| 219 |
+
|
| 220 |
+
if not latent_paths:
|
| 221 |
+
print(f" β No latents produced for {vname}, skipping")
|
| 222 |
+
del vae
|
| 223 |
+
torch.cuda.empty_cache()
|
| 224 |
+
continue
|
| 225 |
+
|
| 226 |
+
# Sanity check: if first latent is NaN, purge cache and re-encode
|
| 227 |
+
sample = torch.load(latent_paths[0])
|
| 228 |
+
if torch.isnan(sample).any():
|
| 229 |
+
print(f" β NaN detected in cached latents β purging {vconf['cache_dir']}")
|
| 230 |
+
import shutil
|
| 231 |
+
shutil.rmtree(vconf['cache_dir'])
|
| 232 |
+
latent_paths = encode_dataset(
|
| 233 |
+
vae, image_paths, vconf['cache_dir'],
|
| 234 |
+
vconf['input_res'], vconf['dtype'])
|
| 235 |
+
sample = torch.load(latent_paths[0])
|
| 236 |
+
|
| 237 |
+
C, H, W = sample.shape
|
| 238 |
+
print(f" Latent: ({C}, {H}, {W}) "
|
| 239 |
+
f"mean={sample.mean():.3f} std={sample.std():.3f} "
|
| 240 |
+
f"[{sample.min():.3f}, {sample.max():.3f}]")
|
| 241 |
+
del sample
|
| 242 |
+
|
| 243 |
+
# Free VAE immediately
|
| 244 |
+
del vae
|
| 245 |
+
torch.cuda.empty_cache()
|
| 246 |
+
|
| 247 |
+
# --- Cluster ---
|
| 248 |
+
N_CL = min(100, len(latent_paths))
|
| 249 |
+
sample_batch = torch.stack([torch.load(latent_paths[i]) for i in range(N_CL)]).to(device)
|
| 250 |
+
channel_groups, corr = cluster_channels_gpu(sample_batch, n_groups=min(8, C))
|
| 251 |
+
print(f" Groups: {channel_groups}")
|
| 252 |
+
del sample_batch
|
| 253 |
+
|
| 254 |
+
# --- Extract ---
|
| 255 |
+
scales = get_scales_for_latent(C, H, W)
|
| 256 |
+
print(f" Scales: {scales}")
|
| 257 |
+
|
| 258 |
+
config = ExtractionConfig(
|
| 259 |
+
confidence_threshold=0.6,
|
| 260 |
+
min_occupancy=0.01,
|
| 261 |
+
image_batch_size=32,
|
| 262 |
+
)
|
| 263 |
+
config.scales = scales
|
| 264 |
+
|
| 265 |
+
extractor = MultiScaleExtractor(model, config)
|
| 266 |
+
|
| 267 |
+
IMG_BATCH = config.image_batch_size
|
| 268 |
+
vae_annotations = []
|
| 269 |
+
vae_records = []
|
| 270 |
+
|
| 271 |
+
for batch_start in tqdm(range(0, len(latent_paths), IMG_BATCH),
|
| 272 |
+
desc=f"{vname} extract", unit=f"Γ{IMG_BATCH}"):
|
| 273 |
+
bp = latent_paths[batch_start:batch_start + IMG_BATCH]
|
| 274 |
+
names = [Path(p).stem for p in bp]
|
| 275 |
+
latents = [torch.load(p).to(device) for p in bp]
|
| 276 |
+
|
| 277 |
+
batch_results = extractor.extract_batch(latents, channel_groups)
|
| 278 |
+
del latents
|
| 279 |
+
|
| 280 |
+
for b_idx, result in enumerate(batch_results):
|
| 281 |
+
raw = result['raw_annotations']
|
| 282 |
+
dev = result['deviance_annotations']
|
| 283 |
+
all_anns = raw + dev
|
| 284 |
+
|
| 285 |
+
vae_records.append({
|
| 286 |
+
'name': names[b_idx],
|
| 287 |
+
'n_total': len(all_anns),
|
| 288 |
+
'n_raw': len(raw),
|
| 289 |
+
'n_deviance': len(dev),
|
| 290 |
+
'classes': Counter(a.class_name for a in all_anns),
|
| 291 |
+
'confidences': [a.confidence for a in all_anns],
|
| 292 |
+
'scales': Counter(a.scale_level for a in all_anns),
|
| 293 |
+
'dimensions': Counter(a.dimension for a in all_anns),
|
| 294 |
+
'curved': sum(1 for a in all_anns if a.is_curved),
|
| 295 |
+
})
|
| 296 |
+
|
| 297 |
+
for a in all_anns:
|
| 298 |
+
vae_annotations.append({
|
| 299 |
+
'class': a.class_name, 'confidence': a.confidence,
|
| 300 |
+
'scale': a.scale_level, 'dimension': a.dimension,
|
| 301 |
+
'curved': a.is_curved, 'curvature': a.curvature_type,
|
| 302 |
+
'source': a.source,
|
| 303 |
+
})
|
| 304 |
+
|
| 305 |
+
# Summarize
|
| 306 |
+
total = len(vae_annotations)
|
| 307 |
+
cls_counts = Counter(a['class'] for a in vae_annotations)
|
| 308 |
+
confs = [a['confidence'] for a in vae_annotations]
|
| 309 |
+
|
| 310 |
+
all_vae_results[vname] = {
|
| 311 |
+
'latent_shape': (C, H, W),
|
| 312 |
+
'n_images': len(vae_records),
|
| 313 |
+
'total_annotations': total,
|
| 314 |
+
'class_counts': cls_counts,
|
| 315 |
+
'mean_confidence': float(np.mean(confs)) if confs else 0,
|
| 316 |
+
'std_confidence': float(np.std(confs)) if confs else 0,
|
| 317 |
+
'records': vae_records,
|
| 318 |
+
'channel_groups': channel_groups,
|
| 319 |
+
'scales': scales,
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
if confs:
|
| 323 |
+
print(f" {vname}: {total:,} annotations, conf={np.mean(confs):.3f}")
|
| 324 |
+
else:
|
| 325 |
+
print(f" {vname}: 0 annotations (check latent stats above)")
|
| 326 |
+
top5 = cls_counts.most_common(5)
|
| 327 |
+
for cls, cnt in top5:
|
| 328 |
+
print(f" {cls:20s} {cnt:>10,} ({cnt/max(total,1)*100:5.1f}%)")
|
| 329 |
+
|
| 330 |
+
del vae_annotations, vae_records
|
| 331 |
+
torch.cuda.empty_cache()
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
# =============================================================================
|
| 335 |
+
# COMPARATIVE ANALYSIS
|
| 336 |
+
# =============================================================================
|
| 337 |
+
print("\n" + "=" * 70)
|
| 338 |
+
print("COMPARATIVE ANALYSIS: VAE Geometric Structures")
|
| 339 |
+
print("=" * 70)
|
| 340 |
+
|
| 341 |
+
vae_names = list(all_vae_results.keys())
|
| 342 |
+
|
| 343 |
+
# --- Table: Overview ---
|
| 344 |
+
print(f"\n{'β'*70}")
|
| 345 |
+
print(f" {'VAE':12s} {'Latent':>14s} {'Ann':>12s} {'Ann/img':>8s} "
|
| 346 |
+
f"{'Conf':>6s} {'Classes':>7s}")
|
| 347 |
+
print(f"{'β'*70}")
|
| 348 |
+
for vn in vae_names:
|
| 349 |
+
r = all_vae_results[vn]
|
| 350 |
+
sh = f"{r['latent_shape'][0]}Γ{r['latent_shape'][1]}Γ{r['latent_shape'][2]}"
|
| 351 |
+
n_cls = len(r['class_counts'])
|
| 352 |
+
ann_per = r['total_annotations'] / max(r['n_images'], 1)
|
| 353 |
+
print(f" {vn:12s} {sh:>14s} {r['total_annotations']:>12,} {ann_per:>8.0f} "
|
| 354 |
+
f"{r['mean_confidence']:>6.3f} {n_cls:>4d}/38")
|
| 355 |
+
|
| 356 |
+
# --- Table: Top-5 classes per VAE ---
|
| 357 |
+
print(f"\n{'β'*70}")
|
| 358 |
+
print("TOP-5 CLASSES PER VAE")
|
| 359 |
+
print(f"{'β'*70}")
|
| 360 |
+
for vn in vae_names:
|
| 361 |
+
r = all_vae_results[vn]
|
| 362 |
+
total = r['total_annotations']
|
| 363 |
+
top5 = r['class_counts'].most_common(5)
|
| 364 |
+
classes_str = " ".join(f"{c}:{cnt/max(total,1)*100:.0f}%" for c, cnt in top5)
|
| 365 |
+
print(f" {vn:12s} {classes_str}")
|
| 366 |
+
|
| 367 |
+
# --- Class presence heatmap (which classes appear in which VAEs) ---
|
| 368 |
+
print(f"\n{'β'*70}")
|
| 369 |
+
print("CLASS PRESENCE ACROSS VAEs (>0.5% of annotations)")
|
| 370 |
+
print(f"{'β'*70}")
|
| 371 |
+
|
| 372 |
+
all_classes_seen = set()
|
| 373 |
+
for vn in vae_names:
|
| 374 |
+
for cls in all_vae_results[vn]['class_counts']:
|
| 375 |
+
all_classes_seen.add(cls)
|
| 376 |
+
|
| 377 |
+
# Sort by total frequency
|
| 378 |
+
class_totals = Counter()
|
| 379 |
+
for vn in vae_names:
|
| 380 |
+
class_totals.update(all_vae_results[vn]['class_counts'])
|
| 381 |
+
|
| 382 |
+
print(f" {'Class':20s}", end="")
|
| 383 |
+
for vn in vae_names:
|
| 384 |
+
print(f" {vn:>10s}", end="")
|
| 385 |
+
print()
|
| 386 |
+
|
| 387 |
+
for cls, _ in class_totals.most_common():
|
| 388 |
+
row_vals = []
|
| 389 |
+
any_significant = False
|
| 390 |
+
for vn in vae_names:
|
| 391 |
+
r = all_vae_results[vn]
|
| 392 |
+
total = max(r['total_annotations'], 1)
|
| 393 |
+
cnt = r['class_counts'].get(cls, 0)
|
| 394 |
+
pct = cnt / total * 100
|
| 395 |
+
row_vals.append(pct)
|
| 396 |
+
if pct >= 0.5:
|
| 397 |
+
any_significant = True
|
| 398 |
+
|
| 399 |
+
if any_significant:
|
| 400 |
+
print(f" {cls:20s}", end="")
|
| 401 |
+
for pct in row_vals:
|
| 402 |
+
if pct >= 5:
|
| 403 |
+
print(f" {pct:>9.1f}%", end="")
|
| 404 |
+
elif pct >= 0.5:
|
| 405 |
+
print(f" {pct:>9.1f}%", end="")
|
| 406 |
+
elif pct > 0:
|
| 407 |
+
print(f" trace", end="")
|
| 408 |
+
else:
|
| 409 |
+
print(f" β", end="")
|
| 410 |
+
print()
|
| 411 |
+
|
| 412 |
+
# --- Geometric fingerprint comparison ---
|
| 413 |
+
print(f"\n{'β'*70}")
|
| 414 |
+
print("GEOMETRIC FINGERPRINT SIMILARITY (cosine between class distributions)")
|
| 415 |
+
print(f"{'β'*70}")
|
| 416 |
+
|
| 417 |
+
if len(vae_names) >= 2:
|
| 418 |
+
vecs = {}
|
| 419 |
+
for vn in vae_names:
|
| 420 |
+
r = all_vae_results[vn]
|
| 421 |
+
total = max(r['total_annotations'], 1)
|
| 422 |
+
vec = np.zeros(len(CLASS_NAMES))
|
| 423 |
+
for cls, cnt in r['class_counts'].items():
|
| 424 |
+
vec[CLASS_NAMES.index(cls)] = cnt / total
|
| 425 |
+
vecs[vn] = vec
|
| 426 |
+
|
| 427 |
+
print(f" {'':12s}", end="")
|
| 428 |
+
for vn in vae_names:
|
| 429 |
+
print(f" {vn:>10s}", end="")
|
| 430 |
+
print()
|
| 431 |
+
|
| 432 |
+
for vn1 in vae_names:
|
| 433 |
+
print(f" {vn1:12s}", end="")
|
| 434 |
+
for vn2 in vae_names:
|
| 435 |
+
v1, v2 = vecs[vn1], vecs[vn2]
|
| 436 |
+
n1, n2 = np.linalg.norm(v1), np.linalg.norm(v2)
|
| 437 |
+
if n1 > 0 and n2 > 0:
|
| 438 |
+
sim = np.dot(v1, v2) / (n1 * n2)
|
| 439 |
+
else:
|
| 440 |
+
sim = 0
|
| 441 |
+
print(f" {sim:>10.3f}", end="")
|
| 442 |
+
print()
|
| 443 |
+
|
| 444 |
+
# --- Dimensional comparison ---
|
| 445 |
+
print(f"\n{'β'*70}")
|
| 446 |
+
print("DIMENSIONAL DISTRIBUTION")
|
| 447 |
+
print(f"{'β'*70}")
|
| 448 |
+
print(f" {'VAE':12s} {'0D':>8s} {'1D':>8s} {'2D':>8s} {'3D':>8s} {'Curved':>8s}")
|
| 449 |
+
for vn in vae_names:
|
| 450 |
+
r = all_vae_results[vn]
|
| 451 |
+
total = max(r['total_annotations'], 1)
|
| 452 |
+
dim_c = Counter()
|
| 453 |
+
curved_n = 0
|
| 454 |
+
for rec in r['records']:
|
| 455 |
+
dim_c.update(rec['dimensions'])
|
| 456 |
+
curved_n += rec['curved']
|
| 457 |
+
print(f" {vn:12s}", end="")
|
| 458 |
+
for d in range(4):
|
| 459 |
+
pct = dim_c.get(d, 0) / total * 100
|
| 460 |
+
print(f" {pct:>7.1f}%", end="")
|
| 461 |
+
print(f" {curved_n/total*100:>7.1f}%")
|
| 462 |
+
|
| 463 |
+
# --- Channel group comparison ---
|
| 464 |
+
print(f"\n{'β'*70}")
|
| 465 |
+
print("CHANNEL GROUPS")
|
| 466 |
+
print(f"{'β'*70}")
|
| 467 |
+
for vn in vae_names:
|
| 468 |
+
r = all_vae_results[vn]
|
| 469 |
+
sh = r['latent_shape']
|
| 470 |
+
print(f" {vn:12s} ({sh[0]}ch): {r['channel_groups']}")
|
| 471 |
+
|
| 472 |
+
# --- Per-image cross-VAE consistency ---
|
| 473 |
+
if len(vae_names) >= 2:
|
| 474 |
+
print(f"\n{'β'*70}")
|
| 475 |
+
print("PER-IMAGE CROSS-VAE CONSISTENCY")
|
| 476 |
+
print(f"{'β'*70}")
|
| 477 |
+
print(" Do images that are geometrically distinct in one VAE stay distinct in another?")
|
| 478 |
+
|
| 479 |
+
# Build per-image class vectors for each VAE
|
| 480 |
+
per_vae_vectors = {}
|
| 481 |
+
common_names = None
|
| 482 |
+
|
| 483 |
+
for vn in vae_names:
|
| 484 |
+
r = all_vae_results[vn]
|
| 485 |
+
name_to_vec = {}
|
| 486 |
+
for rec in r['records']:
|
| 487 |
+
vec = np.zeros(len(CLASS_NAMES))
|
| 488 |
+
total = max(rec['n_total'], 1)
|
| 489 |
+
for cls, cnt in rec['classes'].items():
|
| 490 |
+
vec[CLASS_NAMES.index(cls)] = cnt / total
|
| 491 |
+
name_to_vec[rec['name']] = vec
|
| 492 |
+
|
| 493 |
+
per_vae_vectors[vn] = name_to_vec
|
| 494 |
+
names_set = set(name_to_vec.keys())
|
| 495 |
+
common_names = names_set if common_names is None else common_names & names_set
|
| 496 |
+
|
| 497 |
+
common_names = sorted(common_names)[:200] # sample for speed
|
| 498 |
+
|
| 499 |
+
if len(common_names) >= 10:
|
| 500 |
+
for vn1_idx, vn1 in enumerate(vae_names):
|
| 501 |
+
for vn2 in vae_names[vn1_idx+1:]:
|
| 502 |
+
v1_mat = np.stack([per_vae_vectors[vn1][n] for n in common_names])
|
| 503 |
+
v2_mat = np.stack([per_vae_vectors[vn2][n] for n in common_names])
|
| 504 |
+
|
| 505 |
+
# Per-image cosine between VAEs
|
| 506 |
+
norms1 = np.linalg.norm(v1_mat, axis=1, keepdims=True)
|
| 507 |
+
norms2 = np.linalg.norm(v2_mat, axis=1, keepdims=True)
|
| 508 |
+
norms1 = np.clip(norms1, 1e-8, None)
|
| 509 |
+
norms2 = np.clip(norms2, 1e-8, None)
|
| 510 |
+
cos = np.sum((v1_mat / norms1) * (v2_mat / norms2), axis=1)
|
| 511 |
+
|
| 512 |
+
print(f" {vn1:12s} β {vn2:12s}: "
|
| 513 |
+
f"mean={cos.mean():.3f} std={cos.std():.3f} "
|
| 514 |
+
f"[{cos.min():.3f}, {cos.max():.3f}]")
|
| 515 |
+
if cos.mean() > 0.9:
|
| 516 |
+
print(f" β Same geometric structure")
|
| 517 |
+
elif cos.mean() > 0.7:
|
| 518 |
+
print(f" β Similar structure")
|
| 519 |
+
elif cos.mean() > 0.4:
|
| 520 |
+
print(f" β Different structures")
|
| 521 |
+
else:
|
| 522 |
+
print(f" β Very different geometric encoding")
|
| 523 |
+
|
| 524 |
+
# === Save =====================================================================
|
| 525 |
+
save_data = {}
|
| 526 |
+
for vn in vae_names:
|
| 527 |
+
r = all_vae_results[vn]
|
| 528 |
+
save_data[vn] = {
|
| 529 |
+
'latent_shape': r['latent_shape'],
|
| 530 |
+
'n_images': r['n_images'],
|
| 531 |
+
'total_annotations': r['total_annotations'],
|
| 532 |
+
'class_counts': dict(r['class_counts']),
|
| 533 |
+
'mean_confidence': r['mean_confidence'],
|
| 534 |
+
'scales': [list(s) for s in r['scales']],
|
| 535 |
+
'channel_groups': r['channel_groups'],
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
with open('/content/multi_vae_comparison_mega.json', 'w') as f:
|
| 539 |
+
json.dump(save_data, f, indent=2)
|
| 540 |
+
|
| 541 |
+
print(f"\nSaved to /content/multi_vae_comparison_mega.json")
|
| 542 |
+
print("=" * 70)
|
| 543 |
+
print("β Multi-VAE comparison complete!")
|
| 544 |
+
print("=" * 70)
|