"""Bank size of the SMC bank (exploratory; declared in docs/research/bank-size.md before any computation). Trains five arms on the 11 N = 16 cells of T2 (8 realizations x 5 seeds): B3d-Sa and M2-Sa (S = 64) as references, and RML banks of S = 16, 256 and 1024 SMC particles. Banks are nested (16 = first 16 of the registered 64-member bank; 256 = that bank plus 192 further particles drawn without replacement; 1024 = all particles), and every bank uses the cell's lambda = 1/tau_c and uniform weights over its valid members. Bank construction, normalization and backbone are those of scripts/32_t2_mechanism.py; ml_porosity/ is not edited. Primary budget 250 iterations, 125 and 500 descriptive. Outside every protocol lock and outside the repro archives. Nothing here changes a registered number, and no choice is made with test labels (they are used for scoring only). CUDA_VISIBLE_DEVICES=0 .venv/bin/python scripts/49_bank_size.py --stage all --workers 4 --device cuda:0 -> outputs/bank_size/{cells/*.csv, ratios.csv, seff.csv, mc_error.csv, selfcheck.json, reading.json, summary.md} """ from __future__ import annotations import argparse import hashlib import importlib.util import json import os import time from concurrent.futures import ProcessPoolExecutor, as_completed from multiprocessing import get_context from pathlib import Path import numpy as np import pandas as pd from ml_porosity.paths import REPO_ROOT, outputs_dir def load_script(name: str): spec = importlib.util.spec_from_file_location("s" + name[:2], REPO_ROOT / "scripts" / name) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod t2 = load_script("32_t2_mechanism.py") run_d2 = t2.run_d2 DECL = REPO_ROOT / "docs" / "research" / "bank-size.md" DECL_HASH = REPO_ROOT / "docs" / "research" / "bank-size.sha256" OUT = outputs_dir() / "bank_size" BUDGETS = [125, 250, 500] PRIMARY = 250 SIZES = {"Bank-S16": 16, "M2-Sa": 64, "Bank-S256": 256, "Bank-S1024": 1024} ARMS = ["B3d-Sa", "Bank-S16", "M2-Sa", "Bank-S256", "Bank-S1024"] BANK_ARMS = tuple(SIZES) PAIRS = {"Q1": ("Bank-S256", "M2-Sa"), "Q2": ("Bank-S1024", "M2-Sa"), "Q3": ("Bank-S16", "M2-Sa"), "Q4_S16": ("Bank-S16", "B3d-Sa"), "Q4_S64": ("M2-Sa", "B3d-Sa"), "Q4_S256": ("Bank-S256", "B3d-Sa"), "Q4_S1024": ("Bank-S1024", "B3d-Sa")} READ_PAIRS = {"Q1": "larger", "Q2": "larger", "Q3": "smaller"} def check_declaration() -> str: expected = DECL_HASH.read_text().split()[0] actual = hashlib.sha256(DECL.read_bytes()).hexdigest() if actual != expected: raise SystemExit(f"{DECL.name} differs from its recorded SHA-256 ({actual[:12]} != {expected[:12]})") return actual def nested_order(sub64: np.ndarray, n: int, i: int) -> np.ndarray: """Particle indices in nesting order: the registered 64, then 192 drawn without replacement, then the rest.""" rest = np.setdiff1d(np.arange(n), sub64) extra = np.random.default_rng([0, i, 29, 256]).choice(rest, 192, replace=False) tail = np.setdiff1d(rest, extra) order = np.concatenate([sub64, extra, tail]) assert len(order) == n and len(np.unique(order)) == n return order def bank_from(Y_all: np.ndarray, ok_all: np.ndarray, idx: np.ndarray) -> tuple[np.ndarray, np.ndarray]: Y, ok = Y_all[idx].copy(), ok_all[idx] if not ok.any(): raise RuntimeError("bank without a valid member") Y[~ok] = Y[ok][0] logpi = np.where(ok, 0.0, -np.inf) - np.log(ok.sum()) return Y, logpi def train_job(job) -> tuple[str, float]: regime, rid, c, N, seeds, device, out_dir, P = job import torch torch.set_num_threads(2) from ml_porosity.losses.rml import responsibilities from ml_porosity.models.bank_train import WIN, train_predict, window_starts_fixed from ml_porosity.registration.labels import invert_warps t0 = time.time() cell = t2.build_cell(regime, rid, c, N, P, with_register=True) R, out, wells = cell["R"], cell["out"], cell["wells"] stem = t2.tag(regime, rid, c, N) key = dict(regime=regime, rid=rid, c=c, n_train=N) m0, s0 = out["norm"] lam = out["lam"] tcfg = P["training"]["model"] | P["training"]["optimizer"] f_c = P["metrics"]["bands"]["f_c_hz"] nb = lambda a: ((np.asarray(a) - m0) / s0).astype(np.float32) banks = {m: [] for m in BANK_ARMS} mc_rows = [] for w in wells: Tf = w["Tf"] Y_all = cell["lab"](w["y_aa"], Tf) # (1024, L) ok_all = np.all(np.isfinite(Y_all), 1) order = nested_order(w["sub"], len(Tf), w["i"]) # the registered 64-member bank must be reproduced exactly by the full label array if not (np.array_equal(ok_all[w["sub"]], w["ok"]) and np.array_equal(Y_all[w["sub"]][w["ok"]], w["Y"][w["ok"]])): raise RuntimeError(f"{stem} {w['name']}: labels of the registered bank are not reproduced") tau_true = invert_warps(w["o"]["t_of_tau_true"][None], R.tau_fine, R.t_main)[0] for m, S in SIZES.items(): idx = order[:S] if m == "M2-Sa": banks[m].append((w["Y"], w["logpi"])) else: banks[m].append(bank_from(Y_all, ok_all, idx)) v = idx[ok_all[idx]] tau = invert_warps(np.stack([Tf[v].mean(0), w["tm"]]), R.tau_fine, R.t_main) rms = lambda a, b: float(np.sqrt(np.nanmean((a - b) ** 2))) mc_rows.append(key | {"method": m, "S": S, "well": w["name"], "n_valid": int(len(v)), "mc_err_ms": rms(tau[0], tau[1]), "warp_err_ms": rms(tau[0], tau_true), "warp_err_1024_ms": rms(tau[1], tau_true)}) Y_pm = nb(np.stack([cell["lab"](w["y_aa"], w["tm"]) for w in wells])) bank = lambda Y, lp, lam_: {"kind": "bank", "Y": Y, "logpi": lp, "lam": lam_} specs = {"B3d-Sa": bank(Y_pm, np.zeros((N, 1), np.float32), lam)} for m in BANK_ARMS: specs[m] = bank(nb(np.stack([b[0] for b in banks[m]])), np.stack([b[1] for b in banks[m]]).astype(np.float32), lam) starts_np = window_starts_fixed(R.t_main.size) T = lambda a: torch.as_tensor(np.asarray(a), dtype=torch.float32, device=device) X_t, starts_t = T(cell["X"]), torch.as_tensor(np.tile(starts_np, (N, 1)), device=device) rows, seff_rows = [], [] for seed in seeds: for m in ARMS: sp = specs[m] store = {} cb = None if m in BANK_ARMS: Y_t, lp_t = T(sp["Y"]), T(sp["logpi"]) def cb(step, model, Y_t=Y_t, lp_t=lp_t, lam_=sp["lam"], store=store): with torch.no_grad(): mu, s = model(X_t) r = responsibilities(mu[:, 0], s[:, 0], Y_t, lp_t, starts_t, WIN, lam_) store[step] = r.cpu().numpy().astype(np.float64) preds = train_predict(cell["X"], cell["Xte"], sp, tcfg, seed, BUDGETS, device, on_budget=cb) for b, (mu, sg) in preds.items(): mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0 for wt, r in zip(R.test, run_d2.evaluate(cell["yt"], mu_p, sg_p, f_c)): rows.append(key | {"seed": seed, "method": m, "budget": b, "test_well": wt.name} | r) for b, r in store.items(): # (N, J, S) for w in wells: rj = r[w["i"]] seff_rows.append(key | {"seed": seed, "method": m, "S": SIZES[m], "lam": sp["lam"], "budget": b, "well": w["name"], "S_eff_win": float(np.mean(1.0 / np.sum(rj ** 2, 1))), "n_valid": int(np.isfinite(sp["logpi"][w["i"]]).sum())}) pd.DataFrame(mc_rows).to_csv(out_dir / f"{stem}_mc.csv", index=False) pd.DataFrame(seff_rows).to_csv(out_dir / f"{stem}_seff.csv", index=False) pd.DataFrame(rows).to_csv(out_dir / f"{stem}.csv", index=False) # written last: marks the job as complete return stem, time.time() - t0 def summarize(out: Path) -> None: files = sorted(f for f in (out / "cells").glob("*_n16.csv")) tr = pd.concat([pd.read_csv(f) for f in files], ignore_index=True) se = pd.concat([pd.read_csv(f) for f in sorted((out / "cells").glob("*_seff.csv"))], ignore_index=True) mc = pd.concat([pd.read_csv(f) for f in sorted((out / "cells").glob("*_mc.csv"))], ignore_index=True) cells = sorted({(r, c) for r, c in tr[["regime", "c"]].drop_duplicates().itertuples(index=False)}) rng = np.random.default_rng(0) # reproduction check against the registered runs reg = t2.registered_cells([(r, c, 16) for r, c in cells]) keys = ["regime", "c", "rid", "seed", "method", "test_well"] rep = tr[tr.method.isin(["B3d-Sa", "M2-Sa"]) & (tr.budget == PRIMARY)] mg = rep.merge(reg[keys + ["band_rmse"]], on=keys, suffixes=("", "_reg")) dev = (mg.band_rmse - mg.band_rmse_reg).abs() sc = {"n_rows": int(len(mg)), "n_expected": int(len(rep)), "band_rmse_abs_dev_max": float(dev.max()), "band_rmse_abs_dev_mean": float(dev.mean()), "by_method": {m: float(d.band_rmse.sub(d.band_rmse_reg).abs().max()) for m, d in mg.groupby("method")}} (out / "selfcheck.json").write_text(json.dumps(sc, indent=1)) # effective bank size (training wells only) s = se[se.budget == PRIMARY].assign(frac=lambda d: d.S_eff_win / d.n_valid) seff = s.groupby(["regime", "c", "method", "S"]).agg(S_eff_win=("S_eff_win", "mean"), n_valid=("n_valid", "mean"), frac=("frac", "mean"), lam=("lam", "mean")).reset_index() seff.to_csv(out / "seff.csv", index=False) # Monte Carlo error of the mean warp (truth-free) and warp error against the true warp (training wells) mce = mc.groupby(["regime", "c", "method", "S"]).agg(mc_err_ms=("mc_err_ms", "mean"), warp_err_ms=("warp_err_ms", "mean"), warp_err_1024_ms=("warp_err_1024_ms", "mean"), n_valid=("n_valid", "mean")).reset_index() mce.to_csv(out / "mc_error.csv", index=False) # ratios rows = [] for regime, c in cells: cell = tr[(tr.regime == regime) & (tr.c == c)] wide = (regime, c) in t2.WIDE16 for b in BUDGETS: at = cell[cell.budget == b] for name, (num, den) in PAIRS.items(): a, d = at[at.method == num], at[at.method == den] rows.append(dict(regime=regime, c=c, wide=wide, budget=b, pair=name, numerator=num, denominator=den) | t2.ratio_row(rng, a, d) | t2.diff_row(rng, a, d, "band_pcc")) rt = pd.DataFrame(rows) rt.to_csv(out / "ratios.csv", index=False) side = lambda d: {"ci_below_1": int((d.hi < 1).sum()), "ci_above_1": int((d.lo > 1).sum()), "ci_contains_1": int(((d.lo <= 1) & (d.hi >= 1)).sum()), "within_0.01": int(((d.ratio - 1).abs() <= 0.01).sum()), "n": int(len(d))} w = rt[rt.wide & (rt.budget == PRIMARY)] counts = {p: side(w[w.pair == p]) for p in PAIRS} counts_c1 = {p: side(w[(w.pair == p) & (w.c == 1.0)]) for p in PAIRS} def reading(p: str) -> str: k, word = counts[p], READ_PAIRS[p] return (f"no gain from the {word} bank in these cells" if k["ci_contains_1"] >= 5 else f"{word} bank better in these cells" if k["ci_below_1"] >= 5 else f"{word} bank worse in these cells" if k["ci_above_1"] >= 5 else "mixed") verdict = {"status": "exploratory; descriptive reading, not a verdict", "declaration_sha256": check_declaration(), "readings_8_wide_cells": {p: reading(p) for p in READ_PAIRS}, "counts_8_wide_cells": counts, "counts_c1_only": counts_c1, "selfcheck": sc} (out / "reading.json").write_text(json.dumps(verdict, indent=1)) fm = lambda d: "\n".join(["| regime | c | wide | ratio | 95% CI | n_rid | band PCC diff | 95% CI |", "|---|---|---|---|---|---|---|---|"] + [f"| {r.regime} | {r.c:g} | {'yes' if r.wide else 'no'} | {r.ratio:.3f} | [{r.lo:.3f}, {r.hi:.3f}] | {r.n_rid} | " f"{r['diff']:+.3f} | [{r.diff_lo:+.3f}, {r.diff_hi:+.3f}] |" for _, r in d.iterrows()]) md = ["# Bank size of the SMC bank (exploratory)\n", "Declared in docs/research/bank-size.md before any computation. Nothing here changes a registered number; " "the readings below are descriptive and are not verdicts.\n", f"Reproduction check: {sc['n_rows']} rows of {sc['n_expected']}; max |band RMSE dev| {sc['band_rmse_abs_dev_max']:.3e}, " f"mean {sc['band_rmse_abs_dev_mean']:.3e}.\n", f"Readings (8 wide cells, budget {PRIMARY}): " + json.dumps(verdict["readings_8_wide_cells"]) + "\n", "Counts over the 8 wide cells:\n", "```", json.dumps(counts, indent=1), "```\n"] for p, (num, den) in PAIRS.items(): md += [f"## {p}: {num} / {den}, budget {PRIMARY}\n", fm(rt[(rt.pair == p) & (rt.budget == PRIMARY)]), ""] means = tr[tr.budget == PRIMARY].groupby(["regime", "c", "method"]).band_rmse.mean().unstack("method")[ARMS] md += [f"## Mean band RMSE (p.u.), budget {PRIMARY}\n", means.round(4).to_markdown(), "", "## Descriptive: Q1-Q3 at budgets 125 and 500 (8 wide cells)\n"] for b in (125, 500): wb = rt[rt.wide & (rt.budget == b)] md += [f"budget {b}: " + json.dumps({p: side(wb[wb.pair == p]) for p in READ_PAIRS}), ""] md += ["## Effective bank size per window at the primary budget\n", seff.round(4).to_markdown(index=False), "", "## Monte Carlo error of the mean warp (ms, truth-free) and warp error against the true warp (training wells)\n", mce.round(4).to_markdown(index=False), ""] (out / "summary.md").write_text("\n".join(md), encoding="utf-8") print("wrote", out / "summary.md", flush=True) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--stage", choices=["train", "summary", "all"], default="all") ap.add_argument("--device", default="cuda:0") ap.add_argument("--workers", type=int, default=4) ap.add_argument("--out-dir", type=Path, default=None) ap.add_argument("--seeds", type=int, nargs="+", default=t2.SEEDS) ap.add_argument("--rids", type=int, nargs="+", default=t2.RIDS) ap.add_argument("--cells", nargs="+", default=None, help="restrict training to these cells (regime_c), e.g. R0_1") args = ap.parse_args() for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMBA_NUM_THREADS", "NUMEXPR_NUM_THREADS"): os.environ.setdefault(k, "2") sha = check_declaration() out = args.out_dir or OUT (out / "cells").mkdir(parents=True, exist_ok=True) P = run_d2.load_protocol(check=True) if run_d2.check_rids(t2.RIDS, P) is None: raise SystemExit("protocol_p2r main grid expected") print(f"declaration {sha[:12]} and the locked protocols match", flush=True) if args.stage in ("train", "all"): cells = t2.TRAIN_CELLS if args.cells is None else [x for x in t2.TRAIN_CELLS if f"{x[0]}_{x[1]:g}" in args.cells] jobs = [(r, rid, c, N, args.seeds, args.device, out / "cells", P) for r, c, N in cells for rid in args.rids if not (out / "cells" / f"{t2.tag(r, rid, c, N)}.csv").exists()] print(f"{len(jobs)} jobs, {args.workers} workers, device {args.device}", flush=True) t0 = time.time() if jobs: with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex: futs = {ex.submit(train_job, j): j[:4] for j in jobs} for i, f in enumerate(as_completed(futs), 1): stem, dt = f.result() print(f"[{i}/{len(jobs)}] {stem} done ({dt:.0f} s; total {time.time() - t0:.0f} s)", flush=True) if args.stage in ("summary", "all"): summarize(out) if __name__ == "__main__": os.environ.setdefault("PYTHONHASHSEED", "0") main()