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
|
||||
@@ -1,6 +1,6 @@
|
||||
"""CNN (dilated) + GRU 2 tầng hai chiều + skip head 1×1.
|
||||
"""Dilated CNN + 2-layer bidirectional GRU + 1×1 skip head.
|
||||
|
||||
Chuyển nguyên trạng từ `test 2/train_open_patch_v2.py` (lớp CNNGRU); không đổi kiến trúc.
|
||||
Ported verbatim from `test 2/train_open_patch_v2.py` (class CNNGRU); the architecture is unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Huấn luyện CNN–GRU cho B2 (loss gốc) và B3 (Gaussian NLL), chọn epoch theo vòng inner."""
|
||||
"""CNN–GRU training for B2 (original loss) and B3 (Gaussian NLL), with epoch selection in the inner loop."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -12,7 +12,7 @@ from ml_porosity.models.cnn_gru import CNNGRU
|
||||
|
||||
|
||||
class CNNGRUHetero(nn.Module):
|
||||
"""Backbone CNN–GRU v2 với head 2 kênh: μ và σ = softplus(·) + σ_min."""
|
||||
"""CNN–GRU v2 backbone with a 2-channel head: μ and σ = softplus(·) + σ_min."""
|
||||
|
||||
def __init__(self, in_ch: int, d: int = 64, pdrop: float = 0.05, sigma_min: float = 1e-3):
|
||||
super().__init__()
|
||||
@@ -35,7 +35,7 @@ def gaussian_nll(mu, sigma, y):
|
||||
|
||||
def train_cnn(Xtr, Ytr, cfg: dict, kind: str, seed: int, epochs: int, device: str,
|
||||
Xva=None, Yva=None, eval_every: int = 25):
|
||||
"""kind: "legacy" (B2) hoặc "nll" (B3). Y ở thang đã chuẩn hoá. Trả về (model, [(epoch, val_mse)])."""
|
||||
"""kind: "legacy" (B2) or "nll" (B3). Y is on the standardised scale. Returns (model, [(epoch, val_mse)])."""
|
||||
torch.manual_seed(seed)
|
||||
np.random.seed(seed)
|
||||
T = lambda a: torch.tensor(a, dtype=torch.float32, device=device)
|
||||
|
||||
Reference in New Issue
Block a user