Files
lamlvh 381b5ffb06 Add P6 benchmark code, locked protocol_bench, T2 study
- ml_porosity/benchmark/ runner, scripts 32-35, scripts/run_bench.sh;
  misspec= option in synth_d2 (default path reproduces P2r bit for bit).
- configs/protocol_bench.{yaml,sha256,lock.json} locked 29/10 14:39 UTC
  (sha256 aa763f0a...), configs/d2_synth_bench.yaml.
- T2 mechanism declaration and results; operations/p6_supervisor.py.
- Docs, report and paper edits of 29/10.

outputs/ stays out of git; the repository folder is synced as a whole to
the new server. Main S1 runs are still training at this commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 01:33:18 +00:00

75 lines
5.0 KiB
Python

"""P2r reproduction check: compare the reproduction cell of protocol_bench (outputs/bench/repro) with the stored
protocol_p2r artifacts. The P2r guard hashes no code, so this comparison is the evidence that the runner's default
path (generator, registration, SMC, label banks, training) is the one that produced outputs/p2r."""
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
import pandas as pd
from ml_porosity.benchmark.cells import Cell, bench_root, posterior_paths, train_paths
from ml_porosity.f3.progress import write_json
from ml_porosity.paths import outputs_dir
def _max_abs(a, b) -> float:
a, b = np.asarray(a, float), np.asarray(b, float)
return float(np.nanmax(np.abs(a - b))) if a.shape == b.shape else float("inf")
def compare(p: dict) -> dict:
rp = p["reproduction"]
cell = Cell("S1", rp["regime"], None, float(rp["c"]), int(rp["n_train"]), int(rp["rid"]), tuple(rp["methods"]))
root = bench_root(repro=True)
reg_seed = int(p["registration"]["reg_seed"])
new, ref = posterior_paths(cell, root, reg_seed), {}
tag = f"r{cell.rid}_c{cell.c:g}_n{cell.n_train}_s{reg_seed}"
p2r = outputs_dir() / "p2r"
ref = {"csv": p2r / "posterior" / cell.regime / f"{tag}.csv", "particles": p2r / "posterior" / cell.regime / f"{tag}_particles.npz",
"phase": p2r / "posterior" / cell.regime / f"{tag}_phase.json",
"train_csv": p2r / "train" / cell.regime / "cells" / f"{cell.tag}.csv", "train_npz": p2r / "train" / cell.regime / "cells" / f"{cell.tag}.npz",
"train_diag": p2r / "train" / cell.regime / "cells" / f"{cell.tag}_diag.csv"}
out = {"cell": {"regime": cell.regime, "rid": cell.rid, "c": cell.c, "n_train": cell.n_train}, "posterior": {}, "train": {}}
# posterior: phase, particles, warp diagnostics
pn, pr = json.loads(new["phase"].read_text()), json.loads(ref["phase"].read_text())
out["posterior"]["phase0"] = {"new": pn["phase0"], "p2r": pr["phase0"], "equal": pn["phase0"] == pr["phase0"]}
out["posterior"]["phase_R"] = {"new": pn["phase_R"], "p2r": pr["phase_R"], "abs_diff_deg": abs(pn["phase_R"] - pr["phase_R"])}
out["posterior"]["logZ_max_abs_diff"] = _max_abs(pn["logZ"], pr["logZ"]) if np.shape(pn["logZ"]) == np.shape(pr["logZ"]) else "shape differs"
with np.load(new["particles"]) as zn, np.load(ref["particles"]) as zr:
keys = sorted(k for k in zn.files if k in zr.files)
out["posterior"]["particle_keys_compared"] = keys
diffs = {k: _max_abs(zn[k], zr[k]) for k in keys}
out["posterior"]["particles_max_abs_diff"] = diffs
out["posterior"]["particles_bitwise"] = all(np.array_equal(zn[k], zr[k]) for k in keys)
out["posterior"]["warp_mean_max_abs_diff_ms"] = {k: _max_abs(zn[k].mean(0), zr[k].mean(0)) for k in keys}
dn, dr = pd.read_csv(new["csv"]), pd.read_csv(ref["csv"])
m = dn.merge(dr, on=["well", "method", "wavelet"], suffixes=("_new", "_p2r"))
cols = ["warp_rmse_ms", "warp_cov90", "warp_width90_ms", "logZ", "kappa_post", "r_post"]
out["posterior"]["csv_max_abs_diff"] = {c: _max_abs(m[f"{c}_new"], m[f"{c}_p2r"]) for c in cols if f"{c}_new" in m}
out["posterior"]["n_stages"] = {"new": dn[dn.method == "SMC_g_acf"].n_stages.tolist(), "p2r": dr[dr.method == "SMC_g_acf"].n_stages.tolist()}
# training: per (method, seed, test well) metrics and predictions
tn, tr = pd.read_csv(train_paths(cell, root)["csv"]), pd.read_csv(ref["train_csv"])
keys = ["method", "seed", "budget", "test_well"]
mt = tn.merge(tr, on=keys, suffixes=("_new", "_p2r"))
out["train"]["rows_compared"] = int(len(mt))
for c in ("band_rmse", "rmse", "band_pcc", "nll", "coverage_90"):
out["train"][f"{c}_max_abs_diff"] = _max_abs(mt[f"{c}_new"], mt[f"{c}_p2r"])
per_m = {m_: _max_abs(g[f"band_rmse_new"], g[f"band_rmse_p2r"]) for m_, g in mt.groupby("method")}
out["train"]["band_rmse_max_abs_diff_per_method"] = per_m
cm = mt.groupby("method")[["band_rmse_new", "band_rmse_p2r"]].mean()
out["train"]["cell_mean_band_rmse"] = {m_: {"new": float(r.band_rmse_new), "p2r": float(r.band_rmse_p2r)} for m_, r in cm.iterrows()}
with np.load(train_paths(cell, root)["npz"]) as zn, np.load(ref["train_npz"]) as zr:
ks = sorted(k for k in zn.files if k in zr.files and k.endswith("/mu"))
out["train"]["pred_mu_max_abs_diff_pu"] = {k: _max_abs(zn[k], zr[k]) for k in ks}
out["train"]["pred_bitwise"] = all(np.array_equal(zn[k], zr[k]) for k in ks)
out["train"]["y_true_bitwise"] = bool(np.array_equal(zn["y_true"], zr["y_true"]))
gn, gr = pd.read_csv(train_paths(cell, root)["diag"]), pd.read_csv(ref["train_diag"])
g = gn.merge(gr, on="well", suffixes=("_new", "_p2r"))
out["train"]["diag_max_abs_diff"] = {c: _max_abs(g[f"{c}_new"], g[f"{c}_p2r"]) for c in ("B3c-R_warp_rmse_ms", "B3d-Sa_warp_rmse_ms", "lam", "phase_R")}
out["train"]["M2-Sa_n_valid_equal"] = bool((g["M2-Sa_n_valid_new"] == g["M2-Sa_n_valid_p2r"]).all())
write_json(root / "comparison.json", out)
return out