| """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 |
|
|
| |
| |
| |
| |
| |
| 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) |
|
|
|
|
| |
| |
| _lf_cloud_io.torch.load = _unsafe_torch_load |
| torch.load = _unsafe_torch_load |
|
|
| |
| 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 |
|
|
| |
| 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 = build_method( |
| method_name=cfg.method.name, |
| method_cfg=cfg.method, |
| backbone_cfg=cfg.backbone, |
| data_cfg=cfg.data, |
| ) |
|
|
| |
| out_dir = Path(cfg.output_dir).resolve() |
| out_dir.mkdir(parents=True, exist_ok=True) |
|
|
| |
| 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}") |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| 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 = 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_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 = bool(getattr(cfg, "test_only", False)) |
| test_ckpt = getattr(cfg, "test_ckpt", None) |
|
|
| |
| |
| 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) |
|
|
| |
| |
| |
| |
| |
| if trainer.is_global_zero: |
| print("[train] fit done. running final test ...") |
| trainer.test(model, datamodule=dm, ckpt_path="best") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|