Files
ML-Porosity/ml_porosity/models/bank_train.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

87 lines
4.0 KiB
Python
Raw Permalink 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.
"""Shared training routine for the P2 methods on D2 (plan §4.4–4.5, §5.3).
A single CNNGRUHetero predicts (μ, σ) over the full main window; the loss is computed on fixed 64-sample
sub-windows (starting at 0, 2, …, L − 64), full batch, with the same optimizer for all methods. The methods
differ only in:
- "bank": label bank Y (N, S, L), log π (N, S) and λ (None → hard-min). S = 1 gives the Gaussian NLL (Oracle,
B3a–d); a bank of ±K shifts with uniform π gives B4a/B4b; posterior warp samples give M1/M2.
- "softdtw" / "dilate": soft-DTW / DILATE with a Gaussian NLL cost on each sub-window (B4c/B4d).
- "mse_win": MSE of μ against per-sub-window labels, Ywin (N, J, win) (H1: fixed per-window shift).
Test predictions are taken at the step counts in `budgets` along a single training trajectory (full batch,
deterministic given the seed), which is equivalent to training separately for each budget.
"""
from __future__ import annotations
import numpy as np
import torch
import torch.nn as nn
from ml_porosity.losses.rml import bank_loss, gather_windows
from ml_porosity.losses.softdtw import dilate_loss_fast, softdtw_loss_fast
from ml_porosity.models.train import CNNGRUHetero, predict
WIN = 64
def window_starts_fixed(L: int, win: int = WIN, step: int = 2) -> np.ndarray:
return np.arange(0, L - win + 1, step)
def zscore_patch(seis: np.ndarray, sel: np.ndarray) -> np.ndarray:
"""Patch (C, n_ext) → (C, L) on the main window, z-scored per channel (as in P1)."""
p = seis[:, sel].astype(np.float64)
return (p - p.mean(1, keepdims=True)) / (p.std(1, keepdims=True) + 1e-8)
def train_predict(X: np.ndarray, Xte: np.ndarray, spec: dict, cfg: dict, seed: int, budgets: list[int],
device: str, on_budget=None) -> dict[int, tuple[np.ndarray, np.ndarray]]:
"""X (N, C, L), Xte (M, C, L); labels in spec are already standardised. Returns {budget: (μ, σ)} for
Xte (M, L), on the standardised scale. on_budget (optional): callback on_budget(step, model) invoked right
after the predictions at each budget step (model in eval mode); the default None leaves the loop unchanged."""
# Same RNG stream as torch.manual_seed, but only touches the selected device: manual_seed_all opens a CUDA
# context on every visible GPU (shared machine).
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)
T = lambda a: torch.as_tensor(np.asarray(a), dtype=torch.float32, device=device)
x = T(X)
N, _, L = X.shape
starts = torch.as_tensor(np.tile(window_starts_fixed(L), (N, 1)), device=device)
kind = spec["kind"]
if kind == "bank":
Y, logpi, lam = T(spec["Y"]), T(spec["logpi"]), spec["lam"]
loss_fn = lambda mu, s: bank_loss(mu, s, Y, logpi, starts, WIN, lam)
elif kind in ("softdtw", "dilate"):
yw = gather_windows(T(spec["Y"]).reshape(N, L), starts, WIN).reshape(-1, WIN)
f = softdtw_loss_fast if kind == "softdtw" else dilate_loss_fast
kw = {k: spec[k] for k in ("gamma", "band", "alpha") if k in spec}
loss_fn = lambda mu, s: f(gather_windows(mu, starts, WIN).reshape(-1, WIN),
gather_windows(s, starts, WIN).reshape(-1, WIN), yw, **kw)
elif kind == "mse_win":
Yw = T(spec["Ywin"])
loss_fn = lambda mu, s: ((gather_windows(mu, starts, WIN) - Yw) ** 2).mean()
else:
raise ValueError(kind)
model = CNNGRUHetero(X.shape[1], cfg["d_channels"], cfg["p_dropout"]).to(device)
opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
out = {}
for step in range(1, max(budgets) + 1):
model.train()
opt.zero_grad()
mu, s = model(x)
loss = loss_fn(mu[:, 0], s[:, 0])
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"])
opt.step()
if step in budgets:
out[step] = predict(model, Xte, device)
if on_budget is not None:
on_budget(step, model)
return out