forked from r9y9/tacotron_pytorch
-
Notifications
You must be signed in to change notification settings - Fork 6
/
train_sgd.py
401 lines (311 loc) · 12.5 KB
/
train_sgd.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
"""Trainining script for Tacotron speech synthesis model.
usage: train.py [options]
options:
--data-root=<dir> Directory contains preprocessed features.
--checkpoint-dir=<dir> Directory where to save model checkpoints [default: checkpoints].
--checkpoint-path=<name> Restore model from checkpoint path if given.
--hparams=<parmas> Hyper parameters [default: ].
-h, --help Show this help message and exit
"""
from docopt import docopt
# Use text & audio modules from existing Tacotron implementation.
import sys
from os.path import dirname, join
tacotron_lib_dir = join(dirname(__file__), "lib", "tacotron")
sys.path.append(tacotron_lib_dir)
from text import text_to_sequence, symbols
from util import audio
from util.plot import plot_alignment
from tqdm import tqdm, trange
# The tacotron model
from tacotron_pytorch import Tacotron
import torch
from torch.utils import data as data_utils
from torch.autograd import Variable
from torch import nn
from torch import optim
import torch.backends.cudnn as cudnn
from torch.utils import data as data_utils
import numpy as np
from nnmnkwii.datasets import FileSourceDataset, FileDataSource
from os.path import join, expanduser
import librosa.display
from matplotlib import pyplot as plt
import sys
import os
import tensorboard_logger
from tensorboard_logger import log_value
from hparams import hparams, hparams_debug_string
# want to see tracebacks
import traceback
# Default DATA_ROOT
DATA_ROOT = join("/content/drive/My Drive/SRU Project/data/",
"tacotron", "training")
fs = hparams.sample_rate
global_step = 0
global_epoch = 0
use_cuda = torch.cuda.is_available()
if use_cuda:
cudnn.benchmark = False
def _pad(seq, max_len):
return np.pad(seq, (0, max_len - len(seq)),
mode='constant', constant_values=0)
def _pad_2d(x, max_len):
x = np.pad(x, [(0, max_len - len(x)), (0, 0)],
mode="constant", constant_values=0)
return x
class TextDataSource(FileDataSource):
def __init__(self):
self._cleaner_names = [x.strip() for x in hparams.cleaners.split(',')]
def collect_files(self):
meta = join(DATA_ROOT, "train.txt")
with open(meta, "rb") as f:
lines = f.readlines()
lines = list(map(lambda l: l.decode("utf-8").split("|")[-1], lines))
return lines
def collect_features(self, text):
return np.asarray(text_to_sequence(text, self._cleaner_names),
dtype=np.int32)
class _NPYDataSource(FileDataSource):
def __init__(self, col):
self.col = col
def collect_files(self):
meta = join(DATA_ROOT, "train.txt")
with open(meta, "rb") as f:
lines = f.readlines()
lines = list(map(lambda l: l.decode(
"utf-8").split("|")[self.col], lines))
paths = list(map(lambda f: join(DATA_ROOT, f), lines))
return paths
def collect_features(self, path):
return np.load(path)
class MelSpecDataSource(_NPYDataSource):
def __init__(self):
super(MelSpecDataSource, self).__init__(1)
class LinearSpecDataSource(_NPYDataSource):
def __init__(self):
super(LinearSpecDataSource, self).__init__(0)
class PyTorchDataset(object):
def __init__(self, X, Mel, Y):
self.X = X
self.Mel = Mel
self.Y = Y
def __getitem__(self, idx):
return self.X[idx], self.Mel[idx], self.Y[idx]
def __len__(self):
return len(self.X)
def collate_fn(batch):
"""Create batch"""
r = hparams.outputs_per_step
input_lengths = [len(x[0]) for x in batch]
max_input_len = np.max(input_lengths)
# Add single zeros frame at least, so plus 1
max_target_len = np.max([len(x[1]) for x in batch]) + 1
if max_target_len % r != 0:
max_target_len += r - max_target_len % r
assert max_target_len % r == 0
a = np.array([_pad(x[0], max_input_len) for x in batch], dtype=np.int)
x_batch = torch.LongTensor(a)
input_lengths = torch.LongTensor(input_lengths)
b = np.array([_pad_2d(x[1], max_target_len) for x in batch],
dtype=np.float32)
mel_batch = torch.FloatTensor(b)
c = np.array([_pad_2d(x[2], max_target_len) for x in batch],
dtype=np.float32)
y_batch = torch.FloatTensor(c)
return x_batch, input_lengths, mel_batch, y_batch
def save_alignment(path, attn):
plot_alignment(attn.T, path, info="tacotron, step={}".format(global_step))
def save_spectrogram(path, linear_output):
spectrogram = audio._denormalize(linear_output)
plt.figure(figsize=(16, 10))
plt.imshow(spectrogram.T, aspect="auto", origin="lower")
plt.colorbar()
plt.tight_layout()
plt.savefig(path, format="png")
plt.close()
def _learning_rate_decay(init_lr, global_step):
warmup_steps = 4000.0
step = global_step + 1.
lr = init_lr * warmup_steps**0.5 * np.minimum(
step * warmup_steps**-1.5, step**-0.5)
return lr
def save_states(global_step, mel_outputs, linear_outputs, attn, y,
input_lengths, checkpoint_dir=None):
print("Save intermediate states at step {}".format(global_step))
# idx = np.random.randint(0, len(input_lengths))
idx = min(1, len(input_lengths) - 1)
input_length = input_lengths[idx]
# Alignment
path = join(checkpoint_dir, "step{}_alignment.png".format(
global_step))
# alignment = attn[idx].cpu().data.numpy()[:, :input_length]
alignment = attn[idx].cpu().data.numpy()
save_alignment(path, alignment)
# Predicted spectrogram
path = join(checkpoint_dir, "step{}_predicted_spectrogram.png".format(
global_step))
linear_output = linear_outputs[idx].cpu().data.numpy()
save_spectrogram(path, linear_output)
# Predicted audio signal
signal = audio.inv_spectrogram(linear_output.T)
path = join(checkpoint_dir, "step{}_predicted.wav".format(
global_step))
audio.save_wav(signal, path)
# Target spectrogram
path = join(checkpoint_dir, "step{}_target_spectrogram.png".format(
global_step))
linear_output = y[idx].cpu().data.numpy()
save_spectrogram(path, linear_output)
def train(model, data_loader, optimizer,
init_lr=0.002,
checkpoint_dir=None, checkpoint_interval=None, nepochs=None,
clip_thresh=1.0):
model.train()
print('cuda:', use_cuda)
# if use_cuda:
# model = model.cuda()
# optimizer = optimizer.to_device('cuda')
linear_dim = model.linear_dim
criterion = nn.L1Loss()
global global_step, global_epoch
while global_epoch < nepochs:
running_loss = 0.
for step, (x, input_lengths, mel, y) in tqdm(enumerate(data_loader)):
# Decay learning rate
current_lr = _learning_rate_decay(init_lr, global_step)
for param_group in optimizer.param_groups:
param_group['lr'] = current_lr
optimizer.zero_grad()
# Sort by length
sorted_lengths, indices = torch.sort(
input_lengths.view(-1), dim=0, descending=True)
sorted_lengths = sorted_lengths.long().numpy()
x, mel, y = x[indices], mel[indices], y[indices]
# Feed data
x, mel, y = Variable(x), Variable(mel), Variable(y)
if use_cuda:
x, mel, y = x.cuda(), mel.cuda(), y.cuda()
mel_outputs, linear_outputs, attn = model(
x, mel, input_lengths=sorted_lengths)
# Loss
mel_loss = criterion(mel_outputs, mel)
n_priority_freq = int(3000 / (fs * 0.5) * linear_dim)
linear_loss = 0.5 * criterion(linear_outputs, y) \
+ 0.5 * criterion(linear_outputs[:, :, :n_priority_freq],
y[:, :, :n_priority_freq])
loss = mel_loss + linear_loss
if global_step > 0 and global_step % checkpoint_interval == 0:
save_states(
global_step, mel_outputs, linear_outputs, attn, y,
sorted_lengths, checkpoint_dir)
save_checkpoint(
model, optimizer, global_step, checkpoint_dir, global_epoch)
# Update
loss.backward()
grad_norm = torch.nn.utils.clip_grad_norm(
model.parameters(), clip_thresh)
optimizer.step()
# Logs
log_value("loss", float(loss.item()), global_step)
log_value("mel loss", float(mel_loss.item()), global_step)
log_value("linear loss", float(linear_loss.item()), global_step)
log_value("gradient norm", grad_norm, global_step)
log_value("learning rate", current_lr, global_step)
global_step += 1
running_loss += loss.item()
averaged_loss = running_loss / (len(data_loader))
log_value("loss (per epoch)", averaged_loss, global_epoch)
print("Loss: {}".format(running_loss / (len(data_loader))))
global_epoch += 1
def save_checkpoint(model, optimizer, step, checkpoint_dir, epoch):
checkpoint_path = join(
checkpoint_dir, "checkpoint_step{}.pth".format(global_step))
torch.save({
"state_dict": model.state_dict(),
"optimizer": optimizer.state_dict(),
"global_step": step,
"global_epoch": epoch,
}, checkpoint_path)
print("Saved checkpoint:", checkpoint_path)
if __name__ == "__main__":
args = docopt(__doc__)
print("Command line args:\n", args)
checkpoint_dir = args["--checkpoint-dir"]
checkpoint_path = args["--checkpoint-path"]
data_root = args["--data-root"]
if data_root:
DATA_ROOT = data_root
# Override hyper parameters
hparams.parse(args["--hparams"])
os.makedirs(checkpoint_dir, exist_ok=True)
# Input dataset definitions
X = FileSourceDataset(TextDataSource())
Mel = FileSourceDataset(MelSpecDataSource())
Y = FileSourceDataset(LinearSpecDataSource())
# Dataset and Dataloader setup
dataset = PyTorchDataset(X, Mel, Y)
data_loader = data_utils.DataLoader(
dataset, batch_size=hparams.batch_size,
num_workers=hparams.num_workers, shuffle=True,
collate_fn=collate_fn, pin_memory=hparams.pin_memory)
# Model
model = Tacotron(n_vocab=len(symbols),
embedding_dim=256,
mel_dim=hparams.num_mels,
linear_dim=hparams.num_freq,
r=hparams.outputs_per_step,
padding_idx=hparams.padding_idx,
use_memory_mask=hparams.use_memory_mask,
)
# Load checkpoint
if checkpoint_path:
print("Load checkpoint from: {}".format(checkpoint_path))
if use_cuda:
checkpoint = torch.load(
checkpoint_path, map_location=torch.device('cuda'))
else:
checkpoint = torch.load(
checkpoint_path, map_location=torch.device('cpu'))
if use_cuda:
model = model.cuda()
# optimizer = optim.SGD(model.parameters(),
# lr=hparams.initial_learning_rate,
# weight_decay=hparams.weight_decay)
# Unfreezing decoder: running this on 18/4/2020 10:21 PM
optimizer = optim.SGD(model.parameters(
), lr=hparams.initial_learning_rate, weight_decay=hparams.weight_decay)
# Load checkpoint
if checkpoint_path:
print("Load checkpoint from: {}".format(checkpoint_path))
if use_cuda:
checkpoint = torch.load(
checkpoint_path, map_location=torch.device('cuda'))
else:
checkpoint = torch.load(
checkpoint_path, map_location=torch.device('cpu'))
model.load_state_dict(checkpoint["state_dict"])
# optimizer.load_state_dict(checkpoint["optimizer"])
try:
global_step = checkpoint["global_step"]
global_epoch = checkpoint["global_epoch"]
except:
# TODO
pass
# Setup tensorboard logger
tensorboard_logger.configure("log/run-test")
print(hparams_debug_string())
# Train!
try:
train(model, data_loader, optimizer,
init_lr=hparams.initial_learning_rate,
checkpoint_dir=checkpoint_dir,
checkpoint_interval=hparams.checkpoint_interval,
nepochs=hparams.nepochs,
clip_thresh=hparams.clip_thresh)
except:
save_checkpoint(
model, optimizer, global_step, checkpoint_dir, global_epoch)
traceback.print_exc()
print("Finished")
sys.exit(0)