"""P4 trajectories: masked bank losses, a checkpoint at every registered budget, no held-out label. Mirrors ml_porosity.f3.training.train_trajectory for the bank methods (same model, optimiser, seeding and checkpoints); the loss is volve.losses.masked_bank_loss on the label support of each bank member (finite samples). """ from __future__ import annotations import time from pathlib import Path import numpy as np import torch from torch import nn from ml_porosity.f3.training import ensemble, make_model from ml_porosity.models.bank_train import window_starts_fixed from ml_porosity.models.train import predict from ml_porosity.volve.losses import masked_bank_loss __all__ = ["ensemble", "method_spec", "train_trajectory"] def method_spec(bundle: dict, label: str, method: str) -> dict: """Normalised bank (NaN outside each member's label support), log prior weights, the member support masks (B, S, L) and λ. Single-member banks reduce to the masked Gaussian NLL for any λ.""" m0, s0 = bundle[f"{label}/norm"] Y = bundle[f"{label}/{method}"] lp = bundle.get(f"{label}/{method}/logpi", np.full(Y.shape[:2], -np.log(Y.shape[1]))) if lp.shape != Y.shape[:2]: raise ValueError(f"Bank weights do not match the bank: {label}/{method}") if np.isinf(Y).any(): raise ValueError(f"Label bank is not finite on its support: {label}/{method}") mask = np.isfinite(Y) if not mask.any(axis=2).all(): raise ValueError(f"A bank member has no label support: {label}/{method}") return dict(Y=(Y - m0) / s0, logpi=lp, mask=mask, lam=float(bundle[f"{label}/lambda"])) def train_trajectory(X, X_targets, spec: dict, method: str, cfg: dict, seed: int, budgets: list[int], device: str, checkpoint: Path | None = None, threads: int = 2) -> tuple[dict, dict]: torch.set_num_threads(threads) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True 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) tensor = lambda a: torch.as_tensor(np.asarray(a), dtype=torch.float32, device=device) x, y, logpi = tensor(X), tensor(spec["Y"]), tensor(spec["logpi"]) mask = torch.as_tensor(np.asarray(spec["mask"], bool), device=device) N, _, L = X.shape win = cfg["window_samples"] starts = torch.as_tensor(np.tile(window_starts_fixed(L, win, cfg["window_step"]), (N, 1)), device=device) model = make_model(method, X.shape[1], cfg).to(device) opt = torch.optim.Adam(model.parameters(), lr=cfg["lr"]) outputs, states = {}, {} if torch.device(device).type == "cuda": torch.cuda.synchronize() torch.cuda.reset_peak_memory_stats() begin = time.perf_counter() for step in range(1, max(budgets) + 1): model.train() opt.zero_grad(set_to_none=True) mu, sigma = model(x) loss = masked_bank_loss(mu[:, 0], sigma[:, 0], y, logpi, mask, starts, win, spec["lam"]) if not torch.isfinite(loss): raise FloatingPointError(f"Non-finite loss in {method}, step {step}") loss.backward() nn.utils.clip_grad_norm_(model.parameters(), cfg["grad_clip"]) opt.step() if step in budgets: m, s = predict(model, X_targets, device) outputs[f"{step}/mu"], outputs[f"{step}/sigma"] = m, s if checkpoint is not None: states[step] = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()} if torch.device(device).type == "cuda": torch.cuda.synchronize() elapsed = time.perf_counter() - begin if checkpoint is not None: tmp = checkpoint.with_suffix(".pt.tmp") torch.save({"states": states, "method": method, "channels": X.shape[1], "config": cfg}, tmp) tmp.replace(checkpoint) return outputs, {"wall_seconds": elapsed, "steps": max(budgets), "seconds_per_step": elapsed / max(budgets), "parameters": sum(v.numel() for v in model.parameters()), "peak_vram_bytes": torch.cuda.max_memory_allocated() if torch.device(device).type == "cuda" else 0}