"""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) -> 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.""" # 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) return out