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>
This commit is contained in:
135
scripts/35_bench_calibration.py
Normal file
135
scripts/35_bench_calibration.py
Normal file
@@ -0,0 +1,135 @@
|
||||
"""S2 level calibration table (phase P6, protocol_bench): tabulate the dev SMC diagnostics of every candidate preset.
|
||||
|
||||
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/35_bench_calibration.py [--rids 902 903 904 905] [--out outputs/bench/dev]
|
||||
|
||||
Reads outputs/bench/dev/smc_qc_rid<rid>.json (scripts/33 --smc: N = 4, c = 1, R10 and Rm5, P = 1024, estR, γ = 1/κ,
|
||||
single-checkpoint SMC) and outputs/bench/dev/generator_qc.json / generator_sweep.json (in-family model error), and
|
||||
writes calibration.csv (one row per preset × regime, mean over the listed realizations and wells) and calibration.md.
|
||||
Columns: in-family model error (relative RMS; ratio to the regime noise), SMC warp RMSE, coverage90, σ_post
|
||||
(width90/3.29), overconfidence (warp RMSE / σ_post), phase_R, |phase_R − phase0|, B3c and B3d warp RMSE, r_post,
|
||||
and the declared L1/L2 targets of configs/protocol_bench.yaml calibration.procedure. Dev only; no main realization.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import yaml
|
||||
|
||||
from ml_porosity.paths import REPO_ROOT
|
||||
|
||||
NOISE = {"R10": 10 ** (-10 / 20), "Rm5": 10 ** (5 / 20), "R0": 1.0} # relative noise RMS of the regimes
|
||||
Z90 = 3.29
|
||||
|
||||
|
||||
def in_family_errors(out: Path) -> dict[str, float]:
|
||||
"""Best in-family model error keyed by the json of the active knobs (generator_qc.json presets, the nominal entry
|
||||
and the single-knob rows of generator_sweep.json when they carry a spec/active block)."""
|
||||
from ml_porosity.data.synth_d2 import active_axes, normalize_misspec
|
||||
|
||||
err = {}
|
||||
f = out / "generator_qc.json"
|
||||
if f.exists():
|
||||
q = json.loads(f.read_text())
|
||||
err["{}"] = float(q["nominal"]["model_err_in_family"]["err_mean"])
|
||||
for d in q.get("presets", {}).values():
|
||||
if "active" in d and "model_err_in_family" in d:
|
||||
err[json.dumps(d["active"], sort_keys=True)] = float(d["model_err_in_family"]["err_mean"])
|
||||
f = out / "generator_sweep.json"
|
||||
if f.exists():
|
||||
for r in json.loads(f.read_text()).get("rows", []):
|
||||
if "model_err_in_family" not in r:
|
||||
continue
|
||||
act = r.get("active")
|
||||
if act is None and "spec" in r:
|
||||
act = active_axes(normalize_misspec({k: v for k, v in r["spec"].items() if k != "note"}))
|
||||
if act is None and {"axis", "key", "value"} <= set(r):
|
||||
act = active_axes(normalize_misspec({r["axis"]: {r["key"]: r["value"]}}))
|
||||
if act is not None:
|
||||
e = r["model_err_in_family"]
|
||||
err.setdefault(json.dumps(act, sort_keys=True), float(e["err_mean"] if isinstance(e, dict) else e))
|
||||
return err
|
||||
|
||||
|
||||
def load_smc(out: Path, rids: list[int]) -> pd.DataFrame:
|
||||
rows = []
|
||||
for rid in rids:
|
||||
f = out / f"smc_qc_rid{rid}.json"
|
||||
if not f.exists():
|
||||
continue
|
||||
q = json.loads(f.read_text())
|
||||
for regime, presets in q.items():
|
||||
if regime == "meta":
|
||||
continue
|
||||
for name, r in presets.items():
|
||||
m = r["mean"]
|
||||
rows.append({"rid": rid, "regime": regime, "preset": name, "phase0": r["phase0"], "phase_R": r["phase_R"],
|
||||
"dphase": abs(r["phase_R"] - r["phase0"]), "phase_edge": r["phase_edge"],
|
||||
"smc_warp_rmse_ms": m["SMC_warp_rmse_ms"], "cov90": m["SMC_warp_cov90"],
|
||||
"sigma_post_ms": m["SMC_warp_width90_ms"] / Z90, "r_post": m["r_post"], "kappa_post": m["kappa_post"],
|
||||
"b3c_warp_rmse_ms": m["B3c_warp_rmse_ms"], "b3d_warp_rmse_ms": m["B3d_warp_rmse_ms"],
|
||||
"lam": r["lam"], "time_s": sum(r["time_s"].values()), "active": json.dumps(r.get("active", {}), sort_keys=True)})
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--rids", type=int, nargs="+", default=[902, 903, 904, 905])
|
||||
ap.add_argument("--out", type=Path, default=REPO_ROOT / "outputs" / "bench" / "dev")
|
||||
a = ap.parse_args()
|
||||
if any(r < 900 for r in a.rids):
|
||||
raise SystemExit("dev realizations only")
|
||||
df = load_smc(a.out, a.rids)
|
||||
if df.empty:
|
||||
raise SystemExit("no smc_qc_rid*.json found")
|
||||
err = in_family_errors(a.out)
|
||||
cfg = yaml.safe_load((REPO_ROOT / "configs" / "d2_synth_bench.yaml").read_text())
|
||||
presets = cfg["misspec_presets"]
|
||||
# Rows are identified by their active knobs, not by the name stored in the json: preset names were redefined on
|
||||
# 29/10 (e.g. wv_L1 was minphase 1.0 on rid 902 and is minphase 0.5 now). Main-preset names win, then cand_*.
|
||||
from ml_porosity.data.synth_d2 import active_axes, normalize_misspec, preset_misspec
|
||||
main = [n for n in presets if not n.startswith("cand_")]
|
||||
by_active = {}
|
||||
for n in main + [n for n in presets if n.startswith("cand_")]:
|
||||
by_active.setdefault(json.dumps(active_axes(normalize_misspec(preset_misspec(cfg, n))), sort_keys=True), n)
|
||||
df["stored_name"] = df.preset
|
||||
df["preset"] = [("nominal" if a == "{}" else by_active.get(a, f"{n} (old definition)")) for a, n in zip(df.active, df.stored_name)]
|
||||
df = df.drop_duplicates(["rid", "regime", "active"]) # the same knobs run twice on one rid under two names
|
||||
df["overconfidence"] = df.smc_warp_rmse_ms / df.sigma_post_ms
|
||||
nom = df[df.preset == "nominal"].set_index(["rid", "regime"])
|
||||
df = df.join(nom[["smc_warp_rmse_ms", "cov90", "sigma_post_ms"]].rename(columns=lambda c: c + "_nom"), on=["rid", "regime"])
|
||||
df["warp_rmse_ratio_to_nominal"] = df.smc_warp_rmse_ms / df.smc_warp_rmse_ms_nom
|
||||
df["smc_beats_b3c"] = df.smc_warp_rmse_ms < df.b3c_warp_rmse_ms
|
||||
agg = df.groupby(["preset", "regime", "active"]).agg(n_rid=("rid", "nunique"), smc_warp_rmse_ms=("smc_warp_rmse_ms", "mean"),
|
||||
ratio_to_nominal=("warp_rmse_ratio_to_nominal", "mean"), cov90=("cov90", "mean"),
|
||||
sigma_post_ms=("sigma_post_ms", "mean"), overconfidence=("overconfidence", "mean"),
|
||||
dphase_deg=("dphase", "mean"), phase_R=("phase_R", "mean"),
|
||||
b3c_warp_rmse_ms=("b3c_warp_rmse_ms", "mean"), b3d_warp_rmse_ms=("b3d_warp_rmse_ms", "mean"),
|
||||
smc_beats_b3c_frac=("smc_beats_b3c", "mean"), r_post=("r_post", "mean"),
|
||||
time_s=("time_s", "mean")).reset_index()
|
||||
agg["in_family_err"] = agg.active.map(lambda a: err.get(a, np.nan))
|
||||
agg["err_over_noise"] = agg.in_family_err / agg.regime.map(NOISE)
|
||||
agg["note"] = agg.preset.map(lambda n: presets.get(n, {}).get("note", "nominal" if n == "nominal" else ""))
|
||||
agg["axis"] = agg.preset.map(lambda n: "nominal" if n == "nominal" else next((p for p in n.split("_") if p in ("rp", "wv", "dr")), "?"))
|
||||
agg = agg.sort_values(["regime", "axis", "preset"]).reset_index(drop=True)
|
||||
agg.to_csv(a.out / "calibration.csv", index=False)
|
||||
cols = ["regime", "axis", "preset", "active", "n_rid", "in_family_err", "err_over_noise", "smc_warp_rmse_ms", "ratio_to_nominal", "cov90",
|
||||
"sigma_post_ms", "overconfidence", "dphase_deg", "b3c_warp_rmse_ms", "smc_beats_b3c_frac", "r_post"]
|
||||
L = ["# S2 level calibration (dev; N = 4, c = 1, P = 1024, estR, γ = 1/κ; single-checkpoint SMC of scripts/33)", "",
|
||||
f"Realizations: {sorted(df.rid.unique().tolist())}. Means over realizations × 4 train wells. in_family_err from generator_qc.json "
|
||||
"(rid 902; NaN for presets without a light-QC entry). Declared targets (protocol calibration.procedure): L1 — err/noise(R10) "
|
||||
"0.5–1.0 and SMC still ahead of B3c at R10; L2 — err/noise(R10) 1.5–2 with coverage90 < 0.5 at R10 or warp RMSE ≥ 2 × nominal.", "",
|
||||
agg[cols].to_markdown(index=False, floatfmt=".3f"), "", "## Per realization", "",
|
||||
df[["rid", "regime", "preset", "stored_name", "smc_warp_rmse_ms", "cov90", "sigma_post_ms", "dphase", "b3c_warp_rmse_ms", "r_post"]]
|
||||
.sort_values(["regime", "preset", "rid"]).to_markdown(index=False, floatfmt=".3f"), ""]
|
||||
(a.out / "calibration.md").write_text("\n".join(L))
|
||||
pd.set_option("display.width", 250)
|
||||
print(agg[cols].round(3).to_string())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user