File size: 10,816 Bytes
a80391b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | #!/usr/bin/env python3
"""
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",
]
# ─── Denoiser ───
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))
# ─── DDPM ───
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]
# Tweedie estimate of clean sample
x0_hat = (x_t - torch.sqrt(1-ab)*eps_pred) / (torch.sqrt(ab)+1e-8)
x0_orig = x0_hat.clone()
# Constraint-guided refinement
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
# Trust radius
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()
# Reconstruct eps and step
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
# ─── Encoder ───
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)
# ─── InfoNCE ───
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
# ─── Load ───
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) # auto log-normalize
return X
# ─── Main ───
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}")
# 1. Load
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})")
# 2. Train DDPM
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")
# 3. CS-SDEdit
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}")
# 4. Contrastive
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}")
# 5. Eval
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)
|