""" STER-GI Idea 2: Identity-Realization Disentanglement (身份-实现解耦) ==================================================================== World Model approach: - VAE disentangles z_id (what building) from z_style (how it's captured) - Multi-view data: same building appears in both cand and index sets - Generate new views: freeze z_id, sample z_style → decode - Contrastive learning on (original, generated) pairs - Zero-shot: encode test buildings, cosine similarity → match """ 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"] # ===== 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(seed): """Load all buildings + multi-view pairs for disentanglement""" 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') # Multi-view pairs: same building ID → two views (cand, index) # Build ID -> vector mapping for both sources cand_all, idx_all = {}, {} for sp, ids in [(trp,id_tc),(epd,id_ec)]: for bid in ids: if bid not in cand_all: cand_all[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_all: idx_all[bid] = np.array([float(sp[pn]['index'].get(bid,0) or 0) for pn in PROPS], dtype=np.float32) # Multi-view pairs: buildings present in BOTH cand and index common = sorted(set(cand_all.keys()) & set(idx_all.keys())) views1 = np.array([cand_all[bid] for bid in common], dtype=np.float32) views2 = np.array([idx_all[bid] for bid in common], dtype=np.float32) print(f"Multi-view pairs: {len(common)} buildings with cand+index views", flush=True) # All buildings for reconstruction pre-training X_all = np.concatenate([Xtc, Xti, Xec, Xei], axis=0) # Eval pairs (same as Idea 3) 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]) cv, iv, lbs = [], [], [] for cid, iid in all_pairs: if cid in cand_all and iid in idx_all: cv.append(cand_all[cid]); iv.append(idx_all[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, views1, views2, cv, iv, lbs # ===== World Model: Disentangled VAE ===== class DisentangledVAE(nn.Module): """Encoder → (z_id, z_style); Decoder → reconstruction""" def __init__(self, d, z_id_dim=32, z_style_dim=16, h=256): super().__init__() # Encoder self.enc = nn.Sequential( nn.Linear(d, h), nn.BatchNorm1d(h), nn.ReLU(), nn.Linear(h, h), nn.BatchNorm1d(h), nn.ReLU()) self.mu_id = nn.Linear(h, z_id_dim) self.logvar_id = nn.Linear(h, z_id_dim) self.mu_style = nn.Linear(h, z_style_dim) self.logvar_style = nn.Linear(h, z_style_dim) # Decoder self.dec = nn.Sequential( nn.Linear(z_id_dim + z_style_dim, h), nn.BatchNorm1d(h), nn.ReLU(), nn.Linear(h, h), nn.BatchNorm1d(h), nn.ReLU(), nn.Linear(h, d)) # Discriminator: predict building ID from z_style (for adversarial disentanglement) self.disc = nn.Sequential( nn.Linear(z_style_dim, 64), nn.ReLU(), nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 1)) # Binary: same or different building? def encode(self, x): h = self.enc(x) return self.mu_id(h), self.logvar_id(h), self.mu_style(h), self.logvar_style(h) def reparameterize(self, mu, logvar): std = torch.exp(0.5 * logvar) eps = torch.randn_like(std) return mu + eps * std def forward(self, x): mu_id, lv_id, mu_style, lv_style = self.encode(x) z_id = self.reparameterize(mu_id, lv_id) z_style = self.reparameterize(mu_style, lv_style) recon = self.dec(torch.cat([z_id, z_style], dim=-1)) return recon, mu_id, lv_id, mu_style, lv_style, z_id, z_style @torch.no_grad() def generate(self, x, device): """Generate a new view: extract z_id, sample new z_style, decode""" mu_id, _, _, _ = self.encode(x.to(device)) z_style = torch.randn(x.shape[0], self.mu_style.out_features).to(device) * 0.5 return self.dec(torch.cat([mu_id, z_style], dim=-1)) def vae_loss(recon, x, mu_id, lv_id, mu_style, lv_style, z_id, z_style, disc, v1, v2, mu_id1, mu_id2, z_style1, z_style2, beta=0.1): """VAE loss: reconstruction + KL + identity consistency + adversarial""" # Reconstruction recon_loss = F.mse_loss(recon, x, reduction='sum') / x.shape[0] # KL divergence kl_id = -0.5 * torch.sum(1 + lv_id - mu_id.pow(2) - lv_id.exp(), dim=-1).mean() kl_style = -0.5 * torch.sum(1 + lv_style - mu_style.pow(2) - lv_style.exp(), dim=-1).mean() # Identity consistency: same building (v1, v2) → same z_id id_consistency = F.mse_loss(mu_id1, mu_id2) # Adversarial: discriminator should NOT be able to tell if two z_styles are from same building # Positive: z_style1 and z_style2 from same building → disc should NOT distinguish # Negative: z_style from different buildings → disc should NOT distinguish either (goal: style is ID-independent) # We train disc to distinguish, and encoder to fool disc # Simplified: minimize cosine similarity between z_styles of same building style_disentangle = F.cosine_similarity(z_style1, z_style2, dim=-1).abs().mean() total = recon_loss + beta * (kl_id + kl_style) + 0.5 * id_consistency + 0.1 * style_disentangle return total, {'recon': recon_loss.item(), 'kl_id': kl_id.item(), 'kl_style': kl_style.item(), 'id_cons': id_consistency.item(), 'style_dis': style_disentangle.item()} # ===== Contrastive 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): 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) # ===== 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(): a = argparse.ArgumentParser() a.add_argument('--seed',type=int,default=1); a.add_argument('--z_id',type=int,default=32) a.add_argument('--z_style',type=int,default=16); a.add_argument('--vae_ep',type=int,default=200) a.add_argument('--enc_ep',type=int,default=100) a.add_argument('--skip_vae',action='store_true'); a.add_argument('--skip_enc',action='store_true') args = a.parse_args() dev = 'cpu' print(f"Device: {dev} | z_id={args.z_id} z_style={args.z_style} | Seed: {args.seed}", flush=True) X_all, v1, v2, cv, iv, lbs = load_all(args.seed) sc = StandardScaler(); Xs = sc.fit_transform(X_all) v1s = sc.transform(v1); v2s = sc.transform(v2) cv_s, iv_s = sc.transform(cv), sc.transform(iv) print("\n=== Baseline ===", flush=True) b_raw = baseline_raw(cv_s, iv_s, lbs) # Stage 1: Train Disentangled VAE vae_path = f"saved_model_files/vae_i2_s{args.seed}.pt" gen_path = f"saved_model_files/gen_i2_s{args.seed}.npz" if args.skip_vae and os.path.exists(vae_path): print(f"Loading cached VAE: {vae_path}", flush=True) ck = torch.load(vae_path, map_location=dev) vae = DisentangledVAE(Xs.shape[1], args.z_id, args.z_style).to(dev) vae.load_state_dict(ck['vae']) else: print(f"\n=== Training Disentangled VAE ({args.vae_ep} epochs) ===", flush=True) vae = DisentangledVAE(Xs.shape[1], args.z_id, args.z_style).to(dev) opt = torch.optim.Adam(vae.parameters(), lr=1e-3) ds1 = TensorDataset(torch.FloatTensor(v1s), torch.FloatTensor(v2s)) ds2 = TensorDataset(torch.FloatTensor(Xs)) dl1 = DataLoader(ds1, batch_size=256, shuffle=True) dl2 = DataLoader(ds2, batch_size=256, shuffle=True) vae.train(); t0_t = time.time() for ep in range(args.vae_ep): tot_loss, tot_comp = 0, {} for (x1, x2) in dl1: x1, x2 = x1.to(dev), x2.to(dev) # Encode both views mu_id1, lv_id1, mu_s1, lv_s1 = vae.encode(x1) mu_id2, lv_id2, mu_s2, lv_s2 = vae.encode(x2) z_id1 = vae.reparameterize(mu_id1, lv_id1) z_s1 = vae.reparameterize(mu_s1, lv_s1) z_id2 = vae.reparameterize(mu_id2, lv_id2) z_s2 = vae.reparameterize(mu_s2, lv_s2) recon1 = vae.dec(torch.cat([z_id1, z_s1], -1)) recon2 = vae.dec(torch.cat([z_id2, z_s2], -1)) loss1, comp1 = vae_loss(recon1, x1, mu_id1, lv_id1, mu_s1, lv_s1, z_id1, z_s1, vae.disc, x1, x2, mu_id1, mu_id2, z_s1, z_s2) loss2, comp2 = vae_loss(recon2, x2, mu_id2, lv_id2, mu_s2, lv_s2, z_id2, z_s2, vae.disc, x2, x1, mu_id2, mu_id1, z_s2, z_s1) loss = loss1 + loss2 opt.zero_grad(); loss.backward(); opt.step() tot_loss += loss.item() for k in comp1: tot_comp[k] = tot_comp.get(k,0) + comp1[k] + comp2[k] if (ep+1)%20==0: n_b = max(1, len(dl1)) print(f" VAE ep {ep+1}/{args.vae_ep}: loss={tot_loss/n_b:.4f} " f"recon={tot_comp.get('recon',0)/n_b:.4f} " f"kl_id={tot_comp.get('kl_id',0)/n_b:.4f} " f"id_cons={tot_comp.get('id_cons',0)/n_b:.4f} " f"t={time.time()-t0_t:.0f}s", flush=True) print(f" Done: loss={tot_loss/max(1,len(dl1)):.4f}", flush=True) torch.save({'vae':vae.state_dict()}, vae_path) # Stage 2: Generate new views if os.path.exists(gen_path): d = np.load(gen_path); gens = d['gens'] print(f"Loaded cached generated views: {len(gens)}", flush=True) else: print("\n=== Generating New Views ===", flush=True) vae.eval(); gens = [] with torch.no_grad(): for i in range(0, len(Xs), 256): xb = torch.FloatTensor(Xs[i:i+256]).to(dev) for _ in range(2): gens.append(vae.generate(xb, dev).cpu().numpy()) gens = np.concatenate(gens) print(f" Generated {len(gens)} views", flush=True) np.savez_compressed(gen_path, gens=gens) # Stage 3: Contrastive Encoder enc_path = f"saved_model_files/enc_i2_s{args.seed}.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=== 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_g = len(gens); idx = np.random.permutation(min(n_g, len(Xs))) data = np.zeros((len(idx)*2, Xs.shape[1]), dtype=np.float32) data[0::2] = Xs[idx]; data[1::2] = gens[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) # Results print("\n=== RESULTS ===", flush=True) f1_i2 = eval_pairs(encoder, cv_s, iv_s, lbs, dev, f"Idea2 (WM disentangle)") print(f"\n Baseline (raw): F1={b_raw:.4f}") print(f" Idea2 (WM): F1={f1_i2:.4f}") print(f" Supervised XGBoost: F1=0.982") print(f" Δ over baseline: {f1_i2-b_raw:+.4f}", flush=True) if __name__=='__main__': main()