Add P6 benchmark code, locked protocol_bench, T2 study and lock inputs
- 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.
- The eight protocol_bench inputs force-added from outputs/ (warp prior,
wavelets, horizon cache, budgets) so load_protocol() and summarize work
after a fresh clone. The 102 P2r reference artifacts (1.4 GB of particle
npz) are not in git; they are only checked by posterior/train stages.
- T2 mechanism declaration and results; operations/p6_supervisor.py.
- Docs, report and paper edits of 29/10.
Main S1 runs are still training at this commit; results follow.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
233
ml_porosity/benchmark/runner.py
Normal file
233
ml_porosity/benchmark/runner.py
Normal file
@@ -0,0 +1,233 @@
|
||||
"""Resumable stages of protocol_bench: posterior (SMC), train, with fingerprinted completion markers.
|
||||
|
||||
Completion marker of a job: its `.json` sidecar carrying the resume fingerprint (lock stamp + cell settings) and the
|
||||
SHA-256 of every artifact. A job whose sidecar matches is skipped; a sidecar with a different fingerprint or a
|
||||
mismatched artifact raises (use a new output root), as in ml_porosity/volve/runner.py. Dev runs (realizations
|
||||
900–905) write under outputs/bench/dev with a protocol-and-generator-only fingerprint; the reproduction cell writes
|
||||
under outputs/bench/repro. Neither is a result.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
|
||||
from datetime import datetime
|
||||
from multiprocessing import get_context
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from ml_porosity.benchmark.cells import (Cell, bench_root, needs_posterior, posterior_dir, posterior_paths,
|
||||
study_cells, train_paths)
|
||||
from ml_porosity.benchmark.protocol import check_rids, dev_stamp, digest, fingerprint, freeze, generator_config
|
||||
from ml_porosity.data.synth_d2 import normalize_misspec, preset_misspec
|
||||
from ml_porosity.f3.progress import write_json
|
||||
|
||||
|
||||
def _threads(n: int) -> None:
|
||||
for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMEXPR_NUM_THREADS", "NUMBA_NUM_THREADS"):
|
||||
os.environ.setdefault(k, str(n))
|
||||
|
||||
|
||||
def cell_from(d: dict) -> Cell:
|
||||
d = dict(d)
|
||||
d["methods"], d["tags"] = tuple(d["methods"]), tuple(d.get("tags", ()))
|
||||
return Cell(**d)
|
||||
|
||||
|
||||
def reusable(meta: Path, key: str, artifacts: list[Path]) -> bool:
|
||||
if not meta.exists():
|
||||
return False
|
||||
stored = json.loads(meta.read_text(encoding="utf-8"))
|
||||
if stored.get("fingerprint") != key:
|
||||
raise RuntimeError(f"resume fingerprint mismatch: {meta}. Use a new output root (or a new protocol version).")
|
||||
for a in artifacts:
|
||||
if not a.exists() or digest(a) != stored.get("artifact_sha256", {}).get(a.name):
|
||||
raise RuntimeError(f"missing or mismatched completed artifact: {a}")
|
||||
return True
|
||||
|
||||
|
||||
def sidecar(meta_path: Path, key: str, artifacts: list[Path], extra: dict) -> None:
|
||||
write_json(meta_path, extra | {"fingerprint": key, "artifact_sha256": {a.name: digest(a) for a in artifacts},
|
||||
"finished": datetime.now().astimezone().isoformat(timespec="seconds")})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- workers (importable, spawn context)
|
||||
|
||||
def posterior_worker(job: dict) -> dict:
|
||||
import torch
|
||||
from ml_porosity.benchmark.data import load_inputs
|
||||
from ml_porosity.benchmark.registration import posterior_cell
|
||||
|
||||
torch.set_num_threads(job["threads"])
|
||||
p, cell, root = job["p"], cell_from(job["cell"]), Path(job["root"])
|
||||
reg_seed = int(p["registration"]["reg_seed"])
|
||||
paths = posterior_paths(cell, root, reg_seed)
|
||||
arts = [paths["csv"], paths["particles"], paths["phase"]]
|
||||
if reusable(paths["meta"], job["key"], arts):
|
||||
return {"cached": True, "path": str(paths["csv"])}
|
||||
inp = load_inputs(p)
|
||||
R = inp.realization(cell.rid, cell.preset)
|
||||
obs, _ = inp.observe(R, cell.c, cell.regime, cell.n_train)
|
||||
smc = p["registration"]["smc"]
|
||||
_, meta = posterior_cell(R, inp, obs, cell.c, cell.n_train, inp.regime(cell.regime), reg_seed,
|
||||
int(smc["smc_seed"]), int(smc["particles"]), job["device"], job["mem_gb"], paths,
|
||||
checkpoints=tuple(smc["checkpoints"]), extra_meta={"cell": dataclasses.asdict(cell)},
|
||||
phase_kw={k: smc[f"phase_{k}"] for k in ("step", "half_width", "max_extra") if f"phase_{k}" in smc})
|
||||
sidecar(paths["meta"], job["key"], arts, meta)
|
||||
return {"cached": False, "path": str(paths["csv"]), "wall_seconds": meta["wall_seconds"]}
|
||||
|
||||
|
||||
def training_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)
|
||||
arts = [paths["csv"], paths["npz"], paths["diag"]]
|
||||
if reusable(paths["meta"], job["key"], arts):
|
||||
return {"cached": True, "path": str(paths["csv"])}
|
||||
post = posterior_paths(cell, root, int(p["registration"]["reg_seed"])) if cell.posterior != "none" else None
|
||||
if post is not None and not post["particles"].exists():
|
||||
raise FileNotFoundError(f"{cell.tag}: posterior not available at {post['particles']}")
|
||||
inp = load_inputs(p)
|
||||
rows, diag, preds, meta = train_cell(cell, p, inp, job["device"], post, save_preds=True, seeds=job.get("seeds"))
|
||||
paths["csv"].parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = paths["npz"].with_suffix(".tmp.npz")
|
||||
np.savez_compressed(tmp, **preds)
|
||||
tmp.replace(paths["npz"])
|
||||
pd.DataFrame(diag).to_csv(paths["diag"], index=False)
|
||||
pd.DataFrame(rows).to_csv(paths["csv"], index=False)
|
||||
sidecar(paths["meta"], job["key"], arts, meta | {"cell": dataclasses.asdict(cell)})
|
||||
return {"cached": False, "path": str(paths["csv"]), "wall_seconds": meta["wall_seconds"]}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- pools
|
||||
|
||||
def progress(root: Path, name: str, **values) -> None:
|
||||
path = root / "progress.json"
|
||||
for attempt in range(10):
|
||||
try:
|
||||
old = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
||||
old[name] = old.get(name, {}) | values | {"updated": datetime.now().astimezone().isoformat(timespec="seconds")}
|
||||
write_json(path, old)
|
||||
return
|
||||
except (PermissionError, json.JSONDecodeError):
|
||||
time.sleep(0.25 * (attempt + 1))
|
||||
|
||||
|
||||
def run_jobs(jobs: list[dict], fn, workers: int, root: Path, name: str) -> list[dict]:
|
||||
if not jobs:
|
||||
print(f"{name}: nothing to do", flush=True)
|
||||
return []
|
||||
started, results = time.perf_counter(), []
|
||||
progress(root, name, status="running", completed=0, total=len(jobs), error=None)
|
||||
with ProcessPoolExecutor(max_workers=workers, mp_context=get_context("spawn")) as pool:
|
||||
futures = {pool.submit(fn, job): job for job in jobs}
|
||||
pending = set(futures)
|
||||
while pending:
|
||||
done, pending = wait(pending, timeout=30, return_when=FIRST_COMPLETED)
|
||||
for fut in done:
|
||||
try:
|
||||
result = fut.result()
|
||||
except Exception as exc:
|
||||
for other in pending:
|
||||
other.cancel()
|
||||
progress(root, name, status="failed; pending jobs cancelled", error=f"{futures[fut]['cell']['study']} "
|
||||
f"{futures[fut]['cell']['regime']} {futures[fut]['cell']['rid']}: {exc}")
|
||||
raise
|
||||
results.append(result)
|
||||
fresh = sum(not r.get("cached") for r in results)
|
||||
elapsed = time.perf_counter() - started
|
||||
eta = elapsed / fresh * (len(jobs) - len(results)) if fresh else None
|
||||
progress(root, name, completed=len(results), cached=len(results) - fresh, elapsed_seconds=elapsed, eta_seconds=eta)
|
||||
print(f"[{name} {len(results)}/{len(jobs)}] {'cached ' if result.get('cached') else ''}{result['path']}"
|
||||
f"{'' if result.get('cached') else f' ({result.get('wall_seconds', 0):.0f} s)'} "
|
||||
f"elapsed {elapsed:.0f} s{'' if eta is None else f', eta {eta:.0f} s'}", flush=True)
|
||||
progress(root, name, status="done", eta_seconds=0)
|
||||
return results
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- planning
|
||||
|
||||
def plan(p: dict, studies: list[str], rids=None, regimes=None, presets=None, controls: bool = False,
|
||||
grid: dict | None = None) -> list[Cell]:
|
||||
cells = []
|
||||
for s in studies:
|
||||
kw = {"presets": presets, "controls": controls} if s == "S2" else {}
|
||||
cells += study_cells(p, s, rids=rids, regimes=regimes, grid=grid, **kw)
|
||||
return cells
|
||||
|
||||
|
||||
def stamp_for(p: dict, mode: str) -> dict:
|
||||
if mode == "dev":
|
||||
return dev_stamp(p)
|
||||
if mode == "repro":
|
||||
return dev_stamp(p) | {"repro": True}
|
||||
return freeze(check=True)
|
||||
|
||||
|
||||
def make_jobs(p: dict, cells: list[Cell], stage: str, stamp: dict, root: Path, device: str, workers_mem_gb: float,
|
||||
threads: int, seeds=None) -> list[dict]:
|
||||
jobs, seen = [], set()
|
||||
cfg = generator_config(p)
|
||||
for cell in cells:
|
||||
misspec = normalize_misspec(preset_misspec(cfg, cell.preset))
|
||||
if stage == "posterior":
|
||||
if not needs_posterior(cell):
|
||||
continue
|
||||
ident = (cell.study, cell.setting, cell.rid, cell.c, cell.n_train)
|
||||
settings = dict(stage="posterior", setting=cell.setting, regime=cell.regime, preset=cell.preset, misspec=misspec,
|
||||
rid=cell.rid, c=cell.c, n_train=cell.n_train, reg_seed=p["registration"]["reg_seed"],
|
||||
smc=p["registration"]["smc"])
|
||||
else:
|
||||
ident = (cell.study, cell.setting, cell.tag, cell.backbone)
|
||||
settings = dict(stage="train", study=cell.study, setting=cell.setting, regime=cell.regime, preset=cell.preset,
|
||||
misspec=misspec, rid=cell.rid, c=cell.c, n_train=cell.n_train, methods=list(cell.methods), backbone=cell.backbone,
|
||||
delta_ms=cell.delta_ms, posterior=cell.posterior, seeds=list(p["grid"]["seeds"] if seeds is None else seeds),
|
||||
budgets={m: p["training"]["budgets"].get(m.removesuffix("-TCN")) for m in cell.methods},
|
||||
equal_budget_arm=p["training"].get("equal_budget_arm"))
|
||||
if ident in seen:
|
||||
continue
|
||||
seen.add(ident)
|
||||
jobs.append(dict(p=p, cell=dataclasses.asdict(cell), root=str(root), device=device, mem_gb=workers_mem_gb,
|
||||
threads=threads, seeds=seeds, key=fingerprint(stamp, **settings)))
|
||||
# largest N first keeps the wall-clock tail short (as scripts 14/15)
|
||||
jobs.sort(key=lambda j: (-j["cell"]["n_train"], j["cell"]["rid"]))
|
||||
return jobs
|
||||
|
||||
|
||||
def run(stage: str, p: dict, studies: list[str], device: str, workers: int, mem_gb: float, threads: int = 2,
|
||||
mode: str = "main", rids=None, regimes=None, presets=None, controls: bool = False, seeds=None,
|
||||
root: Path | None = None, grid: dict | None = None) -> list[dict]:
|
||||
"""stage: posterior | train. mode: main (locked), dev (outputs/bench/dev), repro (outputs/bench/repro).
|
||||
grid / seeds: dev-only overrides of the (c, N) lists and the network seeds."""
|
||||
_threads(threads)
|
||||
if (grid or seeds) and mode != "dev":
|
||||
raise SystemExit("--drift / --n-train / --seeds are dev-only overrides")
|
||||
if mode == "repro":
|
||||
rp = p["reproduction"]
|
||||
rids, regimes = [rp["rid"]], [rp["regime"]]
|
||||
cells = [Cell("S1", rp["regime"], None, float(rp["c"]), int(rp["n_train"]), int(rp["rid"]), tuple(rp["methods"]))]
|
||||
else:
|
||||
cells = plan(p, studies, rids=rids, regimes=regimes, presets=presets, controls=controls, grid=grid)
|
||||
check_rids([c.rid for c in cells] or (rids or []), p, dev=(mode == "dev"), repro=(mode == "repro"))
|
||||
stamp = stamp_for(p, mode)
|
||||
root = root or bench_root(dev=(mode == "dev"), repro=(mode == "repro"))
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
jobs = make_jobs(p, cells, stage, stamp, root, device, mem_gb, threads, seeds)
|
||||
name = f"{stage}:{'+'.join(studies) if mode != 'repro' else 'repro'}:{mode}"
|
||||
print(f"{name}: {len(jobs)} jobs, {workers} workers, device {device}, root {root}", flush=True)
|
||||
fn = posterior_worker if stage == "posterior" else training_worker
|
||||
return run_jobs(jobs, fn, workers, root, name)
|
||||
|
||||
|
||||
def status(root: Path) -> str:
|
||||
path = root / "progress.json"
|
||||
return path.read_text(encoding="utf-8") if path.exists() else "protocol_bench has not started."
|
||||
Reference in New Issue
Block a user