-
Notifications
You must be signed in to change notification settings - Fork 1
/
train.py
executable file
·143 lines (113 loc) · 4.14 KB
/
train.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
from models.diffusion import DiffusionModule
import hydra
import shutil
import wandb
import os
from callbacks import EMACallback, LogGeneratedImages, FixNANinGrad, IncreaseDataEpoch
from pytorch_lightning.callbacks import LearningRateMonitor
from lightning_fabric.utilities.rank_zero import _get_rank
from pathlib import Path
from omegaconf import OmegaConf
from hydra.core.hydra_config import HydraConfig
import torch
torch.set_float32_matmul_precision("high")
@hydra.main(config_path="configs", config_name="config", version_base=None)
def train(cfg):
# print(OmegaConf.to_yaml(cfg, resolve=True))
dict_config = OmegaConf.to_container(cfg, resolve=True)
Path(cfg.checkpoints.dirpath).mkdir(parents=True, exist_ok=True)
print("Working directory : {}".format(os.getcwd()))
shutil.copyfile(
Path(".hydra/config.yaml"),
f"{cfg.checkpoints.dirpath}/config.yaml",
)
hydra_overrides = dict([x.split("=") for x in HydraConfig.get().overrides.task])
hydra_overrides["root_dir"] = cfg.root_dir
log_dict = {}
log_dict["model"] = dict_config["model"]
log_dict["data"] = dict_config["data"]
datamodule = hydra.utils.instantiate(cfg.data.datamodule)
datamodule.setup()
checkpoint_callback = hydra.utils.instantiate(
cfg.checkpoints, hydra_overrides=hydra_overrides
)
progress_bar = hydra.utils.instantiate(cfg.progress_bar)
ema_callback = EMACallback(
"network",
"ema_network",
decay=cfg.model.ema_decay,
start_ema_step=cfg.model.start_ema_step,
init_ema_random=False,
)
log_images_callback = LogGeneratedImages(
root_dir=cfg.root_dir,
mode=cfg.data.type,
num_classes=cfg.data.label_dim,
shape=(
cfg.model.network.num_input_channels,
cfg.data.data_resolution,
cfg.data.data_resolution,
),
log_every_n_steps=cfg.checkpoints.every_n_train_steps,
log_conditional=cfg.checkpoints.validate_conditional,
log_unconditional=cfg.checkpoints.validate_unconditional,
text_embedding_name=(
cfg.model.text_embedding_name
if hasattr(cfg.model, "text_embedding_name")
else None
),
batch_size=datamodule.batch_size,
cfg_rate=cfg.model.cfg_rate if hasattr(cfg.model, "cfg_rate") else 0,
negative_prompts=(
cfg.model.negative_prompts
if hasattr(cfg.model, "negative_prompts")
else None
),
)
lr_monitor = LearningRateMonitor()
fix_nan_callback = FixNANinGrad(
monitor=["train/loss"],
)
increase_data_epoch = IncreaseDataEpoch()
callbacks = [
checkpoint_callback,
progress_bar,
ema_callback,
log_images_callback,
lr_monitor,
fix_nan_callback,
increase_data_epoch,
]
rank = _get_rank()
if os.path.isfile(Path(cfg.checkpoints.dirpath) / Path("wandb_id.txt")):
with open(
Path(cfg.checkpoints.dirpath) / Path("wandb_id.txt"), "r"
) as wandb_id_file:
wandb_id = wandb_id_file.readline()
else:
wandb_id = wandb.util.generate_id()
print(f"generated id{wandb_id}")
if rank == 0 or rank is None:
with open(
Path(cfg.checkpoints.dirpath) / Path("wandb_id.txt"), "w"
) as wandb_id_file:
wandb_id_file.write(str(wandb_id))
logger = hydra.utils.instantiate(cfg.logger, id=wandb_id, resume="allow")
logger._wandb_init.update({"config": log_dict})
# logger.log_hyperparams(dict_config)
model = DiffusionModule(cfg.model)
trainer = hydra.utils.instantiate(
cfg.trainer,
logger=logger,
callbacks=callbacks,
)
ckpt_path = None
if (Path(cfg.checkpoints.dirpath) / Path("last.ckpt")).exists():
ckpt_path = Path(cfg.checkpoints.dirpath) / Path("last.ckpt")
else:
ckpt_path = None
logger.experiment.watch(model, log="all", log_graph=True, log_freq=1000)
trainer.fit(model, datamodule, ckpt_path=ckpt_path)
trainer.test(model, datamodule=datamodule)
if __name__ == "__main__":
train()