"""P3 trajectories: checkpoint all registered budgets without looking at target labels.""" from __future__ import annotations import time from pathlib import Path import numpy as np import torch from torch import nn from ml_porosity.losses.legacy_v2 import LegacyV2Loss 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.bank_train import window_starts_fixed from ml_porosity.models.cnn_gru import CNNGRU from ml_porosity.models.train import CNNGRUHetero, predict class TCNHetero(nn.Module): def __init__(self, channels: int, d: int, dropout: float): super().__init__() layers = [] for dilation in (1, 2, 4, 8): layers.extend([nn.Conv1d(channels, d, 5, padding=2*dilation, dilation=dilation), nn.ReLU(), nn.Dropout(dropout)]) channels = d self.net = nn.Sequential(*layers, nn.Conv1d(d, 2, 1)) def forward(self, x): out = self.net(x) return out[:, :1], torch.nn.functional.softplus(out[:, 1:]) + 1e-3 class FixedSigmaHetero(CNNGRUHetero): def __init__(self, channels: int, d: int, dropout: float, fixed_sigma: float): super().__init__(channels, d, dropout) self.fixed_sigma = fixed_sigma def forward(self, x): mean, _ = super().forward(x) return mean, torch.full_like(mean, self.fixed_sigma) def make_model(method: str, channels: int, cfg: dict): torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True if method == 'M2-fixed-sigma': return FixedSigmaHetero(channels, cfg['d_channels'], cfg['p_dropout'], cfg.get('fixed_sigma', 1.0)) cls = TCNHetero if method.endswith('-TCN') else CNNGRU if method == 'B2' else CNNGRUHetero return cls(channels, cfg['d_channels'], cfg['p_dropout']) def method_spec(bundle: dict, label: str, method: str, p: dict) -> dict: m0, s0 = bundle[f'{label}/norm'] lam = float(bundle[f'{label}/lambda']) base = method if base in ('M2-anchor-only',): base = 'M1' elif base.startswith('M2-') and base not in ('M2-S256', 'M2-bulk'): base = 'M2-Sa' elif base == 'B3d-Sa-TCN': base = 'B3d-Sa' if method in ('B4a', 'B4b'): Y = bundle[f'{label}/B4'] lp = np.full(Y.shape[:2], -np.log(Y.shape[1])) return dict(kind='bank', Y=(Y-m0)/s0, logpi=lp, lam=None if method == 'B4a' else lam) if method in ('B4c', 'B4d'): return dict(kind='softdtw' if method == 'B4c' else 'dilate', Y=(bundle[f'{label}/B3b'][:, 0]-m0)/s0, **p['training']['softdtw' if method == 'B4c' else 'dilate']) Y = bundle[f'{label}/{base}'] if method in ('M2-S1', 'M2-S8'): Y = Y[:, :int(method[4:])] lp = bundle.get(f'{label}/{base}/logpi', np.full(Y.shape[:2], -np.log(Y.shape[1]))) if lp.shape != Y.shape[:2]: lp = np.full(Y.shape[:2], -np.log(Y.shape[1])) return dict(kind='legacy' if method == 'B2' else 'bank', Y=(Y-m0)/s0, logpi=lp, lam=1.0 if method == 'M2-lambda1' else lam) def ensemble(means: np.ndarray, sigmas: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray]: means = np.asarray(means, float) within = 0.0 if sigmas is None else np.mean(np.asarray(sigmas, float)**2, axis=0) return means.mean(axis=0), np.sqrt(np.maximum(within + means.var(axis=0), 0)) def train_trajectory(X, X_targets, spec: dict, method: str, cfg: dict, seed: int, budgets: list[int], device: str, checkpoint: Path | None = None) -> tuple[dict, dict]: torch.set_num_threads(2) 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 = tensor(X), tensor(spec['Y']) N, _, L = X.shape starts = torch.as_tensor(np.tile(window_starts_fixed(L), (N, 1)), device=device) logpi = tensor(spec.get('logpi', np.zeros(y.shape[:2]))) model = make_model(method, X.shape[1], cfg).to(device) opt = torch.optim.Adam(model.parameters(), lr=cfg['lr']) legacy = LegacyV2Loss() 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) if method == 'B2': mu = model(x) if step <= 50: mu = mu + 0.01 * torch.randn_like(mu) loss = legacy(mu, y[:, 0, None]) else: mu, sigma = model(x) if method == 'M2-fixed-sigma': sigma = torch.full_like(sigma, cfg.get('fixed_sigma', 1.0)) if spec['kind'] == 'bank': loss = bank_loss(mu[:, 0], sigma[:, 0], y, logpi, starts, 64, spec['lam']) else: f = softdtw_loss_fast if spec['kind'] == 'softdtw' else dilate_loss_fast kw = {k: spec[k] for k in ('gamma', 'band', 'alpha') if k in spec} loss = f(gather_windows(mu[:, 0], starts, 64).reshape(-1, 64), gather_windows(sigma[:, 0], starts, 64).reshape(-1, 64), gather_windows(y, starts, 64).reshape(-1, 64), **kw) if method == 'M2-legacy-loss': loss = loss + legacy(mu, y.mean(axis=1)[:, None]) 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) if method == 'M2-fixed-sigma': s = np.full_like(m, cfg.get('fixed_sigma', 1.0)) outputs[f'{step}/mu'] = m outputs[f'{step}/sigma'] = np.zeros_like(m) if s is None else 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}