File size: 10,860 Bytes
bb5e4ec | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | """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,
}
|