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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ============================================================================
|
| 2 |
+
# ALIGNMENT BANK: Production 5-Expert CaptionBERT-8192
|
| 3 |
+
#
|
| 4 |
+
# Trains the geometric interface layer for the deployed model.
|
| 5 |
+
# Uses cached expert embeddings — no re-extraction needed.
|
| 6 |
+
# GPA alignment — no reference expert bias.
|
| 7 |
+
# Full whitened Procrustes chain per expert.
|
| 8 |
+
# Disagreement preservation calibrated from GPA center.
|
| 9 |
+
#
|
| 10 |
+
# Inputs: consensus_500k/{bert,modern,roberta,albert,distil}.pt
|
| 11 |
+
# AbstractPhil/geolip-captionbert-8192 (frozen student)
|
| 12 |
+
# Outputs: alignment_bank.pt (upload alongside model)
|
| 13 |
+
# ============================================================================
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import math
|
| 17 |
+
import os
|
| 18 |
+
import time
|
| 19 |
+
import json
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn as nn
|
| 24 |
+
import torch.nn.functional as F
|
| 25 |
+
from tqdm import tqdm
|
| 26 |
+
|
| 27 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 28 |
+
|
| 29 |
+
EXPERTS = [
|
| 30 |
+
("google-bert/bert-base-uncased", "bert", 512),
|
| 31 |
+
("answerdotai/ModernBERT-base", "modern", 8192),
|
| 32 |
+
("FacebookAI/roberta-base", "roberta", 512),
|
| 33 |
+
("albert/albert-base-v2", "albert", 512),
|
| 34 |
+
("distilbert/distilbert-base-uncased", "distil", 512),
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
CACHE_DIR = "/home/claude/consensus_500k"
|
| 38 |
+
REPO_ID = "AbstractPhil/geolip-captionbert-8192"
|
| 39 |
+
|
| 40 |
+
# Bank config
|
| 41 |
+
N_EXTRACT = 500000
|
| 42 |
+
N_ANCHORS = 512
|
| 43 |
+
D_BANK = 128
|
| 44 |
+
BANK_EPOCHS = 30
|
| 45 |
+
BANK_BATCH = 256
|
| 46 |
+
BANK_LR = 1e-3
|
| 47 |
+
N_VAL = 5000
|
| 48 |
+
|
| 49 |
+
print("=" * 65)
|
| 50 |
+
print("ALIGNMENT BANK: 5-Expert CaptionBERT-8192")
|
| 51 |
+
print("=" * 65)
|
| 52 |
+
print(f" Device: {DEVICE}")
|
| 53 |
+
print(f" Experts: {len(EXPERTS)}")
|
| 54 |
+
print(f" Anchors: {N_ANCHORS}")
|
| 55 |
+
print(f" Bank dim: {D_BANK}")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# ══════════════════════════════════════════════════════════════════
|
| 59 |
+
# ALIGNMENT BANK MODULE
|
| 60 |
+
# ══════════════════════════════════════════════════════════════════
|
| 61 |
+
|
| 62 |
+
class AlignmentBank(nn.Module):
|
| 63 |
+
def __init__(self, d_embed=768, n_experts=5, n_anchors=512, d_bank=128):
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.d_embed = d_embed
|
| 66 |
+
self.n_experts = n_experts
|
| 67 |
+
self.n_anchors = n_anchors
|
| 68 |
+
self.d_bank = d_bank
|
| 69 |
+
|
| 70 |
+
self.expert_rotations = nn.ParameterList([
|
| 71 |
+
nn.Parameter(torch.eye(d_embed)) for _ in range(n_experts)])
|
| 72 |
+
self.expert_whiteners = nn.ParameterList([
|
| 73 |
+
nn.Parameter(torch.eye(d_embed)) for _ in range(n_experts)])
|
| 74 |
+
self.expert_means = nn.ParameterList([
|
| 75 |
+
nn.Parameter(torch.zeros(d_embed)) for _ in range(n_experts)])
|
| 76 |
+
|
| 77 |
+
self.anchors = nn.Parameter(
|
| 78 |
+
F.normalize(torch.randn(n_anchors, d_embed), dim=-1))
|
| 79 |
+
|
| 80 |
+
n_cross = n_experts * (n_experts - 1) // 2
|
| 81 |
+
geo_dim = n_experts + n_experts + n_cross + 1 + n_experts + n_anchors
|
| 82 |
+
self.geo_proj = nn.Sequential(
|
| 83 |
+
nn.Linear(geo_dim, d_bank * 2), nn.GELU(), nn.LayerNorm(d_bank * 2),
|
| 84 |
+
nn.Linear(d_bank * 2, d_bank), nn.LayerNorm(d_bank))
|
| 85 |
+
|
| 86 |
+
self.register_buffer("target_cv", torch.tensor(0.084))
|
| 87 |
+
self.register_buffer("target_mean_cos", torch.tensor(0.0))
|
| 88 |
+
self.register_buffer("target_spectral", torch.zeros(50))
|
| 89 |
+
self.register_buffer("target_cross_cos_mean", torch.tensor(0.0))
|
| 90 |
+
self.register_buffer("target_cross_cos_std", torch.tensor(0.0))
|
| 91 |
+
self.register_buffer("target_disagreement_ratio", torch.tensor(0.0))
|
| 92 |
+
|
| 93 |
+
def init_from_procrustes(self, procrustes_results, expert_names,
|
| 94 |
+
consensus_embeddings=None, consensus_stats=None):
|
| 95 |
+
device = self.anchors.device
|
| 96 |
+
for i, name in enumerate(expert_names[:self.n_experts]):
|
| 97 |
+
info = procrustes_results[name]
|
| 98 |
+
self.expert_rotations[i].data = info["rotation"].float().to(device)
|
| 99 |
+
if "source_whitener" in info:
|
| 100 |
+
self.expert_whiteners[i].data = info["source_whitener"].float().to(device)
|
| 101 |
+
if "source_mean" in info:
|
| 102 |
+
self.expert_means[i].data = info["source_mean"].float().to(device)
|
| 103 |
+
print(f" Expert {i} ({name}): loaded, cos_after={info['cos_after']:.4f}")
|
| 104 |
+
|
| 105 |
+
if consensus_embeddings is not None:
|
| 106 |
+
n = min(self.n_anchors, consensus_embeddings.shape[0])
|
| 107 |
+
indices = torch.linspace(0, consensus_embeddings.shape[0] - 1, n).long()
|
| 108 |
+
self.anchors.data[:n] = F.normalize(
|
| 109 |
+
consensus_embeddings[indices].float(), dim=-1).to(device)
|
| 110 |
+
print(f" Anchors: {n} from consensus")
|
| 111 |
+
|
| 112 |
+
if consensus_stats is not None:
|
| 113 |
+
self.target_cv.fill_(consensus_stats["cv"])
|
| 114 |
+
self.target_mean_cos.fill_(consensus_stats["mean_cos"])
|
| 115 |
+
if "spectral" in consensus_stats:
|
| 116 |
+
s = torch.tensor(consensus_stats["spectral"][:50], dtype=torch.float32)
|
| 117 |
+
self.target_spectral[:len(s)] = s.to(device)
|
| 118 |
+
print(f" Targets: CV={consensus_stats['cv']:.4f}")
|
| 119 |
+
|
| 120 |
+
def forward(self, embedding):
|
| 121 |
+
B = embedding.shape[0]
|
| 122 |
+
emb = embedding.float()
|
| 123 |
+
|
| 124 |
+
# Full whitened Procrustes: center → whiten → normalize → rotate
|
| 125 |
+
expert_consistency = []
|
| 126 |
+
expert_recon = []
|
| 127 |
+
expert_projected = []
|
| 128 |
+
for i in range(self.n_experts):
|
| 129 |
+
R = self.expert_rotations[i]
|
| 130 |
+
W = self.expert_whiteners[i]
|
| 131 |
+
mu = self.expert_means[i]
|
| 132 |
+
centered = emb - mu
|
| 133 |
+
whitened = centered @ W
|
| 134 |
+
whitened_n = F.normalize(whitened, dim=-1)
|
| 135 |
+
in_expert = whitened_n @ R.T
|
| 136 |
+
back = in_expert @ R
|
| 137 |
+
cos = F.cosine_similarity(whitened_n, back, dim=-1)
|
| 138 |
+
recon = (whitened_n - back).pow(2).mean(dim=-1)
|
| 139 |
+
expert_consistency.append(cos)
|
| 140 |
+
expert_recon.append(recon)
|
| 141 |
+
expert_projected.append(in_expert)
|
| 142 |
+
|
| 143 |
+
expert_cos = torch.stack(expert_consistency, dim=-1)
|
| 144 |
+
expert_mse = torch.stack(expert_recon, dim=-1)
|
| 145 |
+
|
| 146 |
+
# Cross-expert differentiation (10 pairs for 5 experts)
|
| 147 |
+
cross_cos = []
|
| 148 |
+
for i in range(self.n_experts):
|
| 149 |
+
for j in range(i + 1, self.n_experts):
|
| 150 |
+
cc = F.cosine_similarity(expert_projected[i], expert_projected[j], dim=-1)
|
| 151 |
+
cross_cos.append(cc)
|
| 152 |
+
cross_features = torch.stack(cross_cos, dim=-1)
|
| 153 |
+
|
| 154 |
+
# Per-sample disagreement
|
| 155 |
+
per_sample_agreement = expert_cos.mean(dim=-1)
|
| 156 |
+
per_sample_disagreement = expert_cos.std(dim=-1)
|
| 157 |
+
disagreement_ratio = per_sample_disagreement / (per_sample_agreement + 1e-8)
|
| 158 |
+
|
| 159 |
+
# Expert norms
|
| 160 |
+
expert_norms = []
|
| 161 |
+
for i in range(self.n_experts):
|
| 162 |
+
W = self.expert_whiteners[i]; mu = self.expert_means[i]
|
| 163 |
+
whitened = (emb - mu) @ W
|
| 164 |
+
expert_norms.append(whitened.norm(dim=-1))
|
| 165 |
+
norm_ratio = torch.stack(expert_norms, dim=-1)
|
| 166 |
+
norm_ratio = norm_ratio / (norm_ratio.mean(dim=-1, keepdim=True) + 1e-8)
|
| 167 |
+
|
| 168 |
+
# Anchor distances
|
| 169 |
+
anchors_n = F.normalize(self.anchors, dim=-1)
|
| 170 |
+
anchor_cos = emb @ anchors_n.T
|
| 171 |
+
|
| 172 |
+
# Geometric context
|
| 173 |
+
geo_input = torch.cat([
|
| 174 |
+
expert_cos, expert_mse, cross_features,
|
| 175 |
+
disagreement_ratio.unsqueeze(-1), norm_ratio, anchor_cos
|
| 176 |
+
], dim=-1)
|
| 177 |
+
geo_context = self.geo_proj(geo_input)
|
| 178 |
+
enriched = torch.cat([embedding, geo_context], dim=-1)
|
| 179 |
+
|
| 180 |
+
# Losses + diagnostics
|
| 181 |
+
aux = {}
|
| 182 |
+
expert_mean = expert_cos.mean(dim=-1, keepdim=True)
|
| 183 |
+
aux["expert_agreement"] = (expert_cos - expert_mean).pow(2).mean()
|
| 184 |
+
|
| 185 |
+
ortho_loss = 0.0
|
| 186 |
+
for i in range(self.n_experts):
|
| 187 |
+
R = self.expert_rotations[i]
|
| 188 |
+
ortho_loss += (R @ R.T - torch.eye(self.d_embed, device=R.device)).pow(2).mean()
|
| 189 |
+
aux["rotation_ortho"] = ortho_loss / self.n_experts
|
| 190 |
+
|
| 191 |
+
anchor_sim = anchors_n @ anchors_n.T
|
| 192 |
+
anchor_sim.fill_diagonal_(0)
|
| 193 |
+
aux["anchor_spread"] = anchor_sim.pow(2).mean()
|
| 194 |
+
|
| 195 |
+
anchor_probs = F.softmax(anchor_cos * 10, dim=-1)
|
| 196 |
+
aux["anchor_entropy"] = -(anchor_probs * (anchor_probs + 1e-12).log()).sum(-1).mean()
|
| 197 |
+
|
| 198 |
+
aux["cross_expert_var"] = cross_features.var(dim=0).mean()
|
| 199 |
+
|
| 200 |
+
batch_cross_mean = cross_features.mean()
|
| 201 |
+
batch_cross_std = cross_features.std()
|
| 202 |
+
batch_disagree_ratio = disagreement_ratio.mean()
|
| 203 |
+
aux["disagree_preserve"] = (
|
| 204 |
+
(batch_cross_mean - self.target_cross_cos_mean).pow(2) +
|
| 205 |
+
(batch_cross_std - self.target_cross_cos_std).pow(2) +
|
| 206 |
+
(batch_disagree_ratio - self.target_disagreement_ratio).pow(2))
|
| 207 |
+
|
| 208 |
+
# CV measurements
|
| 209 |
+
for label, data in [("bank_cv", F.normalize(geo_context, dim=-1)),
|
| 210 |
+
("emb_cv", F.normalize(emb, dim=-1))]:
|
| 211 |
+
if B >= 10:
|
| 212 |
+
vols = []
|
| 213 |
+
for _ in range(32):
|
| 214 |
+
idx = torch.randperm(B, device=emb.device)[:5]
|
| 215 |
+
pts = data[idx].unsqueeze(0)
|
| 216 |
+
diff = pts.unsqueeze(-2) - pts.unsqueeze(-3)
|
| 217 |
+
d2 = (diff * diff).sum(-1)
|
| 218 |
+
Bv, V, _ = d2.shape
|
| 219 |
+
cm = torch.zeros(Bv, V+1, V+1, device=d2.device, dtype=torch.float32)
|
| 220 |
+
cm[:, 0, 1:] = 1; cm[:, 1:, 0] = 1; cm[:, 1:, 1:] = d2
|
| 221 |
+
s = (-1.0)**V; f = math.factorial(V-1)
|
| 222 |
+
v2 = s / ((2.0**(V-1)) * f*f) * torch.linalg.det(cm)
|
| 223 |
+
vols.append(torch.sqrt(F.relu(v2[0]) + 1e-12))
|
| 224 |
+
stacked = torch.stack(vols)
|
| 225 |
+
aux[label] = stacked.std() / (stacked.mean() + 1e-8)
|
| 226 |
+
else:
|
| 227 |
+
aux[label] = torch.tensor(0.0, device=emb.device)
|
| 228 |
+
|
| 229 |
+
# Diagnostics
|
| 230 |
+
aux["expert_cos_mean"] = expert_cos.mean().item()
|
| 231 |
+
aux["expert_cos_std"] = expert_cos.std().item()
|
| 232 |
+
aux["anchor_max_cos"] = anchor_cos.max(dim=-1).values.mean().item()
|
| 233 |
+
aux["cross_expert_cos"] = cross_features.mean().item()
|
| 234 |
+
aux["cross_expert_cos_std"] = cross_features.std().item()
|
| 235 |
+
aux["disagreement_ratio"] = disagreement_ratio.mean().item()
|
| 236 |
+
aux["norm_ratio_spread"] = norm_ratio.std(dim=-1).mean().item()
|
| 237 |
+
|
| 238 |
+
return enriched, aux
|
| 239 |
+
|
| 240 |
+
def bank_loss(self, aux):
|
| 241 |
+
return (
|
| 242 |
+
1.0 * aux["expert_agreement"] +
|
| 243 |
+
1.0 * aux["rotation_ortho"] +
|
| 244 |
+
0.5 * aux["anchor_spread"] +
|
| 245 |
+
0.1 * aux["anchor_entropy"] +
|
| 246 |
+
0.3 * aux["cross_expert_var"] +
|
| 247 |
+
0.3 * (aux["bank_cv"] - self.target_cv).abs() +
|
| 248 |
+
0.3 * (aux["emb_cv"] - self.target_cv).abs() +
|
| 249 |
+
0.5 * aux["disagree_preserve"])
|
| 250 |
+
|
| 251 |
+
@torch.no_grad()
|
| 252 |
+
def calibrate_disagreement(self, embeddings):
|
| 253 |
+
B = embeddings.shape[0]
|
| 254 |
+
emb = embeddings.float()
|
| 255 |
+
per_sample_expert_cos = []
|
| 256 |
+
expert_projected = []
|
| 257 |
+
for i in range(self.n_experts):
|
| 258 |
+
R = self.expert_rotations[i]; W = self.expert_whiteners[i]; mu = self.expert_means[i]
|
| 259 |
+
centered = emb - mu; whitened = centered @ W
|
| 260 |
+
whitened_n = F.normalize(whitened, dim=-1)
|
| 261 |
+
in_expert = whitened_n @ R.T
|
| 262 |
+
back = in_expert @ R
|
| 263 |
+
per_sample_expert_cos.append(F.cosine_similarity(whitened_n, back, dim=-1))
|
| 264 |
+
expert_projected.append(in_expert)
|
| 265 |
+
expert_cos = torch.stack(per_sample_expert_cos, dim=-1)
|
| 266 |
+
per_sample_ratio = expert_cos.std(dim=-1) / (expert_cos.mean(dim=-1) + 1e-8)
|
| 267 |
+
cross_vals = []
|
| 268 |
+
for i in range(self.n_experts):
|
| 269 |
+
for j in range(i + 1, self.n_experts):
|
| 270 |
+
cross_vals.append(F.cosine_similarity(expert_projected[i], expert_projected[j], dim=-1))
|
| 271 |
+
cross_all = torch.stack(cross_vals, dim=-1)
|
| 272 |
+
self.target_cross_cos_mean.fill_(cross_all.mean().item())
|
| 273 |
+
self.target_cross_cos_std.fill_(cross_all.std().item())
|
| 274 |
+
self.target_disagreement_ratio.fill_(per_sample_ratio.median().item())
|
| 275 |
+
print(f" Calibrated (n={B}):")
|
| 276 |
+
print(f" cross_cos: {self.target_cross_cos_mean.item():.4f} ± {self.target_cross_cos_std.item():.4f}")
|
| 277 |
+
print(f" disagree_ratio: median={self.target_disagreement_ratio.item():.6f}")
|
| 278 |
+
print(f" expert_cos: {expert_cos.mean().item():.4f} ± {expert_cos.std().item():.4f}")
|
| 279 |
+
print(f" cross pairs: {len(cross_vals)}")
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
# ══════════════════════════════════════════════════════════════════
|
| 283 |
+
# ALIGNMENT UTILITIES
|
| 284 |
+
# ══════════════════════════════════════════════════════════════════
|
| 285 |
+
|
| 286 |
+
def symmetric_inv_sqrt(cov, eps=1e-6):
|
| 287 |
+
evals, evecs = torch.linalg.eigh(cov)
|
| 288 |
+
evals = torch.clamp(evals, min=eps)
|
| 289 |
+
return evecs @ torch.diag(evals.rsqrt()) @ evecs.T
|
| 290 |
+
|
| 291 |
+
def procrustes_align(source, target, n_align=10000):
|
| 292 |
+
N = min(n_align, source.shape[0], target.shape[0])
|
| 293 |
+
S = source[:N].float(); T = target[:N].float()
|
| 294 |
+
s_mean = S.mean(0, keepdim=True); t_mean = T.mean(0, keepdim=True)
|
| 295 |
+
Sc = S - s_mean; Tc = T - t_mean; N_s = Sc.shape[0]
|
| 296 |
+
cos_before = F.cosine_similarity(Sc, Tc, dim=-1).mean().item()
|
| 297 |
+
s_cov = (Sc.T @ Sc) / max(N_s - 1, 1)
|
| 298 |
+
t_cov = (Tc.T @ Tc) / max(N_s - 1, 1)
|
| 299 |
+
s_whiten = symmetric_inv_sqrt(s_cov)
|
| 300 |
+
t_whiten = symmetric_inv_sqrt(t_cov)
|
| 301 |
+
Sc_w = F.normalize(Sc @ s_whiten, dim=-1)
|
| 302 |
+
Tc_w = F.normalize(Tc @ t_whiten, dim=-1)
|
| 303 |
+
U, _, Vt = torch.linalg.svd(Tc_w.T @ Sc_w, full_matrices=False)
|
| 304 |
+
R = U @ Vt
|
| 305 |
+
cos_after = F.cosine_similarity(Sc_w @ R.T, Tc_w, dim=-1).mean().item()
|
| 306 |
+
return {
|
| 307 |
+
"rotation": R, "source_mean": s_mean.squeeze(0),
|
| 308 |
+
"source_whitener": s_whiten,
|
| 309 |
+
"target_unwhitener": torch.linalg.pinv(t_whiten),
|
| 310 |
+
"cos_before": cos_before, "cos_after": cos_after,
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
def apply_align(emb, a):
|
| 314 |
+
x = emb.float() - a["source_mean"]
|
| 315 |
+
x = x @ a["source_whitener"]; x = x @ a["rotation"].T
|
| 316 |
+
x = x @ a["target_unwhitener"]; return x
|
| 317 |
+
|
| 318 |
+
def cv_metric(emb, n=200):
|
| 319 |
+
B = emb.shape[0]
|
| 320 |
+
if B < 5: return 0.0
|
| 321 |
+
vols = []
|
| 322 |
+
for _ in range(n):
|
| 323 |
+
idx = torch.randperm(B, device=emb.device)[:5]
|
| 324 |
+
pts = emb[idx].unsqueeze(0).float()
|
| 325 |
+
diff = pts.unsqueeze(-2) - pts.unsqueeze(-3)
|
| 326 |
+
d2 = (diff * diff).sum(-1)
|
| 327 |
+
Bv, V, _ = d2.shape
|
| 328 |
+
cm = torch.zeros(Bv, V+1, V+1, device=d2.device, dtype=torch.float32)
|
| 329 |
+
cm[:, 0, 1:] = 1; cm[:, 1:, 0] = 1; cm[:, 1:, 1:] = d2
|
| 330 |
+
s = (-1.0)**V; f = math.factorial(V-1)
|
| 331 |
+
v2 = s / ((2.0**(V-1)) * f*f) * torch.linalg.det(cm)
|
| 332 |
+
v = torch.sqrt(F.relu(v2[0]) + 1e-12).item()
|
| 333 |
+
if v > 0: vols.append(v)
|
| 334 |
+
if len(vols) < 10: return 0.0
|
| 335 |
+
a = np.array(vols)
|
| 336 |
+
return float(a.std() / (a.mean() + 1e-8))
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
# ══════════════════════════════════════════════════════════════════
|
| 340 |
+
# MAIN
|
| 341 |
+
# ══════════════════════════════════════════════════════════════════
|
| 342 |
+
|
| 343 |
+
def run():
|
| 344 |
+
torch.manual_seed(42)
|
| 345 |
+
np.random.seed(42)
|
| 346 |
+
names = [s for _, s, _ in EXPERTS]
|
| 347 |
+
|
| 348 |
+
# ── Phase 0: Extract or Load Embeddings ──
|
| 349 |
+
print(f"\n{'='*65}")
|
| 350 |
+
print("PHASE 0: EXPERT EMBEDDINGS")
|
| 351 |
+
print(f"{'='*65}")
|
| 352 |
+
|
| 353 |
+
os.makedirs(CACHE_DIR, exist_ok=True)
|
| 354 |
+
caps_path = os.path.join(CACHE_DIR, "captions.json")
|
| 355 |
+
|
| 356 |
+
# Check what's cached
|
| 357 |
+
all_cached = all(
|
| 358 |
+
os.path.exists(os.path.join(CACHE_DIR, f"{s}.pt"))
|
| 359 |
+
for _, s, _ in EXPERTS)
|
| 360 |
+
|
| 361 |
+
if all_cached:
|
| 362 |
+
print(" Loading cached embeddings...")
|
| 363 |
+
embeds = {}
|
| 364 |
+
for _, short, _ in EXPERTS:
|
| 365 |
+
embeds[short] = torch.load(
|
| 366 |
+
os.path.join(CACHE_DIR, f"{short}.pt"), weights_only=True)
|
| 367 |
+
print(f" {short}: {embeds[short].shape}")
|
| 368 |
+
if os.path.exists(caps_path):
|
| 369 |
+
with open(caps_path) as f:
|
| 370 |
+
captions = json.load(f)
|
| 371 |
+
print(f" Captions: {len(captions):,}")
|
| 372 |
+
else:
|
| 373 |
+
print(" captions.json missing, reloading...")
|
| 374 |
+
from datasets import load_dataset
|
| 375 |
+
ds = load_dataset("CaptionEmporium/conceptual-captions-cc12m-llavanext",
|
| 376 |
+
split="train", streaming=True)
|
| 377 |
+
captions = []
|
| 378 |
+
for row in ds:
|
| 379 |
+
cap = row.get("caption_llava", "")
|
| 380 |
+
if isinstance(cap, str) and len(cap) > 50:
|
| 381 |
+
captions.append(cap)
|
| 382 |
+
if len(captions) >= N_EXTRACT:
|
| 383 |
+
break
|
| 384 |
+
with open(caps_path, "w") as f:
|
| 385 |
+
json.dump(captions, f)
|
| 386 |
+
else:
|
| 387 |
+
# Extract from scratch
|
| 388 |
+
from datasets import load_dataset
|
| 389 |
+
from transformers import AutoModel, AutoTokenizer
|
| 390 |
+
|
| 391 |
+
print(f" Loading {N_EXTRACT:,} captions...")
|
| 392 |
+
ds = load_dataset("CaptionEmporium/conceptual-captions-cc12m-llavanext",
|
| 393 |
+
split="train", streaming=True)
|
| 394 |
+
captions = []
|
| 395 |
+
for row in ds:
|
| 396 |
+
cap = row.get("caption_llava", "")
|
| 397 |
+
if isinstance(cap, str) and len(cap) > 50:
|
| 398 |
+
captions.append(cap)
|
| 399 |
+
if len(captions) >= N_EXTRACT:
|
| 400 |
+
break
|
| 401 |
+
print(f" Got {len(captions):,} captions")
|
| 402 |
+
|
| 403 |
+
with open(caps_path, "w") as f:
|
| 404 |
+
json.dump(captions, f)
|
| 405 |
+
|
| 406 |
+
embeds = {}
|
| 407 |
+
for model_name, short, max_len in EXPERTS:
|
| 408 |
+
out_path = os.path.join(CACHE_DIR, f"{short}.pt")
|
| 409 |
+
if os.path.exists(out_path):
|
| 410 |
+
embeds[short] = torch.load(out_path, weights_only=True)
|
| 411 |
+
print(f" {short}: cached {embeds[short].shape}")
|
| 412 |
+
continue
|
| 413 |
+
|
| 414 |
+
print(f"\n Extracting: {short} ({model_name}, max_len={max_len})...")
|
| 415 |
+
ext_model = AutoModel.from_pretrained(model_name).to(DEVICE).eval()
|
| 416 |
+
ext_tok = AutoTokenizer.from_pretrained(model_name)
|
| 417 |
+
n_p = sum(p.numel() for p in ext_model.parameters())
|
| 418 |
+
print(f" {n_p:,} params")
|
| 419 |
+
|
| 420 |
+
all_emb = []
|
| 421 |
+
with torch.no_grad():
|
| 422 |
+
for i in tqdm(range(0, len(captions), 128), desc=f" {short}"):
|
| 423 |
+
batch = captions[i:i+128]
|
| 424 |
+
inputs = ext_tok(batch, max_length=max_len, padding=True,
|
| 425 |
+
truncation=True, return_tensors="pt").to(DEVICE)
|
| 426 |
+
out = ext_model(**inputs)
|
| 427 |
+
m = inputs.attention_mask.unsqueeze(-1).float()
|
| 428 |
+
pooled = (out.last_hidden_state * m).sum(1) / m.sum(1).clamp(min=1)
|
| 429 |
+
all_emb.append(pooled.cpu())
|
| 430 |
+
|
| 431 |
+
emb = torch.cat(all_emb)
|
| 432 |
+
if emb.shape[1] != 768:
|
| 433 |
+
emb = emb[:, :768] if emb.shape[1] > 768 else F.pad(emb, (0, 768 - emb.shape[1]))
|
| 434 |
+
embeds[short] = emb
|
| 435 |
+
torch.save(emb, out_path)
|
| 436 |
+
print(f" Saved: {emb.shape}")
|
| 437 |
+
del ext_model, ext_tok; gc.collect(); torch.cuda.empty_cache()
|
| 438 |
+
|
| 439 |
+
N = min(len(captions), min(e.shape[0] for e in embeds.values()))
|
| 440 |
+
print(f" Using {N:,} samples")
|
| 441 |
+
|
| 442 |
+
# ── Phase 1: GPA Alignment ──
|
| 443 |
+
print(f"\n{'='*65}")
|
| 444 |
+
print("PHASE 1: GENERALIZED PROCRUSTES ALIGNMENT")
|
| 445 |
+
print(f"{'='*65}")
|
| 446 |
+
|
| 447 |
+
current = {name: embeds[name][:N].float() for name in names}
|
| 448 |
+
for gpa_iter in range(15):
|
| 449 |
+
mean_shape = sum(current[n] for n in names) / len(names)
|
| 450 |
+
total_delta = 0.0
|
| 451 |
+
new_current = {}
|
| 452 |
+
for name in names:
|
| 453 |
+
info = procrustes_align(current[name], mean_shape)
|
| 454 |
+
new_current[name] = apply_align(current[name], info)
|
| 455 |
+
total_delta += (new_current[name] - current[name]).pow(2).mean().item()
|
| 456 |
+
current = new_current
|
| 457 |
+
if gpa_iter == 0 or (gpa_iter + 1) % 3 == 0:
|
| 458 |
+
print(f" GPA iter {gpa_iter+1}: delta={total_delta:.8f}")
|
| 459 |
+
if total_delta < 1e-8:
|
| 460 |
+
print(f" Converged at iteration {gpa_iter+1}")
|
| 461 |
+
break
|
| 462 |
+
|
| 463 |
+
# Final alignment to converged mean
|
| 464 |
+
mean_shape = sum(current[n] for n in names) / len(names)
|
| 465 |
+
procrustes_results = {}
|
| 466 |
+
aligned = {}
|
| 467 |
+
for name in names:
|
| 468 |
+
info = procrustes_align(embeds[name][:N], mean_shape)
|
| 469 |
+
procrustes_results[name] = info
|
| 470 |
+
aligned[name] = apply_align(embeds[name][:N], info)
|
| 471 |
+
cos_to_mean = F.cosine_similarity(
|
| 472 |
+
aligned[name][:5000], mean_shape[:5000], dim=-1).mean().item()
|
| 473 |
+
print(f" {name:10s}: cos_after={info['cos_after']:.4f} cos_to_mean={cos_to_mean:.4f}")
|
| 474 |
+
|
| 475 |
+
consensus = F.normalize(sum(aligned[n] for n in names) / len(names), dim=-1)
|
| 476 |
+
expert_cos_to_consensus = []
|
| 477 |
+
for name in names:
|
| 478 |
+
c = F.cosine_similarity(consensus[:5000], aligned[name][:5000], dim=-1).mean().item()
|
| 479 |
+
expert_cos_to_consensus.append(c)
|
| 480 |
+
print(f" cos(consensus, {name}): {c:.4f}")
|
| 481 |
+
equidist = max(expert_cos_to_consensus) - min(expert_cos_to_consensus)
|
| 482 |
+
print(f" Equidistance range: {equidist:.4f}")
|
| 483 |
+
|
| 484 |
+
# Measure consensus statistics
|
| 485 |
+
print(f"\n Measuring consensus statistics...")
|
| 486 |
+
c_sub = consensus[:5000].to(DEVICE)
|
| 487 |
+
consensus_cv = cv_metric(c_sub)
|
| 488 |
+
sim = c_sub @ c_sub.T
|
| 489 |
+
mask = ~torch.eye(5000, dtype=torch.bool, device=DEVICE)
|
| 490 |
+
mean_cos = sim[mask].mean().item()
|
| 491 |
+
centered = c_sub.float() - c_sub.float().mean(0, keepdim=True)
|
| 492 |
+
S = torch.linalg.svdvals(centered)
|
| 493 |
+
spectral = (S / (S.sum() + 1e-8)).cpu().tolist()[:50]
|
| 494 |
+
eff_dim = float((S.sum() ** 2) / (S.pow(2).sum() + 1e-12))
|
| 495 |
+
consensus_stats = {"cv": consensus_cv, "mean_cos": mean_cos,
|
| 496 |
+
"spectral": spectral, "eff_dim": eff_dim}
|
| 497 |
+
print(f" CV: {consensus_cv:.4f}")
|
| 498 |
+
print(f" Mean cos: {mean_cos:.4f}")
|
| 499 |
+
print(f" Eff dim: {eff_dim:.1f}")
|
| 500 |
+
del c_sub, sim; torch.cuda.empty_cache()
|
| 501 |
+
|
| 502 |
+
del embeds, aligned, current, mean_shape
|
| 503 |
+
gc.collect(); torch.cuda.empty_cache()
|
| 504 |
+
|
| 505 |
+
# ── Phase 2: Load + Encode Frozen Student ──
|
| 506 |
+
print(f"\n{'='*65}")
|
| 507 |
+
print("PHASE 2: ENCODE FROZEN STUDENT")
|
| 508 |
+
print(f"{'='*65}")
|
| 509 |
+
|
| 510 |
+
from transformers import AutoModel, AutoTokenizer
|
| 511 |
+
|
| 512 |
+
model = AutoModel.from_pretrained(REPO_ID, trust_remote_code=True).to(DEVICE).eval()
|
| 513 |
+
tokenizer = AutoTokenizer.from_pretrained(REPO_ID, trust_remote_code=True)
|
| 514 |
+
for p in model.parameters():
|
| 515 |
+
p.requires_grad = False
|
| 516 |
+
print(f" Student: {sum(p.numel() for p in model.parameters()):,} params (frozen)")
|
| 517 |
+
|
| 518 |
+
# captions already loaded from Phase 0
|
| 519 |
+
captions = captions[:N]
|
| 520 |
+
print(f" Encoding {N:,} captions...")
|
| 521 |
+
all_student_embs = []
|
| 522 |
+
with torch.no_grad():
|
| 523 |
+
for i in tqdm(range(0, N, 256), desc=" Encoding"):
|
| 524 |
+
j = min(i + 256, N)
|
| 525 |
+
inputs = tokenizer(captions[i:j], max_length=512, padding="max_length",
|
| 526 |
+
truncation=True, return_tensors="pt").to(DEVICE)
|
| 527 |
+
out = model(**inputs)
|
| 528 |
+
all_student_embs.append(out.last_hidden_state.cpu())
|
| 529 |
+
student_embs = torch.cat(all_student_embs).to(DEVICE)
|
| 530 |
+
print(f" Student embeddings: {student_embs.shape}")
|
| 531 |
+
|
| 532 |
+
del model
|
| 533 |
+
gc.collect(); torch.cuda.empty_cache()
|
| 534 |
+
|
| 535 |
+
# Split
|
| 536 |
+
n_train = N - N_VAL
|
| 537 |
+
train_embs = student_embs[:n_train]
|
| 538 |
+
val_embs = student_embs[n_train:n_train + N_VAL]
|
| 539 |
+
print(f" Train: {n_train:,} Val: {N_VAL:,}")
|
| 540 |
+
|
| 541 |
+
# ── Phase 3: Train Alignment Bank ──
|
| 542 |
+
print(f"\n{'='*65}")
|
| 543 |
+
print("PHASE 3: TRAIN ALIGNMENT BANK")
|
| 544 |
+
print(f"{'='*65}")
|
| 545 |
+
|
| 546 |
+
bank = AlignmentBank(
|
| 547 |
+
d_embed=768, n_experts=len(EXPERTS),
|
| 548 |
+
n_anchors=N_ANCHORS, d_bank=D_BANK
|
| 549 |
+
).to(DEVICE)
|
| 550 |
+
|
| 551 |
+
bank.init_from_procrustes(procrustes_results, names,
|
| 552 |
+
consensus[:n_train], consensus_stats)
|
| 553 |
+
bank.calibrate_disagreement(train_embs[:5000])
|
| 554 |
+
|
| 555 |
+
bank_params = sum(p.numel() for p in bank.parameters())
|
| 556 |
+
print(f" Bank: {bank_params:,} params")
|
| 557 |
+
|
| 558 |
+
bank_opt = torch.optim.AdamW(bank.parameters(), lr=BANK_LR, weight_decay=0.01)
|
| 559 |
+
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
|
| 560 |
+
bank_opt, T_max=(n_train // BANK_BATCH) * BANK_EPOCHS, eta_min=1e-5)
|
| 561 |
+
|
| 562 |
+
best_v_loss = float("inf")
|
| 563 |
+
for epoch in range(BANK_EPOCHS):
|
| 564 |
+
bank.train()
|
| 565 |
+
perm = torch.randperm(n_train, device=DEVICE)
|
| 566 |
+
total_loss = 0
|
| 567 |
+
stats = {"expert_agreement": 0, "rotation_ortho": 0, "anchor_spread": 0,
|
| 568 |
+
"bank_cv": 0, "emb_cv": 0, "cross_expert_var": 0, "disagree_preserve": 0}
|
| 569 |
+
n = 0
|
| 570 |
+
t0 = time.time()
|
| 571 |
+
|
| 572 |
+
for i in range(0, n_train, BANK_BATCH):
|
| 573 |
+
idx = perm[i:i+BANK_BATCH]
|
| 574 |
+
if len(idx) < 16: continue
|
| 575 |
+
_, aux = bank(train_embs[idx])
|
| 576 |
+
loss = bank.bank_loss(aux)
|
| 577 |
+
loss.backward()
|
| 578 |
+
torch.nn.utils.clip_grad_norm_(bank.parameters(), 1.0)
|
| 579 |
+
bank_opt.step(); bank_opt.zero_grad(set_to_none=True)
|
| 580 |
+
scheduler.step()
|
| 581 |
+
total_loss += loss.item()
|
| 582 |
+
for k in stats:
|
| 583 |
+
if k in aux:
|
| 584 |
+
v = aux[k]
|
| 585 |
+
stats[k] += v.item() if torch.is_tensor(v) else v
|
| 586 |
+
n += 1
|
| 587 |
+
|
| 588 |
+
elapsed = time.time() - t0; d = max(n, 1)
|
| 589 |
+
|
| 590 |
+
bank.eval()
|
| 591 |
+
with torch.no_grad():
|
| 592 |
+
_, v_aux = bank(val_embs)
|
| 593 |
+
v_loss = bank.bank_loss(v_aux).item()
|
| 594 |
+
|
| 595 |
+
if v_loss < best_v_loss:
|
| 596 |
+
best_v_loss = v_loss
|
| 597 |
+
torch.save(bank.state_dict(), "alignment_bank_best.pt")
|
| 598 |
+
|
| 599 |
+
if (epoch + 1) % 5 == 0 or epoch == 0:
|
| 600 |
+
print(f"\n E{epoch+1:2d}: {elapsed:.0f}s loss={total_loss/d:.4f} v_loss={v_loss:.4f}")
|
| 601 |
+
print(f" Geometry: b_cv={stats['bank_cv']/d:.4f} e_cv={stats['emb_cv']/d:.4f} "
|
| 602 |
+
f"spread={stats['anchor_spread']/d:.5f} a_max={v_aux['anchor_max_cos']:.3f}")
|
| 603 |
+
print(f" Experts: cos={v_aux['expert_cos_mean']:.3f}±{v_aux['expert_cos_std']:.3f} "
|
| 604 |
+
f"agr={stats['expert_agreement']/d:.6f} ortho={stats['rotation_ortho']/d:.6f}")
|
| 605 |
+
print(f" Disagree: x_cos={v_aux['cross_expert_cos']:.4f}±{v_aux['cross_expert_cos_std']:.4f} "
|
| 606 |
+
f"ratio={v_aux['disagreement_ratio']:.6f} "
|
| 607 |
+
f"preserve={stats['disagree_preserve']/d:.6f}")
|
| 608 |
+
else:
|
| 609 |
+
print(f" E{epoch+1:2d}: {elapsed:.0f}s loss={total_loss/d:.4f} v_loss={v_loss:.4f} "
|
| 610 |
+
f"exp={v_aux['expert_cos_mean']:.3f} "
|
| 611 |
+
f"b_cv={stats['bank_cv']/d:.4f} "
|
| 612 |
+
f"x_cos={v_aux['cross_expert_cos']:.4f}")
|
| 613 |
+
|
| 614 |
+
torch.save(bank.state_dict(), "alignment_bank_final.pt")
|
| 615 |
+
|
| 616 |
+
# ── Phase 4: Geometric Verification ──
|
| 617 |
+
print(f"\n{'='*65}")
|
| 618 |
+
print("PHASE 4: GEOMETRIC VERIFICATION")
|
| 619 |
+
print(f"{'='*65}")
|
| 620 |
+
|
| 621 |
+
bank.load_state_dict(torch.load("alignment_bank_best.pt", weights_only=True))
|
| 622 |
+
bank.eval()
|
| 623 |
+
|
| 624 |
+
with torch.no_grad():
|
| 625 |
+
enriched_val, v_aux = bank(val_embs)
|
| 626 |
+
original_768 = enriched_val[:, :768]
|
| 627 |
+
geo_context = enriched_val[:, 768:]
|
| 628 |
+
|
| 629 |
+
passthrough = F.cosine_similarity(
|
| 630 |
+
original_768[:100], val_embs[:100], dim=-1).mean().item()
|
| 631 |
+
geo_cv = cv_metric(F.normalize(geo_context[:2000], dim=-1))
|
| 632 |
+
S = torch.linalg.svdvals(
|
| 633 |
+
geo_context[:2000].float() - geo_context[:2000].float().mean(0))
|
| 634 |
+
geo_eff_dim = float((S.sum() ** 2) / (S.pow(2).sum() + 1e-12))
|
| 635 |
+
emb_cv = cv_metric(val_embs[:2000])
|
| 636 |
+
|
| 637 |
+
print(f" Passthrough: {passthrough:.6f}")
|
| 638 |
+
print(f" Emb CV: {emb_cv:.4f} (consensus: {consensus_stats['cv']:.4f})")
|
| 639 |
+
print(f" Geo context CV: {geo_cv:.4f}")
|
| 640 |
+
print(f" Geo eff_dim: {geo_eff_dim:.1f} / {D_BANK}")
|
| 641 |
+
print(f" Expert cos: {v_aux['expert_cos_mean']:.3f} ± {v_aux['expert_cos_std']:.3f}")
|
| 642 |
+
print(f" Anchor max cos: {v_aux['anchor_max_cos']:.3f}")
|
| 643 |
+
print(f" Cross-expert: {v_aux['cross_expert_cos']:.4f} ± {v_aux['cross_expert_cos_std']:.4f}")
|
| 644 |
+
print(f" Disagree ratio: {v_aux['disagreement_ratio']:.6f}")
|
| 645 |
+
|
| 646 |
+
# ── Phase 5: Classifier Test ──
|
| 647 |
+
print(f"\n{'='*65}")
|
| 648 |
+
print("PHASE 5: CLASSIFIER STABILITY TEST")
|
| 649 |
+
print(f"{'='*65}")
|
| 650 |
+
|
| 651 |
+
with torch.no_grad():
|
| 652 |
+
embs = val_embs[:2000]
|
| 653 |
+
sim = embs @ embs.T; sim.fill_diagonal_(-1)
|
| 654 |
+
n_pairs = 5000
|
| 655 |
+
idx_a = torch.randint(0, 2000, (n_pairs,))
|
| 656 |
+
idx_b = torch.randint(0, 2000, (n_pairs,))
|
| 657 |
+
pair_cos = sim[idx_a, idx_b]
|
| 658 |
+
sorted_cos, _ = pair_cos.sort()
|
| 659 |
+
t1 = sorted_cos[n_pairs // 3].item()
|
| 660 |
+
t2 = sorted_cos[2 * n_pairs // 3].item()
|
| 661 |
+
labels = torch.zeros(n_pairs, dtype=torch.long, device=DEVICE)
|
| 662 |
+
labels[pair_cos > t2] = 0
|
| 663 |
+
labels[(pair_cos <= t2) & (pair_cos > t1)] = 1
|
| 664 |
+
labels[pair_cos <= t1] = 2
|
| 665 |
+
enriched_a, _ = bank(embs[idx_a])
|
| 666 |
+
enriched_b, _ = bank(embs[idx_b])
|
| 667 |
+
a_emb = embs[idx_a]; b_emb = embs[idx_b]
|
| 668 |
+
a_geo = enriched_a[:, 768:]; b_geo = enriched_b[:, 768:]
|
| 669 |
+
geo_explicit = torch.cat([
|
| 670 |
+
F.cosine_similarity(a_emb, b_emb, dim=-1).unsqueeze(-1),
|
| 671 |
+
(a_emb - b_emb).pow(2).mean(dim=-1).unsqueeze(-1),
|
| 672 |
+
F.cosine_similarity(a_geo, b_geo, dim=-1).unsqueeze(-1),
|
| 673 |
+
(a_geo - b_geo).pow(2).mean(dim=-1).unsqueeze(-1),
|
| 674 |
+
torch.abs(a_emb - b_emb).mean(dim=-1).unsqueeze(-1),
|
| 675 |
+
(a_emb * b_emb).sum(dim=-1).unsqueeze(-1),
|
| 676 |
+
], dim=-1)
|
| 677 |
+
|
| 678 |
+
modes = {
|
| 679 |
+
"raw_768": torch.cat([a_emb, b_emb], dim=-1),
|
| 680 |
+
"raw+diff": torch.cat([a_emb, b_emb, torch.abs(a_emb - b_emb), a_emb * b_emb], dim=-1),
|
| 681 |
+
"bank_enriched": torch.cat([enriched_a, enriched_b], dim=-1),
|
| 682 |
+
"bank+diff": torch.cat([enriched_a, enriched_b,
|
| 683 |
+
torch.abs(enriched_a - enriched_b),
|
| 684 |
+
enriched_a * enriched_b], dim=-1),
|
| 685 |
+
"geo_explicit": geo_explicit,
|
| 686 |
+
}
|
| 687 |
+
|
| 688 |
+
print(f"\n {'Mode':<20} {'Dim':>6} {'Train':>7} {'Val':>7} {'Gap':>7}")
|
| 689 |
+
print(f" {'-'*50}")
|
| 690 |
+
|
| 691 |
+
n_clf_train = 4000
|
| 692 |
+
for mode_name, features in modes.items():
|
| 693 |
+
feat_dim = features.shape[1]
|
| 694 |
+
clf = nn.Sequential(
|
| 695 |
+
nn.Linear(feat_dim, min(256, feat_dim)), nn.GELU(),
|
| 696 |
+
nn.LayerNorm(min(256, feat_dim)), nn.Dropout(0.1),
|
| 697 |
+
nn.Linear(min(256, feat_dim), 3)).to(DEVICE)
|
| 698 |
+
clf_opt = torch.optim.Adam(clf.parameters(), lr=1e-3)
|
| 699 |
+
train_f = features[:n_clf_train].detach()
|
| 700 |
+
train_l = labels[:n_clf_train]
|
| 701 |
+
val_f = features[n_clf_train:].detach()
|
| 702 |
+
val_l = labels[n_clf_train:]
|
| 703 |
+
for e in range(30):
|
| 704 |
+
clf.train()
|
| 705 |
+
loss = F.cross_entropy(clf(train_f), train_l)
|
| 706 |
+
loss.backward(); clf_opt.step(); clf_opt.zero_grad()
|
| 707 |
+
clf.eval()
|
| 708 |
+
with torch.no_grad():
|
| 709 |
+
v_acc = (clf(val_f).argmax(-1) == val_l).float().mean().item()
|
| 710 |
+
t_acc = (clf(train_f).argmax(-1) == train_l).float().mean().item()
|
| 711 |
+
print(f" {mode_name:<20} {feat_dim:>6} {t_acc:>7.3f} {v_acc:>7.3f} {t_acc-v_acc:>7.3f}")
|
| 712 |
+
|
| 713 |
+
print(f"\n{'='*65}")
|
| 714 |
+
print("SUMMARY")
|
| 715 |
+
print(f"{'='*65}")
|
| 716 |
+
print(f" Consensus CV: {consensus_stats['cv']:.4f}")
|
| 717 |
+
print(f" Consensus eff_dim: {consensus_stats['eff_dim']:.1f}")
|
| 718 |
+
print(f" Equidistance: {equidist:.4f}")
|
| 719 |
+
print(f" Bank params: {bank_params:,}")
|
| 720 |
+
print(f" Bank geo eff_dim: {geo_eff_dim:.1f}")
|
| 721 |
+
print(f" Bank geo CV: {geo_cv:.4f}")
|
| 722 |
+
print(f" Best val loss: {best_v_loss:.4f}")
|
| 723 |
+
print(f"\n Files: alignment_bank_best.pt, alignment_bank_final.pt")
|
| 724 |
+
print(f"\n{'='*65}")
|
| 725 |
+
print("DONE")
|
| 726 |
+
print(f"{'='*65}")
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
if __name__ == "__main__":
|
| 730 |
+
run()
|