File size: 6,969 Bytes
a17b394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()