"""Resumable P4 stages. A worker only ever loads the data view of its own training wells and selects nothing. Progress goes to outputs/p4//progress.json (retried when Windows locks the file, and never fatal), not to the P3 dashboard. """ from __future__ import annotations import copy import itertools import json 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 from ml_porosity.f3.progress import write_json from ml_porosity.paths import outputs_dir from ml_porosity.volve.data import VolveData from ml_porosity.volve.folds import prediction_targets, target_name, training_sets from ml_porosity.volve.protocol import current_stamp, digest, fingerprint, freeze, source_config from ml_porosity.volve.registration import METHODS def set_name(names) -> str: """'F-1A__F-1B__F-11A__F-12': sorted well names without spaces.""" return "__".join(sorted(n.replace(" ", "") for n in names)) def reg_path(root: Path, names, sigma_a: float = 7) -> Path: return root / "registration" / f"{set_name(names)}_sa{sigma_a:g}.npz" def job_path(root: Path, names, method: str, label: str, seed: int, sigma_a: float = 7) -> Path: return root / "train" / f"{set_name(names)}__{method}__{label}__s{seed}__sa{sigma_a:g}.npz" def load_bundle(path: Path) -> dict: with np.load(path) as z: return {k: z[k] for k in z.files} def nan_allowed(key: str) -> bool: """Label banks are NaN outside each member's label support; every other numeric array must be finite.""" parts = key.split("/") return len(parts) == 2 and parts[1] in METHODS def check_arrays(path: Path, arrays: dict) -> None: if not arrays: raise RuntimeError(f"Empty completed artifact: {path}") for k, a in arrays.items(): if not np.issubdtype(a.dtype, np.number): continue if np.isinf(a).any() or (np.isnan(a).any() and not nan_allowed(k)) or np.isnan(a).all(): raise RuntimeError(f"Corrupt/non-finite artifact: {path}/{k}") def reusable(path: Path, key: str) -> bool: meta = path.with_suffix(".json") if not path.exists() or 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: {path}. Use a new output directory.") if stored.get("artifact_sha256") is None or digest(path) != stored["artifact_sha256"]: raise RuntimeError(f"Missing or mismatched completed-artifact checksum: {path}") if path.parent.name == "train": ckpt = path.with_suffix(".pt") if not ckpt.exists() or digest(ckpt) != stored.get("checkpoint_sha256"): raise RuntimeError(f"Missing or mismatched model checkpoint: {ckpt}") check_arrays(path, load_bundle(path)) return True def save_npz(path: Path, arrays: dict) -> None: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(".tmp.npz") np.savez_compressed(tmp, **arrays) tmp.replace(path) def registration_worker(job: dict) -> dict: import torch from ml_porosity.volve.registration import register_set torch.set_num_threads(job["p"]["runtime"]["cpu_threads_per_worker"]) path = reg_path(Path(job["root"]), job["names"], job["sa"]) if reusable(path, job["key"]): return {"cached": True, "path": str(path)} data = VolveData(job["p"], training_wells=tuple(job["names"])) bundle, meta = register_set(data, tuple(job["names"]), job["p"], job["device"], job["sa"]) check_arrays(path, bundle) save_npz(path, bundle) write_json(path.with_suffix(".json"), meta | {"fingerprint": job["key"], "artifact_sha256": digest(path)}) return {"cached": False, "path": str(path), **meta} def training_worker(job: dict) -> dict: from ml_porosity.volve.training import method_spec, train_trajectory root, p = Path(job["root"]), job["p"] label, names = p["data"]["label"], tuple(sorted(job["names"])) path = job_path(root, names, job["method"], label, job["seed"], job["sa"]) if reusable(path, job["key"]): return {"cached": True, "path": str(path)} data = VolveData(p, training_wells=names) bundle = load_bundle(reg_path(root, names, job["sa"])) if tuple(bundle["wells"]) != names: raise RuntimeError("Registration cache contains different wells") targets = prediction_targets(data.wells, names) X = np.stack([data.X(w, "reference") for w in names]) X_targets = np.stack([data.X(w, k) for w, k in targets]) spec = method_spec(bundle, label, job["method"]) ckpt = path.with_suffix(".pt") ckpt.parent.mkdir(parents=True, exist_ok=True) pred, meta = train_trajectory(X, X_targets, spec, job["method"], p["training"], job["seed"], p["training"]["budgets"], job["device"], ckpt, p["runtime"]["cpu_threads_per_worker"]) mean, sd = bundle[f"{label}/norm"] pred = {k: v * sd + (mean if k.endswith("/mu") else 0) for k, v in pred.items()} pred |= {"targets": np.asarray([target_name(w, k) for w, k in targets]), "wells": np.asarray(names), "norm": bundle[f"{label}/norm"]} check_arrays(path, pred) save_npz(path, pred) write_json(path.with_suffix(".json"), meta | { "fingerprint": job["key"], "artifact_sha256": digest(path), "checkpoint_sha256": digest(ckpt), "training_wells": list(names), "label": label, "method": job["method"], "seed": job["seed"], "sigma_a_ms": job["sa"], "n_targets": len(targets)}) return {"cached": False, "path": str(path), **meta} def progress(root: Path, **values) -> None: path = root / "progress.json" for attempt in range(20): try: old = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} write_json(path, old | values | {"updated": datetime.now().astimezone().isoformat(timespec="seconds")}) return except (PermissionError, json.JSONDecodeError): time.sleep(0.25 * (attempt + 1)) print(f"warning: progress file not updated: {path}", flush=True) def run_jobs(jobs: list[dict], fn, workers: int, stage: str) -> list[dict]: if not jobs: return [] root = Path(jobs[0]["root"]) started, results = time.perf_counter(), [] progress(root, stage=stage, 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, status="failed; pending jobs cancelled", error=f"{futures[fut]['key'][:12]}: {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, completed=len(results), cached=len(results) - fresh, elapsed_seconds=elapsed, eta_seconds=eta) print(f"{stage} {len(results)}/{len(jobs)} {'cached ' if result.get('cached') else ''}" f"{result['path']}", flush=True) progress(root, status="done", eta_seconds=0) return results def sigma_arms(p: dict, arms: str) -> list[float]: """'primary' → [σ_a], 'sensitivity' → the misspecification arms, 'all' → both.""" primary, extra = [p["registration"]["sigma_a_ms"]], list(p["registration"]["sigma_a_sensitivity_ms"]) return {"primary": primary, "sensitivity": extra, "all": primary + extra}[arms] def fold_sets(p: dict) -> list[tuple[str, ...]]: return training_sets(p["data"]["wells"], p["split"]["schemes"], source_config(p)["p4"]) def registration_jobs(p: dict, stamp: dict, root: Path, device: str, arms: str = "primary") -> list[dict]: jobs = [] for names, sa in itertools.product(fold_sets(p), sigma_arms(p, arms)): settings = dict(names=list(names), sa=sa) jobs.append(dict(p=p, root=str(root), device=device, **settings, key=fingerprint(stamp, stage="registration", **settings))) return jobs def arm_methods(p: dict, sa: float) -> list[str]: main = sa == p["registration"]["sigma_a_ms"] return list(p["methods"]["main"] if main else p["registration"]["sensitivity_methods"]) def training_jobs(p: dict, stamp: dict, root: Path, device: str, arms: str = "primary") -> list[dict]: jobs = [] for names, sa in itertools.product(fold_sets(p), sigma_arms(p, arms)): for method, seed in itertools.product(arm_methods(p, sa), p["split"]["seeds"]): settings = dict(names=list(names), method=method, label=p["data"]["label"], seed=seed, sa=sa) jobs.append(dict(p=p, root=str(root), device=device, **settings, key=fingerprint(stamp, stage="train", **settings))) return jobs def smoke_protocol(p: dict) -> dict: """Reduced settings for a pipeline check; outputs go to outputs/p4/smoke and are never results.""" p = copy.deepcopy(p) p["split"]["seeds"] = [0] p["registration"].update(particles=16, S=8, hyper_starts=1, smc_moves=1, phase_half_width=0, phase_max_extra=0, sigma_a_sensitivity_ms=[]) p["training"]["budgets"] = [2, 4] return p def benchmark(p: dict, device: str, steps: int = 100) -> dict: """Runtime pilot outside the result tree: one registration of the first (largest) training set and `steps` training steps of B3b and M2-Sa on it. Training wells only; no held-out label, nothing selected.""" from ml_porosity.volve.training import method_spec, train_trajectory root, sa, label = outputs_dir() / "p4" / "benchmark", p["registration"]["sigma_a_ms"], p["data"]["label"] sets = fold_sets(p) names = sets[0] stamp = current_stamp(p) | {"benchmark_only": True} registration_worker(dict(p=p, root=str(root), device=device, names=list(names), sa=sa, key=fingerprint(stamp, stage="registration", names=list(names), sa=sa))) seconds = json.loads(reg_path(root, names, sa).with_suffix(".json").read_text(encoding="utf-8"))["wall_seconds"] data = VolveData(p, training_wells=names) bundle = load_bundle(reg_path(root, names, sa)) X = np.stack([data.X(w, "reference") for w in names]) X_targets = np.stack([data.X(w, k) for w, k in prediction_targets(data.wells, names)]) per_step = {m: train_trajectory(X, X_targets, method_spec(bundle, label, m), m, p["training"], 0, [steps], device, None, p["runtime"]["cpu_threads_per_worker"])[1]["seconds_per_step"] for m in ("B3b", "M2-Sa")} # Registration cost grows with the number of wells; the largest set gives the training-step upper bound. reg_primary = seconds * sum(len(s) for s in sets) / len(names) n_sens = len(p["registration"]["sigma_a_sensitivity_ms"]) steps_per_job = max(p["training"]["budgets"]) * max(per_step.values()) jobs = {"primary": len(sets) * len(p["methods"]["main"]) * len(p["split"]["seeds"]), "sensitivity": len(sets) * len(p["registration"]["sensitivity_methods"]) * len(p["split"]["seeds"]) * n_sens} out = {"device": device, "training_wells": list(names), "registration_seconds_largest_set": seconds, "seconds_per_step": per_step, "registration_jobs": {"primary": len(sets), "sensitivity": len(sets) * n_sens}, "training_jobs": jobs, "sequential_seconds": {"registration_primary": reg_primary, "registration_sensitivity": reg_primary * n_sens, "training_primary": jobs["primary"] * steps_per_job, "training_sensitivity": jobs["sensitivity"] * steps_per_job}, "note": "One-worker extrapolation from one real training set; parallel workers on one GPU speed this up " "sublinearly. Not a confidence interval."} write_json(outputs_dir() / "p4" / "benchmark.json", out) return out def run(stage: str, p: dict, device: str, workers: int, smoke: bool = False, arms: str = "primary") -> None: root = outputs_dir() / "p4" if smoke: if arms != "primary": raise ValueError("Smoke runs use the primary σ_a arm only") p = smoke_protocol(p) root = root / "smoke" if stage == "summarize": # Scores held-out PHIF: only once the design is frozen. stamp = freeze(check=True) | {"smoke": p} else: stamp = current_stamp() | {"smoke": p, "unlocked_draft": True} else: stamp = freeze(check=True) if stage == "register": run_jobs(registration_jobs(p, stamp, root, device, arms), registration_worker, workers, stage) elif stage == "train": run_jobs(training_jobs(p, stamp, root, device, arms), training_worker, workers, stage) elif stage == "summarize": from ml_porosity.volve.evaluation import summarize # The G-D report always needs the primary arm. summarize(p, root, sigma_arms(p, "primary" if arms == "primary" else "all")) else: raise ValueError(stage)