""" STER-GI Idea 4: Geometric Grammar Score Guard (几何语法守门) ============================================================= Uses the diffusion model's score as a "grammar checker": - Take generated siblings from Idea 3 - Score each sibling using the diffusion model's negative loss (lower = more "legal") - Only keep top-K% most "legal" siblings - Train contrastive encoder on filtered high-quality pairs - Expected: better F1 than unfiltered Idea 3 """ 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 # Reuse building blocks from Idea 3 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"] from ster_gi_idea3_v3 import (get_vecs, load_all, DiffMLP, DiffSched, Encoder, infonce, eval_pairs, baseline_raw) # Override load_all to work standalone def load_all_local(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) 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,idx_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 idx_map: idx_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 idx_map: cv.append(cand_map[cid]); iv.append(idx_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"Buildings: {len(X_all)} | Eval pairs: {len(lbs)}",flush=True) return X_all,cv,iv,lbs def score_siblings(model, sched, origs, sibs, dev): """Score siblings using diffusion model: average MSE of noise prediction across timesteps. Lower score = more 'legal' (closer to building manifold).""" print("Scoring siblings...", flush=True) model.eval() scores = [] bs = 512 with torch.no_grad(): for i in range(0, len(sibs), bs): sb = torch.FloatTensor(sibs[i:i+bs]).to(dev) ob = torch.FloatTensor(origs[i:i+bs]).to(dev) n_b = sb.shape[0] # Average score over several timesteps score_sum = 0 for t_frac in [0.1, 0.3, 0.5, 0.7, 0.9]: t_val = int(t_frac * 1000) t = torch.full((n_b,), t_val, device=dev) xt, noise = sched.noise(sb, t) pred = model(xt, t.float()) score_sum += F.mse_loss(pred, noise, reduction='none').mean(dim=-1).cpu().numpy() scores.append(score_sum / 5.0) # average across timesteps scores = np.concatenate(scores) # Lower score = closer to manifold threshold = np.percentile(scores, 50) # keep top 50% keep = scores <= threshold print(f" Score range: [{scores.min():.4f}, {scores.max():.4f}]") print(f" Keeping {keep.sum()}/{len(scores)} ({keep.sum()/len(scores)*100:.0f}%) siblings", flush=True) return keep def main(): a = argparse.ArgumentParser() a.add_argument('--seed',type=int,default=1); a.add_argument('--t0',type=int,default=400) a.add_argument('--keep_frac',type=float,default=0.5); a.add_argument('--enc_ep',type=int,default=100) args = a.parse_args() dev = 'cpu' print(f"Device: {dev} | t0: {args.t0} | keep_frac: {args.keep_frac} | Seed: {args.seed}", flush=True) X_all, cv, iv, lbs = load_all_local(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) # Load pretrained diffusion model diff_path = f"saved_model_files/diff_i3_s{args.seed}.pt" print(f"Loading 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']] # Generate siblings (same as Idea 3) sib_path = f"saved_model_files/sib_i3_s{args.seed}_t{args.t0}.npz" if os.path.exists(sib_path): d = np.load(sib_path); origs, sibs = d['o'], d['s'] print(f"Loaded {len(origs)} siblings from cache", flush=True) else: print(f"Generating siblings at t0={args.t0}...", 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) np.savez_compressed(sib_path, o=origs, s=sibs) print(f" Generated {len(origs)} pairs", flush=True) # Score and filter siblings keep = score_siblings(model, sched, origs, sibs, dev) origs_f, sibs_f = origs[keep], sibs[keep] # Contrastive encoder on FILTERED pairs enc_path = f"saved_model_files/enc_i4_s{args.seed}_t{args.t0}_k{args.keep_frac}.pt" print(f"\n=== Contrastive 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_f); idx = np.random.permutation(n) data = np.zeros((n*2, Xs.shape[1]), dtype=np.float32) data[0::2] = origs_f[idx]; data[1::2] = sibs_f[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) # Eval print("\n=== RESULTS ===", flush=True) f1_i4 = eval_pairs(encoder, cv_s, iv_s, lbs, dev, f"Idea4 (score guard, t0={args.t0}, keep={args.keep_frac})") print(f"\n Baseline (raw): F1={b_raw:.4f}") print(f" Idea4 (grammar guard): F1={f1_i4:.4f}") print(f" Supervised XGBoost: F1=0.982") print(f" Δ over baseline: {f1_i4-b_raw:+.4f}", flush=True) if __name__=='__main__': main()