-
Notifications
You must be signed in to change notification settings - Fork 1
/
train.py
190 lines (165 loc) · 5.11 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
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
179
180
181
182
183
184
185
186
187
188
189
190
import shutil
import typing as tp
import logging
import traceback
import hydra
from hydra.core.hydra_config import HydraConfig
from hydra.utils import instantiate
from omegaconf import DictConfig, OmegaConf
import torch
import torch.nn as nn
import pytorch_lightning as pl
from torch.utils.data import DataLoader
from torch.optim import Optimizer, lr_scheduler
from data import musdbDataset, collate_fn
from model import BandSplitRNN, BSRoformer, PLModel
from utils.callbacks import ValidationProgressBar
log = logging.getLogger(__name__)
def initialize_loaders(cfg: DictConfig) -> tp.Tuple[DataLoader, DataLoader]:
"""
Initializes train and validation dataloaders from configuration file.
"""
train_dataset = musdbDataset(
**cfg.train_dataset,
)
train_loader = DataLoader(
train_dataset,
**cfg.train_loader,
collate_fn=collate_fn
)
if hasattr(cfg, 'val_dataset'):
val_dataset = musdbDataset(
**cfg.val_dataset,
)
val_loader = DataLoader(
val_dataset,
**cfg.val_loader,
collate_fn=collate_fn
)
else:
val_loader = None
return (
train_loader,
val_loader
)
def initialize_featurizer(
cfg: DictConfig
) -> tp.Tuple[nn.Module, nn.Module]:
"""
Initializes direct and inverse featurizers for audio.
"""
featurizer = instantiate(
cfg.featurizer.direct_transform,
)
inv_featurizer = instantiate(
cfg.featurizer.inverse_transform,
)
return featurizer, inv_featurizer
def initialize_augmentations(
cfg: DictConfig
) -> nn.Module:
"""
Initializes augmentations.
"""
augs = instantiate(cfg.augmentations)
augs = nn.Sequential(*augs.values())
return augs
def initialize_model(
cfg: DictConfig
) -> tp.Tuple[nn.Module, Optimizer, lr_scheduler._LRScheduler]:
"""
Initializes model from configuration file.
"""
# initialize model
model = BSRoformer(
**cfg.model
)
# initialize optimizer
if hasattr(cfg, 'opt'):
opt = instantiate(
cfg.opt,
params=model.parameters()
)
else:
opt = None
# initialize scheduler
if hasattr(cfg, 'sch'):
if hasattr(cfg.sch, '_target_'):
# other than LambdaLR
sch = instantiate(
cfg.sch,
optimizer=opt
)
else:
# if LambdaLR
lr_lambda = lambda epoch: (
cfg.sch.alpha ** (cfg.sch.warmup_step - epoch)
if epoch < cfg.sch.warmup_step
else cfg.sch.gamma ** (epoch - cfg.sch.warmup_step)
)
sch = torch.optim.lr_scheduler.LambdaLR(
optimizer=opt,
lr_lambda=lr_lambda
)
else:
sch = None
return model, opt, sch
def initialize_utils(
cfg: DictConfig
):
# change model and logs saving directory to logging directory of hydra
if HydraConfig.instance().cfg is not None:
hydra_cfg = hydra.core.hydra_config.HydraConfig.get()
save_dir = hydra_cfg['runtime']['output_dir']
cfg.logger.save_dir = save_dir + cfg.logger.save_dir
if hasattr(cfg.callbacks, 'model_ckpt'):
cfg.callbacks.model_ckpt.dirpath = save_dir + cfg.callbacks.model_ckpt.dirpath
# delete early stopping if there is no validation dataset
if not hasattr(cfg, 'val_dataset') and hasattr(cfg.callbacks, 'early_stop'):
del cfg.callbacks.early_stop
# initialize logger and callbacks
logger = instantiate(cfg.logger)
callbacks = list(instantiate(cfg.callbacks).values())
callbacks.append(ValidationProgressBar())
return logger, callbacks
@hydra.main(version_base=None, config_path="conf", config_name="config")
def my_app(cfg: DictConfig) -> None:
pl.seed_everything(42, workers=True)
log.info(OmegaConf.to_yaml(cfg))
log.info("Initializing loaders, featurizers.")
train_loader, val_loader = initialize_loaders(cfg)
featurizer, inverse_featurizer = initialize_featurizer(cfg)
augs = initialize_augmentations(cfg)
log.info("Initializing model, optimizer, scheduler.")
model, opt, sch = initialize_model(cfg)
log.info("Initializing Lightning logger and callbacks.")
logger, callbacks = initialize_utils(cfg)
log.info("Initializing Lightning modules.")
plmodel = PLModel(
model,
featurizer, inverse_featurizer,
augs,
opt, sch,
cfg
)
trainer = pl.Trainer(
**cfg.trainer,
logger=logger,
callbacks=callbacks,
)
log.info("Starting training...")
try:
trainer.fit(
plmodel,
train_dataloaders=train_loader,
val_dataloaders=val_loader,
ckpt_path=cfg.ckpt_path
)
except Exception as e:
log.error(traceback.format_exc())
log.info("Training finished!")
if cfg.trainer.fast_dev_run:
hydra_cfg = hydra.core.hydra_config.HydraConfig.get()
shutil.rmtree(hydra_cfg['runtime']['output_dir'])
if __name__ == "__main__":
my_app()