| """ |
| STER-GI Idea 3: Denoise-to-Sibling (去噪造兄弟) |
| ================================================ |
| - Train unconditional diffusion on ALL building property vectors (no labels) |
| - Generate "sibling" buildings via SDEdit (partial noise + denoise) |
| - Contrastive learning on (original, sibling) pairs |
| - Zero-shot evaluation on test pairs: encode → cosine sim → threshold → match |
| |
| Baselines: |
| - real-only (raw property cosine): no training at all |
| - Idea 3 (denoise-to-sibling): diffusion + contrastive |
| """ |
|
|
| import os, sys, time, warnings, argparse |
| import numpy as np |
| import joblib, pickle as pkl |
| import torch, torch.nn as nn, torch.nn.functional as F |
| from torch.utils.data import DataLoader, TensorDataset |
| from sklearn.preprocessing import StandardScaler |
| from sklearn.metrics import precision_score, recall_score, f1_score, average_precision_score |
| from collections import defaultdict |
|
|
| warnings.filterwarnings("ignore") |
|
|
| |
| |
| |
| PROPERTY_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" |
| ] |
|
|
| CFG = { |
| 'diffusion_steps': 1000, |
| 'diffusion_hidden': 256, |
| 'diffusion_layers': 4, |
| 'diffusion_epochs': 500, |
| 'diffusion_lr': 1e-3, |
| 'diffusion_batch_size': 512, |
| |
| 'sdedit_t0': 200, |
| 'num_siblings': 3, |
| |
| 'encoder_hidden': 128, |
| 'encoder_dim': 64, |
| 'contrastive_epochs': 200, |
| 'contrastive_lr': 1e-3, |
| 'contrastive_temp': 0.07, |
| 'contrastive_batch': 1024, |
| |
| 'eval_thresholds': [0.5, 0.6, 0.7, 0.75, 0.8, 0.85, 0.9, 0.92, 0.95, 0.97, 0.99], |
| 'device': 'cuda' if torch.cuda.is_available() else 'cpu', |
| } |
|
|
| |
| |
| |
| def extract_vectors(prop_dict, source, id_list=None): |
| """Extract property matrix for given source ('cands'/'index') and optional id filter""" |
| first_prop = PROPERTY_NAMES[0] |
| all_ids = list(prop_dict[first_prop][source].keys()) if id_list is None else id_list |
| X = np.zeros((len(all_ids), len(PROPERTY_NAMES)), dtype=np.float32) |
| valid_ids = [] |
| for i, bid in enumerate(all_ids): |
| vec = [] |
| ok = True |
| for pname in PROPERTY_NAMES: |
| val = prop_dict[pname][source].get(bid, None) |
| if val is None or (isinstance(val, float) and np.isnan(val)): |
| val = 0.0 |
| vec.append(float(val)) |
| X[i] = vec |
| valid_ids.append(bid) |
| return X, valid_ids |
|
|
|
|
| def load_all_train_vectors(seed): |
| """Load property vectors for ALL training buildings (both cands and index)""" |
| train_path = (f"data/property_dicts/Hague_allmodels_v1_train_matching_medium_" |
| f"neg_samples_num=2_vector_normalization=True_seed={seed}.joblib") |
| prop = joblib.load(train_path) |
|
|
| X_cands, ids_cands = extract_vectors(prop, 'cands') |
| X_index, ids_index = extract_vectors(prop, 'index') |
| X = np.concatenate([X_cands, X_index], axis=0) |
| all_ids = ids_cands + ids_index |
| print(f"Loaded {len(X)} train building vectors ({len(X_cands)} cands + {len(X_index)} index)") |
| return X, all_ids, prop |
|
|
|
|
| def load_test_pairs(seed): |
| """Load test pairs with labels: list of (cand_id, index_id, label)""" |
| test_path = (f"data/property_dicts/Hague_allmodels_v1_test_matching_medium_" |
| f"neg_samples_num=2_vector_normalization=True_seed={seed}.joblib") |
| prop = joblib.load(test_path) |
|
|
| partition = pkl.load(open(f"data/dataset_partitions/Hague_seed{seed}.pkl", 'rb')) |
| test_pairs = partition['test']['matching']['negative_sampling']['medium'][2] |
|
|
| |
| cand_map = {} |
| for bid in prop[PROPERTY_NAMES[0]]['cands'].keys(): |
| vec = [] |
| for pname in PROPERTY_NAMES: |
| val = prop[pname]['cands'].get(bid, None) |
| if val is None or (isinstance(val, float) and np.isnan(val)): |
| val = 0.0 |
| vec.append(float(val)) |
| cand_map[bid] = np.array(vec, dtype=np.float32) |
|
|
| index_map = {} |
| for bid in prop[PROPERTY_NAMES[0]]['index'].keys(): |
| vec = [] |
| for pname in PROPERTY_NAMES: |
| val = prop[pname]['index'].get(bid, None) |
| if val is None or (isinstance(val, float) and np.isnan(val)): |
| val = 0.0 |
| vec.append(float(val)) |
| index_map[bid] = np.array(vec, dtype=np.float32) |
|
|
| cand_vecs, index_vecs, labels = [], [], [] |
| for cid, iid in test_pairs: |
| if cid in cand_map and iid in index_map: |
| cand_vecs.append(cand_map[cid]) |
| index_vecs.append(index_map[iid]) |
| labels.append(1 if cid == iid else 0) |
|
|
| cand_vecs = np.array(cand_vecs, dtype=np.float32) |
| index_vecs = np.array(index_vecs, dtype=np.float32) |
| labels = np.array(labels, dtype=np.int32) |
|
|
| print(f"Test pairs: {len(labels)} ({labels.sum()} pos, {(1-labels).sum()} neg)") |
| return cand_vecs, index_vecs, labels |
|
|
|
|
| |
| |
| |
| class MLPDiffusion(nn.Module): |
| def __init__(self, dim, hidden=256, layers=4): |
| super().__init__() |
| self.time_embed = nn.Sequential( |
| nn.Linear(1, hidden), nn.SiLU(), nn.Linear(hidden, hidden)) |
| net = [nn.Linear(dim + hidden, hidden), nn.SiLU()] |
| for _ in range(layers - 1): |
| net += [nn.Linear(hidden, hidden), nn.SiLU()] |
| net.append(nn.Linear(hidden, dim)) |
| self.net = nn.Sequential(*net) |
|
|
| def forward(self, x, t): |
| t_emb = self.time_embed(t.unsqueeze(-1).float()) |
| return self.net(torch.cat([x, t_emb], dim=-1)) |
|
|
|
|
| class DiffusionScheduler: |
| def __init__(self, steps=1000, beta_start=1e-4, beta_end=0.02): |
| self.steps = steps |
| self.betas = torch.linspace(beta_start, beta_end, steps) |
| self.alphas = 1 - self.betas |
| self.alpha_bars = torch.cumprod(self.alphas, dim=0) |
|
|
| def add_noise(self, x0, t): |
| ab = self.alpha_bars[t].view(-1, 1) |
| noise = torch.randn_like(x0) |
| return torch.sqrt(ab) * x0 + torch.sqrt(1 - ab) * noise, noise |
|
|
| @torch.no_grad() |
| def denoise_step(self, model, xt, t): |
| """Single DDPM reverse step""" |
| a = self.alphas[t].view(-1, 1) |
| ab = self.alpha_bars[t].view(-1, 1) |
| b = self.betas[t].view(-1, 1) |
| eps = model(xt, t.float()) |
| x0_hat = (xt - torch.sqrt(1 - ab) * eps) / torch.sqrt(a) |
| if t.min() == 0: |
| return x0_hat |
| ab_prev = self.alpha_bars[t - 1].view(-1, 1) |
| mean = (torch.sqrt(ab_prev) * b / (1 - ab) * x0_hat + |
| torch.sqrt(a) * (1 - ab_prev) / (1 - ab) * xt) |
| var = b * (1 - ab_prev) / (1 - ab) |
| return mean + torch.sqrt(var) * torch.randn_like(xt) |
|
|
| @torch.no_grad() |
| def sdedit(self, model, x0, t0, device): |
| """Add noise to t0, then denoise back → sibling""" |
| n = x0.shape[0] |
| t0_t = torch.full((n,), t0, device=device, dtype=torch.long) |
| ab_t0 = self.alpha_bars[t0] |
| noise = torch.randn_like(x0) |
| xt = torch.sqrt(ab_t0) * x0 + torch.sqrt(1 - ab_t0) * noise |
| for t in range(t0, -1, -1): |
| tb = torch.full((n,), t, device=device, dtype=torch.long) |
| xt = self.denoise_step(model, xt, tb) |
| return xt |
|
|
|
|
| |
| |
| |
| class BuildingEncoder(nn.Module): |
| def __init__(self, dim, hidden=128, out_dim=64): |
| super().__init__() |
| self.net = nn.Sequential( |
| nn.Linear(dim, hidden), nn.BatchNorm1d(hidden), nn.ReLU(), |
| nn.Linear(hidden, hidden), nn.BatchNorm1d(hidden), nn.ReLU(), |
| nn.Linear(hidden, out_dim)) |
|
|
| def forward(self, x): |
| return F.normalize(self.net(x), dim=-1) |
|
|
|
|
| def info_nce_loss(embs, temp=0.07): |
| """embs: [2B, D] where (0,1), (2,3)... are positives""" |
| n = embs.shape[0] // 2 |
| sim = embs @ embs.T / temp |
| |
| sim = sim.masked_fill(torch.eye(2 * n, device=embs.device, dtype=torch.bool), -1e9) |
| |
| labels = torch.arange(2 * n, device=embs.device) |
| labels = labels ^ 1 |
| return F.cross_entropy(sim, labels) |
|
|
|
|
| |
| |
| |
| def train_diffusion(X, device): |
| print("\n" + "=" * 50) |
| print("Stage 1: Train Diffusion on Building Vectors") |
| print("=" * 50) |
| dim = X.shape[1] |
| model = MLPDiffusion(dim, CFG['diffusion_hidden'], CFG['diffusion_layers']).to(device) |
| sched = DiffusionScheduler(CFG['diffusion_steps']) |
| sched.betas = sched.betas.to(device) |
| sched.alphas = sched.alphas.to(device) |
| sched.alpha_bars = sched.alpha_bars.to(device) |
|
|
| opt = torch.optim.Adam(model.parameters(), lr=CFG['diffusion_lr']) |
| ds = TensorDataset(torch.FloatTensor(X)) |
| dl = DataLoader(ds, batch_size=CFG['diffusion_batch_size'], shuffle=True) |
|
|
| model.train() |
| for ep in range(CFG['diffusion_epochs']): |
| total = 0 |
| for (xb,) in dl: |
| xb = xb.to(device) |
| bs = xb.shape[0] |
| t = torch.randint(0, CFG['diffusion_steps'], (bs,), device=device) |
| xt, noise = sched.add_noise(xb, t) |
| loss = F.mse_loss(model(xt, t.float()), noise) |
| opt.zero_grad() |
| loss.backward() |
| opt.step() |
| total += loss.item() * bs |
| if (ep + 1) % 100 == 0: |
| print(f" Epoch {ep+1}/{CFG['diffusion_epochs']} | Loss: {total/len(ds):.6f}") |
| print(f" Done. Final loss: {total/len(ds):.6f}") |
| return model, sched |
|
|
|
|
| def generate_siblings(model, sched, X, device): |
| print("\n" + "=" * 50) |
| print(f"Stage 2: Generate Siblings (t0={CFG['sdedit_t0']})") |
| print("=" * 50) |
| model.eval() |
| origs, sibs = [], [] |
| bs = CFG['diffusion_batch_size'] |
| for i in range(0, len(X), bs): |
| xb = torch.FloatTensor(X[i:i+bs]).to(device) |
| for _ in range(CFG['num_siblings']): |
| sib = sched.sdedit(model, xb, CFG['sdedit_t0'], device) |
| origs.append(xb.cpu().numpy()) |
| sibs.append(sib.cpu().numpy()) |
|
|
| origs = np.concatenate(origs, axis=0) |
| sibs = np.concatenate(sibs, axis=0) |
| l2 = np.mean(np.linalg.norm(origs - sibs, axis=1)) |
| print(f" Generated {len(origs)} pairs | Mean L2 diff: {l2:.4f}") |
| return origs, sibs |
|
|
|
|
| def train_encoder(origs, sibs, device): |
| print("\n" + "=" * 50) |
| print("Stage 3: Contrastive Encoder Training") |
| print("=" * 50) |
| dim = origs.shape[1] |
| encoder = BuildingEncoder(dim, CFG['encoder_hidden'], CFG['encoder_dim']).to(device) |
| opt = torch.optim.Adam(encoder.parameters(), lr=CFG['contrastive_lr']) |
|
|
| |
| n = len(origs) |
| data = np.zeros((n * 2, dim), dtype=np.float32) |
| data[0::2] = origs |
| data[1::2] = sibs |
| ds = TensorDataset(torch.FloatTensor(data)) |
| dl = DataLoader(ds, batch_size=CFG['contrastive_batch'], shuffle=True) |
|
|
| encoder.train() |
| for ep in range(CFG['contrastive_epochs']): |
| total = 0 |
| for (xb,) in dl: |
| xb = xb.to(device) |
| emb = encoder(xb) |
| loss = info_nce_loss(emb, CFG['contrastive_temp']) |
| opt.zero_grad() |
| loss.backward() |
| opt.step() |
| total += loss.item() * xb.shape[0] |
| if (ep + 1) % 50 == 0: |
| print(f" Epoch {ep+1}/{CFG['contrastive_epochs']} | Loss: {total/len(ds):.4f}") |
| print(f" Done. Final loss: {total/len(ds):.4f}") |
| return encoder |
|
|
|
|
| |
| |
| |
| @torch.no_grad() |
| def eval_zero_shot(encoder, cand_vecs, index_vecs, labels, device, tag="Model"): |
| """Zero-shot pair classification via cosine similarity""" |
| encoder.eval() |
| ct = torch.FloatTensor(cand_vecs).to(device) |
| it = torch.FloatTensor(index_vecs).to(device) |
| ce = encoder(ct).cpu().numpy() |
| ie = encoder(it).cpu().numpy() |
|
|
| |
| sims = np.sum(ce * ie, axis=1) |
|
|
| |
| best_f1, best_thresh, best_res = 0, 0.5, None |
| for th in CFG['eval_thresholds']: |
| pred = (sims >= th).astype(np.int32) |
| p = precision_score(labels, pred, zero_division=0) |
| r = recall_score(labels, pred, zero_division=0) |
| f = f1_score(labels, pred, zero_division=0) |
| if f > best_f1: |
| best_f1, best_thresh, best_res = f, th, (p, r, f) |
|
|
| print(f"\n {tag} (best threshold={best_thresh:.2f}):") |
| print(f" Precision: {best_res[0]:.4f}") |
| print(f" Recall: {best_res[1]:.4f}") |
| print(f" F1: {best_res[2]:.4f}") |
|
|
| |
| ap = average_precision_score(labels, sims) |
| print(f" AvgPrecision: {ap:.4f}") |
|
|
| return {'precision': best_res[0], 'recall': best_res[1], 'f1': best_res[2], |
| 'ap': ap, 'threshold': best_thresh} |
|
|
|
|
| def eval_real_only(cand_vecs, index_vecs, labels): |
| """Baseline: raw property cosine similarity, no training""" |
| |
| cn = cand_vecs / (np.linalg.norm(cand_vecs, axis=1, keepdims=True) + 1e-8) |
| i_n = index_vecs / (np.linalg.norm(index_vecs, axis=1, keepdims=True) + 1e-8) |
| sims = np.sum(cn * i_n, axis=1) |
|
|
| best_f1, best_thresh, best_res = 0, 0.5, None |
| for th in CFG['eval_thresholds']: |
| pred = (sims >= th).astype(np.int32) |
| p = precision_score(labels, pred, zero_division=0) |
| r = recall_score(labels, pred, zero_division=0) |
| f = f1_score(labels, pred, zero_division=0) |
| if f > best_f1: |
| best_f1, best_thresh, best_res = f, th, (p, r, f) |
|
|
| ap = average_precision_score(labels, sims) |
| print(f"\n Baseline Real-Only (best th={best_thresh:.2f}):") |
| print(f" P={best_res[0]:.4f} R={best_res[1]:.4f} F1={best_res[2]:.4f} AP={ap:.4f}") |
|
|
| return {'precision': best_res[0], 'recall': best_res[1], 'f1': best_res[2], |
| 'ap': ap, 'threshold': best_thresh} |
|
|
|
|
| |
| |
| |
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument('--seed', type=int, default=1) |
| parser.add_argument('--t0', type=int, default=200, help='SDEdit noise level') |
| parser.add_argument('--skip_diff', action='store_true') |
| parser.add_argument('--skip_enc', action='store_true') |
| args = parser.parse_args() |
|
|
| CFG['sdedit_t0'] = args.t0 |
| device = CFG['device'] |
| seed = args.seed |
| print(f"Device: {device} | t0: {args.t0} | Seed: {seed}") |
|
|
| |
| X_train, train_ids, train_prop = load_all_train_vectors(seed) |
| cand_vecs, idx_vecs, labels = load_test_pairs(seed) |
|
|
| |
| scaler = StandardScaler() |
| X_train_s = scaler.fit_transform(X_train) |
| cand_s = scaler.transform(cand_vecs) |
| idx_s = scaler.transform(idx_vecs) |
|
|
| |
| diff_path = f"saved_model_files/diff_idea3_s{seed}_t{args.t0}.pt" |
| sib_path = f"saved_model_files/siblings_idea3_s{seed}_t{args.t0}.npz" |
|
|
| if args.skip_diff and os.path.exists(diff_path): |
| print(f"Loading cached diffusion model: {diff_path}") |
| ck = torch.load(diff_path, map_location=device) |
| model = MLPDiffusion(X_train_s.shape[1], CFG['diffusion_hidden'], |
| CFG['diffusion_layers']).to(device) |
| model.load_state_dict(ck['model']) |
| sched = DiffusionScheduler(CFG['diffusion_steps']) |
| sched.betas = sched.betas.to(device) |
| sched.alphas = sched.alphas.to(device) |
| sched.alpha_bars = sched.alpha_bars.to(device) |
| else: |
| model, sched = train_diffusion(X_train_s, device) |
| torch.save({'model': model.state_dict()}, diff_path) |
|
|
| if os.path.exists(sib_path): |
| print(f"Loading cached siblings: {sib_path}") |
| data = np.load(sib_path) |
| origs, sibs = data['origs'], data['sibs'] |
| else: |
| origs, sibs = generate_siblings(model, sched, X_train_s, device) |
| np.savez_compressed(sib_path, origs=origs, sibs=sibs) |
|
|
| |
| enc_path = f"saved_model_files/enc_idea3_s{seed}_t{args.t0}.pt" |
|
|
| if args.skip_enc and os.path.exists(enc_path): |
| print(f"Loading cached encoder: {enc_path}") |
| ck = torch.load(enc_path, map_location=device) |
| encoder = BuildingEncoder(X_train_s.shape[1], CFG['encoder_hidden'], |
| CFG['encoder_dim']).to(device) |
| encoder.load_state_dict(ck['encoder']) |
| else: |
| encoder = train_encoder(origs, sibs, device) |
| torch.save({'encoder': encoder.state_dict()}, enc_path) |
|
|
| |
| print("\n" + "=" * 50) |
| print("RESULTS") |
| print("=" * 50) |
|
|
| r_base = eval_real_only(cand_s, idx_s, labels) |
| r_idea3 = eval_zero_shot(encoder, cand_s, idx_s, labels, device, |
| f"Idea 3 (t0={args.t0})") |
|
|
| print("\n" + "=" * 50) |
| print(f"SUMMARY (seed={seed}, t0={args.t0})") |
| print("=" * 50) |
| print(f" Baseline (real-only): F1={r_base['f1']:.4f} AP={r_base['ap']:.4f}") |
| print(f" Idea 3 (denoise-sib): F1={r_idea3['f1']:.4f} AP={r_idea3['ap']:.4f}") |
| print(f" ΔF1: {r_idea3['f1'] - r_base['f1']:.4f} ΔAP: {r_idea3['ap'] - r_base['ap']:.4f}") |
|
|
| return r_base, r_idea3 |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|