""" STER-GI Idea 3: Denoise-to-Sibling - Train: diffusion + contrastive on ALL building vectors (NO labels) - Eval: ALL train+test pairs, zero-shot cosine similarity → F1 """ import numpy as np, joblib, pickle as pkl, torch, torch.nn as nn, torch.nn.functional as F, time, os, argparse from torch.utils.data import DataLoader, TensorDataset from sklearn.preprocessing import StandardScaler from sklearn.metrics import precision_score, recall_score, f1_score PROPS = ["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"] CFG = {'diff_steps':1000,'diff_hidden':256,'diff_layers':4,'diff_epochs':100,'diff_lr':1e-3,'diff_bs':512, 't0':200,'n_sib':2,'enc_hidden':128,'enc_dim':64,'ctr_epochs':100,'ctr_lr':1e-3,'ctr_temp':0.07,'ctr_bs':1024} # ---------- Data ---------- def get_vecs(prop_dict, source): ids = list(prop_dict[PROPS[0]][source].keys()) X = np.zeros((len(ids), len(PROPS)), dtype=np.float32) for i, bid in enumerate(ids): for j, pn in enumerate(PROPS): v = prop_dict[pn][source].get(bid, None) X[i,j] = float(v) if v is not None and not (isinstance(v,float) and np.isnan(v)) else 0.0 return X, ids def load_all_data(seed): """Load ALL building vectors (train+test) and ALL pairs (train+test)""" # Train buildings tp = f"data/property_dicts/Hague_allmodels_v1_train_matching_medium_neg_samples_num=2_vector_normalization=True_seed={seed}.joblib" trp = joblib.load(tp) Xtc, id_tc = get_vecs(trp, 'cands') Xti, id_ti = get_vecs(trp, 'index') X_all = np.concatenate([Xtc, Xti], axis=0) print(f"Train buildings: {len(Xtc)} cands + {len(Xti)} index = {len(X_all)}", flush=True) # Test buildings ep = f"data/property_dicts/Hague_allmodels_v1_test_matching_medium_neg_samples_num=2_vector_normalization=True_seed={seed}.joblib" epd = joblib.load(ep) Xec, id_ec = get_vecs(epd, 'cands') Xei, id_ei = get_vecs(epd, 'index') # Combine ALL building vectors (for diffusion training) X_all = np.concatenate([X_all, Xec, Xei], axis=0) print(f"All buildings for diffusion: {len(X_all)}", flush=True) # ALL pairs (train+test) for evaluation part = pkl.load(open(f"data/dataset_partitions/Hague_seed{seed}.pkl", 'rb')) train_pairs = part['train']['negative_sampling']['medium'][2] test_pairs = part['test']['matching']['negative_sampling']['medium'][2] all_pairs = list(train_pairs) + list(test_pairs) # Build lookup for all buildings cand_map = {} for src_prop, src_ids in [(trp,id_tc), (epd,id_ec)]: for bid in src_ids: if bid not in cand_map: v = [float(src_prop[pn]['cands'].get(bid,0) or 0) for pn in PROPS] cand_map[bid] = np.array(v, dtype=np.float32) index_map = {} for src_prop, src_ids in [(trp,id_ti), (epd,id_ei)]: for bid in src_ids: if bid not in index_map: v = [float(src_prop[pn]['index'].get(bid,0) or 0) for pn in PROPS] index_map[bid] = np.array(v, dtype=np.float32) # Build pair vectors + labels cv, iv, lbs = [], [], [] for cid, iid in all_pairs: if cid in cand_map and iid in index_map: cv.append(cand_map[cid]) iv.append(index_map[iid]) lbs.append(1 if cid == iid else 0) cv, iv, lbs = np.array(cv,dtype=np.float32), np.array(iv,dtype=np.float32), np.array(lbs,dtype=np.int32) print(f"All eval pairs: {len(lbs)} ({lbs.sum()} pos, {(1-lbs).sum()} neg)", flush=True) return X_all, cv, iv, lbs # ---------- Diffusion ---------- class DiffMLP(nn.Module): def __init__(self,d,h=256,L=4): super().__init__() self.te = nn.Sequential(nn.Linear(1,h),nn.SiLU(),nn.Linear(h,h)) net = [nn.Linear(d+h,h),nn.SiLU()] for _ in range(L-1): net += [nn.Linear(h,h),nn.SiLU()] net.append(nn.Linear(h,d)) self.net = nn.Sequential(*net) def forward(self,x,t): return self.net(torch.cat([x,self.te(t.unsqueeze(-1).float())],-1)) class DiffSched: def __init__(self,S=1000): self.S=S; self.b=torch.linspace(1e-4,0.02,S); self.a=1-self.b; self.ab=torch.cumprod(self.a,0) def noise(self,x0,t): ab=self.ab[t].view(-1,1); eps=torch.randn_like(x0) return torch.sqrt(ab)*x0+torch.sqrt(1-ab)*eps, eps @torch.no_grad() def step(self,m,xt,t): a=self.a[t].view(-1,1); ab=self.ab[t].view(-1,1); b_=self.b[t].view(-1,1) e=m(xt,t.float()); x0h=(xt-torch.sqrt(1-ab)*e)/torch.sqrt(a) if t.min()==0: return x0h abp=self.ab[t-1].view(-1,1) mu=torch.sqrt(abp)*b_/(1-ab)*x0h+torch.sqrt(a)*(1-abp)/(1-ab)*xt return mu+torch.sqrt(b_*(1-abp)/(1-ab))*torch.randn_like(xt) @torch.no_grad() def sdedit(self,m,x0,t0,dev): n=x0.shape[0]; abt=self.ab[t0] xt=torch.sqrt(abt)*x0+torch.sqrt(1-abt)*torch.randn_like(x0) for t in range(t0,-1,-1): xt=self.step(m,xt,torch.full((n,),t,device=dev,dtype=torch.long)) return xt # ---------- Encoder ---------- class Encoder(nn.Module): def __init__(self,d,h=128,o=64): super().__init__() self.net=nn.Sequential(nn.Linear(d,h),nn.BatchNorm1d(h),nn.ReLU(), nn.Linear(h,h),nn.BatchNorm1d(h),nn.ReLU(),nn.Linear(h,o)) def forward(self,x): return F.normalize(self.net(x),-1) def infonce(emb,temp=0.07): n=emb.shape[0]//2; sim=emb@emb.T/temp sim=sim.masked_fill(torch.eye(2*n,device=emb.device,dtype=torch.bool),-1e9) return F.cross_entropy(sim,torch.arange(2*n,device=emb.device)^1) # ---------- Eval ---------- def eval_pairs(encoder, cv, iv, lbs, dev, tag=""): encoder.eval() with torch.no_grad(): ce = encoder(torch.FloatTensor(cv).to(dev)).cpu().numpy() ie = encoder(torch.FloatTensor(iv).to(dev)).cpu().numpy() sims = np.sum(ce * ie, axis=1) best_f1, best_th = 0, 0 for th in np.arange(0.3, 1.0, 0.02): pred = (sims >= th).astype(np.int32) f = f1_score(lbs, pred, zero_division=0) if f > best_f1: best_f1, best_th = f, th p = precision_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0) r = recall_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0) print(f" {tag}: P={p:.4f} R={r:.4f} F1={best_f1:.4f} (th={best_th:.2f})", flush=True) return best_f1 def baseline_raw(cv, iv, lbs): cn = cv/(np.linalg.norm(cv,axis=1,keepdims=True)+1e-8) i_n = iv/(np.linalg.norm(iv,axis=1,keepdims=True)+1e-8) sims = np.sum(cn * i_n, axis=1) best_f1, best_th = 0, 0 for th in np.arange(0.3, 1.0, 0.02): pred = (sims >= th).astype(np.int32) f = f1_score(lbs, pred, zero_division=0) if f > best_f1: best_f1, best_th = f, th p = precision_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0) r = recall_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0) print(f" Baseline Raw: P={p:.4f} R={r:.4f} F1={best_f1:.4f} (th={best_th:.2f})", flush=True) return best_f1 # ---------- Main ---------- def main(): p = argparse.ArgumentParser() p.add_argument('--seed',type=int,default=1) p.add_argument('--t0',type=int,default=200) p.add_argument('--skip_diff',action='store_true') p.add_argument('--skip_enc',action='store_true') a = p.parse_args() CFG['t0']=a.t0 dev = 'cuda' if torch.cuda.is_available() else 'cpu' print(f"Device: {dev} | t0: {a.t0} | Seed: {a.seed}", flush=True) # Load X_all, cv, iv, lbs = load_all_data(a.seed) sc = StandardScaler(); Xs = sc.fit_transform(X_all) cv_s, iv_s = sc.transform(cv), sc.transform(iv) # Baseline print("\n=== Zero-Shot Baseline ===") b_raw = baseline_raw(cv_s, iv_s, lbs) # Diffusion diff_path = f"saved_model_files/diff_i3_s{a.seed}_t{a.t0}.pt" sib_path = f"saved_model_files/sib_i3_s{a.seed}_t{a.t0}.npz" if a.skip_diff and os.path.exists(diff_path): ck = torch.load(diff_path, map_location=dev) model = DiffMLP(Xs.shape[1], CFG['diff_hidden'], CFG['diff_layers']).to(dev) model.load_state_dict(ck['m']) sched = DiffSched(CFG['diff_steps']) for attr in ['b','a','ab']: setattr(sched, attr, getattr(sched, attr).to(dev)) else: print("\n=== Training Diffusion ===") model = DiffMLP(Xs.shape[1], CFG['diff_hidden'], CFG['diff_layers']).to(dev) sched = DiffSched(CFG['diff_steps']) for attr in ['b','a','ab']: setattr(sched, attr, getattr(sched, attr).to(dev)) opt = torch.optim.Adam(model.parameters(), lr=CFG['diff_lr']) ds = TensorDataset(torch.FloatTensor(Xs)); dl = DataLoader(ds, batch_size=CFG['diff_bs'], shuffle=True) model.train() for ep in range(CFG['diff_epochs']): tot = 0 for (xb,) in dl: xb = xb.to(dev); bs = xb.shape[0] t = torch.randint(0, CFG['diff_steps'], (bs,), device=dev) xt, noise = sched.noise(xb, t) loss = F.mse_loss(model(xt, t.float()), noise) opt.zero_grad(); loss.backward(); opt.step(); tot += loss.item()*bs if (ep+1)%10==0: print(f" Diff ep {ep+1}/{CFG['diff_epochs']}: loss={tot/len(ds):.6f}", flush=True) print(f" Done: loss={tot/len(ds):.6f}", flush=True) torch.save({'m':model.state_dict()}, diff_path) # Siblings if os.path.exists(sib_path): d = np.load(sib_path); origs, sibs = d['o'], d['s'] else: print("\n=== Generating Siblings ===") model.eval(); origs, sibs = [], [] with torch.no_grad(): for i in range(0, len(Xs), CFG['diff_bs']): xb = torch.FloatTensor(Xs[i:i+CFG['diff_bs']]).to(dev) for _ in range(CFG['n_sib']): sib = sched.sdedit(model, xb, CFG['t0'], dev) origs.append(xb.cpu().numpy()); sibs.append(sib.cpu().numpy()) origs = np.concatenate(origs); sibs = np.concatenate(sibs) print(f" {len(origs)} pairs, mean L2 diff: {np.mean(np.linalg.norm(origs-sibs,axis=1)):.4f}", flush=True) np.savez_compressed(sib_path, o=origs, s=sibs) # Encoder enc_path = f"saved_model_files/enc_i3_s{a.seed}_t{a.t0}.pt" if a.skip_enc and os.path.exists(enc_path): ck = torch.load(enc_path, map_location=dev) encoder = Encoder(Xs.shape[1], CFG['enc_hidden'], CFG['enc_dim']).to(dev) encoder.load_state_dict(ck['e']) else: print("\n=== Training Encoder ===") encoder = Encoder(Xs.shape[1], CFG['enc_hidden'], CFG['enc_dim']).to(dev) opt = torch.optim.Adam(encoder.parameters(), lr=CFG['ctr_lr']) n = len(origs) # Shuffle pairs (not individual samples) to keep (orig, sib) adjacent pair_idx = np.random.permutation(n) origs_shuffled = origs[pair_idx] sibs_shuffled = sibs[pair_idx] data = np.zeros((n*2, Xs.shape[1]), dtype=np.float32) data[0::2]=origs_shuffled; data[1::2]=sibs_shuffled ds = TensorDataset(torch.FloatTensor(data)); dl = DataLoader(ds, batch_size=CFG['ctr_bs'], shuffle=False) encoder.train() for ep in range(CFG['ctr_epochs']): tot = 0 for (xb,) in dl: xb = xb.to(dev); emb = encoder(xb); loss = infonce(emb, CFG['ctr_temp']) opt.zero_grad(); loss.backward(); opt.step(); tot += loss.item()*xb.shape[0] if (ep+1)%10==0: print(f" Enc ep {ep+1}/{CFG['ctr_epochs']}: loss={tot/len(ds):.4f}", flush=True) print(f" Done: loss={tot/len(ds):.4f}", flush=True) torch.save({'e':encoder.state_dict()}, enc_path) # Eval print("\n=== Results ===") eval_pairs(encoder, cv_s, iv_s, lbs, dev, f"Idea3 (t0={a.t0})") print(f"\n Baseline (raw props): F1={b_raw:.4f}", flush=True) print(f" Supervised XGBoost ref: F1=0.982", flush=True) # Patched if __name__=='__main__': main() sibs_shuffled = sibs[pair_idx] in()