"""Shared training, validation, warmup-cosine scheduling, and collapse-detection loop.""" from __future__ import annotations import copy import time from dataclasses import dataclass from pathlib import Path import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import CosineAnnealingLR, LinearLR, SequentialLR from torch.utils.data import DataLoader from src.data.dataset import ( ChestXrayDataset, build_weighted_sampler, compute_inverse_class_weights, get_transforms, ) from src.losses.losses import FocalLoss, compute_loss_with_consistency from src.models.biohcl_sssm import strip_thop_keys from src.utils.metrics import compute_classification_metrics @dataclass class TrainConfig: epochs: int = 50 warmup_epochs: int = 5 patience: int = 10 batch_size: int = 16 lr: float = 1e-4 warmup_start_lr: float = 1e-6 weight_decay: float = 1e-2 grad_clip: float = 1.0 loss_type: str = "ce" # "ce" | "weighted_ce" | "focal" use_weighted_sampler: bool = True lambda_phys: float = 0.0 focal_gamma: float = 2.0 num_workers: int = 4 seed: int = 42 def set_seed(seed: int) -> None: np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) @torch.no_grad() def predict_probs( model: nn.Module, loader: DataLoader, device: torch.device ) -> tuple[np.ndarray, np.ndarray, float]: """Evaluate model cleanly in strict FP32 and return `(labels, probs_pos, mean_ce_loss)`.""" model.eval() probs_all, labels_all = [], [] ce_total, n_total = 0.0, 0 for imgs, labels in loader: imgs = imgs.to(device, non_blocking=True) labels_dev = labels.to(device, non_blocking=True) out = model(imgs) # Strict FP32 inference (handles tuple or logits tensor) logits = out[0] if isinstance(out, tuple) else out logits_f = logits.float() ce = F.cross_entropy(logits_f, labels_dev, reduction="sum") ce_total += float(ce.item()) n_total += labels.size(0) probs = F.softmax(logits_f, dim=1)[:, 1] probs_all.append(probs.cpu().numpy()) labels_all.append(labels.numpy()) return np.concatenate(labels_all), np.concatenate(probs_all), ce_total / max(n_total, 1) def fit_and_select_best( model: nn.Module, df_train, df_val, cfg: TrainConfig, device: torch.device, save_path: Path | None = None, run_name: str = "run", ) -> dict: """Train model on `df_train`, select best checkpoint strictly by Val Macro-F1 at `t=0.50`.""" set_seed(cfg.seed) if cfg.use_weighted_sampler and cfg.loss_type in ("weighted_ce", "focal"): raise ValueError( "Protocol violation: never combine WeightedRandomSampler with weighted loss!" ) train_tf, eval_tf = get_transforms() train_ds = ChestXrayDataset(df_train, transform=train_tf) val_ds = ChestXrayDataset(df_val, transform=eval_tf) pin = device.type == "cuda" if cfg.use_weighted_sampler: sampler = build_weighted_sampler(df_train) train_loader = DataLoader( train_ds, batch_size=cfg.batch_size, sampler=sampler, num_workers=cfg.num_workers, pin_memory=pin, persistent_workers=cfg.num_workers > 0, ) else: train_loader = DataLoader( train_ds, batch_size=cfg.batch_size, shuffle=True, num_workers=cfg.num_workers, pin_memory=pin, persistent_workers=cfg.num_workers > 0, ) val_loader = DataLoader( val_ds, batch_size=max(cfg.batch_size * 2, 32), shuffle=False, num_workers=cfg.num_workers, pin_memory=pin, persistent_workers=cfg.num_workers > 0, ) class_weights_list = compute_inverse_class_weights(df_train) class_weights_tensor = torch.tensor(class_weights_list, dtype=torch.float32, device=device) focal_fn = ( FocalLoss(gamma=cfg.focal_gamma, alpha=class_weights_list).to(device) if cfg.loss_type == "focal" else None ) optimizer = AdamW(model.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay) warmup_ep = min(cfg.warmup_epochs, max(cfg.epochs - 1, 1)) start_factor = max(min(cfg.warmup_start_lr / cfg.lr, 1.0), 1e-4) warmup_sched = LinearLR(optimizer, start_factor=start_factor, total_iters=warmup_ep) cosine_sched = CosineAnnealingLR(optimizer, T_max=max(cfg.epochs - warmup_ep, 1)) scheduler = SequentialLR( optimizer, schedulers=[warmup_sched, cosine_sched], milestones=[warmup_ep] ) scaler = torch.amp.GradScaler("cuda", enabled=device.type == "cuda") best_macro_f1 = -1.0 best_epoch = 0 best_metrics = None best_state = None best_val_labels = None best_val_probs = None fallback_state = None fallback_metrics = None fallback_labels = None fallback_probs = None no_improve = 0 consecutive_collapsed = 0 collapse_reason = "" history = [] t_start = time.time() for epoch in range(1, cfg.epochs + 1): ep_t0 = time.time() model.train() loss_sum, ce_sum, phys_sum, n_seen = 0.0, 0.0, 0.0, 0 for imgs, targets in train_loader: imgs = imgs.to(device, non_blocking=True) targets = targets.to(device, non_blocking=True) optimizer.zero_grad(set_to_none=True) with torch.amp.autocast("cuda", enabled=device.type == "cuda"): logits, feats = model(imgs) total_loss, cls_loss, phys_loss = compute_loss_with_consistency( logits=logits, features=feats, targets=targets, loss_type=cfg.loss_type, class_weights=class_weights_tensor if cfg.loss_type == "weighted_ce" else None, focal_fn=focal_fn, lambda_phys=cfg.lambda_phys, ) if torch.isnan(total_loss) or torch.isinf(total_loss): collapse_reason = f"NaN/Inf loss at epoch {epoch}" break scaler.scale(total_loss).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip) scaler.step(optimizer) scaler.update() bs = targets.size(0) loss_sum += float(total_loss.item()) * bs ce_sum += float(cls_loss.item()) * bs phys_sum += float(phys_loss.item()) * bs n_seen += bs if collapse_reason: print(f"[{run_name}] HALT: {collapse_reason}", flush=True) break scheduler.step() val_labels, val_probs, val_ce = predict_probs(model, val_loader, device) vm = compute_classification_metrics(val_labels, val_probs, threshold=0.50) collapsed_now = vm["unique_preds"] <= 1 if collapsed_now: consecutive_collapsed += 1 else: consecutive_collapsed = 0 ep_rec = { "epoch": epoch, "lr": float(optimizer.param_groups[0]["lr"]), "train_loss": round(loss_sum / max(n_seen, 1), 4), "train_ce": round(ce_sum / max(n_seen, 1), 4), "train_phys": round(phys_sum / max(n_seen, 1), 4), "val_ce": round(val_ce, 4), "val_acc": round(vm["accuracy"], 4), "val_macro_f1": round(vm["macro_f1"], 4), "val_f1": round(vm["f1"], 4), "val_auc": round(vm["roc_auc"], 4), "val_unique_preds": vm["unique_preds"], "sec": round(time.time() - ep_t0, 1), } history.append(ep_rec) print( f"[{run_name}] E{epoch:02d}/{cfg.epochs} | lr={ep_rec['lr']:.1e} " f"| tr_ce={ep_rec['train_ce']:.3f} phys={ep_rec['train_phys']:.3f} " f"| val_acc={vm['accuracy']*100:5.2f}% val_mf1={vm['macro_f1']:.4f} auc={vm['roc_auc']:.4f} " f"| uniq={vm['unique_preds']} | {ep_rec['sec']}s", flush=True, ) # Track non-collapsed best checkpoint strictly on Val Macro-F1 if not collapsed_now and vm["macro_f1"] > best_macro_f1: best_macro_f1 = vm["macro_f1"] best_epoch = epoch best_metrics = vm best_state = strip_thop_keys(copy.deepcopy({k: v.cpu() for k, v in model.state_dict().items()})) best_val_labels = val_labels best_val_probs = val_probs no_improve = 0 else: no_improve += 1 if fallback_state is None or epoch == 1: fallback_state = strip_thop_keys(copy.deepcopy({k: v.cpu() for k, v in model.state_dict().items()})) fallback_metrics = vm fallback_labels = val_labels fallback_probs = val_probs # Opus binding collapse check: detect persistent post-warmup single-class prediction if (epoch >= 2 and consecutive_collapsed >= 2) or (epoch >= cfg.warmup_epochs and collapsed_now): collapse_reason = f"COLLAPSE DETECTED at epoch {epoch}: single-class prediction (unique_preds={vm['unique_preds']})" print(f"[{run_name}] {collapse_reason}", flush=True) break if best_state is not None and no_improve >= cfg.patience: print(f"[{run_name}] Early stopping at epoch {epoch} (best epoch {best_epoch}, val_macro_f1={best_macro_f1:.4f})", flush=True) break status = "CONVERGED" if best_state is not None and not collapse_reason else "COLLAPSED" if best_state is not None and collapse_reason: # Recovered early then collapsed (or collapsed later) -> keep honest status status = "COLLAPSED_LATE" chosen_state = best_state if best_state is not None else fallback_state chosen_metrics = best_metrics if best_metrics is not None else fallback_metrics chosen_labels = best_val_labels if best_val_labels is not None else fallback_labels chosen_probs = best_val_probs if best_val_probs is not None else fallback_probs if save_path is not None and chosen_state is not None: save_path.parent.mkdir(parents=True, exist_ok=True) torch.save(chosen_state, save_path) return { "status": status, "collapse_reason": collapse_reason, "best_epoch": best_epoch if best_state is not None else len(history), "epochs_ran": len(history), "elapsed_sec": round(time.time() - t_start, 1), "best_val_metrics": chosen_metrics, "best_state": chosen_state, "val_labels": chosen_labels, "val_probs": chosen_probs, "history": history, }