File size: 6,115 Bytes
314ecfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["OPENBLAS_NUM_THREADS"] = "1"

import cv2
cv2.setNumThreads(1)

import hydra
import pytorch_lightning as pl
import torch
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
from omegaconf import OmegaConf
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelSummary
from pytorch_lightning.loggers import CSVLogger, WandbLogger

from callbacks.rank_zero_output import RankZeroOutputCallback
from callbacks.visualise import VisualiseCallback
from config import TrainConfig
from utils.logging_project import rank_zero_print, setup_logging

class SamplerEpochCallback(pl.Callback):
    """Keep the epoch-reseeded train sampler in sync with the trainer epoch.

    Lightning only calls set_epoch() on the outermost sampler; under DDP the
    custom sampler gets wrapped in a DistributedSamplerWrapper, so we reach
    the original sampler through the datamodule to make each epoch's sample
    sequence a pure function of (seed, epoch) — including after a resume.
    """

    def on_train_epoch_start(self, trainer, pl_module):
        datamodule = getattr(trainer, "datamodule", None)
        sampler = getattr(datamodule, "sampler_train", None)
        if sampler is not None and hasattr(sampler, "set_epoch"):
            sampler.set_epoch(trainer.current_epoch)


@hydra.main(config_path=f"config", config_name="config", version_base="1.1")
def main(cfg: TrainConfig):
    torch.set_float32_matmul_precision("high")
    if cfg.deterministic:
        # Required by cuBLAS for deterministic GEMMs (CUDA >= 10.2).
        os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
    pl.seed_everything(cfg.seed, workers=True)

    if cfg.debug:
        os.environ["WANDB_MODE"] = "offline"

    cfg.wandb_name = f"{cfg.wandb_name}_{cfg.name}"
    setup_logging(cfg, console_log_file=cfg.console_log_file)
    os.environ["WANDB_DISABLE_CODE"] = "True"

    cfg.model.vision_model.use_global_img = cfg.data_module.use_global_img

    rank_zero_print("Building data module...", flush=True)
    data_module = hydra.utils.instantiate(
        cfg.data_module, 
        encoder_variant=OmegaConf.select(cfg, "model.vision_model.variant"),
        llm_variant=OmegaConf.select(cfg, "model.language_model.variant"),
        predict=False,
        sampler_seed=cfg.seed,
    )
    rank_zero_print("Building model...", flush=True)
    model = hydra.utils.instantiate(
        cfg.model,
        route_as=cfg.data_module.route_as,
        )
    rank_zero_print("Model ready.", flush=True)

    if cfg.checkpoint is not None:
        if os.path.isdir(cfg.checkpoint):
            state_dict = get_fp32_state_dict_from_zero_checkpoint(cfg.checkpoint)
        else:
            state_dict = torch.load(cfg.checkpoint, map_location="cpu")
        model.load_state_dict(state_dict)

        
    # print config
    rank_zero_print(OmegaConf.to_yaml(cfg))
    
    if cfg.overfit > 0:
        overfit = cfg.overfit
        
    csv_logger = CSVLogger(save_dir=".", name="logs", version=cfg.name)
    loggers = [csv_logger]
    wandb_logger = None
    if not cfg.debug and cfg.enable_wandb:
        resume_wandb = bool(cfg.resume and cfg.resume_path and os.path.exists(cfg.resume_path))
        wandb_logger = WandbLogger(
            project=cfg.wandb_project,
            id=cfg.wandb_name,
            name=cfg.wandb_name,
            config=OmegaConf.to_container(cfg, resolve=True, throw_on_missing=True),
            resume="allow" if resume_wandb else False,
        )
        wandb_logger.watch(model)
        loggers.append(wandb_logger)

    # resume training
    resume_path = cfg.resume_path

    if resume_path is None or not (os.path.exists(resume_path) and cfg.resume):
        resume_path = None

    strategy = cfg.strategy
    if strategy == "deepspeed_stage_2":
        # bf16-mixed does not need loss scaling; loss_scale is only for fp16
        use_bf16 = "bf16" in str(cfg.precision)
        strategy = pl.strategies.DeepSpeedStrategy(
            stage=2,
            logging_batch_size_per_gpu=cfg.data_module.batch_size,
            **({"loss_scale": cfg.fp16_loss_scale} if not use_bf16 else {}),
        )

    checkpoint_dir = "./checkpoints"
    epoch_checkpoint_callback = pl.callbacks.ModelCheckpoint(
        save_top_k=-1,
        monitor=None,
        dirpath=checkpoint_dir,
        filename="{epoch:03d}",
        save_last=False,
        every_n_epochs=cfg.val_every_n_epochs,
        # every_n_train_steps=cfg.val_check_interval,
    )
    last_checkpoint_callback = pl.callbacks.ModelCheckpoint(
        save_top_k=0,
        monitor=None,
        dirpath=checkpoint_dir,
        save_last=True,
        every_n_epochs=1,
    )

    model_summary = ModelSummary(max_depth=3)
    callbacks = [
        RankZeroOutputCallback(),
        epoch_checkpoint_callback,
        last_checkpoint_callback,
        model_summary,
        VisualiseCallback(interval=1000),
        SamplerEpochCallback(),
    ]
    
    rank_zero_print(f"Number of GPUS: {cfg.gpus}")
    overfit = 0
    
    if cfg.gpus >= 1:
        trainer = Trainer(
            accelerator="gpu",
            benchmark=not cfg.deterministic,
            deterministic="warn" if cfg.deterministic else None,
            callbacks=callbacks,
            devices=cfg.gpus,
            # enable_checkpointing=False,
            gradient_clip_val=1.0,
            log_every_n_steps=20,
            logger=loggers,
            # max_steps=cfg.max_steps,
            precision=cfg.precision,
            strategy=strategy,
            sync_batchnorm=True,
            # use_distributed_sampler=False,
            accumulate_grad_batches=cfg.accumulate_grad_batches,
            max_epochs=cfg.max_epochs,
            overfit_batches=overfit,
            # val_check_interval=cfg.val_check_interval,
        )

    trainer.fit(model, data_module, ckpt_path=resume_path)

    if wandb_logger is not None:
        import wandb
        wandb.finish()


if __name__ == "__main__":
    main()