Update tests.py
Browse files
tests.py
CHANGED
|
@@ -1,92 +1,362 @@
|
|
| 1 |
"""
|
| 2 |
-
Flow
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
"""
|
| 4 |
import torch
|
| 5 |
import torch.nn as nn
|
| 6 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
sys.path.insert(0, '.')
|
| 9 |
-
from flows import (
|
| 10 |
-
QuaternionFlow, QuaternionLiteFlow, VelocityFlow,
|
| 11 |
-
MagnitudeFlow, OrbitalFlow, AlignmentFlow, FlowEnsemble,
|
| 12 |
-
)
|
| 13 |
|
| 14 |
dev = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 15 |
-
B, n, k, d = 32, 128, 64, 256
|
| 16 |
|
| 17 |
-
anchors = torch.randn(B, k, d, device=dev)
|
| 18 |
-
queries = torch.randn(B, n, d, device=dev)
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
# Test each flow independently
|
| 26 |
flows_cfg = [
|
| 27 |
-
('QuaternionFlow', lambda: QuaternionFlow(d, k, n_heads=4)),
|
| 28 |
-
('QuaternionLiteFlow', lambda: QuaternionLiteFlow(d, k)),
|
| 29 |
-
('VelocityFlow', lambda: VelocityFlow(d, k)),
|
| 30 |
-
('MagnitudeFlow', lambda: MagnitudeFlow(d, k)),
|
| 31 |
-
('OrbitalFlow', lambda: OrbitalFlow(d, k)),
|
| 32 |
-
('AlignmentFlow', lambda: AlignmentFlow(d, k)),
|
| 33 |
]
|
| 34 |
|
| 35 |
-
print(f"\n {'Flow':<22} {'Params':>8} {'
|
| 36 |
-
print(f" {'β'*22} {'β'*8} {'β'*14} {'β'*10} {'β'*8}")
|
| 37 |
|
| 38 |
live_flows = []
|
|
|
|
| 39 |
for name, ctor in flows_cfg:
|
| 40 |
try:
|
| 41 |
-
flow = ctor().to(dev)
|
| 42 |
params = sum(p.numel() for p in flow.parameters())
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
torch.cuda.synchronize()
|
| 49 |
-
|
| 50 |
-
# Time
|
| 51 |
-
t0 = time.perf_counter()
|
| 52 |
-
N_runs = 50
|
| 53 |
-
for _ in range(N_runs):
|
| 54 |
-
pred, conf = flow(anchors, queries)
|
| 55 |
-
if dev.type == 'cuda':
|
| 56 |
-
torch.cuda.synchronize()
|
| 57 |
-
elapsed = (time.perf_counter() - t0) / N_runs * 1000
|
| 58 |
-
|
| 59 |
-
print(f" {name:<22} {params:>8,} {str(tuple(pred.shape)):>14} {elapsed:>9.2f} {conf.mean().item():>8.3f}")
|
| 60 |
live_flows.append(flow)
|
|
|
|
| 61 |
except Exception as e:
|
| 62 |
-
print(f" {name:<22} FAILED: {str(e)[:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
# Test ensemble
|
| 65 |
-
print(f"\n Ensemble tests:")
|
| 66 |
for fusion in ['weighted', 'gated', 'residual']:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
try:
|
| 68 |
-
|
|
|
|
| 69 |
params = sum(p.numel() for p in ens.parameters())
|
| 70 |
-
|
| 71 |
-
print(f" {fusion:<
|
| 72 |
-
|
| 73 |
-
# Diagnostics
|
| 74 |
-
diag = ens.flow_diagnostics(anchors, queries)
|
| 75 |
-
for fname, stats in diag.items():
|
| 76 |
-
print(f" {fname:<18} conf={stats['confidence_mean']:.3f}Β±{stats['confidence_std']:.3f} "
|
| 77 |
-
f"residual={stats['residual_norm']:.3f} temp={stats['temperature']:.3f}")
|
| 78 |
except Exception as e:
|
| 79 |
-
print(f" {fusion:<
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
Flow Ensemble β Expanded Test Suite.
|
| 3 |
+
|
| 4 |
+
Assumes geolip-core is installed (Colab with repo loaded).
|
| 5 |
+
Tests: smoke, linalg integration, multi-scale, ensemble fusion,
|
| 6 |
+
gradient health, ablation, compile compatibility, memory.
|
| 7 |
"""
|
| 8 |
import torch
|
| 9 |
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
import sys, time, gc
|
| 12 |
+
|
| 13 |
+
# ββ Verify geolip_core.linalg is available ββ
|
| 14 |
+
try:
|
| 15 |
+
import geolip_core.linalg as LA
|
| 16 |
+
HAS_GEOLIP_LINALG = True
|
| 17 |
+
print(f"geolip_core.linalg: available")
|
| 18 |
+
LA.backend.status()
|
| 19 |
+
except ImportError:
|
| 20 |
+
import torch.linalg as LA
|
| 21 |
+
HAS_GEOLIP_LINALG = False
|
| 22 |
+
print("geolip_core.linalg: NOT available, using torch.linalg fallback")
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
dev = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
|
|
|
| 26 |
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
def sync():
|
| 29 |
+
if dev.type == 'cuda':
|
| 30 |
+
torch.cuda.synchronize()
|
| 31 |
+
|
| 32 |
+
def time_fn(fn, warmup=5, runs=50):
|
| 33 |
+
for _ in range(warmup): fn()
|
| 34 |
+
sync()
|
| 35 |
+
t0 = time.perf_counter()
|
| 36 |
+
for _ in range(runs): fn()
|
| 37 |
+
sync()
|
| 38 |
+
return (time.perf_counter() - t0) / runs * 1000
|
| 39 |
+
|
| 40 |
+
def fmt(ms):
|
| 41 |
+
if ms < 1: return f"{ms*1000:.0f}us"
|
| 42 |
+
return f"{ms:.2f}ms"
|
| 43 |
+
|
| 44 |
+
def make_data(B, n, k, d):
|
| 45 |
+
anchors = F.normalize(torch.randn(B, k, d, device=dev), dim=-1)
|
| 46 |
+
queries = F.normalize(torch.randn(B, n, d, device=dev), dim=-1)
|
| 47 |
+
return anchors, queries
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 51 |
+
print("=" * 72)
|
| 52 |
+
print(" Flow Ensemble β Expanded Test Suite")
|
| 53 |
+
print("=" * 72)
|
| 54 |
+
print(f" device={dev} geolip_core.linalg={HAS_GEOLIP_LINALG}")
|
| 55 |
+
if dev.type == 'cuda':
|
| 56 |
+
print(f" GPU: {torch.cuda.get_device_name()}")
|
| 57 |
+
print()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 61 |
+
# 1. SMOKE TEST β all flows, all shapes
|
| 62 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 63 |
+
print(f"{'='*72}\n 1. SMOKE TEST\n{'='*72}")
|
| 64 |
+
|
| 65 |
+
B, n, k, d = 16, 64, 32, 128
|
| 66 |
+
anchors, queries = make_data(B, n, k, d)
|
| 67 |
|
|
|
|
| 68 |
flows_cfg = [
|
| 69 |
+
('QuaternionFlow', lambda d,k: QuaternionFlow(d, k, n_heads=4)),
|
| 70 |
+
('QuaternionLiteFlow', lambda d,k: QuaternionLiteFlow(d, k)),
|
| 71 |
+
('VelocityFlow', lambda d,k: VelocityFlow(d, k)),
|
| 72 |
+
('MagnitudeFlow', lambda d,k: MagnitudeFlow(d, k)),
|
| 73 |
+
('OrbitalFlow', lambda d,k: OrbitalFlow(d, k)),
|
| 74 |
+
('AlignmentFlow', lambda d,k: AlignmentFlow(d, k)),
|
| 75 |
]
|
| 76 |
|
| 77 |
+
print(f"\n {'Flow':<22} {'Params':>8} {'Shape':>14} {'Time':>10} {'Conf':>8} {'Res norm':>10}")
|
| 78 |
+
print(f" {'β'*22} {'β'*8} {'β'*14} {'β'*10} {'β'*8} {'β'*10}")
|
| 79 |
|
| 80 |
live_flows = []
|
| 81 |
+
flow_ctors = []
|
| 82 |
for name, ctor in flows_cfg:
|
| 83 |
try:
|
| 84 |
+
flow = ctor(d, k).to(dev)
|
| 85 |
params = sum(p.numel() for p in flow.parameters())
|
| 86 |
+
pred, conf = flow(anchors, queries)
|
| 87 |
+
ms = time_fn(lambda: flow(anchors, queries))
|
| 88 |
+
res = (pred - queries).norm(dim=-1).mean().item()
|
| 89 |
+
shape_str = str(tuple(pred.shape))
|
| 90 |
+
print(f" {name:<22} {params:>8,} {shape_str:>14} {fmt(ms):>10} {conf.mean().item():>8.3f} {res:>10.3f}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
live_flows.append(flow)
|
| 92 |
+
flow_ctors.append((name, ctor))
|
| 93 |
except Exception as e:
|
| 94 |
+
print(f" {name:<22} FAILED: {str(e)[:50]}")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 98 |
+
# 2. LINALG INTEGRATION
|
| 99 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 100 |
+
print(f"\n{'='*72}\n 2. LINALG INTEGRATION\n{'='*72}")
|
| 101 |
+
|
| 102 |
+
if HAS_GEOLIP_LINALG:
|
| 103 |
+
print(f"\n Testing eigh dispatch in MagnitudeFlow and OrbitalFlow...")
|
| 104 |
+
for FlowCls in [MagnitudeFlow, OrbitalFlow]:
|
| 105 |
+
flow = FlowCls(d, k).to(dev)
|
| 106 |
+
pred, conf = flow(anchors, queries)
|
| 107 |
+
ok = torch.isfinite(pred).all().item() and torch.isfinite(conf).all().item()
|
| 108 |
+
print(f" {flow.name:<18} finite={ok} conf={conf.mean():.3f}")
|
| 109 |
+
|
| 110 |
+
oflow = OrbitalFlow(d, k).to(dev)
|
| 111 |
+
a_geom = oflow.anchor_proj(anchors)
|
| 112 |
+
G = torch.bmm(a_geom.transpose(-2, -1), a_geom)
|
| 113 |
+
vals, vecs = LA.eigh(G)
|
| 114 |
+
print(f"\n Gram eigenspectrum: shape={tuple(vals.shape)} "
|
| 115 |
+
f"range=[{vals.min().item():.4f}, {vals.max().item():.4f}]")
|
| 116 |
+
print(f" Eigenvector orth err: {(torch.bmm(vecs.mT, vecs) - torch.eye(oflow.geom_dim, device=dev)).abs().max().item():.2e}")
|
| 117 |
+
else:
|
| 118 |
+
print(" Skipped β geolip_core.linalg not available")
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 122 |
+
# 3. MULTI-SCALE
|
| 123 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 124 |
+
print(f"\n{'='*72}\n 3. MULTI-SCALE\n{'='*72}")
|
| 125 |
+
|
| 126 |
+
configs = [
|
| 127 |
+
(4, 16, 8, 64, 'tiny'),
|
| 128 |
+
(16, 64, 32, 128, 'small'),
|
| 129 |
+
(32, 128, 64, 256, 'medium'),
|
| 130 |
+
(64, 256, 128, 256, 'large'),
|
| 131 |
+
(8, 512, 256, 512, 'wide'),
|
| 132 |
+
]
|
| 133 |
+
|
| 134 |
+
print(f"\n OrbitalFlow across scales:")
|
| 135 |
+
print(f" {'Config':<10} {'B':>4} {'n':>5} {'k':>5} {'d':>5} {'Time':>10} {'OK':>4}")
|
| 136 |
+
print(f" {'β'*10} {'β'*4} {'β'*5} {'β'*5} {'β'*5} {'β'*10} {'β'*4}")
|
| 137 |
+
|
| 138 |
+
for B_, n_, k_, d_, label in configs:
|
| 139 |
+
try:
|
| 140 |
+
of = OrbitalFlow(d_, k_).to(dev)
|
| 141 |
+
a, q = make_data(B_, n_, k_, d_)
|
| 142 |
+
pred, conf = of(a, q)
|
| 143 |
+
ms = time_fn(lambda: of(a, q), warmup=3, runs=20)
|
| 144 |
+
ok = torch.isfinite(pred).all().item()
|
| 145 |
+
print(f" {label:<10} {B_:>4} {n_:>5} {k_:>5} {d_:>5} {fmt(ms):>10} {'OK' if ok else 'NO':>4}")
|
| 146 |
+
del of, a, q
|
| 147 |
+
except Exception as e:
|
| 148 |
+
print(f" {label:<10} {B_:>4} {n_:>5} {k_:>5} {d_:>5} FAILED: {str(e)[:30]}")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 152 |
+
# 4. ENSEMBLE FUSION MODES
|
| 153 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 154 |
+
print(f"\n{'='*72}\n 4. ENSEMBLE FUSION\n{'='*72}")
|
| 155 |
+
|
| 156 |
+
B, n, k, d = 16, 64, 32, 128
|
| 157 |
+
anchors, queries = make_data(B, n, k, d)
|
| 158 |
|
|
|
|
|
|
|
| 159 |
for fusion in ['weighted', 'gated', 'residual']:
|
| 160 |
+
ens = FlowEnsemble(live_flows, d, fusion=fusion).to(dev)
|
| 161 |
+
out = ens(anchors, queries)
|
| 162 |
+
ms = time_fn(lambda: ens(anchors, queries), warmup=3, runs=20)
|
| 163 |
+
|
| 164 |
+
preds = [flow(anchors, queries)[0] for flow in ens.flows]
|
| 165 |
+
cos_sims = []
|
| 166 |
+
for i in range(len(preds)):
|
| 167 |
+
for j in range(i+1, len(preds)):
|
| 168 |
+
cs = F.cosine_similarity(preds[i].flatten(1), preds[j].flatten(1), dim=-1).mean().item()
|
| 169 |
+
cos_sims.append(cs)
|
| 170 |
+
avg_sim = sum(cos_sims) / max(len(cos_sims), 1)
|
| 171 |
+
|
| 172 |
+
print(f"\n {fusion}: time={fmt(ms)} norm={out.norm(dim=-1).mean():.3f} diversity={1-avg_sim:.3f}")
|
| 173 |
+
diag = ens.flow_diagnostics(anchors, queries)
|
| 174 |
+
for fname, stats in diag.items():
|
| 175 |
+
print(f" {fname:<18} conf={stats['confidence_mean']:.3f}Β±{stats['confidence_std']:.3f} "
|
| 176 |
+
f"res={stats['residual_norm']:.3f}")
|
| 177 |
+
del ens
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 181 |
+
# 5. GRADIENT HEALTH
|
| 182 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 183 |
+
print(f"\n{'='*72}\n 5. GRADIENT HEALTH\n{'='*72}")
|
| 184 |
+
|
| 185 |
+
B, n, k, d = 16, 64, 32, 128
|
| 186 |
+
anchors, queries = make_data(B, n, k, d)
|
| 187 |
+
|
| 188 |
+
losses = {
|
| 189 |
+
'mse': (lambda o,q: (o - q).pow(2).mean()),
|
| 190 |
+
'cosine': (lambda o,q: (1 - F.cosine_similarity(o, q, dim=-1)).mean()),
|
| 191 |
+
'norm': (lambda o,q: o.norm(dim=-1).mean()),
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
print(f"\n {'Flow':<18} {'Loss':<10} {'Grad norm':>12} {'Status':>8}")
|
| 195 |
+
print(f" {'β'*18} {'β'*10} {'β'*12} {'β'*8}")
|
| 196 |
+
|
| 197 |
+
for loss_name, loss_fn in losses.items():
|
| 198 |
+
# Fresh flows for each loss β avoids in-place grad corruption across losses
|
| 199 |
+
try:
|
| 200 |
+
test_flows_grad = [ctor(d, k).to(dev) for _, ctor in flow_ctors]
|
| 201 |
+
ens_g = FlowEnsemble(test_flows_grad, d, fusion='residual').to(dev)
|
| 202 |
+
ens_g.zero_grad()
|
| 203 |
+
anchors_g = anchors.detach().clone().requires_grad_(True)
|
| 204 |
+
queries_g = queries.detach().clone().requires_grad_(True)
|
| 205 |
+
out = ens_g(anchors_g, queries_g)
|
| 206 |
+
loss = loss_fn(out, queries_g.detach())
|
| 207 |
+
loss.backward()
|
| 208 |
+
|
| 209 |
+
for flow in ens_g.flows:
|
| 210 |
+
grads = [p.grad for p in flow.parameters() if p.grad is not None]
|
| 211 |
+
if grads:
|
| 212 |
+
gn = torch.cat([g.flatten() for g in grads]).norm().item()
|
| 213 |
+
status = "OK" if 1e-8 < gn < 1e4 else "WARN"
|
| 214 |
+
print(f" {flow.name:<18} {loss_name:<10} {gn:>12.2e} {status:>8}")
|
| 215 |
+
else:
|
| 216 |
+
print(f" {flow.name:<18} {loss_name:<10} {'no grads':>12} {'WARN':>8}")
|
| 217 |
+
del ens_g, test_flows_grad
|
| 218 |
+
except RuntimeError as e:
|
| 219 |
+
if 'inplace' in str(e).lower() or 'in-place' in str(e).lower() or 'modified by' in str(e):
|
| 220 |
+
print(f" {'*':>18} {loss_name:<10} {'IN-PLACE ERR':>12} {'NOTE':>8}")
|
| 221 |
+
print(f" FL eigh deflation uses indexed assignment β needs .clone() fix")
|
| 222 |
+
else:
|
| 223 |
+
print(f" {'*':>18} {loss_name:<10} {'ERROR':>12}")
|
| 224 |
+
print(f" {str(e)[:60]}")
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 228 |
+
# 6. ABLATION β solo vs pairs vs full ensemble
|
| 229 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 230 |
+
print(f"\n{'='*72}\n 6. ABLATION (100 training steps, rotation target)\n{'='*72}")
|
| 231 |
+
|
| 232 |
+
B, n, k, d = 32, 128, 64, 256
|
| 233 |
+
anchors, queries = make_data(B, n, k, d)
|
| 234 |
+
R = torch.linalg.qr(torch.randn(d, d, device=dev)).Q.unsqueeze(0)
|
| 235 |
+
target = torch.bmm(queries, R.expand(B, -1, -1))
|
| 236 |
+
|
| 237 |
+
def eval_quality(model, anchors, queries, target, steps=100, lr=1e-3):
|
| 238 |
+
opt = torch.optim.Adam(model.parameters(), lr=lr)
|
| 239 |
+
for _ in range(steps):
|
| 240 |
+
opt.zero_grad()
|
| 241 |
+
pred = model(anchors, queries) if isinstance(model, FlowEnsemble) else model(anchors, queries)[0]
|
| 242 |
+
loss = (pred - target).pow(2).mean()
|
| 243 |
+
loss.backward()
|
| 244 |
+
opt.step()
|
| 245 |
+
with torch.no_grad():
|
| 246 |
+
pred = model(anchors, queries) if isinstance(model, FlowEnsemble) else model(anchors, queries)[0]
|
| 247 |
+
return (pred - target).pow(2).mean().item()
|
| 248 |
+
|
| 249 |
+
print(f"\n {'Configuration':<35} {'MSE':>10} {'Params':>10}")
|
| 250 |
+
print(f" {'β'*35} {'β'*10} {'β'*10}")
|
| 251 |
+
|
| 252 |
+
for name, ctor in flow_ctors:
|
| 253 |
+
try:
|
| 254 |
+
flow = ctor(d, k).to(dev)
|
| 255 |
+
params = sum(p.numel() for p in flow.parameters())
|
| 256 |
+
mse = eval_quality(flow, anchors, queries, target)
|
| 257 |
+
print(f" {name:<35} {mse:>10.4f} {params:>10,}")
|
| 258 |
+
del flow
|
| 259 |
+
except Exception as e:
|
| 260 |
+
print(f" {name:<35} FAILED: {str(e)[:30]}")
|
| 261 |
+
|
| 262 |
+
pairs = [
|
| 263 |
+
('Quat + Orbital', [0, 4]),
|
| 264 |
+
('Velocity + Magnitude', [2, 3]),
|
| 265 |
+
('Orbital + Alignment', [4, 5]),
|
| 266 |
+
('Velocity + Orbital', [2, 4]),
|
| 267 |
+
]
|
| 268 |
+
for pair_name, indices in pairs:
|
| 269 |
+
try:
|
| 270 |
+
pair_flows = [flow_ctors[i][1](d, k).to(dev) for i in indices if i < len(flow_ctors)]
|
| 271 |
+
if len(pair_flows) >= 2:
|
| 272 |
+
ens = FlowEnsemble(pair_flows, d, fusion='weighted').to(dev)
|
| 273 |
+
params = sum(p.numel() for p in ens.parameters())
|
| 274 |
+
mse = eval_quality(ens, anchors, queries, target)
|
| 275 |
+
print(f" {pair_name:<35} {mse:>10.4f} {params:>10,}")
|
| 276 |
+
del ens, pair_flows
|
| 277 |
+
except Exception as e:
|
| 278 |
+
print(f" {pair_name:<35} FAILED: {str(e)[:30]}")
|
| 279 |
+
|
| 280 |
+
for fusion in ['weighted', 'residual']:
|
| 281 |
try:
|
| 282 |
+
all_flows = [ctor(d, k).to(dev) for _, ctor in flow_ctors]
|
| 283 |
+
ens = FlowEnsemble(all_flows, d, fusion=fusion).to(dev)
|
| 284 |
params = sum(p.numel() for p in ens.parameters())
|
| 285 |
+
mse = eval_quality(ens, anchors, queries, target)
|
| 286 |
+
print(f" {'Full (' + fusion + ')':<35} {mse:>10.4f} {params:>10,}")
|
| 287 |
+
del ens, all_flows
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
except Exception as e:
|
| 289 |
+
print(f" {'Full (' + fusion + ')':<35} FAILED: {str(e)[:30]}")
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 293 |
+
# 7. COMPILE COMPATIBILITY
|
| 294 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 295 |
+
print(f"\n{'='*72}\n 7. COMPILE COMPATIBILITY\n{'='*72}")
|
| 296 |
+
|
| 297 |
+
B, n, k, d = 8, 32, 16, 64
|
| 298 |
+
anchors, queries = make_data(B, n, k, d)
|
| 299 |
+
|
| 300 |
+
print(f"\n {'Flow':<22} {'fullgraph':>12} {'Raw':>10} {'Compiled':>12}")
|
| 301 |
+
print(f" {'β'*22} {'β'*12} {'β'*10} {'β'*12}")
|
| 302 |
+
|
| 303 |
+
for name, ctor in flow_ctors:
|
| 304 |
+
try:
|
| 305 |
+
flow = ctor(d, k).to(dev)
|
| 306 |
+
t_raw = time_fn(lambda: flow(anchors, queries), warmup=3, runs=30)
|
| 307 |
+
try:
|
| 308 |
+
compiled = torch.compile(flow, fullgraph=True)
|
| 309 |
+
compiled(anchors, queries); sync()
|
| 310 |
+
t_comp = time_fn(lambda: compiled(anchors, queries), warmup=3, runs=30)
|
| 311 |
+
status = "OK"
|
| 312 |
+
except Exception as e:
|
| 313 |
+
t_comp = -1
|
| 314 |
+
status = str(e)[:12]
|
| 315 |
+
t_str = fmt(t_comp) if t_comp > 0 else "N/A"
|
| 316 |
+
print(f" {name:<22} {status:>12} {fmt(t_raw):>10} {t_str:>12}")
|
| 317 |
+
del flow
|
| 318 |
+
except Exception as e:
|
| 319 |
+
print(f" {name:<22} FAILED: {str(e)[:40]}")
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 323 |
+
# 8. MEMORY
|
| 324 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 325 |
+
if dev.type == 'cuda':
|
| 326 |
+
print(f"\n{'='*72}\n 8. MEMORY (B=32, n=128, k=64, d=256)\n{'='*72}")
|
| 327 |
+
|
| 328 |
+
B, n, k, d = 32, 128, 64, 256
|
| 329 |
+
anchors, queries = make_data(B, n, k, d)
|
| 330 |
+
|
| 331 |
+
print(f"\n {'Flow':<22} {'Peak MB':>10}")
|
| 332 |
+
print(f" {'β'*22} {'β'*10}")
|
| 333 |
+
|
| 334 |
+
for name, ctor in flow_ctors:
|
| 335 |
+
try:
|
| 336 |
+
flow = ctor(d, k).to(dev)
|
| 337 |
+
torch.cuda.empty_cache(); gc.collect()
|
| 338 |
+
torch.cuda.reset_peak_memory_stats()
|
| 339 |
+
base = torch.cuda.memory_allocated()
|
| 340 |
+
pred, conf = flow(anchors, queries); sync()
|
| 341 |
+
peak = (torch.cuda.max_memory_allocated() - base) / 1024**2
|
| 342 |
+
print(f" {name:<22} {peak:>9.1f}")
|
| 343 |
+
del flow, pred, conf
|
| 344 |
+
except Exception as e:
|
| 345 |
+
print(f" {name:<22} FAILED: {str(e)[:30]}")
|
| 346 |
+
|
| 347 |
+
try:
|
| 348 |
+
all_flows = [ctor(d, k).to(dev) for _, ctor in flow_ctors]
|
| 349 |
+
ens = FlowEnsemble(all_flows, d, fusion='weighted').to(dev)
|
| 350 |
+
torch.cuda.empty_cache(); gc.collect()
|
| 351 |
+
torch.cuda.reset_peak_memory_stats()
|
| 352 |
+
base = torch.cuda.memory_allocated()
|
| 353 |
+
out = ens(anchors, queries); sync()
|
| 354 |
+
peak = (torch.cuda.max_memory_allocated() - base) / 1024**2
|
| 355 |
+
print(f" {'Full ensemble':<22} {peak:>9.1f}")
|
| 356 |
+
del ens, all_flows
|
| 357 |
+
except Exception as e:
|
| 358 |
+
print(f" {'Full ensemble':<22} FAILED: {str(e)[:30]}")
|
| 359 |
+
|
| 360 |
+
print(f"\n{'='*72}")
|
| 361 |
+
print(f" Done.")
|
| 362 |
+
print(f"{'='*72}")
|