Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
TensorSpeech
GitHub Repository: TensorSpeech/TensorFlowTTS
Path: blob/master/examples/fastspeech/train_fastspeech.py
1558 views
1
# -*- coding: utf-8 -*-
2
# Copyright 2020 Minh Nguyen (@dathudeptrai)
3
#
4
# Licensed under the Apache License, Version 2.0 (the "License");
5
# you may not use this file except in compliance with the License.
6
# You may obtain a copy of the License at
7
#
8
# http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
"""Train FastSpeech."""
16
17
import tensorflow as tf
18
19
physical_devices = tf.config.list_physical_devices("GPU")
20
for i in range(len(physical_devices)):
21
tf.config.experimental.set_memory_growth(physical_devices[i], True)
22
23
import argparse
24
import logging
25
import os
26
import sys
27
28
sys.path.append(".")
29
30
import numpy as np
31
import yaml
32
33
import tensorflow_tts
34
import tensorflow_tts.configs.fastspeech as FASTSPEECH_CONFIG
35
from examples.fastspeech.fastspeech_dataset import CharactorDurationMelDataset
36
from tensorflow_tts.models import TFFastSpeech
37
from tensorflow_tts.optimizers import AdamWeightDecay, WarmUp
38
from tensorflow_tts.trainers import Seq2SeqBasedTrainer
39
from tensorflow_tts.utils import calculate_2d_loss, calculate_3d_loss, return_strategy
40
41
42
class FastSpeechTrainer(Seq2SeqBasedTrainer):
43
"""FastSpeech Trainer class based on Seq2SeqBasedTrainer."""
44
45
def __init__(
46
self, config, strategy, steps=0, epochs=0, is_mixed_precision=False,
47
):
48
"""Initialize trainer.
49
50
Args:
51
steps (int): Initial global steps.
52
epochs (int): Initial global epochs.
53
config (dict): Config dict loaded from yaml format configuration file.
54
is_mixed_precision (bool): Use mixed precision or not.
55
56
"""
57
super(FastSpeechTrainer, self).__init__(
58
steps=steps,
59
epochs=epochs,
60
config=config,
61
strategy=strategy,
62
is_mixed_precision=is_mixed_precision,
63
)
64
# define metrics to aggregates data and use tf.summary logs them
65
self.list_metrics_name = ["duration_loss", "mel_loss_before", "mel_loss_after"]
66
self.init_train_eval_metrics(self.list_metrics_name)
67
self.reset_states_train()
68
self.reset_states_eval()
69
70
self.config = config
71
72
def compile(self, model, optimizer):
73
super().compile(model, optimizer)
74
self.mse = tf.keras.losses.MeanSquaredError(
75
reduction=tf.keras.losses.Reduction.NONE
76
)
77
self.mae = tf.keras.losses.MeanAbsoluteError(
78
reduction=tf.keras.losses.Reduction.NONE
79
)
80
81
def compute_per_example_losses(self, batch, outputs):
82
"""Compute per example losses and return dict_metrics_losses
83
Note that all element of the loss MUST has a shape [batch_size] and
84
the keys of dict_metrics_losses MUST be in self.list_metrics_name.
85
86
Args:
87
batch: dictionary batch input return from dataloader
88
outputs: outputs of the model
89
90
Returns:
91
per_example_losses: per example losses for each GPU, shape [B]
92
dict_metrics_losses: dictionary loss.
93
"""
94
mel_before, mel_after, duration_outputs = outputs
95
96
log_duration = tf.math.log(
97
tf.cast(tf.math.add(batch["duration_gts"], 1), tf.float32)
98
)
99
duration_loss = self.mse(log_duration, duration_outputs)
100
mel_loss_before = calculate_3d_loss(batch["mel_gts"], mel_before, self.mae)
101
mel_loss_after = calculate_3d_loss(batch["mel_gts"], mel_after, self.mae)
102
103
per_example_losses = duration_loss + mel_loss_before + mel_loss_after
104
105
dict_metrics_losses = {
106
"duration_loss": duration_loss,
107
"mel_loss_before": mel_loss_before,
108
"mel_loss_after": mel_loss_after,
109
}
110
111
return per_example_losses, dict_metrics_losses
112
113
def generate_and_save_intermediate_result(self, batch):
114
"""Generate and save intermediate result."""
115
import matplotlib.pyplot as plt
116
117
# predict with tf.function.
118
outputs = self.one_step_predict(batch)
119
120
mels_before, mels_after, *_ = outputs
121
mel_gts = batch["mel_gts"]
122
utt_ids = batch["utt_ids"]
123
124
# convert to tensor.
125
# here we just take a sample at first replica.
126
try:
127
mels_before = mels_before.values[0].numpy()
128
mels_after = mels_after.values[0].numpy()
129
mel_gts = mel_gts.values[0].numpy()
130
utt_ids = utt_ids.values[0].numpy()
131
except Exception:
132
mels_before = mels_before.numpy()
133
mels_after = mels_after.numpy()
134
mel_gts = mel_gts.numpy()
135
utt_ids = utt_ids.numpy()
136
137
# check directory
138
dirname = os.path.join(self.config["outdir"], f"predictions/{self.steps}steps")
139
if not os.path.exists(dirname):
140
os.makedirs(dirname)
141
142
for idx, (mel_gt, mel_before, mel_after) in enumerate(
143
zip(mel_gts, mels_before, mels_after), 0
144
):
145
mel_gt = tf.reshape(mel_gt, (-1, 80)).numpy() # [length, 80]
146
mel_before = tf.reshape(mel_before, (-1, 80)).numpy() # [length, 80]
147
mel_after = tf.reshape(mel_after, (-1, 80)).numpy() # [length, 80]
148
149
# plit figure and save it
150
utt_id = utt_ids[idx].decode("utf-8")
151
figname = os.path.join(dirname, f"{utt_id}.png")
152
fig = plt.figure(figsize=(10, 8))
153
ax1 = fig.add_subplot(311)
154
ax2 = fig.add_subplot(312)
155
ax3 = fig.add_subplot(313)
156
im = ax1.imshow(np.rot90(mel_gt), aspect="auto", interpolation="none")
157
ax1.set_title("Target Mel-Spectrogram")
158
fig.colorbar(mappable=im, shrink=0.65, orientation="horizontal", ax=ax1)
159
ax2.set_title("Predicted Mel-before-Spectrogram")
160
im = ax2.imshow(np.rot90(mel_before), aspect="auto", interpolation="none")
161
fig.colorbar(mappable=im, shrink=0.65, orientation="horizontal", ax=ax2)
162
ax3.set_title("Predicted Mel-after-Spectrogram")
163
im = ax3.imshow(np.rot90(mel_after), aspect="auto", interpolation="none")
164
fig.colorbar(mappable=im, shrink=0.65, orientation="horizontal", ax=ax3)
165
plt.tight_layout()
166
plt.savefig(figname)
167
plt.close()
168
169
170
def main():
171
"""Run training process."""
172
parser = argparse.ArgumentParser(
173
description="Train FastSpeech (See detail in tensorflow_tts/bin/train-fastspeech.py)"
174
)
175
parser.add_argument(
176
"--train-dir",
177
default=None,
178
type=str,
179
help="directory including training data. ",
180
)
181
parser.add_argument(
182
"--dev-dir",
183
default=None,
184
type=str,
185
help="directory including development data. ",
186
)
187
parser.add_argument(
188
"--use-norm", default=1, type=int, help="usr norm-mels for train or raw."
189
)
190
parser.add_argument(
191
"--outdir", type=str, required=True, help="directory to save checkpoints."
192
)
193
parser.add_argument(
194
"--config", type=str, required=True, help="yaml format configuration file."
195
)
196
parser.add_argument(
197
"--resume",
198
default="",
199
type=str,
200
nargs="?",
201
help='checkpoint file path to resume training. (default="")',
202
)
203
parser.add_argument(
204
"--verbose",
205
type=int,
206
default=1,
207
help="logging level. higher is more logging. (default=1)",
208
)
209
parser.add_argument(
210
"--mixed_precision",
211
default=0,
212
type=int,
213
help="using mixed precision for generator or not.",
214
)
215
parser.add_argument(
216
"--pretrained",
217
default="",
218
type=str,
219
nargs="?",
220
help="pretrained checkpoint file to load weights from. Auto-skips non-matching layers",
221
)
222
args = parser.parse_args()
223
224
# return strategy
225
STRATEGY = return_strategy()
226
227
# set mixed precision config
228
if args.mixed_precision == 1:
229
tf.config.optimizer.set_experimental_options({"auto_mixed_precision": True})
230
231
args.mixed_precision = bool(args.mixed_precision)
232
args.use_norm = bool(args.use_norm)
233
234
# set logger
235
if args.verbose > 1:
236
logging.basicConfig(
237
level=logging.DEBUG,
238
stream=sys.stdout,
239
format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
240
)
241
elif args.verbose > 0:
242
logging.basicConfig(
243
level=logging.INFO,
244
stream=sys.stdout,
245
format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
246
)
247
else:
248
logging.basicConfig(
249
level=logging.WARN,
250
stream=sys.stdout,
251
format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
252
)
253
logging.warning("Skip DEBUG/INFO messages")
254
255
# check directory existence
256
if not os.path.exists(args.outdir):
257
os.makedirs(args.outdir)
258
259
# check arguments
260
if args.train_dir is None:
261
raise ValueError("Please specify --train-dir")
262
if args.dev_dir is None:
263
raise ValueError("Please specify --valid-dir")
264
265
# load and save config
266
with open(args.config) as f:
267
config = yaml.load(f, Loader=yaml.Loader)
268
config.update(vars(args))
269
config["version"] = tensorflow_tts.__version__
270
with open(os.path.join(args.outdir, "config.yml"), "w") as f:
271
yaml.dump(config, f, Dumper=yaml.Dumper)
272
for key, value in config.items():
273
logging.info(f"{key} = {value}")
274
275
# get dataset
276
if config["remove_short_samples"]:
277
mel_length_threshold = config["mel_length_threshold"]
278
else:
279
mel_length_threshold = None
280
281
if config["format"] == "npy":
282
charactor_query = "*-ids.npy"
283
mel_query = "*-raw-feats.npy" if args.use_norm is False else "*-norm-feats.npy"
284
duration_query = "*-durations.npy"
285
charactor_load_fn = np.load
286
mel_load_fn = np.load
287
duration_load_fn = np.load
288
else:
289
raise ValueError("Only npy are supported.")
290
291
# define train/valid dataset
292
train_dataset = CharactorDurationMelDataset(
293
root_dir=args.train_dir,
294
charactor_query=charactor_query,
295
mel_query=mel_query,
296
duration_query=duration_query,
297
charactor_load_fn=charactor_load_fn,
298
mel_load_fn=mel_load_fn,
299
duration_load_fn=duration_load_fn,
300
mel_length_threshold=mel_length_threshold,
301
).create(
302
is_shuffle=config["is_shuffle"],
303
allow_cache=config["allow_cache"],
304
batch_size=config["batch_size"]
305
* STRATEGY.num_replicas_in_sync
306
* config["gradient_accumulation_steps"],
307
)
308
309
valid_dataset = CharactorDurationMelDataset(
310
root_dir=args.dev_dir,
311
charactor_query=charactor_query,
312
mel_query=mel_query,
313
duration_query=duration_query,
314
charactor_load_fn=charactor_load_fn,
315
mel_load_fn=mel_load_fn,
316
duration_load_fn=duration_load_fn,
317
).create(
318
is_shuffle=config["is_shuffle"],
319
allow_cache=config["allow_cache"],
320
batch_size=config["batch_size"] * STRATEGY.num_replicas_in_sync,
321
)
322
323
# define trainer
324
trainer = FastSpeechTrainer(
325
config=config,
326
strategy=STRATEGY,
327
steps=0,
328
epochs=0,
329
is_mixed_precision=args.mixed_precision,
330
)
331
332
with STRATEGY.scope():
333
# define model
334
fastspeech = TFFastSpeech(
335
config=FASTSPEECH_CONFIG.FastSpeechConfig(**config["fastspeech_params"])
336
)
337
fastspeech._build()
338
fastspeech.summary()
339
340
if len(args.pretrained) > 1:
341
fastspeech.load_weights(args.pretrained, by_name=True, skip_mismatch=True)
342
logging.info(
343
f"Successfully loaded pretrained weight from {args.pretrained}."
344
)
345
346
# AdamW for fastspeech
347
learning_rate_fn = tf.keras.optimizers.schedules.PolynomialDecay(
348
initial_learning_rate=config["optimizer_params"]["initial_learning_rate"],
349
decay_steps=config["optimizer_params"]["decay_steps"],
350
end_learning_rate=config["optimizer_params"]["end_learning_rate"],
351
)
352
353
learning_rate_fn = WarmUp(
354
initial_learning_rate=config["optimizer_params"]["initial_learning_rate"],
355
decay_schedule_fn=learning_rate_fn,
356
warmup_steps=int(
357
config["train_max_steps"]
358
* config["optimizer_params"]["warmup_proportion"]
359
),
360
)
361
362
optimizer = AdamWeightDecay(
363
learning_rate=learning_rate_fn,
364
weight_decay_rate=config["optimizer_params"]["weight_decay"],
365
beta_1=0.9,
366
beta_2=0.98,
367
epsilon=1e-6,
368
exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"],
369
)
370
371
_ = optimizer.iterations
372
373
# compile trainer
374
trainer.compile(model=fastspeech, optimizer=optimizer)
375
376
# start training
377
try:
378
trainer.fit(
379
train_dataset,
380
valid_dataset,
381
saved_path=os.path.join(config["outdir"], "checkpoints/"),
382
resume=args.resume,
383
)
384
except KeyboardInterrupt:
385
trainer.save_checkpoint()
386
logging.info(f"Successfully saved checkpoint @ {trainer.steps}steps.")
387
388
389
if __name__ == "__main__":
390
main()
391
392