-
Notifications
You must be signed in to change notification settings - Fork 0
/
trainer.py
376 lines (309 loc) · 15.4 KB
/
trainer.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
from pathlib import Path
import re
import os
from shutil import rmtree
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import CosineAnnealingLR
from torch.utils.data import Dataset
from torch.utils.tensorboard import SummaryWriter
from einops import rearrange
from typing import Optional
from accelerate import Accelerator, DistributedType, DistributedDataParallelKwargs
from utautai.soundstorm import SoundStorm
from utautai.dataset.data_processor import DataProcessor
from utautai.optimizer import get_optimizer
from utautai.prompt_tts.style_module import StyleModule
import joblib
# helpers
def exists(val):
return val is not None
def noop(*args, **kwargs):
pass
def cycle(dl):
while True:
for data in dl:
yield data
def cast_tuple(t):
return t if isinstance(t, (tuple, list)) else (t,)
def yes_or_no(question):
answer = input(f'{question} (y/n) ')
return answer.lower() in ('yes', 'y')
def accum_log(log, new_logs):
for key, new_value in new_logs.items():
old_value = log.get(key, 0.)
log[key] = old_value + new_value
return log
def checkpoint_num_steps(checkpoint_path):
"""Returns the number of steps trained from a checkpoint based on the filename.
Filename format assumed to be something like "/path/to/soundstorm.20000.pt" which is
for 20k train steps. Returns 20000 in that case.
"""
results = re.findall(r'\d+', str(checkpoint_path))
if len(results) == 0:
return 0
return int(results[-1])
class UTAUTAI_Trainer(nn.Moduele):
def __init__(
self,
model: SoundStorm,
kmeans,
dataprocessor: DataProcessor,
stylemodule: StyleModule,
*,
num_warmup_steps,
batch_size,
epochs = 20,
is_raw_wav: bool = False,
lr = 3e-4,
initial_lr = 1e-5,
grad_accum_every = 1,
wd = 0.,
max_grad_norm = 0.5,
log_steps = 10,
save_model_steps = 5000,
results_folder = './results',
log_dir = './log',
accelerate_kwargs: dict = dict(),
split_batches = False,
num_ckpt_keep = 8,
use_tensorboard = False,
loss_weight = [1, 1]
):
super().__init__()
if use_tensorboard:
self.tb_writer = SummaryWriter(log_dir=log_dir)
else:
self.tb_writer = None
ddp_kwargs = DistributedDataParallelKwargs(find_unused_parameters=True)
self.accelerator = Accelerator(
split_batches = split_batches,
kwargs_handlers=[ddp_kwargs],
**accelerate_kwargs
)
self.model = model
self.register_buffer('steps', torch.Tensor([0]))
self.epochs = epochs
self.num_warmup_steps = num_warmup_steps
self.batch_size = batch_size
self.grad_accum_every = grad_accum_every
# max grad norm
self.max_grad_norm = max_grad_norm
#create dataset
self.data_processor = dataprocessor
self.dl = self.data_processor.train_loader
self.valid_dl = self.data_processor.valid_loader
#create style module
self.style_module = stylemodule
self.kmeans = kmeans #mert_kmeans for infer
self.loss_weight = loss_weight
if self.loss_weight is not None:
self.lambda1 = loss_weight[0] # for soundstorm
self.lambda2 = loss_weight[1] # for stylemodule
if self.is_main:
self.data_processor.print_stats()
self.is_raw_wav = is_raw_wav
#optimizer
self.optim = get_optimizer(model.parameters(), lr=lr, wd=wd)
#lr and scheduler
self.lr = lr
self.initial_lr = initial_lr
num_train_steps = epochs * self.data_processor.train_dataset.__len__() // (batch_size * grad_accum_every)
self.scheduler = CosineAnnealingLR(self.optim, T_max=num_train_steps)
#prepare with accelerator
(
self.model,
self.style_module,
self.optim,
self.scheduler,
self.dl,
self.valid_dl
) = self.accelerator.prepare(
self.model,
self.style_module,
self.optim,
self.scheduler,
self.dl,
self.valid_dl
)
#datloader iterators
self.log_steps = log_steps
self.save_model_steps = save_model_steps
self.results_folder = Path(results_folder)
self.num_ckpt_keep = num_ckpt_keep
if not results_folder.exists():
self.results_folder.mkdir(parents=True, exist_ok=True)
hps = {"num_train_steps": num_train_steps, "num_warmup_steps": num_warmup_steps, "learning_rate": lr, "initial_learning_rate": lr, "epochs": epochs}
self.accelerator.init_trackers("soundstorm", config=hps)
self.best_dev_loss = float('inf')
def save(self, path, stylemodule_path, dev_loss):
if dev_loss < self.best_dev_loss:
self.best_dev_loss = dev_loss
torch.save(self.accelerator.get_state_dict(self.model), f'{self.results_folder}/SoundStorm_best_dev.pt')
torch.save(self.accelerator.get_state_dict(self.style_module), f'{self.results_folder}/StyleModule_best_dev.pt')
ckpts = sorted(Path(path).parent.glob(f'SoundStormTrainer_*'))
stylemodule_ckpts = sorted(Path(path).parent.glob(f'StyleModuleTrainer_*'))
if len(ckpts) > self.num_ckpt_keep:
[os.remove(c) for c in ckpts[:-self.num_ckpt_keep]]
[os.remove(c) for c in stylemodule_ckpts[:-self.num_ckpt_keep]]
pkg = dict(
model = self.accelerator.get_state_dict(self.model),
optim = self.optim.state_dict(),
scheduler = self.scheduler.state_dict(),
best_dev_loss = self.best_dev_loss
)
stylemodule_pkg = dict(
model=self.accelerator.get_state_dict(self.style_module),
optim = self.optim.state_dict(),
scheduler = self.scheduler.state_dict(),
best_dev_loss = self.best_dev_loss
)
torch.save(pkg, path)
torch.save(stylemodule_pkg, stylemodule_path)
def load(self, path = None, stylemodule_path = None, restore_optimizer = True):
if not exists(path):
ckpts = sorted(self.results_folder.glob(f'SoundStormTrainer_*'))
path = str(ckpts[-1])
if not exists(stylemodule_path):
stylemodule_ckpts = sorted(self.results_folder.glob(f'StyleModuleTrainer_*'))
stylemodule_path = str(ckpts[-1])
model = self.accelerator.unwrap_model(self.model)
pkg = torch.load(path, map_location='cpu')
model.load_state_dict(pkg['model'])
stylemodule = self.accelerator.unwrap_model(self.style_module)
stylemodule_pkg = torch.load(stylemodule_path, map_location='cpu')
stylemodule.load_state_dict(stylemodule_pkg['model'])
if restore_optimizer:
self.optim.load_state_dict(pkg['optim'])
self.scheduler.load_state_dict(pkg['scheduler'])
if 'best_dev_loss' in pkg.keys():
self.best_dev_loss = pkg['best_dev_loss']
if self.is_main:
self.print(f'The best dev loss before is {self.best_dev_loss}')
# + 1 to start from the next step and avoid overwriting the last checkpoint
self.steps = torch.tensor([checkpoint_num_steps(path) + 1], device=self.device)
def print(self, msg):
self.accelerator.print(msg)
@property
def device(self):
return self.accelerator.device
@property
def is_distributed(self):
return not (self.accelerator.distributed_type == DistributedType.NO and self.accelerator.num_processes == 1)
@property
def is_main(self):
return self.accelerator.is_main_process
@property
def is_local_main(self):
return self.accelerator.is_local_main_process
def warmup(self, step):
if step < self.num_warmup_steps:
return self.initial_lr + (self.lr - self.initial_lr) * step / self.num_warmup_steps
else:
return self.lr
def train(self):
self.model.train()
grad_accum = 0
logs = {}
steps = int(self.steps.item())
if steps < self.num_warmup_steps:
lr = self.warmup(steps)
for param_group in self.optim.param_groups:
param_group['lr'] = lr
else:
self.scheduler.step()
lr = self.scheduler.get_last_lr()[0]
for epoch in range(self.epochs):
if self.is_main:
print(f'Epoch:{epoch} start...')
for batch in self.dl:
(acoustic_token_ids, music_semantic_token_ids,
lyrics_semantic_token_ids, mert_feat) = (batch['audio_features'],
batch['stok_music'],
batch['stok_lyric'],
batch['mert_feat'])
prompts = batch['prompts']
variation_loss, _, _ = self.style_module(prompts, mert_feat)
semantic_token_ids = torch.cat([lyrics_semantic_token_ids, music_semantic_token_ids],
axis=1)
loss, acc, _ = self.model(x=acoustic_token_ids, cond_ids=semantic_token_ids)
if self.loss_weight is not None:
all_loss = loss * self.lambda1 + variation_loss * self.lambda2
else:
all_loss = loss + variation_loss # loss weighting should be considered.
if self.tb_writer is not None:
self.tb_writer.add_scalar('Loss/train', loss.item(), steps)
self.tb_writer.add_scalar('Accuracy/train', acc.item(), steps)
self.tb_writer.add_scalar('Variation_Loss/train', variation_loss, steps)
self.tb_writer.add_scalar('All_Loss/train', all_loss, steps)
accum_log(logs, {'loss': loss.item() / self.grad_accum_every, 'acc': acc.item() / self.grad_accum_every,
'variation_loss': variation_loss.item()/ self.grad_accum_every,
'all_loss': all_loss.item() / self.grad_accum_every})
self.accelerator.backward(all_loss/ self.grad_accum_every)
grad_accum += 1
# update params
if grad_accum == self.grad_accum_every:
if exists(self.max_grad_norm):
self.accelerator.clip_grad_norm_(self.model.parameters(), self.max_grad_norm)
self.optim.step()
self.optim.zero_grad()
grad_accum = 0
# log
if self.is_main and not (steps % self.log_steps):
self.print(f"Epoch {epoch} -- Step {steps}: loss: {logs['loss']:0.3f}\tacc:{logs['acc']:0.3f}\tvariation_loss:{logs['variation_loss']:0.3f}\tall_loss:{logs['all_loss']:0.3f}")
self.accelerator.log({"train/loss": logs['loss'], "train/acc": logs['acc'], "train/variation_loss":logs['variation_loss'], "train/all_loss":logs['all_loss'], "train/learning_rate": lr}, step=steps)
logs = {}
self.accelerator.wait_for_everyone()
# validate and save model
if self.is_main and not(steps % self.save_model_steps):
# validate
losses = []
total_loss = 0.0
total_acc = 0.0
num = 0
self.model.eval()
for batch in self.valid_dl:
with torch.inference_mode():
(acoustic_token_ids, music_semantic_token_ids,
lyric_semantic_token_ids, mert_feat) = (batch['audio_features'],
batch['stok_music'],
batch['stok_lyric'],
batch['mert_feat'])
prompts = batch['prompts']
variation_loss, _, _ = self.style_module(prompts, mert_feat)
semantic_token_ids = torch.cat([lyric_semantic_token_ids, music_semantic_token_ids], axis=1)
b = semantic_token_ids.size(0)
num += b
loss, acc, _ = self.model(x = acoustic_token_ids, cond_ids=semantic_token_ids)
if self.loss_weight is not None:
all_loss = loss * self.lambda1 + variation_loss * self.lambda2
else:
all_loss = loss + variation_loss # loss weighting should be considered.
total_loss += all_loss.item() * b
losses.append(all_loss.item())
total_acc += acc.item() * b
self.print(f'{steps}: valid loss {total_loss / num:0.3f}, valid acc {total_acc / num:0.3f}')
self.accelerator.log({"valid/loss": total_loss / num, "valid/acc": total_acc / num}, step=steps)
if self.tb_writer is not None:
self.tb_writer.add_scalar('Loss/validate', total_loss / num, steps)
self.tb_writer.add_scalar('Accuracy/validate', total_acc / num, steps)
# save model
model_path = str(self.results_folder / f'SoundStormTrainer_{steps:08d}')
stylemodule_path = str(self.results_folder / f'StyleModuleTrainer_{steps:08d}')
self.save(model_path, stylemodule_path, total_loss / num)
self.print(f'{steps}: saving model to {str(self.results_folder)}')
self.model.train()
# Update lr
self.steps += 1
steps = int(self.steps.item())
if steps < self.num_warmup_steps:
lr = self.warmup(steps)
for param_group in self.optim.param_groups:
param_group['lr'] = lr
else:
self.scheduler.step()
lr = self.scheduler.get_last_lr()[0]
self.print('training complete')
def continue_train(self):
self.load()
self.train()