-
Notifications
You must be signed in to change notification settings - Fork 39
/
main.py
154 lines (135 loc) · 4.66 KB
/
main.py
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
import os
from pathlib import Path
import warnings
import hydra
import torch
import wandb
from colorama import Fore
from jaxtyping import install_import_hook
from omegaconf import DictConfig, OmegaConf
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import (
LearningRateMonitor,
ModelCheckpoint,
)
from pytorch_lightning.loggers.wandb import WandbLogger
# Configure beartype and jaxtyping.
with install_import_hook(
("src",),
("beartype", "beartype"),
):
from src.config import load_typed_root_config
from src.dataset.data_module import DataModule
from src.global_cfg import set_cfg
from src.loss import get_losses
from src.misc.LocalLogger import LocalLogger
from src.misc.step_tracker import StepTracker
from src.misc.wandb_tools import update_checkpoint_path
from src.model.decoder import get_decoder
from src.model.encoder import get_encoder
from src.model.model_wrapper import ModelWrapper
def cyan(text: str) -> str:
return f"{Fore.CYAN}{text}{Fore.RESET}"
@hydra.main(
version_base=None,
config_path="../config",
config_name="main",
)
def train(cfg_dict: DictConfig):
cfg = load_typed_root_config(cfg_dict)
set_cfg(cfg_dict)
# Set up the output directory.
if cfg_dict.output_dir is None:
output_dir = Path(
hydra.core.hydra_config.HydraConfig.get()["runtime"]["output_dir"]
)
else: # for resuming
output_dir = Path(cfg_dict.output_dir)
os.makedirs(output_dir, exist_ok=True)
print(cyan(f"Saving outputs to {output_dir}."))
latest_run = output_dir.parents[1] / "latest-run"
os.system(f"rm {latest_run}")
os.system(f"ln -s {output_dir} {latest_run}")
# Set up logging with wandb.
callbacks = []
if cfg_dict.wandb.mode != "disabled":
wandb_extra_kwargs = {}
if cfg_dict.wandb.id is not None:
wandb_extra_kwargs.update({'id': cfg_dict.wandb.id,
'resume': "must"})
logger = WandbLogger(
entity=cfg_dict.wandb.entity,
project=cfg_dict.wandb.project,
mode=cfg_dict.wandb.mode,
name=f"{cfg_dict.wandb.name} ({output_dir.parent.name}/{output_dir.name})",
tags=cfg_dict.wandb.get("tags", None),
log_model=False,
save_dir=output_dir,
config=OmegaConf.to_container(cfg_dict),
**wandb_extra_kwargs,
)
callbacks.append(LearningRateMonitor("step", True))
# On rank != 0, wandb.run is None.
if wandb.run is not None:
wandb.run.log_code("src")
else:
logger = LocalLogger()
# Set up checkpointing.
callbacks.append(
ModelCheckpoint(
output_dir / "checkpoints",
every_n_train_steps=cfg.checkpointing.every_n_train_steps,
save_top_k=cfg.checkpointing.save_top_k,
monitor="info/global_step",
mode="max", # save the lastest k ckpt, can do offline test later
)
)
for cb in callbacks:
cb.CHECKPOINT_EQUALS_CHAR = '_'
# Prepare the checkpoint for loading.
checkpoint_path = update_checkpoint_path(cfg.checkpointing.load, cfg.wandb)
# This allows the current step to be shared with the data loader processes.
step_tracker = StepTracker()
trainer = Trainer(
max_epochs=-1,
accelerator="gpu",
logger=logger,
devices="auto",
strategy="ddp" if torch.cuda.device_count() > 1 else "auto",
callbacks=callbacks,
val_check_interval=cfg.trainer.val_check_interval,
enable_progress_bar=cfg.mode == "test",
gradient_clip_val=cfg.trainer.gradient_clip_val,
max_steps=cfg.trainer.max_steps,
num_sanity_val_steps=cfg.trainer.num_sanity_val_steps,
)
torch.manual_seed(cfg_dict.seed + trainer.global_rank)
encoder, encoder_visualizer = get_encoder(cfg.model.encoder)
model_wrapper = ModelWrapper(
cfg.optimizer,
cfg.test,
cfg.train,
encoder,
encoder_visualizer,
get_decoder(cfg.model.decoder, cfg.dataset),
get_losses(cfg.loss),
step_tracker
)
data_module = DataModule(
cfg.dataset,
cfg.data_loader,
step_tracker,
global_rank=trainer.global_rank,
)
if cfg.mode == "train":
trainer.fit(model_wrapper, datamodule=data_module, ckpt_path=checkpoint_path)
else:
trainer.test(
model_wrapper,
datamodule=data_module,
ckpt_path=checkpoint_path,
)
if __name__ == "__main__":
warnings.filterwarnings("ignore")
torch.set_float32_matmul_precision('high')
train()