Fix contributions, rename the paper, add the lambda-to-zero arm

- Run the exploratory lambda -> 0 arm of the SMC bank (declared and hashed
  in docs/research/lambda-limit.md before computing; script 41, outside
  every lock). Results in docs/research/lambda-limit-results.md; reported
  only in Limitations and Appendix C, as declared.
- Fix four contributions (theory; controlled test of training on a tie
  posterior; benchmark with known timing; requirements for a field test)
  and rename the paper to "Uncertain well ties in learned seismic property
  prediction: theory, a benchmark with known timing, and requirements for
  blind-well tests". Abstract, highlights, introduction, related work,
  section openings, discussion and conclusions follow them.
- Add six verified references (benchmarks; comparison design).
- Add the simulated referee reports of 04/11 and the contribution review
  of 10/11 (major revision), and sync plan, AGENTS.md and report.html.

No verdict, threshold or locked protocol changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 08:34:11 +00:00
parent df5cb937e8
commit 894fbdfc59
31 changed files with 1384 additions and 38 deletions

233
scripts/41_lambda_limit.py Normal file
View File

@@ -0,0 +1,233 @@
"""lambda -> 0 arm of the SMC bank (exploratory; declared in docs/research/lambda-limit.md before any computation).
Trains four arms on the 11 N = 16 cells of T2 (8 realizations x 5 seeds): B3d-Sa and M2-Sa as references, Bank-lam0
(RML on the same 64-member bank with lambda = 1e-3, an approximation of the lambda -> 0 limit) and Mean-MSE (MSE on the
pi-weighted mean label of the bank). 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/41_lambda_limit.py --stage all --workers 4 --device cuda:0
-> outputs/lambda_limit/{cells/*.csv, ratios.csv, seff.csv, selfcheck.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" / "lambda-limit.md"
DECL_HASH = REPO_ROOT / "docs" / "research" / "lambda-limit.sha256"
OUT = outputs_dir() / "lambda_limit"
LAM0 = 1e-3
BUDGETS = [125, 250, 500]
PRIMARY = 250
ARMS = ["B3d-Sa", "M2-Sa", "Bank-lam0", "Mean-MSE"]
BANK_ARMS = ("M2-Sa", "Bank-lam0")
PAIRS = {"R1": ("Bank-lam0", "M2-Sa"), "R2": ("Bank-lam0", "B3d-Sa"), "R3": ("Mean-MSE", "B3d-Sa"),
"R4": ("Mean-MSE", "Bank-lam0")}
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 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
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)
Y_pm = nb(np.stack([cell["lab"](w["y_aa"], w["tm"]) for w in wells]))
Y_rml = nb(np.stack([w["Y"] for w in wells])) # (N, S, L)
logpi = np.stack([w["logpi"] for w in wells]).astype(np.float32) # (N, S); -inf marks invalid members
Y_mean = (Y_rml.astype(np.float64) * np.exp(logpi.astype(np.float64))[:, :, None]).sum(1).astype(np.float32) # (N, L)
starts_np = window_starts_fixed(R.t_main.size)
Ywin = np.stack([Y_mean[:, j: j + WIN] for j in starts_np], 1) # (N, J, WIN)
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),
"M2-Sa": bank(Y_rml, logpi, lam),
"Bank-lam0": bank(Y_rml, logpi, LAM0),
"Mean-MSE": {"kind": "mse_win", "Ywin": Ywin}}
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, sp in specs.items():
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, "lam": sp["lam"], "budget": b, "well": w["name"],
"S_eff_win": float(np.mean(1.0 / np.sum(rj ** 2, 1))),
"n_valid": int(w["ok"].sum())})
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") if not f.name.endswith("_seff.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)
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"]).agg(S_eff_win=("S_eff_win", "mean"), n_valid=("n_valid", "mean"),
frac_min=("frac", "min"), lam=("lam", "mean")).reset_index()
seff.to_csv(out / "seff.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()), "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}
r1 = counts["R1"]
reading = ("no difference between lambda->0 and lambda=1/tau_c in these cells" if r1["ci_contains_1"] >= 5 else
"finite tempering contributes beyond lambda->0 in these cells" if r1["ci_above_1"] >= 5 else
"lambda->0 better in these cells" if r1["ci_below_1"] >= 5 else "mixed")
verdict = {"status": "exploratory; descriptive reading, not a verdict", "declaration_sha256": check_declaration(),
"R1_reading_8_wide_cells": reading, "counts_8_wide_cells": counts, "counts_c1_only": counts_c1, "selfcheck": sc,
"seff_lam0_min_fraction": float(seff[seff.method == "Bank-lam0"].frac_min.min())}
(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 = ["# lambda -> 0 arm of the SMC bank (exploratory)\n",
"Declared in docs/research/lambda-limit.md before any computation. Nothing here changes a registered number; "
"the reading below is descriptive and is not a verdict.\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"Effective bank size of Bank-lam0, minimum S_eff/n_valid over wells: {verdict['seff_lam0_min_fraction']:.4f} (criterion 0.95).\n",
f"Reading of R1 (8 wide cells, budget {PRIMARY}): {reading}.\n", "Counts over the 8 wide cells:\n", "```", json.dumps(counts), "```\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(), "",
"## Effective bank size per window at the primary budget\n", seff.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()