STER / code /ster_multi_seed.py
eduzrh's picture
Upload code/ster_multi_seed.py with huggingface_hub
c42dd78 verified
Raw
History Blame Contribute Delete
8.37 kB
"""Multi-seed validation of Idea 3 on synthetic cross-LoD data."""
import sys, os, json, time, datetime
os.environ['PYTHONUNBUFFERED'] = '1'
import numpy as np
import torch, torch.nn as nn, torch.nn.functional as F
torch.set_num_threads(1)
import os as _os
_os.environ['OMP_NUM_THREADS'] = '1'
_os.environ['MKL_NUM_THREADS'] = '1'
from collections import OrderedDict
import joblib, warnings
warnings.filterwarnings('ignore')
DEV = 'cpu'
PROP_NAMES = ["bounding_box_width", "bounding_box_length", "area", "perimeter",
"perimeter_ind", "volume", "convex_hull_area", "convex_hull_volume",
"ave_centroid_distance", "height_diff", "num_floors", "axes_symmetry",
"compactness_2d", "compactness_3d", "density", "elongation", "shape_ind",
"hemisphericality", "fractality", "cubeness", "circumference",
"aligned_bounding_box_width", "aligned_bounding_box_length",
"aligned_bounding_box_height", "num_vertices"]
class Encoder(nn.Module):
def __init__(self, d=25, h=128, o=64):
super().__init__()
self.net = nn.Sequential(OrderedDict([
('0', nn.Linear(d, h)), ('1', nn.BatchNorm1d(h)), ('2', nn.ReLU()),
('3', nn.Linear(h, h)), ('4', nn.BatchNorm1d(h)), ('5', nn.ReLU()),
('6', nn.Linear(h, o))
]))
def forward(self, x):
z = self.net(x)
return z / (torch.norm(z, dim=-1, keepdim=True).clamp(min=1e-8))
def infonce_loss(z_a, z_b, tau=0.1):
B = z_a.shape[0]
z_a = F.normalize(z_a, dim=-1)
z_b = F.normalize(z_b, dim=-1)
sim = torch.mm(z_a, z_b.T) / tau
labels = torch.arange(B, device=z_a.device)
return (F.cross_entropy(sim, labels) + F.cross_entropy(sim.T, labels)) / 2
def aggressive_lod_noise(props, seed=42):
rng = np.random.RandomState(seed)
p = props.copy().astype(np.float64)
N, D = p.shape
for j, pn in enumerate(PROP_NAMES):
if pn in ['volume', 'convex_hull_volume']:
p[:, j] *= rng.uniform(0.3, 3.0, N)
elif pn in ['area', 'convex_hull_area', 'perimeter', 'circumference']:
p[:, j] *= rng.uniform(0.5, 2.0, N)
elif pn in ['height_diff', 'aligned_bounding_box_height']:
p[:, j] += rng.randn(N) * 5.0; p[:, j] = np.maximum(0.1, p[:, j])
elif pn == 'num_vertices':
p[:, j] *= rng.uniform(0.3, 0.8, N)
elif pn == 'num_floors':
p[:, j] += rng.randint(-2, 3, N).astype(np.float64); p[:, j] = np.maximum(1, p[:, j])
else:
p[:, j] *= rng.uniform(0.5, 1.5, N)
p += rng.randn(N, D) * 0.1
return p.astype(np.float32)
def evaluate_encoder(enc, test_fine, test_coarse):
fine_t = torch.tensor(test_fine, dtype=torch.float32).to(DEV)
coarse_t = torch.tensor(test_coarse, dtype=torch.float32).to(DEV)
N = len(test_fine); bs = 512
emb_fine, emb_coarse = [], []
with torch.no_grad():
for start in range(0, N, bs):
emb_fine.append(enc(fine_t[start:start+bs]).cpu().numpy())
emb_coarse.append(enc(coarse_t[start:start+bs]).cpu().numpy())
emb_fine = np.vstack(emb_fine); emb_coarse = np.vstack(emb_coarse)
pos_sims = np.sum(emb_fine * emb_coarse, axis=1)
rng = np.random.RandomState(42); neg_idx = rng.permutation(N)
neg_sims = np.sum(emb_fine * emb_coarse[neg_idx], axis=1)
all_sims = np.concatenate([pos_sims, neg_sims])
all_labels = np.concatenate([np.ones(N, dtype=np.int32), np.zeros(N, dtype=np.int32)])
best_f1 = 0.0
for t in np.linspace(0.1, 0.999, 100):
pred = (all_sims >= t).astype(np.int32)
tp = float(((pred == 1) & (all_labels == 1)).sum())
fp = float(((pred == 1) & (all_labels == 0)).sum())
fn = float(((pred == 0) & (all_labels == 1)).sum())
p = tp / (tp + fp + 1e-9); r = tp / (tp + fn + 1e-9)
f1 = 2.0 * p * r / (p + r + 1e-9)
if f1 > best_f1: best_f1 = f1
return float(best_f1)
def baseline_f1(test_fine, test_coarse):
fn = test_fine / (np.linalg.norm(test_fine, axis=1, keepdims=True) + 1e-8)
cn = test_coarse / (np.linalg.norm(test_coarse, axis=1, keepdims=True) + 1e-8)
pos = np.sum(fn * cn, axis=1)
rng = np.random.RandomState(42); neg_idx = rng.permutation(len(cn))
neg = np.sum(fn * cn[neg_idx], axis=1)
all_sims = np.concatenate([pos, neg])
all_labels = np.concatenate([np.ones(len(pos), dtype=np.int32), np.zeros(len(neg), dtype=np.int32)])
best_f1 = 0.0
for t in np.linspace(0.1, 0.999, 100):
pred = (all_sims >= t).astype(np.int32)
tp = float(((pred == 1) & (all_labels == 1)).sum())
fp = float(((pred == 1) & (all_labels == 0)).sum())
fn = float(((pred == 0) & (all_labels == 1)).sum())
p = tp / (tp + fp + 1e-9); r = tp / (tp + fn + 1e-9)
f1 = 2.0 * p * r / (p + r + 1e-9)
if f1 > best_f1: best_f1 = f1
return float(best_f1)
print("Loading data...", flush=True)
all_mats, all_ids = [], []
for suf in ['Hague_allmodels_v1_train_matching_medium_neg_samples_num=2_vector_normalization=True_seed=1',
'Hague_allmodels_v1_test_matching_medium_neg_samples_num=2_vector_normalization=True_seed=1']:
pdict = joblib.load(f'data/property_dicts/{suf}.joblib')
for side in ['cands', 'index']:
ids = list(pdict[PROP_NAMES[0]][side].keys())
mat = np.zeros((len(ids), len(PROP_NAMES)), dtype=np.float32)
for j, pn in enumerate(PROP_NAMES):
for i, bid in enumerate(ids):
val = pdict[pn][side].get(bid)
if val is not None: mat[i, j] = float(val)
mat = np.nan_to_num(mat, nan=0.0, posinf=1e6, neginf=-1e6)
all_mats.append(mat); all_ids.extend(ids)
X = np.vstack(all_mats); N = len(X)
rng = np.random.RandomState(42); perm = rng.permutation(N)
n_train = int(N * 0.6)
train_props = X[perm[:n_train]]; test_props = X[perm[n_train:]]
train_coarse_raw = aggressive_lod_noise(train_props, seed=1)
test_coarse_raw = aggressive_lod_noise(test_props, seed=123)
all_cat = np.vstack([train_props, train_coarse_raw])
mean = all_cat.mean(axis=0, keepdims=True)
std = all_cat.std(axis=0, keepdims=True); std[std < 1e-8] = 1.0
test_fine_n = (test_props - mean) / std
test_coarse_n = (test_coarse_raw - mean) / std
bl = baseline_f1(test_fine_n, test_coarse_n)
print(f"Baseline F1: {bl:.4f}", flush=True)
seeds = [1, 42, 123, 456]
results = {}; all_f1s = []
for seed in seeds:
print(f"\n=== Seed {seed} ===", flush=True)
train_coarse_s = aggressive_lod_noise(train_props, seed=seed)
train_fine_n_s = (train_props - mean) / std
train_coarse_n_s = (train_coarse_s - mean) / std
torch.manual_seed(seed)
encoder = Encoder().to(DEV)
optimizer = torch.optim.AdamW(encoder.parameters(), lr=3e-4, weight_decay=1e-5)
best_f1 = 0.0; N_train = len(train_fine_n_s)
for ep in range(200):
idx = np.random.permutation(N_train)
total_loss = 0; nb = 0
for start in range(0, N_train, 256):
bi = idx[start:start+256]
ba = torch.tensor(train_fine_n_s[bi], dtype=torch.float32).to(DEV)
bb = torch.tensor(train_coarse_n_s[bi], dtype=torch.float32).to(DEV)
za = encoder(ba); zb = encoder(bb)
loss = infonce_loss(za, zb, 0.1)
optimizer.zero_grad(); loss.backward(); optimizer.step()
total_loss += loss.item(); nb += 1
if ep % 20 == 0:
f1 = evaluate_encoder(encoder, test_fine_n, test_coarse_n)
if f1 > best_f1:
best_f1 = f1
torch.save({'e': encoder.state_dict()}, f'saved_model_files/enc_synth_i3_s{seed}.pt')
print(f" Ep {ep}: F1={f1:.4f} (best={best_f1:.4f})", flush=True)
all_f1s.append(best_f1)
results[f'seed_{seed}'] = {'best_f1': best_f1}
print(f" DONE seed={seed}: best F1={best_f1:.4f}", flush=True)
all_f1s = np.array(all_f1s)
results['mean_f1'] = float(all_f1s.mean())
results['std_f1'] = float(all_f1s.std())
results['baseline_f1'] = bl
results['all_f1s'] = [float(f) for f in all_f1s]
json.dump(results, open('experiments/synth_multi_seed.json', 'w'), indent=2)
print(f"\nMulti-seed: {all_f1s.mean():.4f}±{all_f1s.std():.4f}", flush=True)
print(f"Best: {all_f1s.max():.4f}, Worst: {all_f1s.min():.4f}", flush=True)
print("ALL DONE", flush=True)