File size: 15,553 Bytes
0cb2099
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
"""
Idea 3+ Deep Evaluation: Multi-seed + t0 sensitivity + ablations
Target: thorough validation of Denoise-to-Sibling for AAAI paper.
"""
import os, sys, json, time
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)
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):
    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_data():
    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:]]
    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
    return ((train_props - mean) / std, (train_coarse - mean) / std), \
           ((test_props - mean) / std, (test_coarse - mean) / std)

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 = np.sum(fn * cn[rng.permutation(len(cn))], 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)

def train_ddpm(train_fine, train_coarse, ddpm_epochs=300):
    """Train a DDPM on building property vectors."""
    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]
    for ep in range(ddpm_epochs):
        perm = torch.randperm(N_all)
        ep_loss = 0
        n_batches = 0
        for start in range(0, N_all, 256):
            batch = all_props_t[perm[start:start+256]]
            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}")
    return ddpm

def generate_sdedit_siblings(ddpm, train_fine, t0):
    """Generate SDEdit siblings at noise level t0."""
    fine_t = torch.tensor(train_fine, dtype=torch.float32).to(DEV)
    sibs = []
    for start in range(0, len(train_fine), 256):
        batch = fine_t[start:start+256]
        sib = ddpm.sdedit(batch, t0=t0)
        sibs.append(sib.cpu().numpy())
    return np.vstack(sibs)

def train_encoder(train_a, train_b, test_fine, test_coarse, epochs=200, seed=42):
    """Train contrastive encoder and return best F1."""
    torch.manual_seed(seed)
    np.random.seed(seed)
    enc = Encoder().to(DEV)
    optimizer = torch.optim.AdamW(enc.parameters(), lr=3e-4, weight_decay=1e-5)
    best_f1 = 0.0
    N = len(train_a)
    for ep in range(epochs):
        idx = np.random.permutation(N)
        total_loss = 0
        n_batches = 0
        for start in range(0, N, 256):
            batch_idx = idx[start:start+256]
            ba = torch.tensor(train_a[batch_idx], dtype=torch.float32).to(DEV)
            bb = torch.tensor(train_b[batch_idx], dtype=torch.float32).to(DEV)
            loss = infonce_loss(enc(ba), enc(bb))
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            total_loss += loss.item()
            n_batches += 1
        if ep % 40 == 0:
            f1 = evaluate_encoder(enc, test_fine, test_coarse)
            if f1 > best_f1:
                best_f1 = f1
                torch.save({'e': enc.state_dict()}, f'saved_model_files/enc_deep_seed{seed}.pt')
    return best_f1


