"""Stage 2 flow-matching training and evaluation loops.""" import time import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader from timm.utils import AverageMeter from .training_utils import ( compute_subject_metrics, format_subject_accuracies, validate_finite_loss, ) def train_one_epoch_flow_matching( *, epoch: int, stage1_model: torch.nn.Module, stage2_models: nn.ModuleDict, train_loader: DataLoader, optimizers: dict[str, torch.optim.Optimizer], device: torch.device, subjects: list[int], ) -> float: """Train all per-subject Stage 2 CFM models for one epoch.""" stage1_model.eval() for model in stage2_models.values(): model.train() use_cuda = device.type == "cuda" if use_cuda: torch.cuda.empty_cache() torch.cuda.reset_peak_memory_stats() loss_m = AverageMeter() data_time_m = AverageMeter() step_time_m = AverageMeter() end = time.monotonic() for batch_idx, batch in enumerate(train_loader): feats = [f.to(device) for f in batch["features"]] fmri = batch["fmri"].to(device) batch_size = fmri.size(0) data_time = time.monotonic() - end with torch.no_grad(): mu_anchor = stage1_model(feats) batch_loss = 0.0 for i, sub in enumerate(subjects): sub_key = str(sub) cfm = stage2_models[sub_key] optimizer = optimizers[sub_key] x1 = fmri[:, i].transpose(1, 2) mu = mu_anchor[:, i].transpose(1, 2) loss, _ = cfm.compute_loss(x1, mu) optimizer.zero_grad() loss.backward() optimizer.step() batch_loss += float(loss.item()) loss_item = batch_loss / len(subjects) validate_finite_loss(loss_item, batch_idx) if use_cuda: torch.cuda.synchronize() step_time = time.monotonic() - end loss_m.update(loss_item, batch_size) data_time_m.update(data_time, batch_size) step_time_m.update(step_time, batch_size) if (batch_idx + 1) % 20 == 0: tput = batch_size / step_time_m.avg if use_cuda: alloc_mem_gb = torch.cuda.max_memory_allocated() / 1e9 res_mem_gb = torch.cuda.max_memory_reserved() / 1e9 else: alloc_mem_gb = 0.0 res_mem_gb = 0.0 print( f"Stage 2 Train: {epoch:>3d} [{batch_idx:>3d}]" f" Loss: {loss_m.val:#.3g} ({loss_m.avg:#.3g})" f" Time: {data_time_m.avg:.3f},{step_time_m.avg:.3f} {tput:.0f}/s" f" Mem: {alloc_mem_gb:.2f},{res_mem_gb:.2f} GB" ) end = time.monotonic() return float(loss_m.avg) @torch.no_grad() def evaluate_stage2( *, epoch: int, stage1_model: torch.nn.Module, stage2_models: nn.ModuleDict, val_loader: DataLoader, device: torch.device, subjects: list[int], ds_name: str = "val", n_timesteps: int = 10, ) -> tuple[float, dict[str, np.ndarray | float]]: """Evaluate Stage 2 model stack on one validation split.""" stage1_model.eval() for model in stage2_models.values(): model.eval() samples = [] outputs = [] for batch in val_loader: feats = [f.to(device) for f in batch["features"]] fmri = batch["fmri"].to(device) mu_anchor = stage1_model(feats) batch_preds = [] for i, sub in enumerate(subjects): cfm = stage2_models[str(sub)] mu = mu_anchor[:, i].transpose(1, 2) pred = cfm(mu, n_timesteps=n_timesteps) pred = pred.transpose(1, 2).unsqueeze(1) batch_preds.append(pred) pred_combined = torch.cat(batch_preds, dim=1) n_samples, n_subjects, seq_len, channels = fmri.shape if n_subjects != len(subjects): raise ValueError( f"Expected {len(subjects)} subjects in batch, got {n_subjects}." ) outputs.append( pred_combined.cpu().numpy().swapaxes(0, 1).reshape((n_subjects, n_samples * seq_len, channels)) ) samples.append( fmri.cpu().numpy().swapaxes(0, 1).reshape((n_subjects, n_samples * seq_len, channels)) ) outputs_np = np.concatenate(outputs, axis=1) samples_np = np.concatenate(samples, axis=1) acc, metrics = compute_subject_metrics(samples_np, outputs_np, subjects) accs_fmt = format_subject_accuracies(metrics) print(f"Evaluate Stage 2 ({ds_name}): {epoch:>3d} Acc: {accs_fmt} ({acc:.3f})") return acc, metrics