File size: 2,537 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
"""Train current-frame FastVLM and explicit PIM streams (no DeepSpeed required)."""
from pathlib import Path
import hydra
import torch
import pytorch_lightning as pl
from omegaconf import OmegaConf
from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor


def load_initial_weights(model, path):
    payload = torch.load(path, map_location='cpu', weights_only=False)
    state = payload.get('state_dict', payload)
    # Only a memory-free version of THIS FastVLM model is a compatible warm start.
    current = model.state_dict()
    unexpected = set(state) - set(current)
    missing = set(current) - set(state)
    if unexpected or any(not k.startswith('pim.') for k in missing):
        raise ValueError(f'Incompatible initialization: missing={sorted(missing)[:8]}, '
                         f'unexpected={sorted(unexpected)[:8]}')
    model.load_state_dict(state, strict=False)  # Shape mismatches still raise.


class SamplerEpoch(pl.Callback):
    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)


@hydra.main(version_base=None, config_path='config', config_name='pim')
def main(cfg):
    if cfg.init_checkpoint and cfg.resume_checkpoint:
        raise ValueError('Choose initialization OR full training resume')
    if cfg.model.pim.enabled and cfg.model.pim.slots != 8:
        raise ValueError('The annotation schema defines exactly eight semantic slots')
    pl.seed_everything(cfg.seed, workers=True)
    cfg.data_module.sampler_seed = cfg.seed
    model = hydra.utils.instantiate(cfg.model)
    if cfg.init_checkpoint:
        load_initial_weights(model, hydra.utils.to_absolute_path(cfg.init_checkpoint))
    data = hydra.utils.instantiate(cfg.data_module)
    output = Path(hydra.utils.to_absolute_path(cfg.output_dir))
    output.mkdir(parents=True, exist_ok=True)
    OmegaConf.save(cfg, output / 'pim.yaml')
    checkpoint = ModelCheckpoint(dirpath=output / 'checkpoints', save_last=True,
                                 save_top_k=-1, every_n_epochs=1)
    trainer = pl.Trainer(**OmegaConf.to_container(cfg.trainer, resolve=True),
                         callbacks=[checkpoint, LearningRateMonitor(), SamplerEpoch()])
    trainer.fit(model, datamodule=data,
                ckpt_path=hydra.utils.to_absolute_path(cfg.resume_checkpoint)
                if cfg.resume_checkpoint else None)


if __name__ == '__main__':
    main()