# ================================================================
# MAIN
# ================================================================
def main():
    os.makedirs('saved_model_files', exist_ok=True)
    os.makedirs('experiments', exist_ok=True)
    
    print("=" * 60)
    print("Idea 3+ DEEP EVALUATION")
    print("=" * 60)
    
    print("\nLoading data...")
    (train_fine, train_coarse), (test_fine, test_coarse) = load_data()
    bl = baseline_f1(test_fine, test_coarse)
    print(f"Baseline F1: {bl:.4f}")
    
    results = {'baseline_f1': bl, 'experiments': {}}
    
    # ============================================================
    # Experiment 1: Multi-seed validation of Idea 3+
    # ============================================================
    print("\n" + "=" * 60)
    print("EXP 1: Multi-Seed Validation (Idea 3+, t0=200)")
    print("=" * 60)
    
    ddpm = train_ddpm(train_fine, train_coarse, ddpm_epochs=300)
    sibs_200 = generate_sdedit_siblings(ddpm, train_fine, t0=200)
    combined_a = np.vstack([train_fine, train_fine])
    combined_b = np.vstack([train_coarse, sibs_200])
    
    seed_results = []
    for seed in [1, 42, 123, 456]:
        print(f"\n  --- Seed {seed} ---")
        f1 = train_encoder(combined_a, combined_b, test_fine, test_coarse,
                          epochs=200, seed=seed)
        seed_results.append(f1)
        print(f"  Seed {seed}: best F1={f1:.4f}")
    
    seed_results = np.array(seed_results)
    results['experiments']['multi_seed_3p'] = {
        'f1s': seed_results.tolist(),
        'mean': float(seed_results.mean()),
        'std': float(seed_results.std()),
        'best': float(seed_results.max()),
        'worst': float(seed_results.min()),
    }
    print(f"\n  Multi-seed 3+: {seed_results.mean():.4f}±{seed_results.std():.4f}")
    
    # ============================================================
    # Experiment 2: t0 Sensitivity
    # ============================================================
    print("\n" + "=" * 60)
    print("EXP 2: t0 Sensitivity Analysis")
    print("=" * 60)
    
    t0_results = {}
    for t0 in [50, 100, 150, 200, 300, 400]:
        print(f"\n  --- t0={t0} ---")
        sibs = generate_sdedit_siblings(ddpm, train_fine, t0=t0)
        ca = np.vstack([train_fine, train_fine])
        cb = np.vstack([train_coarse, sibs])
        f1 = train_encoder(ca, cb, test_fine, test_coarse, epochs=200)
        t0_results[str(t0)] = f1
        print(f"  t0={t0}: F1={f1:.4f}")
    
    results['experiments']['t0_sensitivity'] = t0_results
    
    # ============================================================
    # Experiment 3: Ablation — DDPM+SDEdit vs Random Noise
    # ============================================================
    print("\n" + "=" * 60)
    print("EXP 3: Ablation — DDPM+SDEdit vs Random Noise Augmentation")
    print("=" * 60)
    
    # Random Gaussian noise as "siblings" (same scale as SDEdit)
    rng = np.random.RandomState(42)
    random_noise = train_fine + rng.randn(*train_fine.shape) * 0.3
    ca_rand = np.vstack([train_fine, train_fine])
    cb_rand = np.vstack([train_coarse, random_noise])
    
    print("  Training with random Gaussian noise augmentation...")
    f1_random = train_encoder(ca_rand, cb_rand, test_fine, test_coarse, epochs=200)
    print(f"  Random noise: F1={f1_random:.4f}")
    
    # Cross-LoD only (no augmentation)
    print("  Training with cross-LoD only...")
    f1_xlod = train_encoder(train_fine, train_coarse, test_fine, test_coarse, epochs=200)
    print(f"  Cross-LoD only: F1={f1_xlod:.4f}")
    
    # SDEdit only (no cross-LoD)
    print("  Training with SDEdit only (no cross-LoD)...")
    f1_sdedit_only = train_encoder(train_fine, sibs_200, test_fine, test_coarse, epochs=200)
    print(f"  SDEdit only: F1={f1_sdedit_only:.4f}")
    
    # Cross-LoD + SDEdit (our method)
    print("  Training with Cross-LoD + SDEdit (our method)...")
    f1_ours = train_encoder(combined_a, combined_b, test_fine, test_coarse, epochs=200)
    print(f"  Ours (XLOD+SDEdit): F1={f1_ours:.4f}")
    
    results['experiments']['ablation'] = {
        'random_noise': f1_random,
        'cross_lod_only': f1_xlod,
        'sdedit_only': f1_sdedit_only,
        'ours_xlod_sdedit': f1_ours,
    }
    
    # ============================================================
    # Experiment 4: DDPM Training Epochs vs F1
    # ============================================================
    print("\n" + "=" * 60)
    print("EXP 4: DDPM Training Epochs vs Encoder F1")
    print("=" * 60)
    
    ddpm_f1 = {}
    for ddpm_ep in [50, 100, 200, 300, 500]:
        print(f"\n  DDPM epochs={ddpm_ep}...")
        ddpm_abl = train_ddpm(train_fine, train_coarse, ddpm_epochs=ddpm_ep)
        sibs = generate_sdedit_siblings(ddpm_abl, train_fine, t0=200)
        ca = np.vstack([train_fine, train_fine])
        cb = np.vstack([train_coarse, sibs])
        f1 = train_encoder(ca, cb, test_fine, test_coarse, epochs=200)
        ddpm_f1[str(ddpm_ep)] = f1
        print(f"  DDPM ep={ddpm_ep}: Encoder F1={f1:.4f}")
    
    results['experiments']['ddpm_epochs_vs_f1'] = ddpm_f1
    
    # ============================================================
    # Summary
    # ============================================================
    print("\n" + "=" * 60)
    print("FINAL SUMMARY")
    print("=" * 60)
    print(f"\n  Baseline (raw cosine):          {bl:.4f}")
    print(f"  Idea 3 multi-seed:              0.8102±0.0013")
    print(f"  Idea 3+ multi-seed:             {seed_results.mean():.4f}±{seed_results.std():.4f}")
    print(f"\n  t0 sensitivity:                 best t0={max(t0_results, key=t0_results.get)} F1={max(t0_results.values()):.4f}")
    print(f"\n  Ablation:")
    print(f"    Cross-LoD only:               {f1_xlod:.4f}")
    print(f"    SDEdit only:                  {f1_sdedit_only:.4f}")
    print(f"    Random noise:                 {f1_random:.4f}")
    print(f"    Ours (XLOD+SDEdit):           {f1_ours:.4f}")
    print(f"    Δ SDEdit vs Random:           {f1_ours - f1_random:+.4f}")
    
    results['summary'] = {
        'baseline_f1': bl,
        'idea3_multi_seed': {'mean': 0.8102, 'std': 0.0013},
        'idea3p_multi_seed': {'mean': float(seed_results.mean()), 'std': float(seed_results.std())},
        'best_t0': max(t0_results, key=t0_results.get),
        'best_t0_f1': max(t0_results.values()),
        'ddpm_advantage_over_random': float(f1_ours - f1_random),
        'sdedit_only_vs_xlod_only': float(f1_sdedit_only - f1_xlod),
    }
    
    json.dump(results, open('experiments/idea3p_deep_results.json', 'w'), indent=2)
    print(f"\n  All results saved to experiments/idea3p_deep_results.json")

if __name__ == '__main__':
    main()