File size: 19,415 Bytes
7215ff1 9bd8b44 7215ff1 | 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 | r"""
train_v3.py — AtmosIQ v3.1 training. Architecture FROZEN (model.py verbatim). Protocol pins:
TP-1 full pruned-graph training (mean-degree assert in dataset_v3; sampler deleted)
TP-2 ORPHAN masking in finetune (p_orphan labeled nodes: Group A blackout all T,
completeness->0, labels still supervised -> gradient must route via neighbors)
TP-3 physics losses ON by default (lam_phys=0.05)
TP-4 loud guards: per-epoch skip-rate; > max_skip -> hard ABORT
TP-5 coordinate jitter in finetune (Gaussian on projection_x/y, sigma=0.1 std ~15-25km):
kills exact-position lookup shortcut while keeping coarse positional signal
P0-1 stride-sampled val/probe-eval days (season-balanced, deterministic)
P0-2 finetune val on train+val graph ONLY (test nodes never context for model selection);
probe EVAL stays full-graph per SSL_ROADMAP §7 pin (held-out nodes must be present)
Stages: pretrain -> probe (raw-space R², branch suggestion, PROVISIONAL until refs.json
space confirmed) -> finetune (early stop on season-balanced val NLL).
Checkpoints: <tensors>/../encoder_v3.pt , atmosiq_v3_best.pt , train_state_v3.json
Run: python data/models_v3/train_v3.py --tensors data/tensors --stage all
"""
from __future__ import annotations
import os, sys, json, argparse, pathlib, time
import numpy as np, torch, torch.nn as nn, torch.nn.functional as F
torch.set_num_threads(os.cpu_count() or 8)
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from model import AtmosIQNet, student_t_nll, ssl_recon_loss
from dataset_v3 import AtmosDataV3, ssl_mask, recon_from_groups, recon_masked
POLL = ["pm2_5", "pm10", "no2", "so2", "co", "o3", "nh3"]
COORD_IDX = (1, 2) # static_num layout: [elevation, proj_x, proj_y, d_hwy, d_ind, +4 yearly]
def stride(days, k):
"""Season-balanced deterministic subset: every len/k-th day (P0-1)."""
if not k or k >= len(days): return list(days)
s = max(1, len(days) // k)
return list(days)[::s][:k]
def grads_finite(net):
for p in net.parameters():
if p.grad is not None and not torch.isfinite(p.grad).all(): return False
return True
def build_model(meta, dev):
n_recon = 9 + meta["dimsB"] + meta["dimsC_static"] + meta["dimsC_yearly"]
cfg = {"calendar_num_dim": meta["dimsD_num"], "n_recon_channels": n_recon,
"categorical": {"land_use_class": 4, "grap_stage": 3,
"n_landuse": meta["n_landuse"], "n_grap": meta["n_grap"]}}
return AtmosIQNet(cfg).to(dev), cfg
def epoch_guard(name, skips, steps, max_skip):
rate = skips / max(steps, 1)
print(f" [{name}] skip_rate={rate:.1%} ({skips}/{steps})", flush=True)
if rate > max_skip:
raise SystemExit(f"ABORT TP-4: {name} skip-rate {rate:.1%} > {max_skip:.0%} — "
f"numerics broke; fix before continuing (no zombie runs).")
def jitter_coords(groups_t, sigma):
"""TP-5: one noise draw per window (static must not wiggle per day), finetune only."""
if sigma <= 0: return groups_t
N = groups_t[0]["static_num"].shape[0]; dev = groups_t[0]["static_num"].device
noise = torch.randn(N, len(COORD_IDX), device=dev) * sigma
out = []
for g in groups_t:
g2 = dict(g); s = g2["static_num"].clone()
s[:, COORD_IDX[0]] += noise[:, 0]; s[:, COORD_IDX[1]] += noise[:, 1]
g2["static_num"] = s; out.append(g2)
return out
def smoothness(net, b, gm, h_seq):
"""§3 with detached anchor (P1-4, memory): gradient flows through the perturbed
branch only — pulls h(x+delta) toward h(x). Recorded deviation from symmetric form."""
noisy = [{k: (v + 0.1 * torch.randn_like(v) if k in ("satellite", "meteorology", "static_num", "calendar_num") else v)
for k, v in g.items()} for g in b["groups_t"]]
h2 = net.encode(noisy, b["ei"], b["e_hat"], b["n_hat"], b["wu"], b["wv"], b["blh"], gm)
return ((h_seq.detach() - h2) ** 2).mean()
# ---------------------------------------------------------------- pretrain
def pretrain(data, net, a, dev, tv):
opt = torch.optim.AdamW(net.parameters(), lr=a.lr, weight_decay=1e-4)
days = list(range(data.w - 1, data.D))
for ep in range(a.ssl_epochs):
net.train(); np.random.shuffle(days); tot = 0; n_ok = 0; skips = 0; t0 = time.time()
used = days[:a.days_per_epoch] if a.days_per_epoch else days
for i, t in enumerate(used):
b = data.window(t, tv)
gm = ssl_mask(b["groups_t"])
h_seq = net.encode(b["groups_t"], b["ei"], b["e_hat"], b["n_hat"], b["wu"], b["wv"], b["blh"], gm)
recon = net.recon(h_seq)
tgt, obs = recon_from_groups(b["groups_t"])
L_rec = ssl_recon_loss(recon, tgt, recon_masked(gm) * obs)
loss = L_rec
if a.lam_smooth > 0 and (i % a.smooth_every == 0):
loss = loss + a.lam_smooth * smoothness(net, b, gm, h_seq)
opt.zero_grad()
if not torch.isfinite(loss): skips += 1; continue
loss.backward()
if not grads_finite(net): opt.zero_grad(); skips += 1; continue
torch.nn.utils.clip_grad_norm_(net.parameters(), 5.0)
opt.step(); tot += L_rec.item(); n_ok += 1
if (i + 1) % a.log_every == 0:
print(f" [SSL {ep+1}] {i+1}/{len(used)} recon={tot/max(n_ok,1):.4f} "
f"{(time.time()-t0)/(i+1):.2f}s/it", flush=True)
print(f"[SSL {ep+1}/{a.ssl_epochs}] recon_mse={tot/max(n_ok,1):.4f} {time.time()-t0:.0f}s", flush=True)
epoch_guard(f"SSL {ep+1}", skips, len(used), a.max_skip)
ck = pathlib.Path(a.tensors).parent / "encoder_v3.pt"
torch.save(net.state_dict(), ck); print(f"-> {ck}")
# ---------------------------------------------------------------- probe (§7)
def probe(data, net, meta, a, dev, tv):
ck = pathlib.Path(a.tensors).parent / "encoder_v3.pt"
if ck.exists():
net.load_state_dict(torch.load(ck, map_location=dev)); print("loaded encoder_v3.pt")
for p in net.parameters(): p.requires_grad = False
net.eval()
nz = np.load(pathlib.Path(a.tensors) / "norm.npz")
ylm = torch.tensor(nz["y_logmean"]).float().to(dev)
yls = torch.tensor(nz["y_logstd"]).float().to(dev)
lin = nn.Linear(meta.get("d_model", 96), 7).to(dev)
opt = torch.optim.Adam(lin.parameters(), lr=1e-2)
tr_days = data.target_days(0)
tr_node_mask = (data.split[tv["nodes"]] == 0).float().unsqueeze(-1).to(dev)
for ep in range(a.probe_epochs):
np.random.shuffle(tr_days); tot = 0; t0 = time.time(); dd = tr_days[:a.probe_days]
for i, t in enumerate(dd):
b = data.window(t, tv) # PRUNED train graph (probe trains here)
with torch.no_grad():
z = net.encode(b["groups_t"], b["ei"], b["e_hat"], b["n_hat"], b["wu"], b["wv"], b["blh"])[:, -1]
pred = lin(z)
yl = (torch.log(b["y"][:, 0, :].clamp_min(0) + 1e-3) - ylm) / yls
m = b["m"][:, 0, :] * tr_node_mask
loss = ((pred - yl) ** 2 * m).sum() / m.sum().clamp_min(1)
opt.zero_grad(); loss.backward(); opt.step(); tot += loss.item()
if (i + 1) % 10 == 0:
print(f" [PROBE {ep+1}] {i+1}/{len(dd)} mse={tot/(i+1):.3f} {(time.time()-t0)/(i+1):.2f}s/it", flush=True)
print(f"[PROBE {ep+1}/{a.probe_epochs}] {time.time()-t0:.0f}s", flush=True)
# ---- eval: FULL graph (SSL_ROADMAP §7 pin), season-balanced days (P0-1), raw-space R²
fv = data.graph_view(None, "full")
te = (data.split == 2).float().unsqueeze(-1).to(dev)
ev_days = stride(data.target_days(2), a.probe_days)
ys = []; ps = []; ms = []
with torch.no_grad():
for t in ev_days:
b = data.window(t, fv)
z = net.encode(b["groups_t"], b["ei"], b["e_hat"], b["n_hat"], b["wu"], b["wv"], b["blh"])[:, -1]
mu = lin(z) * yls.view(1, -1) + ylm.view(1, -1)
pred = (torch.exp(mu.clamp(max=12)) - 1e-3).clamp_min(0)
ys.append(b["y"][:, 0, :]); ps.append(pred); ms.append(b["m"][:, 0, :] * te)
Y = torch.cat(ys); P = torch.cat(ps); M = torch.cat(ms)
assert int((M.sum(-1) > 0).sum()) > 0, "probe eval produced no held-out predictions — full-graph forward broken"
refs = json.load(open(a.refs)) if a.refs and os.path.exists(a.refs) else {}
print(f"\n§7 LINEAR PROBE — spatial-held-out RAW-space R², {len(ev_days)} season-balanced days:")
print("NOTE: branch PROVISIONAL until refs.json R²-space (raw vs log) is confirmed against M1 eval code.")
res = {}
for j, pn in enumerate(POLL):
mm = M[:, j] > 0
if mm.sum() < 5: print(f" {pn}: n<5 skip"); continue
y = Y[mm, j].cpu().numpy(); p = P[mm, j].cpu().numpy()
r2 = 1 - ((y - p) ** 2).sum() / (((y - y.mean()) ** 2).sum() + 1e-9)
xg = refs.get(pn, {}).get("xgboost")
gap = float(r2 / xg) if (xg is not None and xg > 0) else None
res[pn] = dict(r2=float(r2), xgb=xg, gap_closed=gap)
gtag = f" gap_closed={gap:+.0%}" if gap is not None else ""
print(f" {pn}: probe R²={r2:+.3f}" + (f" (xgb {xg:+.2f}){gtag}" if xg is not None else ""))
pm = res.get("pm2_5", {})
sparse_set = ["so2", "co", "o3", "nh3"]
pm_pass = pm.get("xgb") is not None and pm.get("r2", -9) >= pm["xgb"]
sp_pass = any(res.get(s, {}).get("xgb") is not None and res[s]["r2"] >= res[s]["xgb"] for s in sparse_set)
if pm_pass and sp_pass: verdict = "FROZEN (pm2_5 AND >=1 sparse match-or-beat)"
elif pm.get("gap_closed") is not None and pm["gap_closed"] < 0.5: verdict = "REFUTED (<50% gap on pm2_5)"
else: verdict = "INCONCLUSIVE"
print(f" suggested branch: {verdict} — decision is joint, not automatic.")
json.dump(res | {"suggested_branch": verdict, "provisional_refs_space": True},
open(pathlib.Path(a.tensors).parent / "probe_result_v3.json", "w"), indent=1)
# ---------------------------------------------------------------- finetune
def physics_losses(pred_log, b):
pm = pred_log[:, 0, 0]
blh = b["blh"][-1]; rain = b["groups_t"][-1]["meteorology"][:, 7]
pm = torch.nan_to_num(pm); blh = torch.nan_to_num(blh); rain = torch.nan_to_num(rain)
L_blh = F.relu((pm - pm.mean()) * (blh - blh.mean())).mean().clamp(max=10.0)
L_rain = F.relu((pm - pm.mean()) * (rain - rain.mean())).mean().clamp(max=10.0)
return torch.nan_to_num(L_blh + L_rain)
def orphan_masks(b, p_orphan):
"""TP-2: p_orphan of today-labeled nodes -> Group A blackout all T + completeness 0."""
T = len(b["groups_t"])
lab = (b["m"].sum(1).sum(-1) > 0)
orph = lab & (torch.rand(lab.shape[0], device=lab.device) < p_orphan)
of = orph.float()
return [{"satellite": of} for _ in range(T)], b["comp"] * (1 - of), int(orph.sum())
def finetune(data, net, a, dev, tv, ylm, yls):
"""LP-FT schedule: freeze_epochs of head-only training at --lr (linear-probe phase,
protects the pretrained representation), then unfreeze ALL at --unfreeze_lr.
Motivation: probe R2 (frozen encoder) exceeded full-FT R2 on pm2_5 -> naive FT was
degrading the representation. Val logs BOTH nll and mu-quality (log-space mse),
because nll can worsen through sigma calibration alone."""
ck = pathlib.Path(a.tensors).parent / "encoder_v3.pt"
if ck.exists():
net.load_state_dict(torch.load(ck, map_location=dev), strict=False); print("loaded pretrained encoder_v3")
enc_p = [p for n, p in net.named_parameters() if not n.startswith("head.")]
head_p = [p for n, p in net.named_parameters() if n.startswith("head.")]
def make_opt(stage):
if stage == "head":
for p in enc_p: p.requires_grad = False
for p in head_p: p.requires_grad = True
return torch.optim.AdamW(head_p, lr=a.lr, weight_decay=a.weight_decay)
for p in net.parameters(): p.requires_grad = True
return torch.optim.AdamW(net.parameters(), lr=a.unfreeze_lr, weight_decay=a.weight_decay)
opt = make_opt("head" if a.freeze_epochs > 0 else "all")
print(f"LP-FT: {a.freeze_epochs} head-only epochs @lr={a.lr}, then ALL @lr={a.unfreeze_lr}")
tr = data.target_days(0)
vv = data.graph_view([0, 1], "train+val") # P0-2: test nodes NEVER context here
van = (data.split[vv["nodes"]] == 1).float().view(-1, 1, 1).to(dev)
va_days = stride(data.target_days(1), a.val_days) # P0-1
print(f"val protocol: {len(va_days)} stride-sampled days on train+val graph")
best = 1e9; bad = 0
for ep in range(a.ft_epochs):
if a.freeze_epochs > 0 and ep == a.freeze_epochs:
opt = make_opt("all")
print(f" [FT] encoder UNFROZEN at epoch {ep+1}, lr -> {a.unfreeze_lr}", flush=True)
net.train(); np.random.shuffle(tr); tot = 0; n_ok = 0; skips = 0; n_orph = 0; t0 = time.time()
used = tr[:a.days_per_epoch] if a.days_per_epoch else tr
for i, t in enumerate(used):
b = data.window(t, tv)
b["groups_t"] = jitter_coords(b["groups_t"], a.coord_jitter) # TP-5
gm_t, comp, k = (None, b["comp"], 0) if a.p_orphan <= 0 else orphan_masks(b, a.p_orphan)
n_orph += k
out = net(b["groups_t"], b["ei"], b["e_hat"], b["n_hat"], b["wu"], b["wv"], b["blh"], comp, gm_t)
nll = student_t_nll(out["mu"], out["log_sigma"], out["nu"], b["y"], b["m"], ylm, yls)
phys = physics_losses(out["mu"], b) if a.lam_phys > 0 else torch.tensor(0., device=dev)
loss = nll + a.lam_phys * phys
opt.zero_grad()
if not torch.isfinite(loss): skips += 1; continue
loss.backward()
if not grads_finite(net): opt.zero_grad(); skips += 1; continue
torch.nn.utils.clip_grad_norm_(net.parameters(), 5.0)
opt.step(); tot += nll.item(); n_ok += 1
if (i + 1) % a.log_every == 0:
print(f" [FT {ep+1}] {i+1}/{len(used)} nll={tot/max(n_ok,1):.3f} "
f"{(time.time()-t0)/(i+1):.2f}s/it", flush=True)
# ---- val: train+val graph, no orphan, no jitter; nll AND mu-quality
net.eval(); vt = 0; se = 0.0; sn = 0.0
with torch.no_grad():
for t in va_days:
b = data.window(t, vv)
out = net(b["groups_t"], b["ei"], b["e_hat"], b["n_hat"], b["wu"], b["wv"], b["blh"], b["comp"])
vt += student_t_nll(out["mu"], out["log_sigma"], out["nu"], b["y"], b["m"] * van, ylm, yls).item()
yl = (torch.log(b["y"].clamp_min(0) + 1e-3) - ylm.view(1, 1, -1)) / yls.view(1, 1, -1)
mm = b["m"] * van
se += (((out["mu"] - yl) ** 2) * mm).sum().item(); sn += mm.sum().item()
vm = vt / max(len(va_days), 1); vmse = se / max(sn, 1.0)
print(f"[FT {ep+1}/{a.ft_epochs}] train_nll={tot/max(n_ok,1):.3f} val_nll={vm:.3f} "
f"val_mse={vmse:.3f} orphaned={n_orph} {time.time()-t0:.0f}s", flush=True)
epoch_guard(f"FT {ep+1}", skips, len(used), a.max_skip)
if vmse < best: # TP-7: select on mu-quality (val_mse), not nll —
best = vmse; bad = 0 # nll can worsen via sigma calibration while mu improves
torch.save(net.state_dict(), pathlib.Path(a.tensors).parent / "atmosiq_v3_best.pt")
else:
bad += 1
if bad >= a.patience:
print(f"early stop (no val_mse improve for {a.patience} epochs)"); break
print(f"done. best val_mse={best:.3f} -> atmosiq_v3_best.pt")
# ---------------------------------------------------------------- main
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--tensors", default="data/tensors")
ap.add_argument("--stage", default="all", choices=["pretrain", "probe", "finetune", "all"])
ap.add_argument("--window", type=int, default=7)
ap.add_argument("--ssl_epochs", type=int, default=8)
ap.add_argument("--probe_epochs", type=int, default=15)
ap.add_argument("--ft_epochs", type=int, default=30)
ap.add_argument("--lr", type=float, default=3e-4)
ap.add_argument("--lam_smooth", type=float, default=0.1)
ap.add_argument("--lam_phys", type=float, default=0.0) # TP-3 amended: covariance proxy REFUTED (EXP-C, pm2_5-h0 0.046->0.270); 0 until true L-1 (perturbation monotonicity)
ap.add_argument("--p_orphan", type=float, default=0.0) # TP-2 amended: orphan lives in SSL blackout; inert in head stage (EXP-A/B)
ap.add_argument("--coord_jitter", type=float, default=0.1) # TP-5 (0 = ablation arm)
ap.add_argument("--smooth_every", type=int, default=4)
ap.add_argument("--days_per_epoch", type=int, default=800) # 0 = all days
ap.add_argument("--probe_days", type=int, default=60)
ap.add_argument("--val_days", type=int, default=25)
ap.add_argument("--patience", type=int, default=5)
ap.add_argument("--freeze_epochs", type=int, default=3, help="LP phase: head-only epochs before unfreezing encoder")
ap.add_argument("--unfreeze_lr", type=float, default=5e-5, help="lr for all params after unfreeze")
ap.add_argument("--weight_decay", type=float, default=1e-3)
ap.add_argument("--max_skip", type=float, default=0.20) # TP-4
ap.add_argument("--log_every", type=int, default=100)
ap.add_argument("--refs", default="data/models/refs.json")
ap.add_argument("--pm25_weight", type=float, default=1.0,
help="P4 ablation: pm2_5 weight in TRAIN loss only (val stays unweighted)")
ap.add_argument("--seed", type=int, default=42)
a = ap.parse_args()
torch.manual_seed(a.seed); np.random.seed(a.seed)
dev = "cuda" if torch.cuda.is_available() else "cpu"; print("device:", dev)
if dev == "cpu":
raise SystemExit("ABORT: CUDA unavailable — full-graph training on CPU would take days. "
"Fix torch/driver match (nvidia-smi CUDA Version vs torch build).")
meta = json.load(open(pathlib.Path(a.tensors) / "meta.json"))
data = AtmosDataV3(a.tensors, window=a.window, device=dev)
nz = np.load(pathlib.Path(a.tensors) / "norm.npz")
assert "y_logmean" in nz, "norm.npz missing y_logmean/y_logstd — run add_ystats.py first"
ylm = torch.tensor(nz["y_logmean"]).float().to(dev)
yls = torch.tensor(nz["y_logstd"]).float().to(dev)
net, cfg = build_model(meta, dev)
print(f"model params: {sum(p.numel() for p in net.parameters()):,}")
tv = data.graph_view([0], "train") # TP-1: THE training graph
json.dump({"pins": {"TP1_full_graph": True, "TP2_p_orphan": a.p_orphan,
"TP3_lam_phys": a.lam_phys, "TP4_max_skip": a.max_skip,
"TP5_coord_jitter": a.coord_jitter,
"P0_1_stride_days": True, "P0_2_val_graph": "train+val only"},
"seed": a.seed, "lr": a.lr, "weight_decay": a.weight_decay,
"train_mean_deg": tv["mean_deg"], "data_tier": data.tier},
open(pathlib.Path(a.tensors).parent / "train_state_v3.json", "w"), indent=1)
if a.stage in ("pretrain", "all"): pretrain(data, net, a, dev, tv)
if a.stage in ("probe", "all"): probe(data, net, meta, a, dev, tv)
if a.stage in ("finetune", "all"): finetune(data, net, a, dev, tv, ylm, yls)
if __name__ == "__main__":
main() |