Files
ML-Porosity/ml_porosity/benchmark/devbudgets.py
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

74 lines
4.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""S4 TCN budgets on dev realizations (protocol_p2 budget_selection rule applied to the TCN backbone).
Every S4 method is trained with the TCN at every candidate budget (one trajectory per seed) on dev realizations
902–905 at R10, c = 1, N ∈ {4, 16}, seeds 0–1; per method the budget with the smallest mean total RMSE (macro over
test wells → mean over rid × N × seed) is selected. The dev SMC posteriors of those cells are produced by the
ordinary posterior stage (outputs/bench/dev/posterior/R10). Output: outputs/bench/dev/budgets_tcn.json; the chosen
values are copied into protocol_bench.yaml training.budgets_tcn before the lock.
"""
from __future__ import annotations
import dataclasses
import json
from pathlib import Path
import pandas as pd
from ml_porosity.benchmark.cells import Cell, bench_root, posterior_paths, train_paths
from ml_porosity.benchmark.protocol import check_rids, dev_stamp, fingerprint
from ml_porosity.benchmark.runner import cell_from, make_jobs, posterior_worker, run_jobs
from ml_porosity.f3.progress import write_json
DEV_RIDS = (902, 903, 904, 905)
DEV_SEEDS = (0, 1)
def dev_budget_worker(job: dict) -> dict:
import torch
from ml_porosity.benchmark.data import load_inputs
from ml_porosity.benchmark.training import train_cell
torch.set_num_threads(job["threads"])
p, cell, root = job["p"], cell_from(job["cell"]), Path(job["root"])
paths = train_paths(cell, root)
if paths["meta"].exists() and json.loads(paths["meta"].read_text()).get("fingerprint") == job["key"]:
return {"cached": True, "path": str(paths["csv"])}
cand = [int(b) for b in p["training"]["budget_candidates"]]
post = posterior_paths(cell, root, int(p["registration"]["reg_seed"]))
rows, diag, _, meta = train_cell(cell, p, load_inputs(p), job["device"], post, save_preds=False, seeds=job["seeds"],
budget_lists={m.removesuffix("-TCN"): cand for m in cell.methods})
paths["csv"].parent.mkdir(parents=True, exist_ok=True)
pd.DataFrame(diag).to_csv(paths["diag"], index=False)
pd.DataFrame(rows).to_csv(paths["csv"], index=False)
write_json(paths["meta"], meta | {"fingerprint": job["key"], "candidates": cand, "cell": dataclasses.asdict(cell)})
return {"cached": False, "path": str(paths["csv"]), "wall_seconds": meta["wall_seconds"]}
def dev_budgets(p: dict, device: str, workers: int, mem_gb: float, threads: int, rids=None) -> dict:
rids = [int(r) for r in (rids or DEV_RIDS)]
check_rids(rids, p, dev=True)
s4, root, stamp = p["studies"]["S4"], bench_root(dev=True), dev_stamp(p)
cells = [Cell("S4", "R10", None, 1.0, int(N), rid, tuple(s4["methods"]), backbone=s4["backbone"], posterior="bench")
for N in s4["n_train"] for rid in rids]
run_jobs(make_jobs(p, cells, "posterior", stamp, root, device, mem_gb, threads), posterior_worker, workers, root,
"posterior:dev-budgets")
jobs = []
for c in cells:
settings = dict(stage="dev-budgets", setting=c.setting, misspec=None, rid=c.rid, c=c.c, n_train=c.n_train, methods=list(c.methods),
backbone=c.backbone, candidates=list(p["training"]["budget_candidates"]), seeds=list(DEV_SEEDS))
jobs.append(dict(p=p, cell=dataclasses.asdict(c), root=str(root), device=device, mem_gb=mem_gb, threads=threads,
seeds=list(DEV_SEEDS), key=fingerprint(stamp, **settings)))
jobs.sort(key=lambda j: -j["cell"]["n_train"])
run_jobs(jobs, dev_budget_worker, workers, root, "train:dev-budgets")
df = pd.concat([pd.read_csv(train_paths(cell_from(j["cell"]), root)["csv"]) for j in jobs], ignore_index=True)
run = df.groupby(["method", "budget", "rid", "n_train", "seed"])["rmse"].mean().groupby(["method", "budget"]).mean()
chosen = {m.removesuffix("-TCN"): int(run.loc[m].idxmin()) for m in run.index.get_level_values(0).unique()}
table = run.unstack("budget")
out = {"rule": "protocol_p2 budget_selection (lowest mean total RMSE at c = 1 over dev rid × N × seed) applied to the TCN backbone",
"rids": rids, "seeds": list(DEV_SEEDS), "candidates": list(p["training"]["budget_candidates"]), "budgets_tcn": chosen,
"mean_total_rmse": {m: {int(b): float(v) for b, v in r.items()} for m, r in table.iterrows()}}
(root / "budgets_tcn.json").write_text(json.dumps(out, indent=1))
print(table.round(4).to_string())
return out