- 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>
79 lines
2.9 KiB
Python
79 lines
2.9 KiB
Python
"""CNN–GRU training for B2 (original loss) and B3 (Gaussian NLL), with epoch selection in the inner loop."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import numpy as np
|
||
import torch
|
||
import torch.nn as nn
|
||
import torch.nn.functional as F
|
||
|
||
from ml_porosity.losses.legacy_v2 import LegacyV2Loss
|
||
from ml_porosity.models.cnn_gru import CNNGRU
|
||
|
||
|
||
class CNNGRUHetero(nn.Module):
|
||
"""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__()
|
||
self.net = CNNGRU(in_ch, d, pdrop)
|
||
self.net.head = nn.Conv1d(2 * d, 2, kernel_size=1)
|
||
self.net.head_skip = nn.Conv1d(in_ch, 2, kernel_size=1)
|
||
self.net.bias = nn.Parameter(torch.zeros(2))
|
||
self.sigma_min = sigma_min
|
||
|
||
def forward(self, x):
|
||
h = self.net.cnn(x)
|
||
h2, _ = self.net.gru(h.transpose(1, 2))
|
||
out = self.net.head(h2.transpose(1, 2)) + self.net.head_skip(x) + self.net.bias.view(1, 2, 1)
|
||
return out[:, :1], F.softplus(out[:, 1:]) + self.sigma_min
|
||
|
||
|
||
def gaussian_nll(mu, sigma, y):
|
||
return torch.mean(torch.log(sigma) + 0.5 * ((y - mu) / sigma) ** 2)
|
||
|
||
|
||
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) 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)
|
||
x, y = T(Xtr), T(Ytr)[:, None]
|
||
in_ch = Xtr.shape[1]
|
||
if kind == "legacy":
|
||
model = CNNGRU(in_ch, cfg["d_channels"], cfg["p_dropout"]).to(device)
|
||
loss_fn = LegacyV2Loss()
|
||
else:
|
||
model = CNNGRUHetero(in_ch, cfg["d_channels"], cfg["p_dropout"]).to(device)
|
||
opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
|
||
curve = []
|
||
xv = T(Xva) if Xva is not None else None
|
||
for ep in range(1, epochs + 1):
|
||
model.train()
|
||
opt.zero_grad()
|
||
if kind == "legacy":
|
||
pred = model(x)
|
||
if ep <= 50:
|
||
pred = pred + 0.01 * torch.randn_like(pred)
|
||
loss = loss_fn(pred, y)
|
||
else:
|
||
mu, sig = model(x)
|
||
loss = gaussian_nll(mu, sig, y)
|
||
loss.backward()
|
||
nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"])
|
||
opt.step()
|
||
if xv is not None and ep % eval_every == 0:
|
||
mu_v = predict(model, Xva, device)[0]
|
||
curve.append((ep, float(np.mean((mu_v - Yva) ** 2))))
|
||
return model, curve
|
||
|
||
|
||
@torch.no_grad()
|
||
def predict(model, X, device):
|
||
model.eval()
|
||
out = model(torch.tensor(X, dtype=torch.float32, device=device))
|
||
if isinstance(out, tuple):
|
||
return out[0][:, 0].cpu().numpy(), out[1][:, 0].cpu().numpy()
|
||
return out[:, 0].cpu().numpy(), None
|