Files
ML-Porosity/ml_porosity/volve/training.py
lamlvh 0cfe202a8b Complete P4 Volve; pivot the manuscript to theory + benchmark
P4 (Volve field case). Add the deviated-well and Volve well builders
(ml_porosity/data/deviated.py, volve_wells.py), the ml_porosity/volve/
pipeline, scripts 23-25, the run_p4 drivers and tests. The protocol
configs/protocol_volve.yaml was locked at 2026-10-29T01:17:42Z before the
run (.sha256, .lock.json) and is committed here after the run. Gate G-D
failed: M2-Sa beats the selected B3 at 2/6 wells (lowo) and 3/6 (slot),
coverage90 is about 0.47, and no method has blind-well skill (R2 < 0).
A post hoc constant at the training-well mean beats every network, so
G-D had no power. The dropped P4x exploratory run is kept as a record
only (exploratory/, docs/research/p4-exploratory.md).

Applicability and Teapot Dome (exploratory, pre-declared). Scripts 26-29
and docs/research/applicability-*.md: F3 and Volve fail C1 and pass C2;
T3 power needs 5-18 blind wells with an exact reference; Teapot T0 and
pilot P-a failed, so Teapot is stopped. Raw Teapot data stay gitignored.

Manuscript (Pivot 1, level A). Reframe paper/ as a theory and synthetic
benchmark paper: Propositions 3-6, Corollaries 3-4, T4 coverage
(script 30) and the post hoc H2b bound check (script 31), with F3/Volve
moved to Appendix B. Correct two earlier claims: the Berkson and
classical bounds differ by 1.5-4.6x at the f^4-weighted band, and the
bank gain exceeds the registered classical bound (7/8 wide cells at
N = 16) but only 3/8 under the post hoc Berkson bound.

Docs. Sync plan, AGENTS.md, README, report.html, theory and technical
overview. The length pass for the venue is dropped by the user
(plan section 12 item 25); the length risk stays recorded as R9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 12:18:22 +00:00

88 lines
4.1 KiB
Python

"""P4 trajectories: masked bank losses, a checkpoint at every registered budget, no held-out label.
Mirrors ml_porosity.f3.training.train_trajectory for the bank methods (same model, optimiser, seeding and
checkpoints); the loss is volve.losses.masked_bank_loss on the label support of each bank member (finite samples).
"""
from __future__ import annotations
import time
from pathlib import Path
import numpy as np
import torch
from torch import nn
from ml_porosity.f3.training import ensemble, make_model
from ml_porosity.models.bank_train import window_starts_fixed
from ml_porosity.models.train import predict
from ml_porosity.volve.losses import masked_bank_loss
__all__ = ["ensemble", "method_spec", "train_trajectory"]
def method_spec(bundle: dict, label: str, method: str) -> dict:
"""Normalised bank (NaN outside each member's label support), log prior weights, the member support masks
(B, S, L) and λ. Single-member banks reduce to the masked Gaussian NLL for any λ."""
m0, s0 = bundle[f"{label}/norm"]
Y = bundle[f"{label}/{method}"]
lp = bundle.get(f"{label}/{method}/logpi", np.full(Y.shape[:2], -np.log(Y.shape[1])))
if lp.shape != Y.shape[:2]:
raise ValueError(f"Bank weights do not match the bank: {label}/{method}")
if np.isinf(Y).any():
raise ValueError(f"Label bank is not finite on its support: {label}/{method}")
mask = np.isfinite(Y)
if not mask.any(axis=2).all():
raise ValueError(f"A bank member has no label support: {label}/{method}")
return dict(Y=(Y - m0) / s0, logpi=lp, mask=mask, lam=float(bundle[f"{label}/lambda"]))
def train_trajectory(X, X_targets, spec: dict, method: str, cfg: dict, seed: int, budgets: list[int],
device: str, checkpoint: Path | None = None, threads: int = 2) -> tuple[dict, dict]:
torch.set_num_threads(threads)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
torch.default_generator.manual_seed(seed)
if torch.device(device).type == "cuda":
torch.cuda.set_device(device)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
tensor = lambda a: torch.as_tensor(np.asarray(a), dtype=torch.float32, device=device)
x, y, logpi = tensor(X), tensor(spec["Y"]), tensor(spec["logpi"])
mask = torch.as_tensor(np.asarray(spec["mask"], bool), device=device)
N, _, L = X.shape
win = cfg["window_samples"]
starts = torch.as_tensor(np.tile(window_starts_fixed(L, win, cfg["window_step"]), (N, 1)), device=device)
model = make_model(method, X.shape[1], cfg).to(device)
opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
outputs, states = {}, {}
if torch.device(device).type == "cuda":
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
begin = time.perf_counter()
for step in range(1, max(budgets) + 1):
model.train()
opt.zero_grad(set_to_none=True)
mu, sigma = model(x)
loss = masked_bank_loss(mu[:, 0], sigma[:, 0], y, logpi, mask, starts, win, spec["lam"])
if not torch.isfinite(loss):
raise FloatingPointError(f"Non-finite loss in {method}, step {step}")
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"])
opt.step()
if step in budgets:
m, s = predict(model, X_targets, device)
outputs[f"{step}/mu"], outputs[f"{step}/sigma"] = m, s
if checkpoint is not None:
states[step] = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
if torch.device(device).type == "cuda":
torch.cuda.synchronize()
elapsed = time.perf_counter() - begin
if checkpoint is not None:
tmp = checkpoint.with_suffix(".pt.tmp")
torch.save({"states": states, "method": method, "channels": X.shape[1], "config": cfg}, tmp)
tmp.replace(checkpoint)
return outputs, {"wall_seconds": elapsed, "steps": max(budgets), "seconds_per_step": elapsed / max(budgets),
"parameters": sum(v.numel() for v in model.parameters()),
"peak_vram_bytes": torch.cuda.max_memory_allocated() if torch.device(device).type == "cuda" else 0}