| |
| """ |
| STER — NS-D2S Experiment Runner (Multi-City, GPU-optimized). |
| |
| Runs the complete NS-D2S pipeline on any city benchmark: |
| DDPM → CS-SDEdit → InfoNCE Contrastive → Zero-shot Evaluation |
| |
| Usage: |
| python ster_run_v2.py --city rotterdam --data_dir data/rotterdam_test --device cuda |
| """ |
| import argparse, json, os, time |
| import numpy as np |
| import torch, torch.nn as nn, torch.nn.functional as F |
| from torch.utils.data import DataLoader, TensorDataset |
| from ster_constraints import constraint_program |
|
|
| 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", |
| ] |
|
|
| |
| class Denoiser(nn.Module): |
| def __init__(self, d=25, hidden=256): |
| super().__init__() |
| self.time_mlp = nn.Sequential(nn.Linear(1,256), nn.SiLU(), nn.Linear(256,256)) |
| self.net = nn.Sequential( |
| nn.Linear(d+256,hidden), nn.SiLU(), nn.LayerNorm(hidden), |
| nn.Linear(hidden,hidden), nn.SiLU(), nn.LayerNorm(hidden), |
| nn.Linear(hidden,hidden), nn.SiLU(), nn.LayerNorm(hidden), |
| nn.Linear(hidden,d)) |
| def forward(self, x_t, t): |
| te = self.time_mlp(t.float().unsqueeze(-1)/1000.) |
| return self.net(torch.cat([x_t, te], dim=-1)) |
|
|
| |
| class DDPM: |
| def __init__(self, denoiser, T=1000, b1=1e-4, b2=0.02, device='cuda'): |
| self.denoiser = denoiser.to(device) |
| self.T, self.device = T, device |
| self.betas = torch.linspace(b1, b2, T, device=device) |
| self.alphas = 1.-self.betas |
| self.alpha_bars = torch.cumprod(self.alphas, 0) |
|
|
| def diffuse(self, x0, t): |
| ab = self.alpha_bars[t].view(-1,1) |
| eps = torch.randn_like(x0) |
| return torch.sqrt(ab)*x0 + torch.sqrt(1-ab)*eps, eps |
|
|
| @torch.no_grad() |
| def sdedit(self, x0, t0=150, constraint_fn=None, eta=0.01, delta=0.5, S=3): |
| self.denoiser.eval() |
| B = x0.shape[0] |
| ab0 = self.alpha_bars[t0] |
| x_t = torch.sqrt(ab0)*x0 + torch.sqrt(1-ab0)*torch.randn_like(x0) |
|
|
| for t in range(t0, 0, -1): |
| tt = torch.full((B,), t, device=self.device, dtype=torch.long) |
| eps_pred = self.denoiser(x_t, tt) |
| ab = self.alpha_bars[t] |
|
|
| |
| x0_hat = (x_t - torch.sqrt(1-ab)*eps_pred) / (torch.sqrt(ab)+1e-8) |
| x0_orig = x0_hat.clone() |
|
|
| |
| if constraint_fn is not None: |
| x0_hat_ref = x0_hat.clone().detach().requires_grad_(True) |
| for s in range(S): |
| C = constraint_fn(x0_hat_ref) |
| if C.sum() > 0: |
| g = torch.autograd.grad(C.sum(), x0_hat_ref, retain_graph=(s<S-1))[0] |
| x0_hat_ref = x0_hat_ref - eta * g |
| |
| diff = x0_hat_ref - x0_orig |
| n = torch.norm(diff, dim=1, keepdim=True).clamp(min=1e-8) |
| x0_hat_ref = torch.where(n > delta, x0_orig + delta*diff/n, x0_hat_ref) |
| if s < S-1: |
| x0_hat_ref = x0_hat_ref.detach().requires_grad_(True) |
| x0_hat = x0_hat_ref.detach() |
|
|
| |
| eps_eff = (x_t - torch.sqrt(ab)*x0_hat) / (torch.sqrt(1-ab)+1e-8) |
| bt = self.betas[t]; at = self.alphas[t] |
| ab_p = self.alpha_bars[t-1] if t>1 else torch.tensor(1., device=self.device) |
| sigma = torch.sqrt(bt*(1-ab_p)/(1-ab+1e-8)) |
| noise = torch.randn_like(x_t) if t > 1 else 0. |
| x_t = (1/torch.sqrt(at))*(x_t - bt/torch.sqrt(1-ab+1e-8)*eps_eff) + sigma*noise |
|
|
| return x_t |
|
|
| |
| class Encoder(nn.Module): |
| def __init__(self, d=25): |
| super().__init__() |
| self.net = nn.Sequential( |
| nn.Linear(d,128), nn.BatchNorm1d(128), nn.ReLU(), |
| nn.Linear(128,128), nn.BatchNorm1d(128), nn.ReLU(), |
| nn.Linear(128,64)) |
| def forward(self, x): |
| return F.normalize(self.net(x), dim=-1) |
|
|
| |
| def info_nce(za, zb, tau=0.1): |
| za, zb = F.normalize(za,dim=-1), F.normalize(zb,dim=-1) |
| B = za.shape[0]; labels = torch.arange(B, device=za.device) |
| return (F.cross_entropy(za@zb.T/tau, labels) + F.cross_entropy(zb@za.T/tau, labels))/2 |
|
|
| |
| def load_props(path): |
| df = None |
| for ext, loader in [('.parquet', lambda p: __import__('pandas').read_parquet(p)), |
| ('.json', lambda p: __import__('pandas').DataFrame.from_dict( |
| __import__('json').load(open(p)), orient='index'))]: |
| fp = path + ext |
| if os.path.exists(fp): |
| df = loader(fp); break |
| if df is None: raise FileNotFoundError(f"No properties at {path}") |
| X = df[PROPERTY_NAMES].values.astype(np.float32) |
| if X.max() > 100: X = np.log1p(X) |
| return X |
|
|
| |
| def run(city, data_dir, device='cuda', epochs_diff=300, epochs_enc=200, |
| lambda_c=0.05, delta=0.5, t0=150, S=3, eta=0.01, bs=256, lr=3e-4): |
| print(f"\n{'='*60}\n NS-D2S: {city} | device={device}\n{'='*60}") |
|
|
| |
| X = load_props(os.path.join(data_dir, 'properties_lod22')) |
| n = len(X); n_tr = int(0.7*n) |
| np.random.seed(42); idx = np.random.permutation(n) |
| X_tr = torch.tensor(X[idx[:n_tr]], dtype=torch.float32) |
| X_te = torch.tensor(X[idx[n_tr:]], dtype=torch.float32) |
| print(f" Buildings: {n} (train={n_tr}, test={n-n_tr})") |
|
|
| |
| print(f"\n [DDPM] T=1000 λ_C={lambda_c}") |
| dns = Denoiser(); ddpm = DDPM(dns, device=device) |
| opt = torch.optim.AdamW(dns.parameters(), lr=lr, wd=1e-5) |
| dl = DataLoader(TensorDataset(X_tr), batch_size=bs, shuffle=True) |
| t0_t = time.time() |
| for ep in range(epochs_diff): |
| tl = 0. |
| for (x0b,) in dl: |
| x0b = x0b.to(device); B = x0b.shape[0] |
| t = torch.randint(1, ddpm.T, (B,), device=device) |
| xt, eps = ddpm.diffuse(x0b, t) |
| ep_pred = dns(xt, t) |
| L = F.mse_loss(ep_pred, eps) |
| if lambda_c > 0: |
| ab = ddpm.alpha_bars[t].view(-1,1) |
| x0h = (xt - torch.sqrt(1-ab)*ep_pred) / (torch.sqrt(ab)+1e-8) |
| L = L + lambda_c * constraint_program(x0h).mean() |
| opt.zero_grad(); L.backward(); opt.step(); tl += L.item() |
| if (ep+1)%50==0: print(f" ep {ep+1}/{epochs_diff} loss={tl/len(dl):.4f}") |
| dt = time.time()-t0_t; print(f" DDPM done in {dt:.0f}s") |
|
|
| |
| print(f"\n [CS-SDEdit] t0={t0} δ={delta} S={S}") |
| dl2 = DataLoader(TensorDataset(X_te), batch_size=bs, shuffle=False) |
| srcs, sibs = [], [] |
| for (x0b,) in dl2: |
| x0b = x0b.to(device) |
| sib = ddpm.sdedit(x0b, t0=t0, constraint_fn=constraint_program, eta=eta, delta=delta, S=S) |
| srcs.append(x0b.cpu()); sibs.append(sib.cpu()) |
| X_src = torch.cat(srcs); X_sib = torch.cat(sibs) |
| cvr = (constraint_program(X_sib.to(device))>0).float().mean().item() |
| print(f" CVR(sibs)={cvr:.4f}") |
|
|
| |
| print(f"\n [InfoNCE] epochs={epochs_enc} τ=0.1") |
| enc = Encoder().to(device) |
| oe = torch.optim.AdamW(enc.parameters(), lr=lr, wd=1e-5) |
| pl = DataLoader(TensorDataset(X_src, X_sib), batch_size=bs, shuffle=True) |
| for ep in range(epochs_enc): |
| tl=0. |
| for xa,xb in pl: |
| xa,xb = xa.to(device), xb.to(device) |
| L = info_nce(enc(xa), enc(xb)) |
| oe.zero_grad(); L.backward(); oe.step(); tl+=L.item() |
| if (ep+1)%50==0: print(f" ep {ep+1}/{epochs_enc} loss={tl/len(pl):.4f}") |
|
|
| |
| print(f"\n [Eval]") |
| enc.eval() |
| with torch.no_grad(): |
| Nt = min(len(X_src), 2000) |
| it = torch.randperm(len(X_src))[:Nt] |
| pos = (enc(X_src[it].to(device))*enc(X_sib[it].to(device))).sum(-1) |
| ni = torch.randperm(Nt) |
| neg = (enc(X_src[it].to(device))*enc(X_sib[ni].to(device))).sum(-1) |
| sc = torch.cat([pos, neg]); lb = torch.cat([torch.ones(Nt), torch.zeros(Nt)]) |
| best_f1, best_t = 0., 0. |
| tp_opt = fp_opt = fn_opt = 0 |
| for th in np.linspace(0., 1., 200): |
| pr = (sc>=th).float() |
| tp = ((pr==1)&(lb==1)).sum().item(); fp = ((pr==1)&(lb==0)).sum().item() |
| fn = ((pr==0)&(lb==1)).sum().item() |
| p = tp/max(tp+fp,1); r = tp/max(tp+fn,1) |
| f1 = 2*p*r/max(p+r,1e-6) |
| if f1>best_f1: best_f1,best_t = f1,th; tp_opt,fp_opt,fn_opt = tp,fp,fn |
|
|
| res = {"city":city, "n_buildings":n, "n_train":n_tr, "n_test":n-n_tr, |
| "lambda_c":lambda_c, "delta":delta, "t0":t0, "S":S, |
| "cvr":float(cvr), "f1":float(best_f1), |
| "precision":float(tp_opt/max(tp_opt+fp_opt,1)), |
| "recall":float(tp_opt/max(tp_opt+fn_opt,1)), |
| "threshold":float(best_t), "diff_time":dt} |
| print(f" → F1={res['f1']:.4f} P={res['precision']:.4f} R={res['recall']:.4f} CVR={res['cvr']:.4f}") |
|
|
| os.makedirs(os.path.join(data_dir,'results'), exist_ok=True) |
| os.makedirs(os.path.join(data_dir,'models'), exist_ok=True) |
| with open(os.path.join(data_dir,'results','nsd2s.json'),'w') as f: json.dump(res,f,indent=2) |
| torch.save(dns.state_dict(), os.path.join(data_dir,'models','ddpm.pt')) |
| torch.save(enc.state_dict(), os.path.join(data_dir,'models','encoder.pt')) |
| np.savez(os.path.join(data_dir,'results','siblings.npz'), |
| sources=X_src.numpy(), siblings=X_sib.numpy()) |
| print(f" Saved → {data_dir}/results/ + models/") |
| return res |
|
|
| if __name__ == '__main__': |
| ap = argparse.ArgumentParser() |
| ap.add_argument('--city', required=True) |
| ap.add_argument('--data_dir', default=None) |
| ap.add_argument('--device', default='cuda') |
| ap.add_argument('--lambda_c', type=float, default=0.05) |
| ap.add_argument('--delta', type=float, default=0.5) |
| ap.add_argument('--t0', type=int, default=150) |
| ap.add_argument('--S', type=int, default=3) |
| ap.add_argument('--epochs_diff', type=int, default=300) |
| ap.add_argument('--epochs_enc', type=int, default=200) |
| ap.add_argument('--batch_size', type=int, default=256) |
| a = ap.parse_args() |
| dd = a.data_dir or os.path.join('data', a.city) |
| run(a.city, dd, a.device, a.epochs_diff, a.epochs_enc, |
| a.lambda_c, a.delta, a.t0, a.S, batch_size=a.batch_size) |
|
|