P2 diagnosis on dev, P3 dev experiments, lock protocol_p3
- P2: SMC tie posterior (numpy + torch), RML/soft-DTW losses, bank training, D2 synthetic generator, scripts 09-13, protocol_p2 (locked) and its outcome (G-B failed; H1 not rejected, H3 rejected, H4 not rejected). - Diagnosis on dev realizations 900/901 only (scripts 14-17, run_p3_dev.sh): posterior screen, SMC stability (P = 1024, K = 1), sigma_a misspecification stress and training, H3 with the SMC posterior, F3 placement on sigma_post. - protocol_p3: H2 split into H2a (posterior-mean labels vs point ties) and H2b (RML vs posterior mean as a function of sigma_post); H3 descriptive only; sigma_a arm; new D2 config d2_synth_p3.yaml; main grid on realizations 8-15. Locked by configs/protocol_p3.sha256 and tag protocol-p3. - runlog: per-run logs and runtime index (logs/index.csv). - Docs: plan §12 items 10-11, theory, technical overview, report; wording aligned with Gunning & Glinsky (2006): the tie posterior is not claimed as new. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
83
ml_porosity/models/bank_train.py
Normal file
83
ml_porosity/models/bank_train.py
Normal file
@@ -0,0 +1,83 @@
|
||||
"""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
|
||||
Reference in New Issue
Block a user