| import time |
| import math |
| import numpy as np |
| import torch |
| import torch.nn as nn |
| from typing import Dict |
| from torch.utils.data import DataLoader |
| from timm.utils import AverageMeter |
|
|
| def train_one_epoch_condition( |
| *, |
| epoch: int, |
| model: torch.nn.Module, |
| train_loader: DataLoader, |
| optimizer: torch.optim.Optimizer, |
| device: torch.device, |
| ): |
| 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 |
|
|
| pred, _ = model(feats) |
|
|
| loss = nn.MSELoss()(pred, fmri) |
| loss_item = loss.item() |
|
|
| if math.isnan(loss_item) or math.isinf(loss_item): |
| raise RuntimeError( |
| f"NaN/Inf loss encountered on step {batch_idx + 1}; exiting" |
| ) |
|
|
| optimizer.zero_grad() |
| loss.backward() |
| optimizer.step() |
|
|
| 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 = res_mem_gb = 0.0 |
|
|
| print( |
| f"Stage 1 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 loss_m.avg |
|
|
| 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, |
| ): |
| 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, embed_anchor = stage1_model(feats) |
|
|
| batch_loss = 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) |
| src_cond = mu_anchor[:, i].transpose(1, 2) |
| mu_fusion = embed_anchor.transpose(1, 2) |
|
|
| loss, _ = cfm.compute_loss(x1, src_cond, mu_fusion) |
|
|
| optimizer.zero_grad() |
| loss.backward() |
| optimizer.step() |
|
|
| batch_loss += loss.item() |
|
|
| loss_item = batch_loss / len(subjects) |
|
|
| if math.isnan(loss_item) or math.isinf(loss_item): |
| raise RuntimeError( |
| f"NaN/Inf loss encountered on step {batch_idx + 1}; exiting" |
| ) |
|
|
| if use_cuda: |
| torch.cuda.synchronize() |
| step_time = time.monotonic() - end |
|
|
| loss_m.update(loss_item, fmri.size(0)) |
| 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 = 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 loss_m.avg |
|
|
| def train_one_epoch_jointly( |
| *, |
| epoch: int, |
| stage1_model: torch.nn.Module, |
| stage2_models: nn.ModuleDict, |
| train_loader: DataLoader, |
| stage1_optimizer: torch.optim.Optimizer, |
| stage2_optimizers: Dict[str, torch.optim.Optimizer], |
| device: torch.device, |
| subjects: list, |
| ): |
| stage1_model.train() |
| 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 |
|
|
| mu_anchor, embed_anchor = stage1_model(feats) |
| stage1_loss = nn.MSELoss()(mu_anchor, fmri) |
|
|
| stage2_loss = 0.0 |
| for i, sub in enumerate(subjects): |
| sub_key = str(sub) |
| cfm = stage2_models[sub_key] |
|
|
| x1 = fmri[:, i].transpose(1, 2) |
| src_cond = mu_anchor[:, i].transpose(1, 2) |
| mu_fusion = embed_anchor.transpose(1, 2) |
|
|
| loss, _ = cfm.compute_loss(x1, src_cond, mu_fusion) |
| stage2_loss += loss |
|
|
| stage2_loss = stage2_loss / len(subjects) |
| total_loss = stage1_loss + stage2_loss |
| loss_item = total_loss.item() |
|
|
| if math.isnan(loss_item) or math.isinf(loss_item): |
| raise RuntimeError( |
| f"NaN/Inf loss encountered on step {batch_idx + 1}; exiting" |
| ) |
|
|
| stage1_optimizer.zero_grad() |
| for opt in stage2_optimizers.values(): |
| opt.zero_grad() |
|
|
| total_loss.backward() |
|
|
| stage1_optimizer.step() |
| for opt in stage2_optimizers.values(): |
| opt.step() |
|
|
| 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 = res_mem_gb = 0.0 |
|
|
| print( |
| f"Joint 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 loss_m.avg |
|
|
| @torch.no_grad() |
| def run_inference( |
| *, |
| stage1_model: nn.Module, |
| stage2_models: nn.ModuleDict, |
| test_loader, |
| fmri_num_samples: dict[str, dict[str, int]], |
| subjects: list[int], |
| device: torch.device, |
| n_timesteps: int = 25, |
| ) -> dict[str, dict[str, np.ndarray]]: |
| stage1_model.eval() |
| stage2_models.eval() |
|
|
| submission = {f"sub-{sub:02d}": {} for sub in subjects} |
|
|
| for batch_idx, batch in enumerate(test_loader): |
| feats = [f.to(device) for f in batch["features"]] |
| episodes = batch["episode"] |
|
|
| mu_anchor, embed_anchor = stage1_model(feats) |
|
|
| N, S, T, V = mu_anchor.shape |
| assert N == 1, "Batch size must be 1 for submission" |
|
|
| batch_preds = [] |
| for i, sub in enumerate(subjects): |
| sub_key = str(sub) |
| cfm = stage2_models[sub_key] |
|
|
| src_cond = mu_anchor[:, i].transpose(1, 2) |
| mu_fusion = embed_anchor.transpose(1, 2) |
|
|
| pred = cfm(src_cond, mu_fusion, n_timesteps=n_timesteps) |
| pred = pred.transpose(1, 2) |
| batch_preds.append(pred) |
|
|
| for ii, episode in enumerate(episodes): |
| for jj, sub_id in enumerate(subjects): |
| sub = f"sub-{sub_id:02d}" |
| pred = batch_preds[jj][ii].cpu().numpy() |
|
|
| num_samples = fmri_num_samples[sub].get(episode, len(pred)) |
| pred = pred[:num_samples].astype(np.float32) |
|
|
| submission[sub][episode] = pred |
|
|
| if (batch_idx + 1) % 10 == 0: |
| print(f" Processed {batch_idx + 1} episodes...") |
|
|
| return submission |
|
|