File size: 3,209 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
"""Stage 1: current-frame FastVLM driving model on IID samples (multi-GPU DDP)."""
import os
os.environ.setdefault("OMP_NUM_THREADS", "1")
os.environ.setdefault("MKL_NUM_THREADS", "1")
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")

import cv2
cv2.setNumThreads(1)

from pathlib import Path

import hydra
import pytorch_lightning as pl
import torch
from omegaconf import OmegaConf
from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint
from pytorch_lightning.loggers import CSVLogger, TensorBoardLogger


class SamplerEpoch(pl.Callback):
    # Under DDP Lightning wraps the custom sampler, so set_epoch must reach the
    # original one to keep each epoch's draws a function of (seed, epoch).
    def on_train_epoch_start(self, trainer, pl_module):
        sampler = getattr(trainer.datamodule, 'sampler_train', None)
        if hasattr(sampler, 'set_epoch'):
            sampler.set_epoch(trainer.current_epoch)


def load_init_checkpoint(model, path):
    """Warm-start from an earlier stage: strict=False, but only new modules may be missing."""
    checkpoint = torch.load(path, map_location='cpu', weights_only=False)
    state = checkpoint.get('state_dict', checkpoint)
    result = model.load_state_dict(state, strict=False)
    if result.unexpected_keys:
        raise RuntimeError(f'init_checkpoint has unknown parameters: {result.unexpected_keys[:8]}')
    missing_modules = sorted({k.split('.')[0] for k in result.missing_keys})
    print(f'init_checkpoint {path}: loaded {len(state)} tensors; '
          f'{len(result.missing_keys)} new parameters in {missing_modules}', flush=True)


@hydra.main(version_base=None, config_path='config', config_name='fastvlm_stage1')
def main(cfg):
    torch.set_float32_matmul_precision('high')
    pl.seed_everything(cfg.seed, workers=True)
    data = hydra.utils.instantiate(cfg.data_module, predict=False, sampler_seed=cfg.seed)
    model = hydra.utils.instantiate(cfg.model, route_as=cfg.data_module.route_as)
    init = cfg.get('init_checkpoint')
    if init and not cfg.get('resume_checkpoint'):
        load_init_checkpoint(model, hydra.utils.to_absolute_path(init))
    output = Path(hydra.utils.to_absolute_path(cfg.output_dir))
    output.mkdir(parents=True, exist_ok=True)
    checkpoints = output / 'checkpoints'
    callbacks = [
        ModelCheckpoint(dirpath=checkpoints, filename='{epoch:03d}', save_top_k=-1,
                        every_n_epochs=1, save_weights_only=True),
        ModelCheckpoint(dirpath=checkpoints, save_last=True, save_top_k=0,
                        every_n_train_steps=int(cfg.last_ckpt_every_n_steps)),
        LearningRateMonitor(logging_interval='step'),
        SamplerEpoch(),
    ]
    loggers = [CSVLogger(str(output), name='logs', version=''),
               TensorBoardLogger(str(output), name='tb', version='')]
    trainer = pl.Trainer(**OmegaConf.to_container(cfg.trainer, resolve=True),
                         callbacks=callbacks, logger=loggers, default_root_dir=str(output))
    resume = cfg.resume_checkpoint
    trainer.fit(model, datamodule=data,
                ckpt_path=hydra.utils.to_absolute_path(resume) if resume else None)


if __name__ == '__main__':
    main()