| """STER-GI Idea 3: Denoise-to-Sibling — Zero-Shot 3D GER""" |
| import numpy as np, joblib, pickle as pkl, torch, torch.nn as nn, torch.nn.functional as F, time, os, argparse, sys |
| 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"] |
|
|
| |
| 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(seed): |
| tp = f"data/property_dicts/Hague_allmodels_v1_train_matching_medium_neg_samples_num=2_vector_normalization=True_seed={seed}.joblib" |
| ep = f"data/property_dicts/Hague_allmodels_v1_test_matching_medium_neg_samples_num=2_vector_normalization=True_seed={seed}.joblib" |
| trp = joblib.load(tp); epd = joblib.load(ep) |
| Xtc, id_tc = get_vecs(trp, 'cands'); Xti, id_ti = get_vecs(trp, 'index') |
| Xec, id_ec = get_vecs(epd, 'cands'); Xei, id_ei = get_vecs(epd, 'index') |
| X_all = np.concatenate([Xtc, Xti, Xec, Xei], axis=0) |
| print(f"Buildings: {len(X_all)} (train cands={len(Xtc)} index={len(Xti)} test cands={len(Xec)} index={len(Xei)})", flush=True) |
|
|
| part = pkl.load(open(f"data/dataset_partitions/Hague_seed{seed}.pkl", 'rb')) |
| all_pairs = list(part['train']['negative_sampling']['medium'][2]) + list(part['test']['matching']['negative_sampling']['medium'][2]) |
|
|
| cand_map, index_map = {}, {} |
| for sp, ids in [(trp,id_tc),(epd,id_ec)]: |
| for bid in ids: |
| if bid not in cand_map: |
| cand_map[bid] = np.array([float(sp[pn]['cands'].get(bid,0) or 0) for pn in PROPS], dtype=np.float32) |
| for sp, ids in [(trp,id_ti),(epd,id_ei)]: |
| for bid in ids: |
| if bid not in index_map: |
| index_map[bid] = np.array([float(sp[pn]['index'].get(bid,0) or 0) for pn in PROPS], dtype=np.float32) |
|
|
| 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"Eval pairs: {len(lbs)} ({lbs.sum()} pos, {(1-lbs).sum()} neg)", flush=True) |
| return X_all, cv, iv, lbs |
|
|
| |
| 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]; xt=torch.sqrt(self.ab[t0])*x0+torch.sqrt(1-self.ab[t0])*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 |
|
|
| |
| 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): z = self.net(x); return z / (torch.norm(z, dim=-1, keepdim=True).clamp(min=1e-8)) |
|
|
| 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) |
|
|
| |
| 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 |
|
|
| |
| def main(): |
| a = argparse.ArgumentParser() |
| a.add_argument('--seed',type=int,default=1); a.add_argument('--t0',type=int,default=200) |
| a.add_argument('--skip_diff',action='store_true'); a.add_argument('--skip_enc',action='store_true') |
| a.add_argument('--diff_ep',type=int,default=100); a.add_argument('--enc_ep',type=int,default=100) |
| args = a.parse_args() |
| dev = 'cpu' |
| print(f"Device: {dev} | t0: {args.t0} | Seed: {args.seed}", flush=True) |
|
|
| X_all, cv, iv, lbs = load_all(args.seed) |
| sc = StandardScaler(); Xs = sc.fit_transform(X_all) |
| cv_s, iv_s = sc.transform(cv), sc.transform(iv) |
|
|
| print("\n=== Baseline ===", flush=True) |
| b_raw = baseline_raw(cv_s, iv_s, lbs) |
|
|
| |
| diff_path = f"saved_model_files/diff_i3_s{args.seed}.pt" |
| sib_path = f"saved_model_files/sib_i3_s{args.seed}_t{args.t0}.npz" |
| if args.skip_diff and os.path.exists(diff_path): |
| print(f"Loading cached diffusion: {diff_path}", flush=True) |
| ck = torch.load(diff_path, map_location=dev) |
| model = DiffMLP(Xs.shape[1]).to(dev); model.load_state_dict(ck['m']) |
| sched = DiffSched(); [setattr(sched,x,getattr(sched,x).to(dev)) for x in ['b','a','ab']] |
| else: |
| print(f"\n=== Diffusion ({args.diff_ep} epochs) ===", flush=True) |
| model = DiffMLP(Xs.shape[1]).to(dev); sched = DiffSched() |
| [setattr(sched,x,getattr(sched,x).to(dev)) for x in ['b','a','ab']] |
| opt = torch.optim.Adam(model.parameters(), lr=1e-3) |
| ds = TensorDataset(torch.FloatTensor(Xs)); dl = DataLoader(ds, batch_size=512, shuffle=True) |
| model.train(); t0_t = time.time() |
| for ep in range(args.diff_ep): |
| tot = 0 |
| for (xb,) in dl: |
| xb = xb.to(dev); bs = xb.shape[0] |
| t = torch.randint(0, 1000, (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}/{args.diff_ep}: loss={tot/len(ds):.6f} t={time.time()-t0_t:.0f}s", flush=True) |
| print(f" Done: loss={tot/len(ds):.6f}", flush=True) |
| torch.save({'m':model.state_dict()}, diff_path) |
|
|
| |
| if os.path.exists(sib_path): |
| d = np.load(sib_path); origs, sibs = d['o'], d['s'] |
| print(f"Loaded cached siblings: {len(origs)} pairs", flush=True) |
| else: |
| print("\n=== Generating Siblings ===", flush=True) |
| model.eval(); origs, sibs = [], [] |
| with torch.no_grad(): |
| for i in range(0, len(Xs), 512): |
| xb = torch.FloatTensor(Xs[i:i+512]).to(dev) |
| for _ in range(2): |
| origs.append(xb.cpu().numpy()); sibs.append(sched.sdedit(model, xb, args.t0, dev).cpu().numpy()) |
| origs = np.concatenate(origs); sibs = np.concatenate(sibs) |
| l2 = np.mean(np.linalg.norm(origs - sibs, axis=1)) |
| print(f" {len(origs)} pairs, mean L2 diff: {l2:.4f}", flush=True) |
| np.savez_compressed(sib_path, o=origs, s=sibs) |
|
|
| |
| enc_path = f"saved_model_files/enc_i3_s{args.seed}_t{args.t0}.pt" |
| if args.skip_enc and os.path.exists(enc_path): |
| print(f"Loading cached encoder: {enc_path}", flush=True) |
| ck = torch.load(enc_path, map_location=dev) |
| encoder = Encoder(Xs.shape[1]).to(dev); encoder.load_state_dict(ck['e']) |
| else: |
| print(f"\n=== Encoder ({args.enc_ep} epochs) ===", flush=True) |
| encoder = Encoder(Xs.shape[1]).to(dev) |
| opt = torch.optim.Adam(encoder.parameters(), lr=1e-4) |
| |
| n = len(origs); idx = np.random.permutation(n) |
| data = np.zeros((n*2, Xs.shape[1]), dtype=np.float32) |
| data[0::2] = origs[idx]; data[1::2] = sibs[idx] |
| ds = TensorDataset(torch.FloatTensor(data)); dl = DataLoader(ds, batch_size=1024, shuffle=False) |
| encoder.train(); t0_t = time.time() |
| for ep in range(args.enc_ep): |
| tot = 0 |
| for (xb,) in dl: |
| xb = xb.to(dev); emb = encoder(xb); loss = infonce(emb, 0.07) |
| opt.zero_grad(); loss.backward(); torch.nn.utils.clip_grad_norm_(encoder.parameters(), 1.0); opt.step(); tot += loss.item()*xb.shape[0] |
| if (ep+1)%10==0: print(f" Enc ep {ep+1}/{args.enc_ep}: loss={tot/len(ds):.4f} t={time.time()-t0_t:.0f}s", flush=True) |
| print(f" Done: loss={tot/len(ds):.4f}", flush=True) |
| torch.save({'e':encoder.state_dict()}, enc_path) |
|
|
| |
| print("\n=== RESULTS ===", flush=True) |
| f1_i3 = eval_pairs(encoder, cv_s, iv_s, lbs, dev, f"Idea3 (t0={args.t0})") |
| print(f"\n Baseline (raw): F1={b_raw:.4f}") |
| print(f" Idea3 (denoise-sib): F1={f1_i3:.4f}") |
| print(f" Supervised XGBoost: F1=0.982 (reference)") |
| print(f" Δ over baseline: {f1_i3-b_raw:+.4f}", flush=True) |
|
|
| if __name__=='__main__': main() |
|
|