| """ |
| STER-GI: Train ALL 6 ideas on synthetic cross-LoD data. |
| Uses aggressive noise model to simulate LoD1.2 ↔ LoD2.2 differences. |
| |
| Baseline: F1≈0.66 (raw cosine, cross-LoD) |
| Target: F1≥0.80 (+20%) |
| |
| Usage: |
| python ster_train_synth.py --idea 3 --epochs 200 |
| python ster_train_synth.py --idea 3p --epochs 200 --t0 200 |
| python ster_train_synth.py --idea 1 --epochs 200 |
| python ster_train_synth.py --idea 2 --epochs 200 |
| python ster_train_synth.py --idea 4 --epochs 200 --t0 200 --keep_frac 0.5 |
| python ster_train_synth.py --idea 5 --epochs 100 --rounds 3 |
| python ster_train_synth.py --idea 6 --epochs 200 --knn 5 |
| """ |
| import os, sys, json, time, argparse |
| import numpy as np |
| from collections import OrderedDict |
| import warnings |
| warnings.filterwarnings('ignore') |
|
|
| import torch, torch.nn as nn, torch.nn.functional as F |
| import joblib |
| from ddpm import DDPM, BetaSchedule |
|
|
| DEV = 'cuda' if torch.cuda.is_available() else 'cpu' |
| print(f"Device: {DEV}") |
| torch.set_num_threads(1) |
| import os as _os |
| _os.environ['OMP_NUM_THREADS'] = '1' |
| _os.environ['MKL_NUM_THREADS'] = '1' |
|
|
| PROP_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"] |
|
|
| |
| |
| |
| class Encoder(nn.Module): |
| def __init__(self, d=25, h=128, o=64): |
| super().__init__() |
| self.net = nn.Sequential(OrderedDict([ |
| ('0', nn.Linear(d, h)), ('1', nn.BatchNorm1d(h)), ('2', nn.ReLU()), |
| ('3', nn.Linear(h, h)), ('4', nn.BatchNorm1d(h)), ('5', nn.ReLU()), |
| ('6', 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_loss(z_a, z_b, tau=0.1): |
| B = z_a.shape[0] |
| z_a = F.normalize(z_a, dim=-1) |
| z_b = F.normalize(z_b, dim=-1) |
| sim = torch.mm(z_a, z_b.T) / tau |
| labels = torch.arange(B, device=z_a.device) |
| return (F.cross_entropy(sim, labels) + F.cross_entropy(sim.T, labels)) / 2 |
|
|
| |
| |
| |
| def aggressive_lod_noise(props, seed=42): |
| """Simulate LoD1.2 → LoD2.2 transformation.""" |
| rng = np.random.RandomState(seed) |
| p = props.copy().astype(np.float64) |
| N, D = p.shape |
| for j, pn in enumerate(PROP_NAMES): |
| if pn in ['volume', 'convex_hull_volume']: |
| p[:, j] *= rng.uniform(0.3, 3.0, N) |
| elif pn in ['area', 'convex_hull_area', 'perimeter', 'circumference']: |
| p[:, j] *= rng.uniform(0.5, 2.0, N) |
| elif pn in ['height_diff', 'aligned_bounding_box_height']: |
| p[:, j] += rng.randn(N) * 5.0 |
| p[:, j] = np.maximum(0.1, p[:, j]) |
| elif pn == 'num_vertices': |
| p[:, j] *= rng.uniform(0.3, 0.8, N) |
| elif pn == 'num_floors': |
| p[:, j] += rng.randint(-2, 3, N).astype(np.float64) |
| p[:, j] = np.maximum(1, p[:, j]) |
| else: |
| p[:, j] *= rng.uniform(0.5, 1.5, N) |
| p += rng.randn(N, D) * 0.1 |
| return p.astype(np.float32) |
|
|
| def load_and_split_data(): |
| """Load all building properties, split into train/test, apply LoD noise.""" |
| all_mats, all_ids = [], [] |
| for suf in ['Hague_allmodels_v1_train_matching_medium_neg_samples_num=2_vector_normalization=True_seed=1', |
| 'Hague_allmodels_v1_test_matching_medium_neg_samples_num=2_vector_normalization=True_seed=1']: |
| pdict = joblib.load(f'data/property_dicts/{suf}.joblib') |
| for side in ['cands', 'index']: |
| ids = list(pdict[PROP_NAMES[0]][side].keys()) |
| mat = np.zeros((len(ids), len(PROP_NAMES)), dtype=np.float32) |
| for j, pn in enumerate(PROP_NAMES): |
| for i, bid in enumerate(ids): |
| val = pdict[pn][side].get(bid) |
| if val is not None: |
| mat[i, j] = float(val) |
| mat = np.nan_to_num(mat, nan=0.0, posinf=1e6, neginf=-1e6) |
| all_mats.append(mat) |
| all_ids.extend(ids) |
| |
| X = np.vstack(all_mats) |
| N = len(X) |
| rng = np.random.RandomState(42) |
| perm = rng.permutation(N) |
| n_train = int(N * 0.6) |
| train_props = X[perm[:n_train]] |
| test_props = X[perm[n_train:]] |
| test_ids = [all_ids[i] for i in perm[n_train:]] |
| |
| train_coarse = aggressive_lod_noise(train_props, seed=1) |
| test_coarse = aggressive_lod_noise(test_props, seed=123) |
| |
| |
| all_cat = np.vstack([train_props, train_coarse]) |
| mean = all_cat.mean(axis=0, keepdims=True) |
| std = all_cat.std(axis=0, keepdims=True) |
| std[std < 1e-8] = 1.0 |
| |
| train_fine_n = (train_props - mean) / std |
| train_coarse_n = (train_coarse - mean) / std |
| test_fine_n = (test_props - mean) / std |
| test_coarse_n = (test_coarse - mean) / std |
| |
| print(f"Train: {len(train_fine_n)} pairs, Test: {len(test_fine_n)} pairs") |
| return (train_fine_n, train_coarse_n), (test_fine_n, test_coarse_n, test_ids) |
|
|
|
|
| |
| |
| |
| class ContrastiveTrainer: |
| def __init__(self, d=25, h=128, o=64, lr=3e-4, tau=0.1): |
| self.encoder = Encoder(d, h, o).to(DEV) |
| self.optimizer = torch.optim.AdamW(self.encoder.parameters(), lr=lr, weight_decay=1e-5) |
| self.tau = tau |
| |
| def train_epoch(self, pairs_a, pairs_b, batch_size=256): |
| N = len(pairs_a) |
| idx = np.random.permutation(N) |
| total_loss = 0 |
| n_batches = 0 |
| for start in range(0, N, batch_size): |
| batch_idx = idx[start:start+batch_size] |
| ba = torch.tensor(pairs_a[batch_idx], dtype=torch.float32).to(DEV) |
| bb = torch.tensor(pairs_b[batch_idx], dtype=torch.float32).to(DEV) |
| z_a = self.encoder(ba) |
| z_b = self.encoder(bb) |
| loss = infonce_loss(z_a, z_b, self.tau) |
| self.optimizer.zero_grad() |
| loss.backward() |
| self.optimizer.step() |
| total_loss += loss.item() |
| n_batches += 1 |
| return total_loss / max(n_batches, 1) |
| |
| def save(self, path): |
| torch.save({'e': self.encoder.state_dict()}, path) |
|
|
| |
| |
| |
| def evaluate_encoder(enc, test_fine, test_coarse): |
| fine_t = torch.tensor(test_fine, dtype=torch.float32).to(DEV) |
| coarse_t = torch.tensor(test_coarse, dtype=torch.float32).to(DEV) |
| N = len(test_fine) |
| bs = 512 |
| emb_fine, emb_coarse = [], [] |
| with torch.no_grad(): |
| for start in range(0, N, bs): |
| emb_fine.append(enc(fine_t[start:start+bs]).cpu().numpy()) |
| emb_coarse.append(enc(coarse_t[start:start+bs]).cpu().numpy()) |
| emb_fine = np.vstack(emb_fine) |
| emb_coarse = np.vstack(emb_coarse) |
| pos_sims = np.sum(emb_fine * emb_coarse, axis=1) |
| rng = np.random.RandomState(42) |
| neg_idx = rng.permutation(N) |
| neg_sims = np.sum(emb_fine * emb_coarse[neg_idx], axis=1) |
| all_sims = np.concatenate([pos_sims, neg_sims]) |
| all_labels = np.concatenate([np.ones(N, dtype=np.int32), np.zeros(N, dtype=np.int32)]) |
| best_f1 = 0.0 |
| for t in np.linspace(0.1, 0.999, 100): |
| pred = (all_sims >= t).astype(np.int32) |
| tp = float(((pred == 1) & (all_labels == 1)).sum()) |
| fp = float(((pred == 1) & (all_labels == 0)).sum()) |
| fn = float(((pred == 0) & (all_labels == 1)).sum()) |
| p = tp / (tp + fp + 1e-9) |
| r = tp / (tp + fn + 1e-9) |
| f1 = 2.0 * p * r / (p + r + 1e-9) |
| if f1 > best_f1: best_f1 = f1 |
| return float(best_f1) |
|
|
| def baseline_f1(test_fine, test_coarse): |
| fn = test_fine / (np.linalg.norm(test_fine, axis=1, keepdims=True) + 1e-8) |
| cn = test_coarse / (np.linalg.norm(test_coarse, axis=1, keepdims=True) + 1e-8) |
| pos = np.sum(fn * cn, axis=1) |
| rng = np.random.RandomState(42) |
| neg_idx = rng.permutation(len(cn)) |
| neg = np.sum(fn * cn[neg_idx], axis=1) |
| all_sims = np.concatenate([pos, neg]) |
| all_labels = np.concatenate([np.ones(len(pos), dtype=np.int32), np.zeros(len(neg), dtype=np.int32)]) |
| best_f1 = 0.0 |
| for t in np.linspace(0.1, 0.999, 100): |
| pred = (all_sims >= t).astype(np.int32) |
| tp = float(((pred == 1) & (all_labels == 1)).sum()) |
| fp = float(((pred == 1) & (all_labels == 0)).sum()) |
| fn = float(((pred == 0) & (all_labels == 1)).sum()) |
| p = tp / (tp + fp + 1e-9) |
| r = tp / (tp + fn + 1e-9) |
| f1 = 2.0 * p * r / (p + r + 1e-9) |
| if f1 > best_f1: best_f1 = f1 |
| return float(best_f1) |
|
|
| |
| |
| |
| class ConditionalDenoiser(nn.Module): |
| def __init__(self, d=25, h=256, T=1000): |
| super().__init__() |
| self.t_emb = nn.Embedding(T, h) |
| self.net = nn.Sequential(OrderedDict([ |
| ('in', nn.Linear(d + d + h, h)), |
| ('n1', nn.LayerNorm(h)), ('a1', nn.SiLU()), |
| ('h1', nn.Linear(h, h)), |
| ('n2', nn.LayerNorm(h)), ('a2', nn.SiLU()), |
| ('h2', nn.Linear(h, h)), |
| ('n3', nn.LayerNorm(h)), ('a3', nn.SiLU()), |
| ('out', nn.Linear(h, d)), |
| ])) |
| def forward(self, x, t, condition): |
| te = self.t_emb(t) |
| return self.net(torch.cat([x, condition, te], dim=-1)) |
|
|
| class ConditionalDDPM: |
| def __init__(self, d=25, h=256, T=1000): |
| self.d, self.h, self.T = d, h, T |
| self.schedule = BetaSchedule(T) |
| self.denoiser = ConditionalDenoiser(d, h, T).to(DEV) |
| self.optimizer = torch.optim.AdamW(self.denoiser.parameters(), lr=3e-4) |
| |
| def train_step(self, x_src, x_tgt): |
| B = x_tgt.shape[0] |
| t = torch.randint(0, self.T, (B,), device=DEV) |
| x_t, noise = self.schedule.forward_diffuse(x_tgt, t) |
| pred = self.denoiser(x_t, t, x_src) |
| loss = F.mse_loss(pred, noise) |
| self.optimizer.zero_grad() |
| loss.backward() |
| self.optimizer.step() |
| return loss.item() |
| |
| @torch.no_grad() |
| def sample(self, x_src, steps=None): |
| if steps is None: steps = min(self.T, 100) |
| self.denoiser.eval() |
| n = x_src.shape[0] |
| x = torch.randn(n, self.d, device=DEV) |
| step_size = self.T // steps |
| for t_idx in reversed(range(0, self.T, step_size)): |
| t = torch.full((n,), t_idx, device=DEV, dtype=torch.long) |
| pred_noise = self.denoiser(x, t, x_src) |
| alpha = self.schedule.alphas[t_idx] |
| alpha_bar = self.schedule.alpha_bars[t_idx] |
| beta = self.schedule.betas[t_idx] |
| if t_idx > 0: |
| noise = torch.randn_like(x) |
| x = (1.0/torch.sqrt(alpha)) * ( |
| x - (beta/torch.sqrt(1.0-alpha_bar)) * pred_noise |
| ) + torch.sqrt(beta) * noise |
| else: |
| x = (1.0/torch.sqrt(alpha)) * ( |
| x - (beta/torch.sqrt(1.0-alpha_bar)) * pred_noise |
| ) |
| self.denoiser.train() |
| return x |
| |
| def save(self, path): |
| torch.save({'denoiser': self.denoiser.state_dict(), |
| 'd': self.d, 'h': self.h, 'T': self.T}, path) |
| |
| @classmethod |
| def load(cls, path): |
| state = torch.load(path, map_location=DEV) |
| model = cls(d=state['d'], h=state['h'], T=state['T']) |
| model.denoiser.load_state_dict(state['denoiser']) |
| model.denoiser.to(DEV) |
| return model |
|
|
| def train_idea1_synth(train_fine, train_coarse, test_fine, test_coarse, |
| epochs=200, batch_size=256): |
| """ |
| Idea 1: Detail-Spectrum Imagination |
| - Train conditional DDPM on (train_fine → train_coarse) to learn LoD transformation |
| - Generate cross-LoD views for train buildings (conditioned on train_fine) |
| - Interpolate: tau*src + (1-tau)*generated = intermediate detail levels |
| - Train InfoNCE encoder on (original, interpolated) pairs |
| """ |
| print(f"Idea 1: Detail-Spectrum Imagination ({len(train_fine)} pairs)") |
| |
| print(" Training conditional DDPM (fine→coarse)...") |
| cddpm = ConditionalDDPM(d=train_fine.shape[1]) |
| N_train = len(train_fine) |
| for ep in range(300): |
| perm = torch.randperm(N_train) |
| ep_loss = 0 |
| n_batches = 0 |
| for start in range(0, N_train, batch_size): |
| idx = perm[start:start+batch_size] |
| src = torch.tensor(train_fine[idx], dtype=torch.float32).to(DEV) |
| tgt = torch.tensor(train_coarse[idx], dtype=torch.float32).to(DEV) |
| ep_loss += cddpm.train_step(src, tgt) |
| n_batches += 1 |
| if ep % 100 == 0: |
| print(f" C-DDPM ep {ep}: loss={ep_loss/max(n_batches,1):.6f}") |
| cddpm.save('saved_model_files/cdiff_synth.pt') |
| |
| |
| print(" Generating detail-spectrum views via C-DDPM...") |
| train_fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV) |
| gen_views = [] |
| for start in range(0, len(train_fine), batch_size): |
| batch = train_fine_t[start:start+batch_size] |
| gen = cddpm.sample(batch) |
| gen_views.append(gen.cpu().numpy()) |
| gen_views = np.vstack(gen_views) |
| |
| |
| combined_a, combined_b = [], [] |
| for tau in [0.3, 0.7]: |
| interpolated = tau * train_fine[:len(gen_views)] + (1 - tau) * gen_views |
| combined_a.append(train_fine[:len(gen_views)]) |
| combined_b.append(interpolated) |
| |
| combined_a = np.vstack(combined_a) |
| combined_b = np.vstack(combined_b) |
| print(f" Combined: {len(combined_a)} pairs (x2 tau levels)") |
| |
| |
| trainer = ContrastiveTrainer(d=train_fine.shape[1]) |
| best_f1 = 0.0 |
| for ep in range(epochs): |
| loss = trainer.train_epoch(combined_a, combined_b, batch_size) |
| if ep % 20 == 0: |
| f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse) |
| print(f" Ep {ep}: loss={loss:.4f}, F1={f1:.4f}") |
| if f1 > best_f1: |
| best_f1 = f1 |
| trainer.save('saved_model_files/enc_synth_i1.pt') |
| |
| return {'encoder_path': 'saved_model_files/enc_synth_i1.pt', |
| 'best_test_f1': best_f1, 'method': 'conditional_ddpm+interpolation'} |
|
|
| |
| |
| |
| class DisentangledVAE(nn.Module): |
| def __init__(self, d=25, id_dim=32, style_dim=64): |
| super().__init__() |
| self.shared = nn.Sequential( |
| nn.Linear(d, 128), nn.ReLU(), |
| nn.Linear(128, 128), nn.ReLU() |
| ) |
| self.id_mu = nn.Linear(128, id_dim) |
| self.id_logvar = nn.Linear(128, id_dim) |
| self.style_mu = nn.Linear(128, style_dim) |
| self.style_logvar = nn.Linear(128, style_dim) |
| self.decoder = nn.Sequential( |
| nn.Linear(id_dim + style_dim, 128), nn.ReLU(), |
| nn.Linear(128, 128), nn.ReLU(), |
| nn.Linear(128, d) |
| ) |
| |
| def encode(self, x): |
| h = self.shared(x) |
| return self.id_mu(h), self.id_logvar(h), self.style_mu(h), self.style_logvar(h) |
| |
| def reparameterize(self, mu, logvar): |
| std = torch.exp(0.5 * logvar) |
| eps = torch.randn_like(std) |
| return mu + eps * std |
| |
| def decode(self, z_id, z_style): |
| return self.decoder(torch.cat([z_id, z_style], dim=-1)) |
| |
| def forward(self, x): |
| im, il, sm, sl = self.encode(x) |
| z_id = self.reparameterize(im, il) |
| z_style = self.reparameterize(sm, sl) |
| recon = self.decode(z_id, z_style) |
| return recon, im, il, sm, sl, z_id, z_style |
|
|
| def train_idea2_synth(train_fine, train_coarse, test_fine, test_coarse, |
| epochs=200, batch_size=256): |
| """ |
| Idea 2: Identity-Realization Disentanglement |
| - Train VAE on paired (fine, coarse) data |
| - Same building → same identity, different LoD → different style |
| - Generate new views by resampling style |
| """ |
| print(f"Idea 2: Identity-Realization VAE ({len(train_fine)} pairs)") |
| |
| d = train_fine.shape[1] |
| vae = DisentangledVAE(d=d).to(DEV) |
| vae_opt = torch.optim.AdamW(vae.parameters(), lr=3e-4) |
| |
| print(" Training VAE...") |
| N = len(train_fine) |
| for ep in range(500): |
| idx = np.random.permutation(N)[:batch_size] |
| x1 = torch.tensor(train_fine[idx], dtype=torch.float32).to(DEV) |
| x2 = torch.tensor(train_coarse[idx], dtype=torch.float32).to(DEV) |
| |
| recon1, im1, il1, sm1, sl1, zi1, zs1 = vae(x1) |
| recon2, im2, il2, sm2, sl2, zi2, zs2 = vae(x2) |
| |
| recon_loss = F.mse_loss(recon1, x1) + F.mse_loss(recon2, x2) |
| |
| kl_loss = 0 |
| for mu, lv in [(im1, il1), (sm1, sl1), (im2, il2), (sm2, sl2)]: |
| kl_loss += (-0.5 * (1 + lv - mu.pow(2) - lv.exp()).sum(-1)).mean() |
| |
| id_cons_loss = F.mse_loss(zi1, zi2) |
| total_loss = recon_loss + 0.0001 * kl_loss + 0.05 * id_cons_loss |
| |
| vae_opt.zero_grad() |
| total_loss.backward() |
| torch.nn.utils.clip_grad_norm_(vae.parameters(), 1.0) |
| vae_opt.step() |
| |
| if ep % 100 == 0: |
| print(f" VAE ep {ep}: recon={recon_loss:.4f}, kl={kl_loss:.4f}, id={id_cons_loss:.4f}") |
| |
| |
| print(" Generating style-augmented views...") |
| train_fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV) |
| gen_views = [] |
| with torch.no_grad(): |
| for start in range(0, len(train_fine), batch_size): |
| batch = train_fine_t[start:start+batch_size] |
| _, im, _, _, _, _, _ = vae(batch) |
| zi = vae.reparameterize(im, torch.zeros_like(im)) |
| for _ in range(3): |
| zs = torch.randn(len(batch), 64).to(DEV) * 0.5 |
| gen_views.append(vae.decode(zi, zs).cpu().numpy()) |
| gen_views = np.vstack(gen_views) |
| anchors = np.tile(train_fine, (3, 1))[:len(gen_views)] |
| print(f" Generated {len(gen_views)} style-augmented views") |
| |
| |
| trainer = ContrastiveTrainer(d=d) |
| best_f1 = 0.0 |
| for ep in range(epochs): |
| loss = trainer.train_epoch(anchors, gen_views, batch_size) |
| if ep % 20 == 0: |
| f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse) |
| print(f" Ep {ep}: loss={loss:.4f}, F1={f1:.4f}") |
| if f1 > best_f1: |
| best_f1 = f1 |
| trainer.save('saved_model_files/enc_synth_i2.pt') |
| |
| torch.save({'vae': vae.state_dict()}, 'saved_model_files/vae_synth.pt') |
| return {'encoder_path': 'saved_model_files/enc_synth_i2.pt', |
| 'best_test_f1': best_f1, 'method': 'vae+style_sampling'} |
|
|
| |
| |
| |
| def train_idea3_synth(train_fine, train_coarse, test_fine, test_coarse, |
| epochs=200, batch_size=256): |
| """Train on (fine, coarse) cross-LoD pairs directly.""" |
| print(f"Idea 3 (Synth): Direct training on {len(train_fine)} cross-LoD pairs") |
| trainer = ContrastiveTrainer() |
| best_f1 = 0.0 |
| for ep in range(epochs): |
| loss = trainer.train_epoch(train_fine, train_coarse, batch_size) |
| if ep % 20 == 0: |
| f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse) |
| print(f" Ep {ep}: loss={loss:.4f}, test F1={f1:.4f}") |
| if f1 > best_f1: |
| best_f1 = f1 |
| trainer.save('saved_model_files/enc_synth_i3.pt') |
| return {'encoder_path': 'saved_model_files/enc_synth_i3.pt', |
| 'best_test_f1': best_f1} |
|
|
| |
| |
| |
| def train_idea3_ddpm_synth(train_fine, train_coarse, test_fine, test_coarse, |
| epochs=200, batch_size=256, t0=200): |
| """Train DDPM on fine props, generate siblings, combine with cross-LoD pairs.""" |
| print(f"Idea 3+DDPM: SDEdit t0={t0}") |
| bsd = min(batch_size, 256) |
| |
| ddpm = DDPM(d=train_fine.shape[1]) |
| all_props_t = torch.tensor(np.vstack([train_fine, train_coarse]), dtype=torch.float32).to(DEV) |
| N_all = all_props_t.shape[0] |
| |
| print(" Training DDPM...") |
| for ep in range(300): |
| perm = torch.randperm(N_all) |
| ep_loss = 0 |
| n_batches = 0 |
| for start in range(0, N_all, bsd): |
| batch = all_props_t[perm[start:start+bsd]] |
| ep_loss += ddpm.train_step(batch) |
| n_batches += 1 |
| if ep % 100 == 0: |
| print(f" DDPM ep {ep}: loss={ep_loss/max(n_batches,1):.6f}") |
| |
| print(" Generating SDEdit siblings...") |
| fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV) |
| sibs = [] |
| for start in range(0, len(train_fine), bsd): |
| batch = fine_t[start:start+bsd] |
| sib = ddpm.sdedit(batch, t0=t0) |
| sibs.append(sib.cpu().numpy()) |
| sibs = np.vstack(sibs) |
| |
| combined_a = np.vstack([train_fine, train_fine[:len(sibs)]]) |
| combined_b = np.vstack([train_coarse, sibs]) |
| print(f" Combined: {len(combined_a)} pairs ({len(train_fine)} cross-LoD + {len(sibs)} SDEdit)") |
| |
| trainer = ContrastiveTrainer() |
| best_f1 = 0.0 |
| for ep in range(epochs): |
| loss = trainer.train_epoch(combined_a, combined_b, batch_size) |
| if ep % 20 == 0: |
| f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse) |
| print(f" Ep {ep}: loss={loss:.4f}, F1={f1:.4f}") |
| if f1 > best_f1: |
| best_f1 = f1 |
| trainer.save(f'saved_model_files/enc_synth_i3p_t{t0}.pt') |
| |
| ddpm.save(f'saved_model_files/diff_synth.pt') |
| return {'encoder_path': f'saved_model_files/enc_synth_i3p_t{t0}.pt', |
| 'best_test_f1': best_f1, 't0': t0} |
|
|
| |
| |
| |
| def train_idea4_synth(train_fine, train_coarse, test_fine, test_coarse, |
| epochs=200, batch_size=256, t0=200, keep_frac=0.5): |
| """ |
| Idea 4: Grammar Score Guard |
| - Train DDPM → generate SDEdit siblings → score by DDPM → filter |
| """ |
| print(f"Idea 4: Grammar Guard, t0={t0}, keep={keep_frac}") |
| bsd = min(batch_size, 256) |
| |
| ddpm = DDPM(d=train_fine.shape[1]) |
| all_props_t = torch.tensor(np.vstack([train_fine, train_coarse]), dtype=torch.float32).to(DEV) |
| N_all = all_props_t.shape[0] |
| |
| print(" Training DDPM...") |
| for ep in range(300): |
| perm = torch.randperm(N_all) |
| ep_loss = 0 |
| n_batches = 0 |
| for start in range(0, N_all, bsd): |
| batch = all_props_t[perm[start:start+bsd]] |
| ep_loss += ddpm.train_step(batch) |
| n_batches += 1 |
| if ep % 100 == 0: |
| print(f" DDPM ep {ep}: loss={ep_loss/max(n_batches,1):.6f}") |
| |
| print(" Generating SDEdit siblings...") |
| fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV) |
| sibs = [] |
| for start in range(0, len(train_fine), bsd): |
| batch = fine_t[start:start+bsd] |
| sib = ddpm.sdedit(batch, t0=t0) |
| sibs.append(sib.cpu().numpy()) |
| sibs = np.vstack(sibs) |
| |
| print(" Scoring siblings...") |
| sibs_t = torch.tensor(sibs, dtype=torch.float32).to(DEV) |
| scores = ddpm.score(sibs_t) |
| mean_score = scores.mean(dim=-1).cpu().numpy() |
| |
| n_keep = int(len(mean_score) * keep_frac) |
| keep_idx = np.argsort(mean_score)[:n_keep] |
| print(f" Kept {n_keep}/{len(mean_score)} (score {mean_score.min():.3f}-{mean_score.max():.3f})") |
| |
| filtered_origs = train_fine[keep_idx] |
| filtered_sibs = sibs[keep_idx] |
| |
| trainer = ContrastiveTrainer() |
| best_f1 = 0.0 |
| for ep in range(epochs): |
| loss = trainer.train_epoch(filtered_origs, filtered_sibs, batch_size) |
| if ep % 20 == 0: |
| f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse) |
| print(f" Ep {ep}: loss={loss:.4f}, F1={f1:.4f}") |
| if f1 > best_f1: |
| best_f1 = f1 |
| trainer.save(f'saved_model_files/enc_synth_i4_t{t0}_k{keep_frac}.pt') |
| |
| return {'encoder_path': f'saved_model_files/enc_synth_i4_t{t0}_k{keep_frac}.pt', |
| 'best_test_f1': best_f1, 'n_kept': n_keep, 't0': t0, 'keep_frac': keep_frac} |
|
|
| |
| |
| |
| def train_idea5_synth(train_fine, train_coarse, test_fine, test_coarse, |
| epochs=100, batch_size=256, rounds=3): |
| """ |
| Idea 5: Adversarial Hard-Positive |
| - Progressive rounds with increasing SDEdit difficulty (t0=100,200,300) |
| """ |
| print(f"Idea 5: Adversarial Hard-Positive, rounds={rounds}") |
| bsd = min(batch_size, 256) |
| |
| ddpm = DDPM(d=train_fine.shape[1]) |
| all_props_t = torch.tensor(np.vstack([train_fine, train_coarse]), dtype=torch.float32).to(DEV) |
| N_all = all_props_t.shape[0] |
| |
| print(" Training DDPM...") |
| for ep in range(300): |
| perm = torch.randperm(N_all) |
| ep_loss = 0 |
| n_batches = 0 |
| for start in range(0, N_all, bsd): |
| batch = all_props_t[perm[start:start+bsd]] |
| ep_loss += ddpm.train_step(batch) |
| n_batches += 1 |
| if ep % 100 == 0: |
| print(f" DDPM ep {ep}: loss={ep_loss/max(n_batches,1):.6f}") |
| |
| trainer = ContrastiveTrainer() |
| best_f1_overall = 0.0 |
| best_round = 0 |
| |
| for r in range(rounds): |
| t0 = 100 + r * 100 |
| print(f"\n --- Round {r+1}/{rounds} (t0={t0}) ---") |
| |
| fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV) |
| sibs = [] |
| for start in range(0, len(train_fine), bsd): |
| batch = fine_t[start:start+bsd] |
| sib = ddpm.sdedit(batch, t0=t0) |
| sibs.append(sib.cpu().numpy()) |
| sibs = np.vstack(sibs) |
| |
| for ep in range(epochs): |
| loss = trainer.train_epoch(train_fine, sibs, batch_size) |
| if ep % 20 == 0: |
| f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse) |
| print(f" Ep {ep}: loss={loss:.4f}, F1={f1:.4f}") |
| if f1 > best_f1_overall: |
| best_f1_overall = f1 |
| best_round = r + 1 |
| trainer.save('saved_model_files/enc_synth_i5.pt') |
| |
| return {'encoder_path': 'saved_model_files/enc_synth_i5.pt', |
| 'best_test_f1': best_f1_overall, 'best_round': best_round, 'rounds': rounds} |
|
|
| |
| |
| |
| def train_idea6_synth(train_fine, train_coarse, test_fine, test_coarse, |
| epochs=200, batch_size=256, knn=5): |
| """ |
| Idea 6: Cross-Building Transformation Transfer |
| - Learn (fine→coarse) delta vectors from train pairs |
| - For each train building, find k nearest neighbors' deltas → average |
| - Apply averaged delta to create synthetic views |
| """ |
| print(f"Idea 6: Cross-Building Transform, k={knn}") |
| from sklearn.neighbors import NearestNeighbors |
| |
| deltas = train_coarse - train_fine |
| print(f" Delta stats: mean_norm={np.linalg.norm(deltas.mean(axis=0)):.3f}, std_norm={np.linalg.norm(deltas.std(axis=0)):.3f}") |
| |
| nn = NearestNeighbors(n_neighbors=min(knn+1, len(train_fine)), metric='cosine') |
| nn.fit(train_fine) |
| |
| dist, idx = nn.kneighbors(train_fine) |
| |
| avg_deltas = np.zeros_like(train_fine) |
| for i in range(len(train_fine)): |
| neighbor_idx = idx[i][idx[i] != i][:knn] |
| if len(neighbor_idx) > 0: |
| avg_deltas[i] = deltas[neighbor_idx].mean(axis=0) |
| else: |
| avg_deltas[i] = deltas[i] |
| |
| synthetic_views = train_fine + avg_deltas |
| print(f" Generated {len(synthetic_views)} cross-building views") |
| |
| trainer = ContrastiveTrainer() |
| best_f1 = 0.0 |
| for ep in range(epochs): |
| loss = trainer.train_epoch(train_fine, synthetic_views, batch_size) |
| if ep % 20 == 0: |
| f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse) |
| print(f" Ep {ep}: loss={loss:.4f}, F1={f1:.4f}") |
| if f1 > best_f1: |
| best_f1 = f1 |
| trainer.save(f'saved_model_files/enc_synth_i6_k{knn}.pt') |
| |
| return {'encoder_path': f'saved_model_files/enc_synth_i6_k{knn}.pt', |
| 'best_test_f1': best_f1, 'k': knn} |
|
|
| |
| |
| |
| if __name__ == '__main__': |
| parser = argparse.ArgumentParser() |
| parser.add_argument('--idea', type=str, required=True, |
| choices=['1','2','3','3p','4','5','6'], |
| help='Which STER-GI idea to train') |
| parser.add_argument('--epochs', type=int, default=200) |
| parser.add_argument('--batch_size', type=int, default=256) |
| parser.add_argument('--t0', type=int, default=200, help='t0 for SDEdit (Idea 3p,4)') |
| parser.add_argument('--keep_frac', type=float, default=0.5, help='Keep fraction for Idea 4') |
| parser.add_argument('--rounds', type=int, default=3, help='Adversarial rounds for Idea 5') |
| parser.add_argument('--knn', type=int, default=5, help='k for Idea 6') |
| parser.add_argument('--out', type=str, default='experiments/synth_train_results.json') |
| args = parser.parse_args() |
| |
| os.makedirs('saved_model_files', exist_ok=True) |
| os.makedirs('experiments', exist_ok=True) |
| |
| print("Loading and splitting data...") |
| (train_fine, train_coarse), (test_fine, test_coarse, test_ids) = load_and_split_data() |
| |
| bl_f1 = baseline_f1(test_fine, test_coarse) |
| print(f"\nCross-LoD Baseline F1: {bl_f1:.4f}") |
| |
| t0_time = time.time() |
| |
| if os.path.exists(args.out): |
| result = json.load(open(args.out)) |
| else: |
| result = {'baseline_f1': bl_f1} |
| |
| idea_map = { |
| '1': lambda: train_idea1_synth(train_fine, train_coarse, test_fine, test_coarse, |
| epochs=args.epochs, batch_size=args.batch_size), |
| '2': lambda: train_idea2_synth(train_fine, train_coarse, test_fine, test_coarse, |
| epochs=args.epochs, batch_size=args.batch_size), |
| '3': lambda: train_idea3_synth(train_fine, train_coarse, test_fine, test_coarse, |
| epochs=args.epochs, batch_size=args.batch_size), |
| '3p': lambda: train_idea3_ddpm_synth(train_fine, train_coarse, test_fine, test_coarse, |
| epochs=args.epochs, batch_size=args.batch_size, t0=args.t0), |
| '4': lambda: train_idea4_synth(train_fine, train_coarse, test_fine, test_coarse, |
| epochs=args.epochs, batch_size=args.batch_size, |
| t0=args.t0, keep_frac=args.keep_frac), |
| '5': lambda: train_idea5_synth(train_fine, train_coarse, test_fine, test_coarse, |
| epochs=args.epochs, batch_size=args.batch_size, rounds=args.rounds), |
| '6': lambda: train_idea6_synth(train_fine, train_coarse, test_fine, test_coarse, |
| epochs=args.epochs, batch_size=args.batch_size, knn=args.knn), |
| } |
| |
| idea_key = f'idea{args.idea}' |
| res = idea_map[args.idea]() |
| result[idea_key] = res |
| |
| delta = res['best_test_f1'] - result.get('baseline_f1', bl_f1) |
| result[idea_key]['delta'] = round(delta, 6) |
| print(f"\nIdea {args.idea}: Best F1={res['best_test_f1']:.4f} (Δ={delta:+.4f})") |
| |
| result['total_time'] = round(time.time() - t0_time, 1) |
| json.dump(result, open(args.out, 'w'), indent=2) |
| print(f"Results saved to {args.out}") |
| print(f"Total time: {result['total_time']:.1f}s") |
|
|