| """ |
| STER-WM v3 — World-Model few-shot ER with few-shot ADAPTATION (GPU). |
| |
| Story (unchanged): pretrain a source/realization-invariant identity encoder from FREE |
| 3DBAG multi-LoD self-supervision, then adapt to the harder CityModel<->3DBAG source |
| gap with only K labels. |
| |
| v3 method: after InfoNCE pretraining, FINE-TUNE the encoder on the K labelled Hague |
| pairs with a supervised contrastive loss (pull matched cand-index together, push |
| mismatches apart). This bridges the LoD-gap -> source-gap domain shift with few labels. |
| |
| Reports at K in {5,10,20,50}: |
| bar_raw_bagging baseline |
| wm_pre_cos frozen pretrained encoder, cosine threshold (label-light) |
| wm_ft_cos fine-tuned encoder, cosine threshold |
| wm_ft_hybrid_bagging raw ratio + fine-tuned WM features -> Bagging (main) |
| ablation_ft_from_scratch fine-tune from RANDOM init (no multi-LoD pretraining) |
| """ |
| import os, json, copy, numpy as np, torch, torch.nn as nn, torch.nn.functional as F |
| from sklearn.ensemble import BaggingClassifier |
| from sklearn.preprocessing import StandardScaler |
| from sklearn.metrics import f1_score |
|
|
| NPZ = "/root/ster/data/ster_wm_vectors.npz" |
| OUT = "/root/ster/exp/ster_wm_results.json" |
| DEV = "cuda" if torch.cuda.is_available() else "cpu" |
| D = 32 |
| torch.manual_seed(1); np.random.seed(1) |
|
|
| z = np.load(NPZ, allow_pickle=True) |
| lod12, lod22, candX, indexX = z["lod12_X"], z["lod22_X"], z["cand_X"], z["index_X"] |
| trP, trY, teP, teY = z["train_pairs"], z["train_y"], z["test_pairs"], z["test_y"] |
| print(f"multiLoD={lod12.shape} cand={candX.shape} index={indexX.shape} " |
| f"train={trP.shape}({trY.sum()}+) test={teP.shape}({teY.sum()}+) dev={DEV}", flush=True) |
|
|
| scaler = StandardScaler().fit(np.vstack([lod12, lod22, candX, indexX])) |
| def S(x): return torch.tensor(scaler.transform(x), dtype=torch.float32, device=DEV) |
| L12, L22, CAND, INDEX = S(lod12), S(lod22), S(candX), S(indexX) |
| DIM = lod12.shape[1] |
|
|
|
|
| class Encoder(nn.Module): |
| def __init__(s, din, d=D): |
| super().__init__() |
| s.net = nn.Sequential(nn.Linear(din, 64), nn.GELU(), nn.Linear(64, 64), nn.GELU(), nn.Linear(64, d)) |
| def forward(s, x): return F.normalize(s.net(x), dim=-1) |
|
|
|
|
| def info_nce(za, zb, tau=0.1): |
| lg = za @ zb.t() / tau |
| lab = torch.arange(za.size(0), device=za.device) |
| return 0.5 * (F.cross_entropy(lg, lab) + F.cross_entropy(lg.t(), lab)) |
|
|
|
|
| def pretrain(epochs=400, bs=256, lr=1e-3): |
| enc = Encoder(DIM).to(DEV) |
| opt = torch.optim.Adam(enc.parameters(), lr=lr, weight_decay=1e-5) |
| n = L12.size(0) |
| for ep in range(epochs): |
| perm = torch.randperm(n, device=DEV) |
| for i in range(0, n, bs): |
| idx = perm[i:i + bs] |
| if idx.numel() < 8: continue |
| loss = info_nce(enc(L12[idx]), enc(L22[idx])) |
| opt.zero_grad(); loss.backward(); opt.step() |
| enc.eval(); return enc |
|
|
|
|
| def finetune(base_enc, pos_c, pos_i, steps=150, lr=3e-4): |
| """Supervised contrastive fine-tune on K positive cand-index pairs (in-batch negs).""" |
| enc = copy.deepcopy(base_enc).to(DEV); enc.train() |
| opt = torch.optim.Adam(enc.parameters(), lr=lr, weight_decay=1e-4) |
| a = CAND[pos_c]; b = INDEX[pos_i] |
| if a.size(0) < 2: |
| enc.eval(); return enc |
| for _ in range(steps): |
| loss = info_nce(enc(a), enc(b)) |
| opt.zero_grad(); loss.backward(); opt.step() |
| enc.eval(); return enc |
|
|
|
|
| @torch.no_grad() |
| def embed(enc, X): return enc(X).cpu().numpy() |
|
|
|
|
| def raw_feats(P): |
| a, b = candX[P[:, 0]], indexX[P[:, 1]] |
| with np.errstate(divide='ignore', invalid='ignore'): |
| r = np.where(b != 0, a / b, 1000.0) |
| return np.clip(np.round(r, 3), None, 1000.0) |
|
|
|
|
| def wm_feats(Ec, Ei, P): |
| a, b = Ec[P[:, 0]], Ei[P[:, 1]] |
| cos = np.sum(a * b, 1, keepdims=True) |
| l2 = -np.linalg.norm(a - b, axis=1, keepdims=True) |
| return np.concatenate([cos, l2], 1), cos.ravel() |
|
|
|
|
| print("\nPretraining WM encoder (InfoNCE on multi-LoD)...", flush=True) |
| enc_pre = pretrain() |
| Ec_pre, Ei_pre = embed(enc_pre, CAND), embed(enc_pre, INDEX) |
| _, cos_pre_te = wm_feats(Ec_pre, Ei_pre, teP) |
| _, cos_pre_tr = wm_feats(Ec_pre, Ei_pre, trP) |
| raw_tr, raw_te = raw_feats(trP), raw_feats(teP) |
|
|
| Ks, NDRAW = [5, 10, 20, 50], 15 |
| pos = np.where(trY == 1)[0]; neg = np.where(trY == 0)[0] |
| report = {} |
| for K in Ks: |
| acc = {k: [] for k in ["bar_raw_bagging", "wm_pre_cos", "wm_ft_cos", |
| "wm_ft_hybrid_bagging", "ablation_ft_from_scratch"]} |
| for rep in range(NDRAW): |
| r = np.random.RandomState(300 + rep) |
| pidx = r.choice(pos, K, replace=False); nidx = r.choice(neg, min(2 * K, len(neg)), replace=False) |
| idx = np.concatenate([pidx, nidx]); y = trY[idx] |
| |
| acc["bar_raw_bagging"].append(f1_score(teY, BaggingClassifier(50, random_state=1).fit(raw_tr[idx], y).predict(raw_te), zero_division=0)) |
| |
| thr = np.median([np.quantile(cos_pre_tr[idx][y == 1], .2) if (y == 1).any() else .5, |
| np.quantile(cos_pre_tr[idx][y == 0], .8) if (y == 0).any() else .5]) |
| acc["wm_pre_cos"].append(f1_score(teY, (cos_pre_te >= thr).astype(int), zero_division=0)) |
| |
| pc, pi = trP[pidx][:, 0], trP[pidx][:, 1] |
| enc_ft = finetune(enc_pre, pc, pi) |
| Ec, Ei = embed(enc_ft, CAND), embed(enc_ft, INDEX) |
| wmf_tr, cos_tr = wm_feats(Ec, Ei, trP); wmf_te, cos_te = wm_feats(Ec, Ei, teP) |
| thr2 = np.median([np.quantile(cos_tr[idx][y == 1], .2) if (y == 1).any() else .5, |
| np.quantile(cos_tr[idx][y == 0], .8) if (y == 0).any() else .5]) |
| acc["wm_ft_cos"].append(f1_score(teY, (cos_te >= thr2).astype(int), zero_division=0)) |
| hyb_tr = np.concatenate([raw_tr, wmf_tr], 1); hyb_te = np.concatenate([raw_te, wmf_te], 1) |
| acc["wm_ft_hybrid_bagging"].append(f1_score(teY, BaggingClassifier(50, random_state=1).fit(hyb_tr[idx], y).predict(hyb_te), zero_division=0)) |
| |
| enc_sc = finetune(Encoder(DIM).to(DEV), pc, pi) |
| Esc_c, Esc_i = embed(enc_sc, CAND), embed(enc_sc, INDEX) |
| _, cos_sc_te = wm_feats(Esc_c, Esc_i, teP); _, cos_sc_tr = wm_feats(Esc_c, Esc_i, trP) |
| thr3 = np.median([np.quantile(cos_sc_tr[idx][y == 1], .2) if (y == 1).any() else .5, |
| np.quantile(cos_sc_tr[idx][y == 0], .8) if (y == 0).any() else .5]) |
| acc["ablation_ft_from_scratch"].append(f1_score(teY, (cos_sc_te >= thr3).astype(int), zero_division=0)) |
| report[K] = {k: dict(f1=round(float(np.mean(v)), 4), std=round(float(np.std(v)), 4)) for k, v in acc.items()} |
| print(f"\n=== K={K} ===", flush=True) |
| for k, s in sorted(report[K].items(), key=lambda kv: -kv[1]['f1']): |
| print(f" {k:28s} F1={s['f1']:.4f} ±{s['std']:.4f}", flush=True) |
|
|
| os.makedirs(os.path.dirname(OUT), exist_ok=True) |
| json.dump(report, open(OUT, "w"), indent=2) |
| print("\nSaved ->", OUT, flush=True) |
|
|