File size: 14,968 Bytes
239a1be 773c429 239a1be 63ccb7e 239a1be 773c429 239a1be 63ccb7e 239a1be 773c429 239a1be 773c429 239a1be 773c429 239a1be 773c429 239a1be 773c429 239a1be 63ccb7e 239a1be 773c429 239a1be 63ccb7e 239a1be | 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 368 | """Single-run training / evaluation engine."""
from __future__ import annotations
import argparse
import json
import time
from dataclasses import dataclass, field, asdict
from pathlib import Path
from typing import Dict, List, Optional, Sequence
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
from .data import (PROC, TARGETS, TARGET_KEYS, Normalizer, PackedDataset,
build_static_frame, collate, kfold_split, loao_split,
random_split)
from .losses import masked_mse, masked_mse_balanced, physics_losses, peak_loss
from .metrics import (curve_metrics, regression_metrics, sigma_decomposition,
summarise)
from .models import build_model
ROOT = Path(__file__).resolve().parents[2]
RUNS = ROOT / "results" / "runs"
@dataclass
class Cfg:
model: str = "pimamba"
seed: int = 0
split: str = "random" # random | loao | kfold
holdout: str = "" # alloy name for loao
# K-fold assignment seed. ``None`` keeps the old behaviour (split changes
# with the run seed); an integer fixes the partition so that different
# seeds / architectures see exactly the same folds, which is required for
# seed averaging and for stacking.
split_seed: Optional[int] = None
n_folds: int = 5
fold: int = 0
test_frac: float = 0.2
epochs: int = 250
batch: int = 8
lr: float = 3e-4
wd: float = 1e-4
d_model: int = 64
n_layers: int = 2
d_state: int = 16
dropout: float = 0.1
coupling: bool = True
w_mono: float = 0.0
w_init: float = 0.0
w_smooth: float = 0.0
w_peak: float = 0.0 # curve-level peak-matching weight
drop_features: Sequence[str] = ()
norm_mode: str = "full" # full | none
train_frac: float = 1.0 # data-efficiency ablation
use_val: bool = True # False -> fixed-epoch fit on all train data
tag: str = ""
device: str = "cuda" if torch.cuda.is_available() else "cpu"
def _seed_all(seed: int):
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
def feature_mask(names: List[str], drop: Sequence[str]) -> np.ndarray:
m = np.ones(len(names), np.float32)
if not drop:
return m
for j, nm in enumerate(names):
for d in drop:
if d == "ensemble" and nm.startswith("ensemble="):
m[j] = 0
elif d == "shape" and nm.startswith("shape_type="):
m[j] = 0
elif d == "geom_flags" and nm.startswith("app_"):
m[j] = 0
elif d == "geom" and nm.startswith(("geom_", "app_", "orient_")):
m[j] = 0
elif d == "composition" and nm.startswith("at_"):
m[j] = 0
elif d == "init_rho" and nm.startswith("init_d_"):
m[j] = 0
elif d == "init_phase" and nm.startswith("init_xi_"):
m[j] = 0
elif d == "descriptors" and nm in {
"VEC", "delta", "rbar", "dHmix", "dSmix", "chi", "Mavg",
"dmu", "Tm", "rhomass"}:
m[j] = 0
elif d == "orientation" and nm.startswith("orient_"):
m[j] = 0
return m
def _split_ids(meta: pd.DataFrame, cfg: Cfg, alloys: List[str]):
if cfg.split == "loao":
return loao_split(alloys, meta, cfg.holdout)
if cfg.split == "kfold":
ss = cfg.seed if cfg.split_seed is None else int(cfg.split_seed)
return kfold_split(alloys, meta, ss, cfg.n_folds, cfg.fold)
tr, te = random_split(alloys, meta, cfg.seed, cfg.test_frac)
return tr, te
def _train_val_split(train_ids, meta, alloys, seed, frac=0.15):
"""Carve a validation set out of the training ids, alloy-aware."""
rng = np.random.default_rng(seed + 991)
by_alloy: Dict[str, List[int]] = {}
amap = dict(zip(meta.sample_id.tolist(), alloys))
for s in train_ids:
by_alloy.setdefault(amap[s], []).append(s)
val = []
for al, ids in by_alloy.items():
if len(ids) >= 3:
k = max(1, int(round(len(ids) * frac)))
val += list(rng.choice(ids, size=k, replace=False))
val = sorted(set(int(x) for x in val))
tr = [s for s in train_ids if s not in val]
return tr, val
@torch.no_grad()
def predict(model, dl, device):
model.eval()
outs = []
for st, x, Y, M, sids in dl:
st, x = st.to(device), x.to(device)
pred = model(st, x)["pred"]
outs.append((pred.cpu().numpy(), Y.numpy(), M.numpy(), list(sids)))
return outs
def evaluate(model, dl, norm, device) -> Dict:
outs = predict(model, dl, device)
P = np.concatenate([o[0] for o in outs], 0)
Y = np.concatenate([o[1] for o in outs], 0)
M = np.concatenate([o[2] for o in outs], 0)
S = np.concatenate([o[3] for o in outs], 0).astype(int)
raw_p = norm.inverse_targets(P)
raw_y = norm.inverse_targets(Y)
per_t = regression_metrics(raw_y.reshape(-1, len(TARGETS)),
raw_p.reshape(-1, len(TARGETS)),
M.reshape(-1, len(TARGETS)))
# curve-level (per sample)
j = TARGET_KEYS.index("sigma")
curves = []
for i, sid in enumerate(S):
m = M[i, :, j] > 0
if m.sum() < 10:
continue
eps = np.linspace(0, 0.2, len(m))[m] # grid is uniform 0->0.2
cm = curve_metrics(eps, raw_y[i, m, j], raw_p[i, m, j])
cm["sample_id"] = int(sid)
curves.append(cm)
cm_df = pd.DataFrame(curves)
agg_curve = {}
if len(cm_df):
for c in ["peak_rel_err", "curve_rmse", "sig@0.02_rel_err",
"sig@0.05_rel_err", "sig@0.1_rel_err"]:
if c in cm_df:
agg_curve[c + "_mean"] = float(cm_df[c].mean())
agg_curve[c + "_median"] = float(cm_df[c].median())
decomp = sigma_decomposition(raw_y, raw_p, M, S)
return {"per_target": per_t, "summary": summarise(per_t), "decomp": decomp,
"curve": agg_curve, "curves": cm_df,
"raw_pred": raw_p, "raw_true": raw_y, "mask": M, "sids": S}
def run(cfg: Cfg, verbose: bool = True) -> Dict:
_seed_all(cfg.seed)
device = torch.device(cfg.device)
meta = pd.read_csv(PROC / "samples_meta.csv")
traj = pd.read_csv(PROC / "trajectories.csv")
Xraw, names, kinds = build_static_frame(meta)
alloys = meta.alloy.tolist()
train_ids, test_ids = _split_ids(meta, cfg, alloys)
if cfg.use_val:
tr_ids, va_ids = _train_val_split(train_ids, meta, alloys, cfg.seed)
if len(va_ids) == 0:
va_ids = tr_ids[-2:]
else:
tr_ids, va_ids = list(train_ids), []
if cfg.train_frac < 1.0:
rng = np.random.default_rng(cfg.seed + 17)
k = max(2, int(round(len(tr_ids) * cfg.train_frac)))
tr_ids = sorted(int(x) for x in rng.choice(tr_ids, size=k, replace=False))
tr_traj = traj[traj.sample_id.isin(tr_ids)]
norm = Normalizer(mode=cfg.norm_mode).fit_static(
Xraw[[i for i, s in enumerate(meta.sample_id) if s in set(tr_ids)]], names, kinds
).fit_targets(tr_traj)
km = feature_mask(names, cfg.drop_features)
ds_tr = PackedDataset(tr_ids, meta, traj, norm, names, kinds, km)
ds_va = PackedDataset(va_ids, meta, traj, norm, names, kinds, km) if va_ids else None
ds_te = PackedDataset(test_ids, meta, traj, norm, names, kinds, km)
dl_tr = DataLoader(ds_tr, batch_size=min(cfg.batch, len(ds_tr)), shuffle=True,
collate_fn=collate)
dl_va = (DataLoader(ds_va, batch_size=min(cfg.batch, len(ds_va)), shuffle=False,
collate_fn=collate) if ds_va is not None else None)
dl_te = DataLoader(ds_te, batch_size=min(cfg.batch, len(ds_te)), shuffle=False,
collate_fn=collate)
model = build_model(cfg.model, n_static=int(km.sum()), n_out=len(TARGETS),
d_model=cfg.d_model, n_layers=cfg.n_layers,
d_state=cfg.d_state, dropout=cfg.dropout,
coupling=cfg.coupling).to(device)
n_par = sum(p.numel() for p in model.parameters())
opt = torch.optim.AdamW(model.parameters(), lr=cfg.lr, weight_decay=cfg.wd)
steps = max(1, len(dl_tr))
total_steps = max(2, cfg.epochs * steps)
sched = torch.optim.lr_scheduler.OneCycleLR(
opt, max_lr=cfg.lr, total_steps=total_steps,
pct_start=0.25 if cfg.epochs * steps >= 8 else 0.0)
best = float("inf")
best_state = None
bad = 0
nan_batches = 0
hist = []
t0 = time.time()
for ep in range(cfg.epochs):
model.train()
tl, n = 0.0, 0
for st, x, Y, M, _ in dl_tr:
st, x, Y, M = st.to(device), x.to(device), Y.to(device), M.to(device)
# models that need the labels (world model posterior, flow matching)
if getattr(model, "needs_y", False):
out = model(st, x, y=Y, m=M)
else:
out = model(st, x)
if "replace_loss" in out:
# generative models define their own objective (e.g. CFM)
loss = out["replace_loss"]
else:
loss = masked_mse_balanced(out["pred"], Y, M,
torch.from_numpy(norm.loss_w))
if out.get("aux_loss") is not None:
loss = loss + out["aux_loss"]
if cfg.w_mono or cfg.w_init or cfg.w_smooth:
pl, _ = physics_losses(out["pred"], Y, M, x[..., 0] * 0.2, cfg)
loss = loss + pl
if cfg.w_peak:
loss = loss + cfg.w_peak * peak_loss(out["pred"], Y, M)
opt.zero_grad(set_to_none=True)
if not torch.isfinite(loss):
# numerically poisoned batch: skip the update, keep the schedule
nan_batches += 1
sched.step()
continue
loss.backward()
gn = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
if not torch.isfinite(gn):
# inf/nan gradients: clip would turn them into nan -> skip update
nan_batches += 1
opt.zero_grad(set_to_none=True)
sched.step()
continue
opt.step()
sched.step()
tl += float(loss.detach()) * len(Y)
n += len(Y)
model.eval()
vl, vn = 0.0, 0
with torch.no_grad():
for st, x, Y, M, _ in (dl_va if dl_va is not None else []):
st, x, Y, M = st.to(device), x.to(device), Y.to(device), M.to(device)
out = model(st, x)
vl += float(masked_mse_balanced(out["pred"], Y, M, torch.from_numpy(norm.loss_w))) * len(Y)
vn += len(Y)
vl = vl / vn if vn else tl / max(n, 1)
hist.append({"epoch": ep, "train": tl / max(n, 1), "val": vl,
"nan_batches": nan_batches})
if not np.isfinite(vl):
continue
if vl < best - 1e-6:
best, bad = vl, 0
best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
else:
bad += 1
if cfg.use_val and bad >= 60 and ep > 80:
break
if best_state is not None:
model.load_state_dict(best_state)
res = evaluate(model, dl_te, norm, device)
out = {
"config": asdict(cfg),
"n_params": n_par,
"n_train": len(tr_ids), "n_val": len(va_ids), "n_test": len(test_ids),
"train_ids": tr_ids, "val_ids": va_ids, "test_ids": test_ids,
"best_val": best,
"nan_batches": nan_batches,
"epochs_run": len(hist),
"wall_time_s": round(time.time() - t0, 1),
"per_target": res["per_target"],
"summary": res["summary"],
"decomp": res.get("decomp", {}),
"curve": res["curve"],
"curves": res["curves"],
"test_alloys": sorted(set(alloys[meta.index[meta.sample_id == s][0]] for s in test_ids)),
"normalizer": norm.to_json(),
"feature_names": names,
"keep_mask": km.tolist(),
}
tag = cfg.tag or f"{cfg.model}_{cfg.split}_s{cfg.seed}"
outdir = RUNS / tag
outdir.mkdir(parents=True, exist_ok=True)
(outdir / "metrics.json").write_text(json.dumps(
{k: v for k, v in out.items() if k not in ("curves",)}, ensure_ascii=False, indent=2))
(outdir / "history.json").write_text(json.dumps(hist))
res["curves"].to_csv(outdir / "curves.csv", index=False)
np.savez_compressed(outdir / "predictions.npz",
pred=res["raw_pred"], true=res["raw_true"],
mask=res["mask"], sids=res["sids"])
torch.save({"state": model.state_dict(), "cfg": asdict(cfg),
"keep_mask": km, "names": names}, outdir / "model.pt")
if verbose:
print(f"[{tag}] params={n_par} best_val={best:.4f} "
f"test macroR2={out['summary']['macro_r2']:.4f} "
f"time={out['wall_time_s']}s")
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", default="pimamba")
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--split", default="random")
ap.add_argument("--holdout", default="")
ap.add_argument("--epochs", type=int, default=250)
ap.add_argument("--lr", type=float, default=3e-3)
ap.add_argument("--batch", type=int, default=8)
ap.add_argument("--d_model", type=int, default=64)
ap.add_argument("--n_layers", type=int, default=2)
ap.add_argument("--physics", type=float, default=0.0)
ap.add_argument("--peak", type=float, default=0.0,
help="weight of the curve-level peak-matching loss")
ap.add_argument("--no-coupling", action="store_true")
ap.add_argument("--drop", nargs="*", default=[])
ap.add_argument("--fold", type=int, default=0)
ap.add_argument("--n_folds", type=int, default=5)
ap.add_argument("--norm", default="full")
ap.add_argument("--train_frac", type=float, default=1.0)
ap.add_argument("--no_val", action="store_true")
ap.add_argument("--tag", default="")
ap.add_argument("--split_seed", type=int, default=None)
a = ap.parse_args()
cfg = Cfg(model=a.model, seed=a.seed, split=a.split, holdout=a.holdout,
epochs=a.epochs, lr=a.lr, batch=a.batch, d_model=a.d_model,
n_layers=a.n_layers, coupling=not a.no_coupling,
w_mono=a.physics, w_init=a.physics, w_smooth=0.1 * a.physics,
w_peak=a.peak,
drop_features=tuple(a.drop), tag=a.tag, fold=a.fold,
split_seed=a.split_seed,
n_folds=a.n_folds, norm_mode=a.norm, train_frac=a.train_frac,
use_val=not a.no_val)
run(cfg)
if __name__ == "__main__":
main() |