"""Huấn luyện CNN–GRU cho B2 (loss gốc) và B3 (Gaussian NLL), chọn epoch theo vòng inner.""" 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): """Backbone CNN–GRU v2 với head 2 kênh: μ và σ = 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) hoặc "nll" (B3). Y ở thang đã chuẩn hoá. Trả về (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