eduzrh commited on
Commit
11ef0bb
·
verified ·
1 Parent(s): d27ef69

Upload code/ster_train_synth.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. code/ster_train_synth.py +777 -0
code/ster_train_synth.py ADDED
@@ -0,0 +1,777 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ STER-GI: Train ALL 6 ideas on synthetic cross-LoD data.
3
+ Uses aggressive noise model to simulate LoD1.2 ↔ LoD2.2 differences.
4
+
5
+ Baseline: F1≈0.66 (raw cosine, cross-LoD)
6
+ Target: F1≥0.80 (+20%)
7
+
8
+ Usage:
9
+ python ster_train_synth.py --idea 3 --epochs 200
10
+ python ster_train_synth.py --idea 3p --epochs 200 --t0 200
11
+ python ster_train_synth.py --idea 1 --epochs 200
12
+ python ster_train_synth.py --idea 2 --epochs 200
13
+ python ster_train_synth.py --idea 4 --epochs 200 --t0 200 --keep_frac 0.5
14
+ python ster_train_synth.py --idea 5 --epochs 100 --rounds 3
15
+ python ster_train_synth.py --idea 6 --epochs 200 --knn 5
16
+ """
17
+ import os, sys, json, time, argparse
18
+ import numpy as np
19
+ from collections import OrderedDict
20
+ import warnings
21
+ warnings.filterwarnings('ignore')
22
+
23
+ import torch, torch.nn as nn, torch.nn.functional as F
24
+ import joblib
25
+ from ddpm import DDPM, BetaSchedule
26
+
27
+ DEV = 'cuda' if torch.cuda.is_available() else 'cpu'
28
+ print(f"Device: {DEV}")
29
+ torch.set_num_threads(1)
30
+ import os as _os
31
+ _os.environ['OMP_NUM_THREADS'] = '1'
32
+ _os.environ['MKL_NUM_THREADS'] = '1'
33
+
34
+ PROP_NAMES = ["bounding_box_width", "bounding_box_length", "area", "perimeter",
35
+ "perimeter_ind", "volume", "convex_hull_area", "convex_hull_volume",
36
+ "ave_centroid_distance", "height_diff", "num_floors", "axes_symmetry",
37
+ "compactness_2d", "compactness_3d", "density", "elongation", "shape_ind",
38
+ "hemisphericality", "fractality", "cubeness", "circumference",
39
+ "aligned_bounding_box_width", "aligned_bounding_box_length",
40
+ "aligned_bounding_box_height", "num_vertices"]
41
+
42
+ # ============================================================
43
+ # Encoder (25→128→128→64, L2-normalized output)
44
+ # ============================================================
45
+ class Encoder(nn.Module):
46
+ def __init__(self, d=25, h=128, o=64):
47
+ super().__init__()
48
+ self.net = nn.Sequential(OrderedDict([
49
+ ('0', nn.Linear(d, h)), ('1', nn.BatchNorm1d(h)), ('2', nn.ReLU()),
50
+ ('3', nn.Linear(h, h)), ('4', nn.BatchNorm1d(h)), ('5', nn.ReLU()),
51
+ ('6', nn.Linear(h, o))
52
+ ]))
53
+ def forward(self, x):
54
+ z = self.net(x)
55
+ return z / (torch.norm(z, dim=-1, keepdim=True).clamp(min=1e-8))
56
+
57
+ # ============================================================
58
+ # InfoNCE Loss
59
+ # ============================================================
60
+ def infonce_loss(z_a, z_b, tau=0.1):
61
+ B = z_a.shape[0]
62
+ z_a = F.normalize(z_a, dim=-1)
63
+ z_b = F.normalize(z_b, dim=-1)
64
+ sim = torch.mm(z_a, z_b.T) / tau
65
+ labels = torch.arange(B, device=z_a.device)
66
+ return (F.cross_entropy(sim, labels) + F.cross_entropy(sim.T, labels)) / 2
67
+
68
+ # ============================================================
69
+ # Data: Aggressive LoD Noise
70
+ # ============================================================
71
+ def aggressive_lod_noise(props, seed=42):
72
+ """Simulate LoD1.2 → LoD2.2 transformation."""
73
+ rng = np.random.RandomState(seed)
74
+ p = props.copy().astype(np.float64)
75
+ N, D = p.shape
76
+ for j, pn in enumerate(PROP_NAMES):
77
+ if pn in ['volume', 'convex_hull_volume']:
78
+ p[:, j] *= rng.uniform(0.3, 3.0, N)
79
+ elif pn in ['area', 'convex_hull_area', 'perimeter', 'circumference']:
80
+ p[:, j] *= rng.uniform(0.5, 2.0, N)
81
+ elif pn in ['height_diff', 'aligned_bounding_box_height']:
82
+ p[:, j] += rng.randn(N) * 5.0
83
+ p[:, j] = np.maximum(0.1, p[:, j])
84
+ elif pn == 'num_vertices':
85
+ p[:, j] *= rng.uniform(0.3, 0.8, N)
86
+ elif pn == 'num_floors':
87
+ p[:, j] += rng.randint(-2, 3, N).astype(np.float64)
88
+ p[:, j] = np.maximum(1, p[:, j])
89
+ else:
90
+ p[:, j] *= rng.uniform(0.5, 1.5, N)
91
+ p += rng.randn(N, D) * 0.1
92
+ return p.astype(np.float32)
93
+
94
+ def load_and_split_data():
95
+ """Load all building properties, split into train/test, apply LoD noise."""
96
+ all_mats, all_ids = [], []
97
+ for suf in ['Hague_allmodels_v1_train_matching_medium_neg_samples_num=2_vector_normalization=True_seed=1',
98
+ 'Hague_allmodels_v1_test_matching_medium_neg_samples_num=2_vector_normalization=True_seed=1']:
99
+ pdict = joblib.load(f'data/property_dicts/{suf}.joblib')
100
+ for side in ['cands', 'index']:
101
+ ids = list(pdict[PROP_NAMES[0]][side].keys())
102
+ mat = np.zeros((len(ids), len(PROP_NAMES)), dtype=np.float32)
103
+ for j, pn in enumerate(PROP_NAMES):
104
+ for i, bid in enumerate(ids):
105
+ val = pdict[pn][side].get(bid)
106
+ if val is not None:
107
+ mat[i, j] = float(val)
108
+ mat = np.nan_to_num(mat, nan=0.0, posinf=1e6, neginf=-1e6)
109
+ all_mats.append(mat)
110
+ all_ids.extend(ids)
111
+
112
+ X = np.vstack(all_mats)
113
+ N = len(X)
114
+ rng = np.random.RandomState(42)
115
+ perm = rng.permutation(N)
116
+ n_train = int(N * 0.6)
117
+ train_props = X[perm[:n_train]]
118
+ test_props = X[perm[n_train:]]
119
+ test_ids = [all_ids[i] for i in perm[n_train:]]
120
+
121
+ train_coarse = aggressive_lod_noise(train_props, seed=1)
122
+ test_coarse = aggressive_lod_noise(test_props, seed=123)
123
+
124
+ # Z-score standardize (fit on train only)
125
+ all_cat = np.vstack([train_props, train_coarse])
126
+ mean = all_cat.mean(axis=0, keepdims=True)
127
+ std = all_cat.std(axis=0, keepdims=True)
128
+ std[std < 1e-8] = 1.0
129
+
130
+ train_fine_n = (train_props - mean) / std
131
+ train_coarse_n = (train_coarse - mean) / std
132
+ test_fine_n = (test_props - mean) / std
133
+ test_coarse_n = (test_coarse - mean) / std
134
+
135
+ print(f"Train: {len(train_fine_n)} pairs, Test: {len(test_fine_n)} pairs")
136
+ return (train_fine_n, train_coarse_n), (test_fine_n, test_coarse_n, test_ids)
137
+
138
+
139
+ # ============================================================
140
+ # Contrastive Trainer
141
+ # ============================================================
142
+ class ContrastiveTrainer:
143
+ def __init__(self, d=25, h=128, o=64, lr=3e-4, tau=0.1):
144
+ self.encoder = Encoder(d, h, o).to(DEV)
145
+ self.optimizer = torch.optim.AdamW(self.encoder.parameters(), lr=lr, weight_decay=1e-5)
146
+ self.tau = tau
147
+
148
+ def train_epoch(self, pairs_a, pairs_b, batch_size=256):
149
+ N = len(pairs_a)
150
+ idx = np.random.permutation(N)
151
+ total_loss = 0
152
+ n_batches = 0
153
+ for start in range(0, N, batch_size):
154
+ batch_idx = idx[start:start+batch_size]
155
+ ba = torch.tensor(pairs_a[batch_idx], dtype=torch.float32).to(DEV)
156
+ bb = torch.tensor(pairs_b[batch_idx], dtype=torch.float32).to(DEV)
157
+ z_a = self.encoder(ba)
158
+ z_b = self.encoder(bb)
159
+ loss = infonce_loss(z_a, z_b, self.tau)
160
+ self.optimizer.zero_grad()
161
+ loss.backward()
162
+ self.optimizer.step()
163
+ total_loss += loss.item()
164
+ n_batches += 1
165
+ return total_loss / max(n_batches, 1)
166
+
167
+ def save(self, path):
168
+ torch.save({'e': self.encoder.state_dict()}, path)
169
+
170
+ # ============================================================
171
+ # Evaluation
172
+ # ============================================================
173
+ def evaluate_encoder(enc, test_fine, test_coarse):
174
+ fine_t = torch.tensor(test_fine, dtype=torch.float32).to(DEV)
175
+ coarse_t = torch.tensor(test_coarse, dtype=torch.float32).to(DEV)
176
+ N = len(test_fine)
177
+ bs = 512
178
+ emb_fine, emb_coarse = [], []
179
+ with torch.no_grad():
180
+ for start in range(0, N, bs):
181
+ emb_fine.append(enc(fine_t[start:start+bs]).cpu().numpy())
182
+ emb_coarse.append(enc(coarse_t[start:start+bs]).cpu().numpy())
183
+ emb_fine = np.vstack(emb_fine)
184
+ emb_coarse = np.vstack(emb_coarse)
185
+ pos_sims = np.sum(emb_fine * emb_coarse, axis=1)
186
+ rng = np.random.RandomState(42)
187
+ neg_idx = rng.permutation(N)
188
+ neg_sims = np.sum(emb_fine * emb_coarse[neg_idx], axis=1)
189
+ all_sims = np.concatenate([pos_sims, neg_sims])
190
+ all_labels = np.concatenate([np.ones(N, dtype=np.int32), np.zeros(N, dtype=np.int32)])
191
+ best_f1 = 0.0
192
+ for t in np.linspace(0.1, 0.999, 100):
193
+ pred = (all_sims >= t).astype(np.int32)
194
+ tp = float(((pred == 1) & (all_labels == 1)).sum())
195
+ fp = float(((pred == 1) & (all_labels == 0)).sum())
196
+ fn = float(((pred == 0) & (all_labels == 1)).sum())
197
+ p = tp / (tp + fp + 1e-9)
198
+ r = tp / (tp + fn + 1e-9)
199
+ f1 = 2.0 * p * r / (p + r + 1e-9)
200
+ if f1 > best_f1: best_f1 = f1
201
+ return float(best_f1)
202
+
203
+ def baseline_f1(test_fine, test_coarse):
204
+ fn = test_fine / (np.linalg.norm(test_fine, axis=1, keepdims=True) + 1e-8)
205
+ cn = test_coarse / (np.linalg.norm(test_coarse, axis=1, keepdims=True) + 1e-8)
206
+ pos = np.sum(fn * cn, axis=1)
207
+ rng = np.random.RandomState(42)
208
+ neg_idx = rng.permutation(len(cn))
209
+ neg = np.sum(fn * cn[neg_idx], axis=1)
210
+ all_sims = np.concatenate([pos, neg])
211
+ all_labels = np.concatenate([np.ones(len(pos), dtype=np.int32), np.zeros(len(neg), dtype=np.int32)])
212
+ best_f1 = 0.0
213
+ for t in np.linspace(0.1, 0.999, 100):
214
+ pred = (all_sims >= t).astype(np.int32)
215
+ tp = float(((pred == 1) & (all_labels == 1)).sum())
216
+ fp = float(((pred == 1) & (all_labels == 0)).sum())
217
+ fn = float(((pred == 0) & (all_labels == 1)).sum())
218
+ p = tp / (tp + fp + 1e-9)
219
+ r = tp / (tp + fn + 1e-9)
220
+ f1 = 2.0 * p * r / (p + r + 1e-9)
221
+ if f1 > best_f1: best_f1 = f1
222
+ return float(best_f1)
223
+
224
+ # ============================================================
225
+ # Idea 1: Detail-Spectrum Imagination (Conditional Diffusion)
226
+ # ============================================================
227
+ class ConditionalDenoiser(nn.Module):
228
+ def __init__(self, d=25, h=256, T=1000):
229
+ super().__init__()
230
+ self.t_emb = nn.Embedding(T, h)
231
+ self.net = nn.Sequential(OrderedDict([
232
+ ('in', nn.Linear(d + d + h, h)),
233
+ ('n1', nn.LayerNorm(h)), ('a1', nn.SiLU()),
234
+ ('h1', nn.Linear(h, h)),
235
+ ('n2', nn.LayerNorm(h)), ('a2', nn.SiLU()),
236
+ ('h2', nn.Linear(h, h)),
237
+ ('n3', nn.LayerNorm(h)), ('a3', nn.SiLU()),
238
+ ('out', nn.Linear(h, d)),
239
+ ]))
240
+ def forward(self, x, t, condition):
241
+ te = self.t_emb(t)
242
+ return self.net(torch.cat([x, condition, te], dim=-1))
243
+
244
+ class ConditionalDDPM:
245
+ def __init__(self, d=25, h=256, T=1000):
246
+ self.d, self.h, self.T = d, h, T
247
+ self.schedule = BetaSchedule(T)
248
+ self.denoiser = ConditionalDenoiser(d, h, T).to(DEV)
249
+ self.optimizer = torch.optim.AdamW(self.denoiser.parameters(), lr=3e-4)
250
+
251
+ def train_step(self, x_src, x_tgt):
252
+ B = x_tgt.shape[0]
253
+ t = torch.randint(0, self.T, (B,), device=DEV)
254
+ x_t, noise = self.schedule.forward_diffuse(x_tgt, t)
255
+ pred = self.denoiser(x_t, t, x_src)
256
+ loss = F.mse_loss(pred, noise)
257
+ self.optimizer.zero_grad()
258
+ loss.backward()
259
+ self.optimizer.step()
260
+ return loss.item()
261
+
262
+ @torch.no_grad()
263
+ def sample(self, x_src, steps=None):
264
+ if steps is None: steps = min(self.T, 100)
265
+ self.denoiser.eval()
266
+ n = x_src.shape[0]
267
+ x = torch.randn(n, self.d, device=DEV)
268
+ step_size = self.T // steps
269
+ for t_idx in reversed(range(0, self.T, step_size)):
270
+ t = torch.full((n,), t_idx, device=DEV, dtype=torch.long)
271
+ pred_noise = self.denoiser(x, t, x_src)
272
+ alpha = self.schedule.alphas[t_idx]
273
+ alpha_bar = self.schedule.alpha_bars[t_idx]
274
+ beta = self.schedule.betas[t_idx]
275
+ if t_idx > 0:
276
+ noise = torch.randn_like(x)
277
+ x = (1.0/torch.sqrt(alpha)) * (
278
+ x - (beta/torch.sqrt(1.0-alpha_bar)) * pred_noise
279
+ ) + torch.sqrt(beta) * noise
280
+ else:
281
+ x = (1.0/torch.sqrt(alpha)) * (
282
+ x - (beta/torch.sqrt(1.0-alpha_bar)) * pred_noise
283
+ )
284
+ self.denoiser.train()
285
+ return x
286
+
287
+ def save(self, path):
288
+ torch.save({'denoiser': self.denoiser.state_dict(),
289
+ 'd': self.d, 'h': self.h, 'T': self.T}, path)
290
+
291
+ @classmethod
292
+ def load(cls, path):
293
+ state = torch.load(path, map_location=DEV)
294
+ model = cls(d=state['d'], h=state['h'], T=state['T'])
295
+ model.denoiser.load_state_dict(state['denoiser'])
296
+ model.denoiser.to(DEV)
297
+ return model
298
+
299
+ def train_idea1_synth(train_fine, train_coarse, test_fine, test_coarse,
300
+ epochs=200, batch_size=256):
301
+ """
302
+ Idea 1: Detail-Spectrum Imagination
303
+ - Train conditional DDPM on (train_fine → train_coarse) to learn LoD transformation
304
+ - Generate cross-LoD views for train buildings (conditioned on train_fine)
305
+ - Interpolate: tau*src + (1-tau)*generated = intermediate detail levels
306
+ - Train InfoNCE encoder on (original, interpolated) pairs
307
+ """
308
+ print(f"Idea 1: Detail-Spectrum Imagination ({len(train_fine)} pairs)")
309
+
310
+ print(" Training conditional DDPM (fine→coarse)...")
311
+ cddpm = ConditionalDDPM(d=train_fine.shape[1])
312
+ N_train = len(train_fine)
313
+ for ep in range(300):
314
+ perm = torch.randperm(N_train)
315
+ ep_loss = 0
316
+ n_batches = 0
317
+ for start in range(0, N_train, batch_size):
318
+ idx = perm[start:start+batch_size]
319
+ src = torch.tensor(train_fine[idx], dtype=torch.float32).to(DEV)
320
+ tgt = torch.tensor(train_coarse[idx], dtype=torch.float32).to(DEV)
321
+ ep_loss += cddpm.train_step(src, tgt)
322
+ n_batches += 1
323
+ if ep % 100 == 0:
324
+ print(f" C-DDPM ep {ep}: loss={ep_loss/max(n_batches,1):.6f}")
325
+ cddpm.save('saved_model_files/cdiff_synth.pt')
326
+
327
+ # Generate coarse-detail views for all train buildings
328
+ print(" Generating detail-spectrum views via C-DDPM...")
329
+ train_fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV)
330
+ gen_views = []
331
+ for start in range(0, len(train_fine), batch_size):
332
+ batch = train_fine_t[start:start+batch_size]
333
+ gen = cddpm.sample(batch)
334
+ gen_views.append(gen.cpu().numpy())
335
+ gen_views = np.vstack(gen_views)
336
+
337
+ # Create interpolated views at multiple tau levels
338
+ combined_a, combined_b = [], []
339
+ for tau in [0.3, 0.7]:
340
+ interpolated = tau * train_fine[:len(gen_views)] + (1 - tau) * gen_views
341
+ combined_a.append(train_fine[:len(gen_views)])
342
+ combined_b.append(interpolated)
343
+
344
+ combined_a = np.vstack(combined_a)
345
+ combined_b = np.vstack(combined_b)
346
+ print(f" Combined: {len(combined_a)} pairs (x2 tau levels)")
347
+
348
+ # Train InfoNCE
349
+ trainer = ContrastiveTrainer(d=train_fine.shape[1])
350
+ best_f1 = 0.0
351
+ for ep in range(epochs):
352
+ loss = trainer.train_epoch(combined_a, combined_b, batch_size)
353
+ if ep % 20 == 0:
354
+ f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse)
355
+ print(f" Ep {ep}: loss={loss:.4f}, F1={f1:.4f}")
356
+ if f1 > best_f1:
357
+ best_f1 = f1
358
+ trainer.save('saved_model_files/enc_synth_i1.pt')
359
+
360
+ return {'encoder_path': 'saved_model_files/enc_synth_i1.pt',
361
+ 'best_test_f1': best_f1, 'method': 'conditional_ddpm+interpolation'}
362
+
363
+ # ============================================================
364
+ # Idea 2: Identity-Realization Disentanglement (VAE)
365
+ # ============================================================
366
+ class DisentangledVAE(nn.Module):
367
+ def __init__(self, d=25, id_dim=32, style_dim=64):
368
+ super().__init__()
369
+ self.shared = nn.Sequential(
370
+ nn.Linear(d, 128), nn.ReLU(),
371
+ nn.Linear(128, 128), nn.ReLU()
372
+ )
373
+ self.id_mu = nn.Linear(128, id_dim)
374
+ self.id_logvar = nn.Linear(128, id_dim)
375
+ self.style_mu = nn.Linear(128, style_dim)
376
+ self.style_logvar = nn.Linear(128, style_dim)
377
+ self.decoder = nn.Sequential(
378
+ nn.Linear(id_dim + style_dim, 128), nn.ReLU(),
379
+ nn.Linear(128, 128), nn.ReLU(),
380
+ nn.Linear(128, d)
381
+ )
382
+
383
+ def encode(self, x):
384
+ h = self.shared(x)
385
+ return self.id_mu(h), self.id_logvar(h), self.style_mu(h), self.style_logvar(h)
386
+
387
+ def reparameterize(self, mu, logvar):
388
+ std = torch.exp(0.5 * logvar)
389
+ eps = torch.randn_like(std)
390
+ return mu + eps * std
391
+
392
+ def decode(self, z_id, z_style):
393
+ return self.decoder(torch.cat([z_id, z_style], dim=-1))
394
+
395
+ def forward(self, x):
396
+ im, il, sm, sl = self.encode(x)
397
+ z_id = self.reparameterize(im, il)
398
+ z_style = self.reparameterize(sm, sl)
399
+ recon = self.decode(z_id, z_style)
400
+ return recon, im, il, sm, sl, z_id, z_style
401
+
402
+ def train_idea2_synth(train_fine, train_coarse, test_fine, test_coarse,
403
+ epochs=200, batch_size=256):
404
+ """
405
+ Idea 2: Identity-Realization Disentanglement
406
+ - Train VAE on paired (fine, coarse) data
407
+ - Same building → same identity, different LoD → different style
408
+ - Generate new views by resampling style
409
+ """
410
+ print(f"Idea 2: Identity-Realization VAE ({len(train_fine)} pairs)")
411
+
412
+ d = train_fine.shape[1]
413
+ vae = DisentangledVAE(d=d).to(DEV)
414
+ vae_opt = torch.optim.AdamW(vae.parameters(), lr=3e-4)
415
+
416
+ print(" Training VAE...")
417
+ N = len(train_fine)
418
+ for ep in range(500):
419
+ idx = np.random.permutation(N)[:batch_size]
420
+ x1 = torch.tensor(train_fine[idx], dtype=torch.float32).to(DEV)
421
+ x2 = torch.tensor(train_coarse[idx], dtype=torch.float32).to(DEV)
422
+
423
+ recon1, im1, il1, sm1, sl1, zi1, zs1 = vae(x1)
424
+ recon2, im2, il2, sm2, sl2, zi2, zs2 = vae(x2)
425
+
426
+ recon_loss = F.mse_loss(recon1, x1) + F.mse_loss(recon2, x2)
427
+
428
+ kl_loss = 0
429
+ for mu, lv in [(im1, il1), (sm1, sl1), (im2, il2), (sm2, sl2)]:
430
+ kl_loss += (-0.5 * (1 + lv - mu.pow(2) - lv.exp()).sum(-1)).mean()
431
+
432
+ id_cons_loss = F.mse_loss(zi1, zi2)
433
+ total_loss = recon_loss + 0.0001 * kl_loss + 0.05 * id_cons_loss
434
+
435
+ vae_opt.zero_grad()
436
+ total_loss.backward()
437
+ torch.nn.utils.clip_grad_norm_(vae.parameters(), 1.0)
438
+ vae_opt.step()
439
+
440
+ if ep % 100 == 0:
441
+ print(f" VAE ep {ep}: recon={recon_loss:.4f}, kl={kl_loss:.4f}, id={id_cons_loss:.4f}")
442
+
443
+ # Generate style-augmented views
444
+ print(" Generating style-augmented views...")
445
+ train_fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV)
446
+ gen_views = []
447
+ with torch.no_grad():
448
+ for start in range(0, len(train_fine), batch_size):
449
+ batch = train_fine_t[start:start+batch_size]
450
+ _, im, _, _, _, _, _ = vae(batch)
451
+ zi = vae.reparameterize(im, torch.zeros_like(im))
452
+ for _ in range(3):
453
+ zs = torch.randn(len(batch), 64).to(DEV) * 0.5
454
+ gen_views.append(vae.decode(zi, zs).cpu().numpy())
455
+ gen_views = np.vstack(gen_views)
456
+ anchors = np.tile(train_fine, (3, 1))[:len(gen_views)]
457
+ print(f" Generated {len(gen_views)} style-augmented views")
458
+
459
+ # Train InfoNCE
460
+ trainer = ContrastiveTrainer(d=d)
461
+ best_f1 = 0.0
462
+ for ep in range(epochs):
463
+ loss = trainer.train_epoch(anchors, gen_views, batch_size)
464
+ if ep % 20 == 0:
465
+ f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse)
466
+ print(f" Ep {ep}: loss={loss:.4f}, F1={f1:.4f}")
467
+ if f1 > best_f1:
468
+ best_f1 = f1
469
+ trainer.save('saved_model_files/enc_synth_i2.pt')
470
+
471
+ torch.save({'vae': vae.state_dict()}, 'saved_model_files/vae_synth.pt')
472
+ return {'encoder_path': 'saved_model_files/enc_synth_i2.pt',
473
+ 'best_test_f1': best_f1, 'method': 'vae+style_sampling'}
474
+
475
+ # ============================================================
476
+ # Idea 3: Denoise-to-Sibling (Direct InfoNCE on cross-LoD pairs)
477
+ # ============================================================
478
+ def train_idea3_synth(train_fine, train_coarse, test_fine, test_coarse,
479
+ epochs=200, batch_size=256):
480
+ """Train on (fine, coarse) cross-LoD pairs directly."""
481
+ print(f"Idea 3 (Synth): Direct training on {len(train_fine)} cross-LoD pairs")
482
+ trainer = ContrastiveTrainer()
483
+ best_f1 = 0.0
484
+ for ep in range(epochs):
485
+ loss = trainer.train_epoch(train_fine, train_coarse, batch_size)
486
+ if ep % 20 == 0:
487
+ f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse)
488
+ print(f" Ep {ep}: loss={loss:.4f}, test F1={f1:.4f}")
489
+ if f1 > best_f1:
490
+ best_f1 = f1
491
+ trainer.save('saved_model_files/enc_synth_i3.pt')
492
+ return {'encoder_path': 'saved_model_files/enc_synth_i3.pt',
493
+ 'best_test_f1': best_f1}
494
+
495
+ # ============================================================
496
+ # Idea 3+: SDEdit augmentation (DDPM → siblings → contrastive)
497
+ # ============================================================
498
+ def train_idea3_ddpm_synth(train_fine, train_coarse, test_fine, test_coarse,
499
+ epochs=200, batch_size=256, t0=200):
500
+ """Train DDPM on fine props, generate siblings, combine with cross-LoD pairs."""
501
+ print(f"Idea 3+DDPM: SDEdit t0={t0}")
502
+ bsd = min(batch_size, 256)
503
+
504
+ ddpm = DDPM(d=train_fine.shape[1])
505
+ all_props_t = torch.tensor(np.vstack([train_fine, train_coarse]), dtype=torch.float32).to(DEV)
506
+ N_all = all_props_t.shape[0]
507
+
508
+ print(" Training DDPM...")
509
+ for ep in range(300):
510
+ perm = torch.randperm(N_all)
511
+ ep_loss = 0
512
+ n_batches = 0
513
+ for start in range(0, N_all, bsd):
514
+ batch = all_props_t[perm[start:start+bsd]]
515
+ ep_loss += ddpm.train_step(batch)
516
+ n_batches += 1
517
+ if ep % 100 == 0:
518
+ print(f" DDPM ep {ep}: loss={ep_loss/max(n_batches,1):.6f}")
519
+
520
+ print(" Generating SDEdit siblings...")
521
+ fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV)
522
+ sibs = []
523
+ for start in range(0, len(train_fine), bsd):
524
+ batch = fine_t[start:start+bsd]
525
+ sib = ddpm.sdedit(batch, t0=t0)
526
+ sibs.append(sib.cpu().numpy())
527
+ sibs = np.vstack(sibs)
528
+
529
+ combined_a = np.vstack([train_fine, train_fine[:len(sibs)]])
530
+ combined_b = np.vstack([train_coarse, sibs])
531
+ print(f" Combined: {len(combined_a)} pairs ({len(train_fine)} cross-LoD + {len(sibs)} SDEdit)")
532
+
533
+ trainer = ContrastiveTrainer()
534
+ best_f1 = 0.0
535
+ for ep in range(epochs):
536
+ loss = trainer.train_epoch(combined_a, combined_b, batch_size)
537
+ if ep % 20 == 0:
538
+ f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse)
539
+ print(f" Ep {ep}: loss={loss:.4f}, F1={f1:.4f}")
540
+ if f1 > best_f1:
541
+ best_f1 = f1
542
+ trainer.save(f'saved_model_files/enc_synth_i3p_t{t0}.pt')
543
+
544
+ ddpm.save(f'saved_model_files/diff_synth.pt')
545
+ return {'encoder_path': f'saved_model_files/enc_synth_i3p_t{t0}.pt',
546
+ 'best_test_f1': best_f1, 't0': t0}
547
+
548
+ # ============================================================
549
+ # Idea 4: Grammar Score Guard (DDPM score filter)
550
+ # ============================================================
551
+ def train_idea4_synth(train_fine, train_coarse, test_fine, test_coarse,
552
+ epochs=200, batch_size=256, t0=200, keep_frac=0.5):
553
+ """
554
+ Idea 4: Grammar Score Guard
555
+ - Train DDPM → generate SDEdit siblings → score by DDPM → filter
556
+ """
557
+ print(f"Idea 4: Grammar Guard, t0={t0}, keep={keep_frac}")
558
+ bsd = min(batch_size, 256)
559
+
560
+ ddpm = DDPM(d=train_fine.shape[1])
561
+ all_props_t = torch.tensor(np.vstack([train_fine, train_coarse]), dtype=torch.float32).to(DEV)
562
+ N_all = all_props_t.shape[0]
563
+
564
+ print(" Training DDPM...")
565
+ for ep in range(300):
566
+ perm = torch.randperm(N_all)
567
+ ep_loss = 0
568
+ n_batches = 0
569
+ for start in range(0, N_all, bsd):
570
+ batch = all_props_t[perm[start:start+bsd]]
571
+ ep_loss += ddpm.train_step(batch)
572
+ n_batches += 1
573
+ if ep % 100 == 0:
574
+ print(f" DDPM ep {ep}: loss={ep_loss/max(n_batches,1):.6f}")
575
+
576
+ print(" Generating SDEdit siblings...")
577
+ fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV)
578
+ sibs = []
579
+ for start in range(0, len(train_fine), bsd):
580
+ batch = fine_t[start:start+bsd]
581
+ sib = ddpm.sdedit(batch, t0=t0)
582
+ sibs.append(sib.cpu().numpy())
583
+ sibs = np.vstack(sibs)
584
+
585
+ print(" Scoring siblings...")
586
+ sibs_t = torch.tensor(sibs, dtype=torch.float32).to(DEV)
587
+ scores = ddpm.score(sibs_t) # (N, 5 time scales)
588
+ mean_score = scores.mean(dim=-1).cpu().numpy()
589
+
590
+ n_keep = int(len(mean_score) * keep_frac)
591
+ keep_idx = np.argsort(mean_score)[:n_keep]
592
+ print(f" Kept {n_keep}/{len(mean_score)} (score {mean_score.min():.3f}-{mean_score.max():.3f})")
593
+
594
+ filtered_origs = train_fine[keep_idx]
595
+ filtered_sibs = sibs[keep_idx]
596
+
597
+ trainer = ContrastiveTrainer()
598
+ best_f1 = 0.0
599
+ for ep in range(epochs):
600
+ loss = trainer.train_epoch(filtered_origs, filtered_sibs, batch_size)
601
+ if ep % 20 == 0:
602
+ f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse)
603
+ print(f" Ep {ep}: loss={loss:.4f}, F1={f1:.4f}")
604
+ if f1 > best_f1:
605
+ best_f1 = f1
606
+ trainer.save(f'saved_model_files/enc_synth_i4_t{t0}_k{keep_frac}.pt')
607
+
608
+ return {'encoder_path': f'saved_model_files/enc_synth_i4_t{t0}_k{keep_frac}.pt',
609
+ 'best_test_f1': best_f1, 'n_kept': n_keep, 't0': t0, 'keep_frac': keep_frac}
610
+
611
+ # ============================================================
612
+ # Idea 5: Adversarial Hard-Positive
613
+ # ============================================================
614
+ def train_idea5_synth(train_fine, train_coarse, test_fine, test_coarse,
615
+ epochs=100, batch_size=256, rounds=3):
616
+ """
617
+ Idea 5: Adversarial Hard-Positive
618
+ - Progressive rounds with increasing SDEdit difficulty (t0=100,200,300)
619
+ """
620
+ print(f"Idea 5: Adversarial Hard-Positive, rounds={rounds}")
621
+ bsd = min(batch_size, 256)
622
+
623
+ ddpm = DDPM(d=train_fine.shape[1])
624
+ all_props_t = torch.tensor(np.vstack([train_fine, train_coarse]), dtype=torch.float32).to(DEV)
625
+ N_all = all_props_t.shape[0]
626
+
627
+ print(" Training DDPM...")
628
+ for ep in range(300):
629
+ perm = torch.randperm(N_all)
630
+ ep_loss = 0
631
+ n_batches = 0
632
+ for start in range(0, N_all, bsd):
633
+ batch = all_props_t[perm[start:start+bsd]]
634
+ ep_loss += ddpm.train_step(batch)
635
+ n_batches += 1
636
+ if ep % 100 == 0:
637
+ print(f" DDPM ep {ep}: loss={ep_loss/max(n_batches,1):.6f}")
638
+
639
+ trainer = ContrastiveTrainer()
640
+ best_f1_overall = 0.0
641
+ best_round = 0
642
+
643
+ for r in range(rounds):
644
+ t0 = 100 + r * 100
645
+ print(f"\n --- Round {r+1}/{rounds} (t0={t0}) ---")
646
+
647
+ fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV)
648
+ sibs = []
649
+ for start in range(0, len(train_fine), bsd):
650
+ batch = fine_t[start:start+bsd]
651
+ sib = ddpm.sdedit(batch, t0=t0)
652
+ sibs.append(sib.cpu().numpy())
653
+ sibs = np.vstack(sibs)
654
+
655
+ for ep in range(epochs):
656
+ loss = trainer.train_epoch(train_fine, sibs, batch_size)
657
+ if ep % 20 == 0:
658
+ f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse)
659
+ print(f" Ep {ep}: loss={loss:.4f}, F1={f1:.4f}")
660
+ if f1 > best_f1_overall:
661
+ best_f1_overall = f1
662
+ best_round = r + 1
663
+ trainer.save('saved_model_files/enc_synth_i5.pt')
664
+
665
+ return {'encoder_path': 'saved_model_files/enc_synth_i5.pt',
666
+ 'best_test_f1': best_f1_overall, 'best_round': best_round, 'rounds': rounds}
667
+
668
+ # ============================================================
669
+ # Idea 6: Cross-Building Transformation Transfer
670
+ # ============================================================
671
+ def train_idea6_synth(train_fine, train_coarse, test_fine, test_coarse,
672
+ epochs=200, batch_size=256, knn=5):
673
+ """
674
+ Idea 6: Cross-Building Transformation Transfer
675
+ - Learn (fine→coarse) delta vectors from train pairs
676
+ - For each train building, find k nearest neighbors' deltas → average
677
+ - Apply averaged delta to create synthetic views
678
+ """
679
+ print(f"Idea 6: Cross-Building Transform, k={knn}")
680
+ from sklearn.neighbors import NearestNeighbors
681
+
682
+ deltas = train_coarse - train_fine # (N_train, 25)
683
+ print(f" Delta stats: mean_norm={np.linalg.norm(deltas.mean(axis=0)):.3f}, std_norm={np.linalg.norm(deltas.std(axis=0)):.3f}")
684
+
685
+ nn = NearestNeighbors(n_neighbors=min(knn+1, len(train_fine)), metric='cosine')
686
+ nn.fit(train_fine)
687
+
688
+ dist, idx = nn.kneighbors(train_fine)
689
+
690
+ avg_deltas = np.zeros_like(train_fine)
691
+ for i in range(len(train_fine)):
692
+ neighbor_idx = idx[i][idx[i] != i][:knn]
693
+ if len(neighbor_idx) > 0:
694
+ avg_deltas[i] = deltas[neighbor_idx].mean(axis=0)
695
+ else:
696
+ avg_deltas[i] = deltas[i]
697
+
698
+ synthetic_views = train_fine + avg_deltas
699
+ print(f" Generated {len(synthetic_views)} cross-building views")
700
+
701
+ trainer = ContrastiveTrainer()
702
+ best_f1 = 0.0
703
+ for ep in range(epochs):
704
+ loss = trainer.train_epoch(train_fine, synthetic_views, batch_size)
705
+ if ep % 20 == 0:
706
+ f1 = evaluate_encoder(trainer.encoder, test_fine, test_coarse)
707
+ print(f" Ep {ep}: loss={loss:.4f}, F1={f1:.4f}")
708
+ if f1 > best_f1:
709
+ best_f1 = f1
710
+ trainer.save(f'saved_model_files/enc_synth_i6_k{knn}.pt')
711
+
712
+ return {'encoder_path': f'saved_model_files/enc_synth_i6_k{knn}.pt',
713
+ 'best_test_f1': best_f1, 'k': knn}
714
+
715
+ # ============================================================
716
+ # Main
717
+ # ============================================================
718
+ if __name__ == '__main__':
719
+ parser = argparse.ArgumentParser()
720
+ parser.add_argument('--idea', type=str, required=True,
721
+ choices=['1','2','3','3p','4','5','6'],
722
+ help='Which STER-GI idea to train')
723
+ parser.add_argument('--epochs', type=int, default=200)
724
+ parser.add_argument('--batch_size', type=int, default=256)
725
+ parser.add_argument('--t0', type=int, default=200, help='t0 for SDEdit (Idea 3p,4)')
726
+ parser.add_argument('--keep_frac', type=float, default=0.5, help='Keep fraction for Idea 4')
727
+ parser.add_argument('--rounds', type=int, default=3, help='Adversarial rounds for Idea 5')
728
+ parser.add_argument('--knn', type=int, default=5, help='k for Idea 6')
729
+ parser.add_argument('--out', type=str, default='experiments/synth_train_results.json')
730
+ args = parser.parse_args()
731
+
732
+ os.makedirs('saved_model_files', exist_ok=True)
733
+ os.makedirs('experiments', exist_ok=True)
734
+
735
+ print("Loading and splitting data...")
736
+ (train_fine, train_coarse), (test_fine, test_coarse, test_ids) = load_and_split_data()
737
+
738
+ bl_f1 = baseline_f1(test_fine, test_coarse)
739
+ print(f"\nCross-LoD Baseline F1: {bl_f1:.4f}")
740
+
741
+ t0_time = time.time()
742
+
743
+ if os.path.exists(args.out):
744
+ result = json.load(open(args.out))
745
+ else:
746
+ result = {'baseline_f1': bl_f1}
747
+
748
+ idea_map = {
749
+ '1': lambda: train_idea1_synth(train_fine, train_coarse, test_fine, test_coarse,
750
+ epochs=args.epochs, batch_size=args.batch_size),
751
+ '2': lambda: train_idea2_synth(train_fine, train_coarse, test_fine, test_coarse,
752
+ epochs=args.epochs, batch_size=args.batch_size),
753
+ '3': lambda: train_idea3_synth(train_fine, train_coarse, test_fine, test_coarse,
754
+ epochs=args.epochs, batch_size=args.batch_size),
755
+ '3p': lambda: train_idea3_ddpm_synth(train_fine, train_coarse, test_fine, test_coarse,
756
+ epochs=args.epochs, batch_size=args.batch_size, t0=args.t0),
757
+ '4': lambda: train_idea4_synth(train_fine, train_coarse, test_fine, test_coarse,
758
+ epochs=args.epochs, batch_size=args.batch_size,
759
+ t0=args.t0, keep_frac=args.keep_frac),
760
+ '5': lambda: train_idea5_synth(train_fine, train_coarse, test_fine, test_coarse,
761
+ epochs=args.epochs, batch_size=args.batch_size, rounds=args.rounds),
762
+ '6': lambda: train_idea6_synth(train_fine, train_coarse, test_fine, test_coarse,
763
+ epochs=args.epochs, batch_size=args.batch_size, knn=args.knn),
764
+ }
765
+
766
+ idea_key = f'idea{args.idea}'
767
+ res = idea_map[args.idea]()
768
+ result[idea_key] = res
769
+
770
+ delta = res['best_test_f1'] - result.get('baseline_f1', bl_f1)
771
+ result[idea_key]['delta'] = round(delta, 6)
772
+ print(f"\nIdea {args.idea}: Best F1={res['best_test_f1']:.4f} (Δ={delta:+.4f})")
773
+
774
+ result['total_time'] = round(time.time() - t0_time, 1)
775
+ json.dump(result, open(args.out, 'w'), indent=2)
776
+ print(f"Results saved to {args.out}")
777
+ print(f"Total time: {result['total_time']:.1f}s")