"""Experiment orchestrator: main comparison / cross-alloy / ablations / data efficiency. All runs use a fixed epoch budget with a full OneCycle anneal and no internal validation split (``use_val=False``): with 33 samples a 15% hold-out is only ~4 trajectories, which makes early stopping pure noise (see report ยง5.1). """ from __future__ import annotations import argparse import json import time from pathlib import Path from typing import Dict, List import pandas as pd from .data import PROC from .train import Cfg, run ROOT = Path(__file__).resolve().parents[2] RUNS = ROOT / "results" / "runs" SUMMARY = ROOT / "results" / "summary.csv" MODELS = ["mlp", "gru", "lstm", "transformer", "mamba", "mamba2", "pimamba"] MODELS_NEXT = ["llama", "xlstm", "gdn", "hymba", "koopman", "node", "rssm", "flow"] # performance-first group: larger model, longer schedule, a fixed fold split so # seeds differ only in initialisation (required for seed averaging / stacking). MODELS_BEST = ["hymba", "gdn", "llama", "pimamba"] ABLATIONS = [ # name, cfg overrides ("pimamba", {}), ("pimamba_nocouple", {"coupling": False}), ("pimamba_phys", {"w_mono": 1.0, "w_init": 1.0, "w_smooth": 0.1}), ("pimamba_nogeom", {"drop_features": ("geom",)}), ("pimamba_noflags", {"drop_features": ("geom_flags",)}), ("pimamba_noensemble", {"drop_features": ("ensemble",)}), ("pimamba_noinit", {"drop_features": ("init_rho", "init_phase")}), ("pimamba_nonorm", {"norm_mode": "none"}), ] def _row(res: Dict, suite: str, variant: str = "", fold: int = -1, seed: int = 0) -> Dict: cfg = res["config"] pt = res["per_target"] sig = pt.get("sigma", {}) dec = res.get("decomp", {}) or {} row = { "suite": suite, "variant": variant or cfg["model"], "model": cfg["model"], "tag": Path(res.get("tag", "")).name or "", "fold": fold if fold >= 0 else cfg.get("fold", -1), "seed": seed, "holdout": cfg.get("holdout", ""), "n_train": res["n_train"], "n_test": res["n_test"], "n_params": res["n_params"], "epochs": res["epochs_run"], "wall_time_s": res["wall_time_s"], "macro_r2": res["summary"]["macro_r2"], "macro_r2_primary": res["summary"].get("macro_r2_primary"), "core_r2": res["summary"].get("core_r2"), "median_r2": res["summary"]["median_r2"], "macro_r2_log": res["summary"]["macro_r2_log"], "macro_nmae": res["summary"]["macro_nmae"], "sigma_r2": sig.get("r2"), "sigma_mae": sig.get("mae"), "sigma_nmae": sig.get("nmae"), "sigma_r2_log": sig.get("r2_log"), "sigma_shape_r2": dec.get("shape_r2"), "sigma_level_r2": dec.get("level_oracle_r2"), "sigma_level_corr": dec.get("level_corr"), "sigma_level_mae": dec.get("level_mae_GPa"), "xi_FCC_r2": pt.get("xi_FCC", {}).get("r2"), "rho_total_r2": pt.get("rho_total", {}).get("r2"), "rho_total_r2log": pt.get("rho_total", {}).get("r2_log"), "twin_r2": pt.get("twin", {}).get("r2"), "peak_rel_err": res["curve"].get("peak_rel_err_mean"), "curve_rmse": res["curve"].get("curve_rmse_mean"), "sig@0.05_rel_err": res["curve"].get("sig@0.05_rel_err_mean"), } return row def _maybe_run(cfg: Cfg, suite: str, variant: str, tag: str, rows: List[Dict], force: bool = False): out = RUNS / tag / "metrics.json" if out.exists() and not force: r = json.loads(out.read_text()) # a cached smoke run (fewer epochs than requested) must not satisfy the # request -- otherwise a 2-epoch debugging run silently blocks the real # 300-epoch experiment. if int(r.get("epochs_run", 0)) >= int(cfg.epochs): rows.append(_row(r, suite, variant, cfg.fold, cfg.seed)) print(f" cached {tag}") return print(f" stale {tag}: {r.get('epochs_run')} < {cfg.epochs} epochs, rerun") cfg.tag = tag res = run(cfg, verbose=True) res["tag"] = tag rows.append(_row(res, suite, variant, cfg.fold, cfg.seed)) def suite_main(seeds, folds, models, force, epochs, lr=3e-4): rows = [] for m in models: for f in folds: for s in seeds: cfg = Cfg(model=m, seed=s, split="kfold", fold=f, n_folds=5, epochs=epochs, d_model=64, n_layers=2, use_val=False, lr=lr) _maybe_run(cfg, "main", m, f"main_{m}_f{f}_s{s}", rows, force) return rows def suite_loao(seeds, models, force, epochs, lr=3e-4): meta = pd.read_csv(PROC / "samples_meta.csv") alloys = sorted(meta.alloy.unique()) rows = [] for m in models: for al in alloys: for s in seeds: cfg = Cfg(model=m, seed=s, split="loao", holdout=al, epochs=epochs, d_model=64, n_layers=2, use_val=False, lr=lr) safe = "".join(ch if ch.isalnum() else "_" for ch in al)[:40] _maybe_run(cfg, "loao", m, f"loao_{m}_{safe}_s{s}", rows, force) return rows def suite_ablation(seeds, folds, force, epochs, lr=3e-4): rows = [] for name, over in ABLATIONS: for f in folds: for s in seeds: cfg = Cfg(model="pimamba", seed=s, split="kfold", fold=f, n_folds=5, epochs=epochs, d_model=64, n_layers=2, use_val=False, lr=lr, **over) _maybe_run(cfg, "ablation", name, f"abl_{name}_f{f}_s{s}", rows, force) return rows def suite_dataeff(fractions, folds, models, force, epochs, lr=3e-4): rows = [] for m in models: for fr in fractions: for f in folds: cfg = Cfg(model=m, seed=0, split="kfold", fold=f, n_folds=5, epochs=epochs, d_model=64, n_layers=2, train_frac=fr, use_val=False, lr=lr) _maybe_run(cfg, "dataeff", f"{m}@{fr:.2f}", f"de_{m}_{int(fr*100):03d}_f{f}", rows, force) return rows def suite_next(seeds, folds, models, force, epochs, lr=3e-4): """Next-generation backbones (2024-2026), same protocol as ``suite_main``.""" rows = [] for m in models: for f in folds: for s in seeds: cfg = Cfg(model=m, seed=s, split="kfold", fold=f, n_folds=5, epochs=epochs, d_model=64, n_layers=2, use_val=False, lr=lr) _maybe_run(cfg, "next", m, f"next_{m}_f{f}_s{s}", rows, force) return rows def suite_best(seeds, folds, models, force, epochs, d_model=128, n_layers=4, lr=3e-4, split_seed=0): """Performance-first group: no equal-budget constraint. ``split_seed`` is pinned so every seed and architecture sees the same five folds; otherwise the OOF predictions cannot be averaged or stacked. """ rows = [] for m in models: for f in folds: for s in seeds: cfg = Cfg(model=m, seed=s, split="kfold", fold=f, n_folds=5, epochs=epochs, d_model=d_model, n_layers=n_layers, use_val=False, lr=lr, split_seed=split_seed) _maybe_run(cfg, "best", m, f"best_{m}_f{f}_s{s}", rows, force) return rows def suite_v2(seeds, folds, force, epochs, lr=3e-4): """PI-Mamba v2: Taylor-form coupling and the curve-level peak loss.""" variants = [ ("pimamba2", {"model": "pimamba2"}), ("pimamba2_peak", {"model": "pimamba2", "w_peak": 0.5}), ("pimamba_peak", {"model": "pimamba", "w_peak": 0.5}), ("pimamba2_nocouple", {"model": "pimamba2", "coupling": False}), ] rows = [] for name, over in variants: for f in folds: for s in seeds: cfg = Cfg(seed=s, split="kfold", fold=f, n_folds=5, epochs=epochs, d_model=64, n_layers=2, use_val=False, lr=lr, **over) _maybe_run(cfg, "v2", name, f"v2_{name}_f{f}_s{s}", rows, force) return rows def append_summary(rows: List[Dict]): if not rows: return df = pd.DataFrame(rows) if SUMMARY.exists(): old = pd.read_csv(SUMMARY) df = pd.concat([old, df], ignore_index=True) df = df.drop_duplicates(subset=["tag"], keep="last") SUMMARY.parent.mkdir(parents=True, exist_ok=True) df.to_csv(SUMMARY, index=False) print(f"\nsummary -> {SUMMARY} ({len(df)} rows)") def main(): ap = argparse.ArgumentParser() ap.add_argument("--suite", required=True, choices=["main", "loao", "ablation", "dataeff", "next", "v2", "best", "all"]) ap.add_argument("--models", nargs="*", default=MODELS) ap.add_argument("--seeds", nargs="*", type=int, default=[0]) ap.add_argument("--folds", nargs="*", type=int, default=[0, 1, 2, 3, 4]) ap.add_argument("--fractions", nargs="*", type=float, default=[0.25, 0.5, 0.75, 1.0]) ap.add_argument("--epochs", type=int, default=None) ap.add_argument("--lr", type=float, default=3e-4) ap.add_argument("--d_model", type=int, default=None) ap.add_argument("--n_layers", type=int, default=None) ap.add_argument("--split_seed", type=int, default=0) ap.add_argument("--force", action="store_true") a = ap.parse_args() rows: List[Dict] = [] ep = 300 if a.epochs is None else a.epochs # equal-budget suites ep_best = 600 if a.epochs is None else a.epochs # performance-first suite if a.suite in ("main", "all"): print("== main ==") rows += suite_main(a.seeds, a.folds, a.models, a.force, ep, a.lr) if a.suite in ("loao", "all"): print("== loao ==") rows += suite_loao(a.seeds, ["pimamba", "mamba", "gru", "mlp"], a.force, ep, a.lr) if a.suite in ("ablation", "all"): print("== ablation ==") rows += suite_ablation(a.seeds, a.folds, a.force, ep, a.lr) if a.suite in ("next", "all"): print("== next ==") ms = [m for m in a.models if m in MODELS_NEXT] or MODELS_NEXT rows += suite_next(a.seeds, a.folds, ms, a.force, ep, a.lr) if a.suite in ("v2", "all"): print("== v2 ==") rows += suite_v2(a.seeds, a.folds, a.force, ep, a.lr) if a.suite in ("best", "all"): print("== best ==") ms = [m for m in a.models if m in MODELS_BEST] or MODELS_BEST rows += suite_best(a.seeds, a.folds, ms, a.force, ep_best, a.d_model or 128, a.n_layers or 4, a.lr, a.split_seed) if a.suite in ("dataeff", "all"): print("== dataeff ==") rows += suite_dataeff(a.fractions, a.folds, ["pimamba", "mamba", "gru", "mlp"], a.force, ep, a.lr) append_summary(rows) if __name__ == "__main__": main()