"""Top-level training script (Hydra + PyTorch Lightning).""" from __future__ import annotations import os import sys from pathlib import Path import hydra import pytorch_lightning as pl import torch from omegaconf import DictConfig, OmegaConf from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger # --- Force weights_only=False for checkpoint loading -------------- # Our checkpoints contain OmegaConf hyperparameters which are not in # the default safe-globals allowlist of PyTorch 2.6+. Since checkpoints # are produced by our own training pipeline, we trust them and disable # the weights_only restriction. import lightning_fabric.utilities.cloud_io as _lf_cloud_io _orig_torch_load = torch.load def _unsafe_torch_load(*args, **kwargs): kwargs["weights_only"] = False return _orig_torch_load(*args, **kwargs) # Patch both the global torch.load reference used inside lightning_fabric # and torch.load itself (belt-and-suspenders). _lf_cloud_io.torch.load = _unsafe_torch_load torch.load = _unsafe_torch_load # ensure `src/` is importable when running as a script sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from src.data import FairTalkingDataModule from src.methods import build_method from src.utils.io import find_latest_ckpt @hydra.main(version_base=None, config_path="../configs", config_name="train") def main(cfg: DictConfig) -> None: pl.seed_everything(cfg.seed, workers=True) torch.backends.cudnn.benchmark = True # --- data ------------------------------------------------------ dm = FairTalkingDataModule( data_cfg=cfg.data, return_paired=bool(getattr(cfg.method, "aux_crossgen", {}).get("enabled", False)) if hasattr(cfg.method, "aux_crossgen") else False, ) # --- model ----------------------------------------------------- model = build_method( method_name=cfg.method.name, method_cfg=cfg.method, backbone_cfg=cfg.backbone, data_cfg=cfg.data, ) # --- output dir ----------------------------------------------- out_dir = Path(cfg.output_dir).resolve() out_dir.mkdir(parents=True, exist_ok=True) # --- loggers -------------------------------------------------- loggers = [TensorBoardLogger(save_dir=str(out_dir), name="tb")] try: wb = WandbLogger( project=cfg.logging.wandb.project, name=cfg.experiment_name, save_dir=str(out_dir), mode=cfg.logging.wandb.mode, tags=list(cfg.logging.wandb.tags), ) loggers.append(wb) except Exception as e: print(f"[train] wandb disabled: {e}") # --- callbacks ------------------------------------------------- # NOTE on filename template: # 1) We log the monitored metric as "val/auc" (with slash) in # BaseMethod.on_validation_epoch_end, so the placeholder in the # filename MUST also be "{val/auc:...}". If we use "{val_auc:...}" # here, Lightning cannot resolve it and silently writes 0.0000. # Lightning will sanitize the "/" to "_" when writing the path. # 2) We intentionally AVOID "=" in the filename so downstream scripts # / shells that split on "=" can parse the path safely. ckpt_cb = ModelCheckpoint( dirpath=str(out_dir / "checkpoints"), filename="epoch{epoch:02d}-valauc{val/auc:.4f}", auto_insert_metric_name=False, monitor=cfg.trainer.monitor_metric, mode=cfg.trainer.monitor_mode, save_top_k=cfg.trainer.save_top_k, save_last=True, ) lr_cb = LearningRateMonitor(logging_interval="epoch") # --- trainer --------------------------------------------------- trainer = pl.Trainer( accelerator=cfg.trainer.accelerator, devices=cfg.trainer.devices, strategy=cfg.trainer.strategy, precision=cfg.trainer.precision, max_epochs=cfg.trainer.max_epochs, accumulate_grad_batches=cfg.trainer.accumulate_grad_batches, gradient_clip_val=cfg.trainer.gradient_clip_val, sync_batchnorm=cfg.trainer.sync_batchnorm, check_val_every_n_epoch=cfg.trainer.check_val_every_n_epoch, deterministic=cfg.trainer.deterministic, logger=loggers, callbacks=[ckpt_cb, lr_cb], default_root_dir=str(out_dir), log_every_n_steps=cfg.logging.log_every_n_steps, ) # --- resume auto-detection ------------------------------------ resume_path = None if cfg.resume == "auto": last = out_dir / "checkpoints" / "last.ckpt" if last.exists(): resume_path = str(last) else: resume_path = find_latest_ckpt(out_dir / "checkpoints") elif isinstance(cfg.resume, str) and cfg.resume and cfg.resume != "null": resume_path = cfg.resume if resume_path: print(f"[train] resuming from {resume_path}") # --- test-only mode (skip training) --------------------------- # Usage: # python src/train.py method=cta ... +test_only=true +test_ckpt=/path/to.ckpt # When test_only is true we skip fit() entirely and run a distributed # test pass on the provided checkpoint (falls back to resume_path / "best"). test_only = bool(getattr(cfg, "test_only", False)) test_ckpt = getattr(cfg, "test_ckpt", None) # Per-sample test predictions will be dumped by BaseMethod.on_test_epoch_end # to this path. Override via +test_predictions_csv=/path/to.csv. import time as _time default_pred_csv = out_dir / f"test_predictions_{_time.strftime('%Y%m%d_%H%M%S')}.csv" pred_csv = getattr(cfg, "test_predictions_csv", None) or str(default_pred_csv) model.test_predictions_csv = pred_csv if trainer.is_global_zero: print(f"[train] per-sample predictions will be written to: {pred_csv}") if test_only: ckpt_for_test = test_ckpt or resume_path if ckpt_for_test is None: raise ValueError( "test_only=true but no checkpoint found. " "Pass +test_ckpt=/path/to.ckpt or ensure a last.ckpt exists." ) if trainer.is_global_zero: print(f"[train] test-only mode. loading checkpoint: {ckpt_for_test}") trainer.test(model, datamodule=dm, ckpt_path=ckpt_for_test) return trainer.fit(model, datamodule=dm, ckpt_path=resume_path) # --- final test on balanced test set -------------------------- # NOTE: trainer.test(...) must be called on ALL ranks under DDP, # otherwise the remaining ranks will exit while rank 0 blocks on # collective ops (ALLREDUCE/barrier) and eventually times out. # Lightning itself handles rank-zero-only printing/saving. if trainer.is_global_zero: print("[train] fit done. running final test ...") trainer.test(model, datamodule=dm, ckpt_path="best") if __name__ == "__main__": main()