"""Training of one protocol_bench cell: scripts/15_diag_train.py run_cell (variant "a": estR wavelet, γ = 1/κ) with three additions. (1) B4a–d from the protocol_p2 label banks (S3). (2) The S8 two-mode banks built from the true warp: per training well a side s = ±1 is drawn from a declared stream, the two modes are t_true and t_true + sΔ, PM2 labels sit at the posterior-mean warp t_true + sΔ/2, BK2 is the two-member bank with uniform π and the protocol λ, HM2 the same bank with the hard-min loss. (3) A second backbone (TCNHetero of ml_porosity/f3/training.py) trained with the same loop as bank_train.train_predict; the CNN-GRU path delegates to bank_train unchanged. """ from __future__ import annotations import json import time from pathlib import Path import numpy as np import torch import torch.nn as nn from ml_porosity.benchmark.cells import Cell from ml_porosity.benchmark.data import Inputs, load_script REGISTER_METHODS = ("Oracle", "B3a", "B3b", "B3c", "B3d", "B4a", "B4b", "B4c", "B4d", "M1", "M2") POSTERIOR_METHODS = ("B3c-R", "B3d-Sa", "M2-Sa") TWO_MODE_METHODS = ("PM2", "BK2", "HM2") CONTROL_METHODS = ("Ctl-GP",) SIDE_STREAM = 20261030 # S8: rng [rid, SIDE_STREAM, 8, i] → side s_i = ±1 of training well i MIN_SLOPE_MS, MAX_ATTEMPTS = 0.05, 1280 # Ctl-GP: monotonicity guard and draw budget, as T2 (scripts/32) def budget_list(p: dict, method: str, backbone: str) -> list[int]: """Registered budget plus, if declared, the equal-budget arm (one trajectory; predictions at both steps).""" b = {budget_of(p, method, backbone)} arm = p["training"].get("equal_budget_arm") if arm: b.add(int(arm)) return sorted(b) def base_name(method: str) -> str: return method.removesuffix("-TCN") def budget_of(p: dict, method: str, backbone: str) -> int: b = base_name(method) if backbone != "cnngru": alt = p["training"].get(f"budgets_{backbone}") or {} if alt.get(b) is not None: return int(alt[b]) return int(p["training"]["budgets"][b]) def train_predict_tcn(X, Xte, spec: dict, cfg: dict, seed: int, budgets: list[int], device: str) -> dict: """bank_train.train_predict with TCNHetero (f3.training) in place of CNNGRUHetero; cudnn deterministic as f3.""" from ml_porosity.f3.training import TCNHetero from ml_porosity.losses.rml import bank_loss, gather_windows from ml_porosity.losses.softdtw import dilate_loss_fast, softdtw_loss_fast from ml_porosity.models.bank_train import WIN, window_starts_fixed from ml_porosity.models.train import predict torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True torch.default_generator.manual_seed(seed) if torch.device(device).type == "cuda": torch.cuda.set_device(device) torch.cuda.manual_seed(seed) np.random.seed(seed) T = lambda a: torch.as_tensor(np.asarray(a), dtype=torch.float32, device=device) x = T(X) N, _, L = X.shape starts = torch.as_tensor(np.tile(window_starts_fixed(L), (N, 1)), device=device) kind = spec["kind"] if kind == "bank": Y, logpi, lam = T(spec["Y"]), T(spec["logpi"]), spec["lam"] loss_fn = lambda mu, s: bank_loss(mu, s, Y, logpi, starts, WIN, lam) elif kind in ("softdtw", "dilate"): yw = gather_windows(T(spec["Y"]).reshape(N, L), starts, WIN).reshape(-1, WIN) f = softdtw_loss_fast if kind == "softdtw" else dilate_loss_fast kw = {k: spec[k] for k in ("gamma", "band", "alpha") if k in spec} loss_fn = lambda mu, s: f(gather_windows(mu, starts, WIN).reshape(-1, WIN), gather_windows(s, starts, WIN).reshape(-1, WIN), yw, **kw) else: raise ValueError(kind) model = TCNHetero(X.shape[1], cfg["d_channels"], cfg["p_dropout"]).to(device) opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"]) out = {} for step in range(1, max(budgets) + 1): model.train() opt.zero_grad() mu, s = model(x) loss = loss_fn(mu[:, 0], s[:, 0]) if not torch.isfinite(loss): raise FloatingPointError(f"non-finite loss at step {step}") loss.backward() nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"]) opt.step() if step in budgets: out[step] = predict(model, Xte, device) return out def train_predict_any(X, Xte, spec, cfg, seed, budgets, device, backbone: str) -> dict: if backbone == "cnngru": from ml_porosity.models.bank_train import train_predict return train_predict(X, Xte, spec, cfg, seed, budgets, device) if backbone == "tcn": return train_predict_tcn(X, Xte, spec, cfg, seed, budgets, device) raise ValueError(backbone) def posterior_banks(R, obs: list[dict], out: dict, reg: dict, ph: dict, smc, reg_seed: int, diag: list[dict]) -> tuple[dict, list]: """B3c-R, B3d-Sa (mean of all particles) and M2-Sa (S particles without replacement, rng [reg_seed, i, 29], uniform π) exactly as scripts/15 (variant a: estR, g_acf). Appends per-well diagnostics to `diag`.""" from ml_porosity.data.wavelet import statistical_wavelet from ml_porosity.registration.labels import antialias, labels_for_warps from ml_porosity.registration.smc import phase_basis, phase_wavelet from ml_porosity.registration.tie_likelihood import synth_for_warps from ml_porosity.registration.ties import tie_b3b, tie_b3c, warp_errors, warp_mean cfg = R.cfg f, fac = cfg["fine_dt_ms"], int(round(R.dt / cfg["fine_dt_ms"])) seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs] wR = phase_wavelet(phase_basis(statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"]), fac), ph["phase_R"]) lab = lambda y, T: labels_for_warps(R.tau_fine, y, np.atleast_2d(T), R.t_main) err = lambda t, o: warp_errors(t[None], R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"] banks, logpi = {"B3c-R": [], "B3d-Sa": [], "M2-Sa": []}, [] for i, o in enumerate(obs): y_aa = antialias(o["phi_log"], f, R.dt) t_b3b = tie_b3b(o["tau_k"], o["t_k"], R.tau_fine) syn_b = synth_for_warps(R.tau_fine, o["ai_log"], t_b3b, R.t_fine, R.t_ext, wR)[0] t3c = tie_b3c(t_b3b, R.tau_fine, syn_b, seis[i], R.t_ext, R.dt) banks["B3c-R"].append(lab(y_aa, t3c)) U = smc[f"{o['name']}/estR/g_acf"].astype(float) Tf = R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine) tm = warp_mean(Tf, np.zeros(len(Tf))) banks["B3d-Sa"].append(lab(y_aa, tm)) sub = np.random.default_rng([reg_seed, i, 29]).choice(len(Tf), reg["S"], replace=False) Y = lab(y_aa, Tf[sub]) ok = np.all(np.isfinite(Y), 1) Y[~ok] = Y[ok][0] banks["M2-Sa"].append(Y) logpi.append(np.where(ok, 0.0, -np.inf) - np.log(ok.sum())) diag[i] |= {"phase_R": ph["phase_R"], "B3c-R_warp_rmse_ms": err(t3c, o), "B3d-Sa_warp_rmse_ms": err(tm, o), "M2-Sa_n_valid": int(ok.sum()), "sigma_post_ms": warp_errors(Tf, R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_width90_ms"] / 3.29} return banks, logpi def control_gp_bank(R, obs: list[dict], smc: dict, reg: dict, reg_seed: int, diag: list[dict]) -> tuple[list, list]: """Ctl-GP (T2 test ii, scripts/32 control_bank): S warps T̄ + η_s, η_s Gaussian with the empirical mean and covariance of the SMC particles on the warp grid (no information beyond the first two moments; no link between a member and the seismic). rng [reg_seed, i, 2029]; a draw is kept if t(τ) is strictly increasing (slope > MIN_SLOPE_MS per node), else redrawn (≤ MAX_ATTEMPTS); fallback: Gaussian in u = [b, g] (monotone by construction), flagged. Labels and invalid members as the SMC bank.""" from ml_porosity.registration.labels import antialias, labels_for_warps f = R.cfg["fine_dt_ms"] lab = lambda y, T: labels_for_warps(R.tau_fine, y, np.atleast_2d(T), R.t_main) banks, logpi = [], [] for i, o in enumerate(obs): U = smc[f"{o['name']}/estR/g_acf"].astype(float) Tg = R.grid.t_of_tau(U[:, 0], U[:, 1:]) Tbar = Tg.mean(0) lam, V = np.linalg.eigh(np.cov(Tg.T, ddof=0)) Lm = V * np.sqrt(np.clip(lam, 0.0, None))[None, :] rng = np.random.default_rng([reg_seed, i, 2029]) members, n_rej, attempts = [], 0, 0 while len(members) < reg["S"] and attempts < MAX_ATTEMPTS: t = Tbar + Lm @ rng.standard_normal(len(Tbar)) attempts += 1 if np.all(np.diff(t) > MIN_SLOPE_MS): members.append(t) else: n_rej += 1 fallback = len(members) < reg["S"] if fallback: lu, Vu = np.linalg.eigh(np.cov(U.T, ddof=0)) Lu = Vu * np.sqrt(np.clip(lu, 0.0, None))[None, :] ubar = U.mean(0) while len(members) < reg["S"]: u = ubar + Lu @ rng.standard_normal(len(ubar)) members.append(R.grid.t_of_tau(u[0], u[1:])[0]) Tc_grid = np.stack(members) Tc = np.stack([np.interp(R.tau_fine, R.grid.tau, t) for t in Tc_grid]) Y = lab(antialias(o["phi_log"], f, R.dt), Tc) ok = np.all(np.isfinite(Y), 1) Y[~ok] = Y[ok][0] banks.append(Y) logpi.append(np.where(ok, 0.0, -np.inf) - np.log(ok.sum())) diag[i] |= {"Ctl-GP_n_valid": int(ok.sum()), "Ctl-GP_n_rejected": n_rej, "Ctl-GP_fallback_u": bool(fallback), "Ctl-GP_sd_ratio": float(Tc_grid.std(0).mean() / Tg.std(0).mean())} return banks, logpi def two_mode_banks(R, obs: list[dict], delta_ms: float, diag: list[dict]) -> dict: """S8 controlled cycle skip: modes t_true and t_true + s·Δ (s = ±1 per training well from rng [rid, SIDE_STREAM, 8, i]); PM2 at the mean warp t_true + sΔ/2; BK2/HM2 the two-member bank.""" from ml_porosity.registration.labels import antialias, labels_for_warps from ml_porosity.registration.ties import warp_errors f = R.cfg["fine_dt_ms"] lab = lambda y, T: labels_for_warps(R.tau_fine, y, np.atleast_2d(T), R.t_main) banks = {"PM2": [], "BK2": []} for i, o in enumerate(obs): s = int(np.random.default_rng([R.rid, SIDE_STREAM, 8, i]).integers(2)) * 2 - 1 y_aa = antialias(o["phi_log"], f, R.dt) t_true = o["t_of_tau_true"] Ypm = lab(y_aa, t_true + s * delta_ms / 2.0) Ybk = lab(y_aa, np.stack([t_true, t_true + s * delta_ms])) if not (np.all(np.isfinite(Ypm)) and np.all(np.isfinite(Ybk))): raise ValueError(f"{o['name']}: two-mode labels leave the label support at Δ = {delta_ms} ms") banks["PM2"].append(Ypm) banks["BK2"].append(Ybk) diag[i] |= {"delta_ms": delta_ms, "side": s, "PM2_warp_rmse_ms": warp_errors((t_true + s * delta_ms / 2.0)[None], R.tau_fine, t_true, R.t_main)["warp_rmse_ms"]} return banks def train_cell(cell: Cell, p: dict, inp: Inputs, device: str, post: dict[str, Path] | None, save_preds: bool = True, seeds=None, budget_lists: dict[str, list[int]] | None = None) -> tuple[list[dict], list[dict], dict, dict]: """Returns (rows, diag, preds, meta). rows: one per (seed, method, budget, test well) with the P2r metrics. budget_lists (dev only): {method: [budgets]} evaluated along one trajectory instead of the locked budget.""" from ml_porosity.models.bank_train import zscore_patch from ml_porosity.registration.pipeline import register run_d2 = load_script("11_run_d2.py") t0 = time.time() P2, reg, tcfg = inp.P2, inp.reg, inp.tcfg reg_seed = int(p["registration"]["reg_seed"]) seeds = list(p["grid"]["seeds"] if seeds is None else seeds) R = inp.realization(cell.rid, cell.preset) obs, test = inp.observe(R, cell.c, cell.regime, cell.n_train) X = np.stack([zscore_patch(o["seis"], R.main) for o in obs]) Xte = np.stack([zscore_patch(o["seis"], R.main) for o in test]) yt = 100 * np.stack([o["y_true"] for o in test]) N = len(obs) out = register(R, obs, reg, reg_seed) m0, s0 = out["norm"] key = dict(rid=cell.rid, c=cell.c, n_train=N) diag = [key | {"reg_seed": reg_seed, "phase": out["phase"], "lam": out["lam"], "tau_c": out["tau_c"], "well": o["name"], "preset": cell.preset or "nominal", "backbone": cell.backbone} for o in obs] methods = [base_name(m) for m in cell.methods] specs = {} old = [m for m in methods if m in REGISTER_METHODS] if old: specs |= run_d2.method_specs(out, P2, old) single = lambda Y: {"kind": "bank", "Y": Y, "logpi": np.zeros((N, 1), np.float32), "lam": out["lam"]} nb = lambda v: ((np.stack(v) - m0) / s0).astype(np.float32) meta = {} if any(m in POSTERIOR_METHODS + CONTROL_METHODS for m in methods): if post is None: raise RuntimeError(f"{cell.tag}: posterior methods requested without a posterior directory") ph = json.loads(post["phase"].read_text()) if ph["phase0"] != out["phase"]: raise RuntimeError(f"{cell.tag}: register phase ({out['phase']}) differs from the posterior run ({ph['phase0']})") with np.load(post["particles"]) as smc: smc = {k: smc[k] for k in smc.files} banks, logpi = posterior_banks(R, obs, out, reg, ph, smc, reg_seed, diag) specs["B3c-R"] = single(nb(banks["B3c-R"])) specs["B3d-Sa"] = single(nb(banks["B3d-Sa"])) specs["M2-Sa"] = {"kind": "bank", "Y": nb(banks["M2-Sa"]), "logpi": np.stack(logpi).astype(np.float32), "lam": out["lam"]} meta["posterior"] = str(post["particles"]) if any(m in CONTROL_METHODS for m in methods): yc, lpc = control_gp_bank(R, obs, smc, reg, reg_seed, diag) specs["Ctl-GP"] = {"kind": "bank", "Y": nb(yc), "logpi": np.stack(lpc).astype(np.float32), "lam": out["lam"]} if any(m in TWO_MODE_METHODS for m in methods): banks = two_mode_banks(R, obs, float(cell.delta_ms), diag) specs["PM2"] = single(nb(banks["PM2"])) Ybk = nb(banks["BK2"]) lp = np.full((N, 2), -np.log(2.0), np.float32) specs["BK2"] = {"kind": "bank", "Y": Ybk, "logpi": lp, "lam": out["lam"]} specs["HM2"] = {"kind": "bank", "Y": Ybk, "logpi": lp, "lam": None} missing = [m for m in methods if m not in specs] if missing: raise ValueError(f"no label specification for methods {missing}") rows, preds = [], {} suffix = "" if cell.backbone == "cnngru" else f"-{cell.backbone.upper()}" for seed in seeds: for m in methods: bud = list(budget_lists[m]) if budget_lists else budget_list(p, m, cell.backbone) for b, (mu, sg) in train_predict_any(X, Xte, specs[m], tcfg, seed, bud, device, cell.backbone).items(): mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0 name = m + suffix for w, r in zip(R.test, run_d2.evaluate(yt, mu_p, sg_p, inp.f_c)): rows.append(key | {"seed": seed, "method": name, "budget": b, "test_well": w.name, "regime": cell.regime, "preset": cell.preset or "nominal", "study": cell.study, "delta_ms": cell.delta_ms} | r) if save_preds: preds[f"{name}/s{seed}/b{b}/mu"] = mu_p.astype(np.float32) preds[f"{name}/s{seed}/b{b}/sigma"] = sg_p.astype(np.float32) preds = {"y_true": yt.astype(np.float32), "test_wells": np.array([w.name for w in R.test])} | preds meta |= {"wall_seconds": time.time() - t0, "device": device, "seeds": seeds, "methods": [m + suffix for m in methods], "budgets": {m + suffix: (list(budget_lists[m]) if budget_lists else budget_list(p, m, cell.backbone)) for m in methods}, "registered_budgets": {m + suffix: budget_of(p, m, cell.backbone) for m in methods}, "phase": out["phase"], "lam": out["lam"], "misspec_active": R.misspec_active, "n_train": N, "backbone": cell.backbone} return rows, diag, preds, meta