2019-02-27 11:50:52 +03:00
|
|
|
import argparse
|
|
|
|
import importlib
|
2018-01-22 12:48:59 +03:00
|
|
|
import os
|
2019-02-27 11:50:52 +03:00
|
|
|
import shutil
|
2018-01-22 12:48:59 +03:00
|
|
|
import sys
|
|
|
|
import time
|
2018-05-11 02:13:05 +03:00
|
|
|
import traceback
|
2018-01-22 12:48:59 +03:00
|
|
|
|
2019-02-27 11:50:52 +03:00
|
|
|
import numpy as np
|
|
|
|
import torch
|
2018-01-22 12:48:59 +03:00
|
|
|
import torch.nn as nn
|
2019-02-27 11:50:52 +03:00
|
|
|
from tensorboardX import SummaryWriter
|
2018-01-22 12:48:59 +03:00
|
|
|
from torch import optim
|
|
|
|
from torch.utils.data import DataLoader
|
|
|
|
|
2018-12-18 14:58:09 +03:00
|
|
|
from datasets.TTSDataset import MyDataset
|
2019-02-27 11:50:52 +03:00
|
|
|
from layers.losses import L1LossMasked
|
|
|
|
from models.tacotron import Tacotron
|
2018-07-20 17:04:29 +03:00
|
|
|
from utils.audio import AudioProcessor
|
2019-02-27 11:50:52 +03:00
|
|
|
from utils.generic_utils import (
|
|
|
|
NoamLR, check_update, count_parameters, create_experiment_folder,
|
|
|
|
get_commit_hash, load_config, lr_decay, remove_experiment_folder,
|
|
|
|
save_best_model, save_checkpoint, sequence_mask, weight_decay)
|
2018-12-13 20:18:37 +03:00
|
|
|
from utils.logger import Logger
|
2019-02-27 11:50:52 +03:00
|
|
|
from utils.synthesis import synthesis
|
|
|
|
from utils.text.symbols import phonemes, symbols
|
|
|
|
from utils.visual import plot_alignment, plot_spectrogram
|
|
|
|
from distribute import init_distributed, apply_gradient_allreduce, reduce_tensor
|
|
|
|
from distribute import DistributedSampler
|
|
|
|
|
2018-08-12 16:02:06 +03:00
|
|
|
|
2019-02-27 11:50:52 +03:00
|
|
|
torch.backends.cudnn.enabled = True
|
|
|
|
torch.backends.cudnn.benchmark = False
|
|
|
|
torch.manual_seed(54321)
|
2018-01-22 12:48:59 +03:00
|
|
|
use_cuda = torch.cuda.is_available()
|
2019-02-27 11:50:52 +03:00
|
|
|
num_gpus = torch.cuda.device_count()
|
2018-11-05 16:05:04 +03:00
|
|
|
print(" > Using CUDA: ", use_cuda)
|
2019-02-27 11:50:52 +03:00
|
|
|
print(" > Number of GPUs: ", num_gpus)
|
2018-01-22 12:48:59 +03:00
|
|
|
|
2018-03-02 18:54:35 +03:00
|
|
|
|
2019-02-27 11:50:52 +03:00
|
|
|
def setup_loader(is_val=False, verbose=False):
|
2018-12-11 19:52:43 +03:00
|
|
|
global ap
|
|
|
|
if is_val and not c.run_eval:
|
|
|
|
loader = None
|
|
|
|
else:
|
|
|
|
dataset = MyDataset(
|
|
|
|
c.data_path,
|
|
|
|
c.meta_file_val if is_val else c.meta_file_train,
|
|
|
|
c.r,
|
|
|
|
c.text_cleaner,
|
|
|
|
preprocessor=preprocessor,
|
|
|
|
ap=ap,
|
2019-02-27 11:50:52 +03:00
|
|
|
batch_group_size=0 if is_val else c.batch_group_size * c.batch_size,
|
2018-12-17 18:37:06 +03:00
|
|
|
min_seq_len=0 if is_val else c.min_seq_len,
|
2018-12-18 14:58:09 +03:00
|
|
|
max_seq_len=float("inf") if is_val else c.max_seq_len,
|
2019-01-15 17:51:13 +03:00
|
|
|
cached=False if c.dataset != "tts_cache" else True,
|
2019-01-16 15:09:47 +03:00
|
|
|
phoneme_cache_path=c.phoneme_cache_path,
|
|
|
|
use_phonemes=c.use_phonemes,
|
2019-02-27 11:50:52 +03:00
|
|
|
phoneme_language=c.phoneme_language,
|
|
|
|
verbose=verbose)
|
|
|
|
sampler = DistributedSampler(dataset) if num_gpus > 1 else None
|
2018-12-11 19:52:43 +03:00
|
|
|
loader = DataLoader(
|
|
|
|
dataset,
|
|
|
|
batch_size=c.eval_batch_size if is_val else c.batch_size,
|
|
|
|
shuffle=False,
|
|
|
|
collate_fn=dataset.collate_fn,
|
|
|
|
drop_last=False,
|
2019-02-27 11:50:52 +03:00
|
|
|
sampler=sampler,
|
|
|
|
num_workers=c.num_val_loader_workers
|
|
|
|
if is_val else c.num_loader_workers,
|
2018-12-11 19:52:43 +03:00
|
|
|
pin_memory=False)
|
|
|
|
return loader
|
|
|
|
|
|
|
|
|
2019-02-27 11:50:52 +03:00
|
|
|
def train(model, criterion, criterion_st, optimizer, optimizer_st, scheduler,
|
|
|
|
ap, epoch):
|
|
|
|
data_loader = setup_loader(is_val=False, verbose=(epoch==0))
|
2018-12-11 19:52:43 +03:00
|
|
|
model.train()
|
2018-03-02 18:54:35 +03:00
|
|
|
epoch_time = 0
|
2018-03-06 16:39:54 +03:00
|
|
|
avg_linear_loss = 0
|
|
|
|
avg_mel_loss = 0
|
2018-05-11 14:15:53 +03:00
|
|
|
avg_stop_loss = 0
|
2018-07-27 17:13:55 +03:00
|
|
|
avg_step_time = 0
|
2019-02-27 11:50:52 +03:00
|
|
|
print("\n > Epoch {}/{}".format(epoch, c.epochs), flush=True)
|
2018-11-05 16:05:04 +03:00
|
|
|
n_priority_freq = int(
|
|
|
|
3000 / (c.audio['sample_rate'] * 0.5) * c.audio['num_freq'])
|
2019-02-27 11:50:52 +03:00
|
|
|
if num_gpus > 0:
|
|
|
|
batch_n_iter = int(len(data_loader.dataset) / (c.batch_size * num_gpus))
|
|
|
|
else:
|
|
|
|
batch_n_iter = int(len(data_loader.dataset) / c.batch_size)
|
2018-03-02 18:54:35 +03:00
|
|
|
for num_iter, data in enumerate(data_loader):
|
|
|
|
start_time = time.time()
|
|
|
|
|
|
|
|
# setup input data
|
|
|
|
text_input = data[0]
|
|
|
|
text_lengths = data[1]
|
2018-05-25 15:17:08 +03:00
|
|
|
linear_input = data[2]
|
|
|
|
mel_input = data[3]
|
2018-03-22 23:46:52 +03:00
|
|
|
mel_lengths = data[4]
|
2018-05-11 14:24:57 +03:00
|
|
|
stop_targets = data[5]
|
2018-11-20 14:54:33 +03:00
|
|
|
avg_text_length = torch.mean(text_lengths.float())
|
2018-12-11 17:08:02 +03:00
|
|
|
avg_spec_length = torch.mean(mel_lengths.float())
|
2018-07-05 18:30:42 +03:00
|
|
|
|
2018-05-11 14:24:57 +03:00
|
|
|
# set stop targets view, we predict a single stop token per r frames prediction
|
2018-08-02 17:34:17 +03:00
|
|
|
stop_targets = stop_targets.view(text_input.shape[0],
|
|
|
|
stop_targets.size(1) // c.r, -1)
|
2018-05-11 14:24:57 +03:00
|
|
|
stop_targets = (stop_targets.sum(2) > 0.0).unsqueeze(2).float()
|
2018-04-03 13:24:57 +03:00
|
|
|
|
|
|
|
current_step = num_iter + args.restore_step + \
|
|
|
|
epoch * len(data_loader) + 1
|
2018-03-02 18:54:35 +03:00
|
|
|
|
|
|
|
# setup lr
|
2018-11-03 21:47:28 +03:00
|
|
|
if c.lr_decay:
|
|
|
|
scheduler.step()
|
2018-03-02 18:54:35 +03:00
|
|
|
optimizer.zero_grad()
|
2018-05-11 18:38:07 +03:00
|
|
|
optimizer_st.zero_grad()
|
2018-03-02 18:54:35 +03:00
|
|
|
|
|
|
|
# dispatch data to GPU
|
|
|
|
if use_cuda:
|
2018-11-20 14:54:33 +03:00
|
|
|
text_input = text_input.cuda(non_blocking=True)
|
|
|
|
text_lengths = text_lengths.cuda(non_blocking=True)
|
|
|
|
mel_input = mel_input.cuda(non_blocking=True)
|
|
|
|
mel_lengths = mel_lengths.cuda(non_blocking=True)
|
|
|
|
linear_input = linear_input.cuda(non_blocking=True)
|
|
|
|
stop_targets = stop_targets.cuda(non_blocking=True)
|
2018-12-31 15:29:39 +03:00
|
|
|
|
2018-08-10 18:48:19 +03:00
|
|
|
# compute mask for padding
|
|
|
|
mask = sequence_mask(text_lengths)
|
|
|
|
|
2018-03-02 18:54:35 +03:00
|
|
|
# forward pass
|
2019-02-27 11:50:52 +03:00
|
|
|
mel_output, linear_output, alignments, stop_tokens = model(
|
|
|
|
text_input, mel_input, mask)
|
2018-04-03 13:24:57 +03:00
|
|
|
|
2018-03-02 18:54:35 +03:00
|
|
|
# loss computation
|
2018-05-11 14:24:57 +03:00
|
|
|
stop_loss = criterion_st(stop_tokens, stop_targets)
|
2018-05-11 02:05:03 +03:00
|
|
|
mel_loss = criterion(mel_output, mel_input, mel_lengths)
|
2019-02-12 12:04:18 +03:00
|
|
|
linear_loss = (1 - c.loss_weight) * criterion(linear_output, linear_input, mel_lengths)\
|
|
|
|
+ c.loss_weight * criterion(linear_output[:, :, :n_priority_freq],
|
2018-05-11 02:05:03 +03:00
|
|
|
linear_input[:, :, :n_priority_freq],
|
|
|
|
mel_lengths)
|
2018-05-11 18:38:07 +03:00
|
|
|
loss = mel_loss + linear_loss
|
2018-03-02 18:54:35 +03:00
|
|
|
|
2018-05-11 18:38:07 +03:00
|
|
|
# backpass and check the grad norm for spec losses
|
|
|
|
loss.backward(retain_graph=True)
|
2019-02-27 11:50:52 +03:00
|
|
|
optimizer, current_lr = weight_decay(optimizer, c.wd)
|
|
|
|
grad_norm, _ = check_update(model, 1.0)
|
2018-03-02 18:54:35 +03:00
|
|
|
optimizer.step()
|
2018-07-05 18:30:42 +03:00
|
|
|
|
2018-05-11 18:38:07 +03:00
|
|
|
# backpass and check the grad norm for stop loss
|
|
|
|
stop_loss.backward()
|
2019-02-27 11:50:52 +03:00
|
|
|
optimizer_st, _ = weight_decay(optimizer_st, c.wd)
|
|
|
|
grad_norm_st, _ = check_update(model.decoder.stopnet, 1.0)
|
2018-05-11 18:38:07 +03:00
|
|
|
optimizer_st.step()
|
2018-03-02 18:54:35 +03:00
|
|
|
|
|
|
|
step_time = time.time() - start_time
|
|
|
|
epoch_time += step_time
|
|
|
|
|
2018-07-05 18:30:42 +03:00
|
|
|
if current_step % c.print_step == 0:
|
2018-08-10 18:48:19 +03:00
|
|
|
print(
|
2019-02-27 11:50:52 +03:00
|
|
|
" | > Step:{}/{} GlobalStep:{} TotalLoss:{:.5f} LinearLoss:{:.5f} "
|
2018-08-10 18:48:19 +03:00
|
|
|
"MelLoss:{:.5f} StopLoss:{:.5f} GradNorm:{:.5f} "
|
2019-02-27 11:50:52 +03:00
|
|
|
"GradNormST:{:.5f} AvgTextLen:{:.1f} AvgSpecLen:{:.1f} StepTime:{:.2f} LR:{:.6f}"
|
|
|
|
.format(num_iter, batch_n_iter, current_step, loss.item(),
|
|
|
|
linear_loss.item(), mel_loss.item(), stop_loss.item(),
|
|
|
|
grad_norm, grad_norm_st, avg_text_length,
|
|
|
|
avg_spec_length, step_time, current_lr),
|
2018-08-10 18:48:19 +03:00
|
|
|
flush=True)
|
2018-07-05 18:30:42 +03:00
|
|
|
|
2019-02-27 11:50:52 +03:00
|
|
|
# aggregate losses from processes
|
|
|
|
if num_gpus > 1:
|
|
|
|
linear_loss = reduce_tensor(linear_loss.data, num_gpus)
|
|
|
|
mel_loss = reduce_tensor(mel_loss.data, num_gpus)
|
|
|
|
loss = reduce_tensor(loss.data, num_gpus)
|
|
|
|
stop_loss = reduce_tensor(stop_loss.data, num_gpus)
|
|
|
|
|
|
|
|
if args.rank == 0:
|
|
|
|
avg_linear_loss += float(linear_loss.item())
|
|
|
|
avg_mel_loss += float(mel_loss.item())
|
|
|
|
avg_stop_loss += stop_loss.item()
|
|
|
|
avg_step_time += step_time
|
|
|
|
|
|
|
|
# Plot Training Iter Stats
|
|
|
|
iter_stats = {
|
|
|
|
"loss_posnet": linear_loss.item(),
|
|
|
|
"loss_decoder": mel_loss.item(),
|
|
|
|
"lr": current_lr,
|
|
|
|
"grad_norm": grad_norm,
|
|
|
|
"grad_norm_st": grad_norm_st,
|
|
|
|
"step_time": step_time
|
|
|
|
}
|
|
|
|
tb_logger.tb_train_iter_stats(current_step, iter_stats)
|
|
|
|
|
|
|
|
if current_step % c.save_step == 0:
|
|
|
|
if c.checkpoint:
|
|
|
|
# save model
|
|
|
|
save_checkpoint(model, optimizer, optimizer_st,
|
|
|
|
linear_loss.item(), OUT_PATH, current_step,
|
|
|
|
epoch)
|
|
|
|
|
|
|
|
# Diagnostic visualizations
|
|
|
|
const_spec = linear_output[0].data.cpu().numpy()
|
|
|
|
gt_spec = linear_input[0].data.cpu().numpy()
|
|
|
|
align_img = alignments[0].data.cpu().numpy()
|
|
|
|
|
|
|
|
figures = {
|
|
|
|
"prediction": plot_spectrogram(const_spec, ap),
|
|
|
|
"ground_truth": plot_spectrogram(gt_spec, ap),
|
|
|
|
"alignment": plot_alignment(align_img)
|
|
|
|
}
|
|
|
|
tb_logger.tb_train_figures(current_step, figures)
|
|
|
|
|
|
|
|
# Sample audio
|
|
|
|
tb_logger.tb_train_audios(
|
|
|
|
current_step, {'TrainAudio': ap.inv_spectrogram(const_spec.T)},
|
|
|
|
c.audio["sample_rate"])
|
2018-04-03 13:24:57 +03:00
|
|
|
|
2018-03-06 16:39:54 +03:00
|
|
|
avg_linear_loss /= (num_iter + 1)
|
|
|
|
avg_mel_loss /= (num_iter + 1)
|
2018-05-11 14:15:53 +03:00
|
|
|
avg_stop_loss /= (num_iter + 1)
|
|
|
|
avg_total_loss = avg_mel_loss + avg_linear_loss + avg_stop_loss
|
2018-07-27 17:13:55 +03:00
|
|
|
avg_step_time /= (num_iter + 1)
|
2018-04-03 13:24:57 +03:00
|
|
|
|
2018-07-11 13:42:59 +03:00
|
|
|
# print epoch stats
|
2018-08-10 18:48:19 +03:00
|
|
|
print(
|
2019-02-27 11:50:52 +03:00
|
|
|
" | > EPOCH END -- GlobalStep:{} AvgTotalLoss:{:.5f} "
|
2018-08-10 18:48:19 +03:00
|
|
|
"AvgLinearLoss:{:.5f} AvgMelLoss:{:.5f} "
|
|
|
|
"AvgStopLoss:{:.5f} EpochTime:{:.2f} "
|
|
|
|
"AvgStepTime:{:.2f}".format(current_step, avg_total_loss,
|
|
|
|
avg_linear_loss, avg_mel_loss,
|
|
|
|
avg_stop_loss, epoch_time, avg_step_time),
|
|
|
|
flush=True)
|
2018-07-11 13:42:59 +03:00
|
|
|
|
2019-02-27 11:50:52 +03:00
|
|
|
# Plot Epoch Stats
|
|
|
|
if args.rank == 0:
|
|
|
|
# Plot Training Epoch Stats
|
|
|
|
epoch_stats = {
|
|
|
|
"loss_postnet": avg_linear_loss,
|
|
|
|
"loss_decoder": avg_mel_loss,
|
|
|
|
"stop_loss": avg_stop_loss,
|
|
|
|
"epoch_time": epoch_time
|
|
|
|
}
|
|
|
|
tb_logger.tb_train_epoch_stats(current_step, epoch_stats)
|
|
|
|
if c.tb_model_param_stats:
|
|
|
|
tb_logger.tb_model_weights(model, current_step)
|
2018-03-02 18:54:35 +03:00
|
|
|
return avg_linear_loss, current_step
|
|
|
|
|
2018-04-03 13:24:57 +03:00
|
|
|
|
2019-02-27 11:50:52 +03:00
|
|
|
def evaluate(model, criterion, criterion_st, ap, current_step, epoch):
|
2018-12-11 19:52:43 +03:00
|
|
|
data_loader = setup_loader(is_val=True)
|
|
|
|
model.eval()
|
2018-03-02 18:54:35 +03:00
|
|
|
epoch_time = 0
|
2018-03-06 16:39:54 +03:00
|
|
|
avg_linear_loss = 0
|
|
|
|
avg_mel_loss = 0
|
2018-05-11 14:15:53 +03:00
|
|
|
avg_stop_loss = 0
|
2019-02-27 11:50:52 +03:00
|
|
|
print("\n > Validation")
|
2018-08-02 17:34:17 +03:00
|
|
|
test_sentences = [
|
|
|
|
"It took me quite a long time to develop a voice, and now that I have it I'm not going to be silent.",
|
|
|
|
"Be a voice, not an echo.",
|
|
|
|
"I'm sorry Dave. I'm afraid I can't do that.",
|
|
|
|
"This cake is great. It's so delicious and moist."
|
|
|
|
]
|
2018-11-05 16:05:04 +03:00
|
|
|
n_priority_freq = int(
|
|
|
|
3000 / (c.audio['sample_rate'] * 0.5) * c.audio['num_freq'])
|
2018-05-11 02:44:37 +03:00
|
|
|
with torch.no_grad():
|
2018-07-20 17:04:29 +03:00
|
|
|
if data_loader is not None:
|
|
|
|
for num_iter, data in enumerate(data_loader):
|
|
|
|
start_time = time.time()
|
|
|
|
|
|
|
|
# setup input data
|
|
|
|
text_input = data[0]
|
|
|
|
text_lengths = data[1]
|
|
|
|
linear_input = data[2]
|
|
|
|
mel_input = data[3]
|
|
|
|
mel_lengths = data[4]
|
|
|
|
stop_targets = data[5]
|
|
|
|
|
|
|
|
# set stop targets view, we predict a single stop token per r frames prediction
|
2018-08-02 17:34:17 +03:00
|
|
|
stop_targets = stop_targets.view(text_input.shape[0],
|
|
|
|
stop_targets.size(1) // c.r,
|
|
|
|
-1)
|
2018-07-20 17:04:29 +03:00
|
|
|
stop_targets = (stop_targets.sum(2) > 0.0).unsqueeze(2).float()
|
|
|
|
|
|
|
|
# dispatch data to GPU
|
|
|
|
if use_cuda:
|
|
|
|
text_input = text_input.cuda()
|
|
|
|
mel_input = mel_input.cuda()
|
|
|
|
mel_lengths = mel_lengths.cuda()
|
|
|
|
linear_input = linear_input.cuda()
|
|
|
|
stop_targets = stop_targets.cuda()
|
|
|
|
|
|
|
|
# forward pass
|
|
|
|
mel_output, linear_output, alignments, stop_tokens =\
|
|
|
|
model.forward(text_input, mel_input)
|
|
|
|
|
|
|
|
# loss computation
|
|
|
|
stop_loss = criterion_st(stop_tokens, stop_targets)
|
|
|
|
mel_loss = criterion(mel_output, mel_input, mel_lengths)
|
|
|
|
linear_loss = 0.5 * criterion(linear_output, linear_input, mel_lengths) \
|
|
|
|
+ 0.5 * criterion(linear_output[:, :, :n_priority_freq],
|
|
|
|
linear_input[:, :, :n_priority_freq],
|
|
|
|
mel_lengths)
|
|
|
|
loss = mel_loss + linear_loss + stop_loss
|
|
|
|
|
|
|
|
step_time = time.time() - start_time
|
|
|
|
epoch_time += step_time
|
|
|
|
|
|
|
|
if num_iter % c.print_step == 0:
|
2018-08-02 17:34:17 +03:00
|
|
|
print(
|
2019-02-27 11:50:52 +03:00
|
|
|
" | > TotalLoss: {:.5f} LinearLoss: {:.5f} MelLoss:{:.5f} "
|
2018-08-10 18:48:19 +03:00
|
|
|
"StopLoss: {:.5f} ".format(loss.item(),
|
|
|
|
linear_loss.item(),
|
|
|
|
mel_loss.item(),
|
|
|
|
stop_loss.item()),
|
2018-08-02 17:34:17 +03:00
|
|
|
flush=True)
|
2018-07-20 17:04:29 +03:00
|
|
|
|
2019-02-27 11:50:52 +03:00
|
|
|
# aggregate losses from processes
|
|
|
|
if num_gpus > 1:
|
|
|
|
linear_loss = reduce_tensor(linear_loss.data, num_gpus)
|
|
|
|
mel_loss = reduce_tensor(mel_loss.data, num_gpus)
|
|
|
|
stop_loss = reduce_tensor(stop_loss.data, num_gpus)
|
|
|
|
|
2018-12-17 18:37:06 +03:00
|
|
|
avg_linear_loss += float(linear_loss.item())
|
|
|
|
avg_mel_loss += float(mel_loss.item())
|
2018-07-20 17:04:29 +03:00
|
|
|
avg_stop_loss += stop_loss.item()
|
2018-04-03 13:24:57 +03:00
|
|
|
|
2019-02-27 11:50:52 +03:00
|
|
|
if args.rank == 0:
|
|
|
|
# Diagnostic visualizations
|
|
|
|
idx = np.random.randint(mel_input.shape[0])
|
|
|
|
const_spec = linear_output[idx].data.cpu().numpy()
|
|
|
|
gt_spec = linear_input[idx].data.cpu().numpy()
|
|
|
|
align_img = alignments[idx].data.cpu().numpy()
|
|
|
|
|
|
|
|
eval_figures = {
|
|
|
|
"prediction": plot_spectrogram(const_spec, ap),
|
|
|
|
"ground_truth": plot_spectrogram(gt_spec, ap),
|
|
|
|
"alignment": plot_alignment(align_img)
|
|
|
|
}
|
|
|
|
tb_logger.tb_eval_figures(current_step, eval_figures)
|
|
|
|
|
|
|
|
# Sample audio
|
|
|
|
tb_logger.tb_eval_audios(
|
|
|
|
current_step, {"ValAudio": ap.inv_spectrogram(const_spec.T)},
|
|
|
|
c.audio["sample_rate"])
|
|
|
|
|
|
|
|
# compute average losses
|
|
|
|
avg_linear_loss /= (num_iter + 1)
|
|
|
|
avg_mel_loss /= (num_iter + 1)
|
|
|
|
avg_stop_loss /= (num_iter + 1)
|
|
|
|
|
|
|
|
# Plot Validation Stats
|
|
|
|
epoch_stats = {
|
|
|
|
"loss_postnet": avg_linear_loss,
|
|
|
|
"loss_decoder": avg_mel_loss,
|
|
|
|
"stop_loss": avg_stop_loss
|
|
|
|
}
|
|
|
|
tb_logger.tb_eval_stats(current_step, epoch_stats)
|
|
|
|
|
|
|
|
if args.rank == 0 and epoch > c.test_delay_epochs:
|
|
|
|
# test sentences
|
|
|
|
test_audios = {}
|
|
|
|
test_figures = {}
|
|
|
|
print(" | > Synthesizing test sentences")
|
|
|
|
for idx, test_sentence in enumerate(test_sentences):
|
|
|
|
try:
|
|
|
|
wav, alignment, linear_spec, _, stop_tokens = synthesis(
|
|
|
|
model, test_sentence, c, use_cuda, ap)
|
|
|
|
file_path = os.path.join(AUDIO_PATH, str(current_step))
|
|
|
|
os.makedirs(file_path, exist_ok=True)
|
|
|
|
file_path = os.path.join(file_path,
|
|
|
|
"TestSentence_{}.wav".format(idx))
|
|
|
|
ap.save_wav(wav, file_path)
|
|
|
|
test_audios['{}-audio'.format(idx)] = wav
|
|
|
|
test_figures['{}-prediction'.format(idx)] = plot_spectrogram(
|
|
|
|
linear_spec, ap)
|
|
|
|
test_figures['{}-alignment'.format(idx)] = plot_alignment(
|
|
|
|
alignment)
|
|
|
|
except:
|
|
|
|
print(" !! Error creating Test Sentence -", idx)
|
|
|
|
traceback.print_exc()
|
|
|
|
tb_logger.tb_test_audios(current_step, test_audios, c.audio['sample_rate'])
|
|
|
|
tb_logger.tb_test_figures(current_step, test_figures)
|
2018-03-02 18:54:35 +03:00
|
|
|
return avg_linear_loss
|
2018-04-03 13:24:57 +03:00
|
|
|
|
|
|
|
|
2018-03-02 18:54:35 +03:00
|
|
|
def main(args):
|
2019-02-27 11:50:52 +03:00
|
|
|
# DISTRUBUTED
|
|
|
|
if num_gpus > 1:
|
|
|
|
init_distributed(args.rank, num_gpus, args.group_id,
|
|
|
|
c.distributed["backend"], c.distributed["url"])
|
2019-01-21 16:52:40 +03:00
|
|
|
num_chars = len(phonemes) if c.use_phonemes else len(symbols)
|
2019-02-27 11:50:52 +03:00
|
|
|
model = Tacotron(
|
|
|
|
num_chars=num_chars,
|
|
|
|
linear_dim=ap.num_freq,
|
|
|
|
mel_dim=ap.num_mels,
|
|
|
|
r=c.r,
|
|
|
|
memory_size=c.memory_size)
|
2018-03-22 22:34:16 +03:00
|
|
|
|
2018-09-19 15:25:30 +03:00
|
|
|
optimizer = optim.Adam(model.parameters(), lr=c.lr, weight_decay=0)
|
2018-09-18 13:56:07 +03:00
|
|
|
optimizer_st = optim.Adam(
|
2018-09-19 15:25:30 +03:00
|
|
|
model.decoder.stopnet.parameters(), lr=c.lr, weight_decay=0)
|
2018-04-03 13:24:57 +03:00
|
|
|
|
2018-05-11 14:15:53 +03:00
|
|
|
criterion = L1LossMasked()
|
2018-07-05 18:30:42 +03:00
|
|
|
criterion_st = nn.BCELoss()
|
2018-01-22 12:48:59 +03:00
|
|
|
|
2018-03-06 16:39:54 +03:00
|
|
|
if args.restore_path:
|
2018-02-26 16:33:54 +03:00
|
|
|
checkpoint = torch.load(args.restore_path)
|
2018-12-13 20:19:02 +03:00
|
|
|
try:
|
|
|
|
model.load_state_dict(checkpoint['model'])
|
2019-02-20 18:46:10 +03:00
|
|
|
optimizer.load_state_dict(checkpoint['optimizer'])
|
2018-12-13 20:19:02 +03:00
|
|
|
except:
|
|
|
|
print(" > Partial model initialization.")
|
2019-02-16 05:19:26 +03:00
|
|
|
partial_init_flag = True
|
2018-12-13 20:19:02 +03:00
|
|
|
model_dict = model.state_dict()
|
|
|
|
# Partial initialization: if there is a mismatch with new and old layer, it is skipped.
|
|
|
|
# 1. filter out unnecessary keys
|
|
|
|
pretrained_dict = {
|
|
|
|
k: v
|
2019-02-27 11:50:52 +03:00
|
|
|
for k, v in checkpoint['model'].items() if k in model_dict
|
2018-12-13 20:19:02 +03:00
|
|
|
}
|
2019-02-16 05:19:26 +03:00
|
|
|
# 2. filter out different size layers
|
|
|
|
pretrained_dict = {
|
|
|
|
k: v
|
2019-02-27 11:50:52 +03:00
|
|
|
for k, v in pretrained_dict.items()
|
|
|
|
if v.numel() == model_dict[k].numel()
|
2019-02-16 05:19:26 +03:00
|
|
|
}
|
|
|
|
# 3. overwrite entries in the existing state dict
|
2018-12-13 20:19:02 +03:00
|
|
|
model_dict.update(pretrained_dict)
|
2019-02-16 05:19:26 +03:00
|
|
|
# 4. load the new state dict
|
2018-12-13 20:19:02 +03:00
|
|
|
model.load_state_dict(model_dict)
|
2019-02-27 11:50:52 +03:00
|
|
|
print(" | > {} / {} layers are initialized".format(
|
|
|
|
len(pretrained_dict), len(model_dict)))
|
2018-07-25 20:14:07 +03:00
|
|
|
if use_cuda:
|
2018-08-10 18:48:19 +03:00
|
|
|
model = model.cuda()
|
2018-07-25 20:14:07 +03:00
|
|
|
criterion.cuda()
|
|
|
|
criterion_st.cuda()
|
2019-02-12 12:04:39 +03:00
|
|
|
for group in optimizer.param_groups:
|
2019-02-27 11:50:52 +03:00
|
|
|
group['lr'] = c.lr
|
2018-08-02 17:34:17 +03:00
|
|
|
print(
|
|
|
|
" > Model restored from step %d" % checkpoint['step'], flush=True)
|
2018-12-31 15:29:39 +03:00
|
|
|
start_epoch = checkpoint['epoch']
|
2018-02-26 16:33:54 +03:00
|
|
|
best_loss = checkpoint['linear_loss']
|
2018-03-02 16:42:23 +03:00
|
|
|
args.restore_step = checkpoint['step']
|
2018-02-26 16:33:54 +03:00
|
|
|
else:
|
2018-10-25 15:05:27 +03:00
|
|
|
args.restore_step = 0
|
2018-07-25 20:14:07 +03:00
|
|
|
if use_cuda:
|
2018-08-10 18:48:19 +03:00
|
|
|
model = model.cuda()
|
2018-07-25 20:14:07 +03:00
|
|
|
criterion.cuda()
|
|
|
|
criterion_st.cuda()
|
2018-02-26 16:33:54 +03:00
|
|
|
|
2019-02-27 11:50:52 +03:00
|
|
|
# DISTRUBUTED
|
|
|
|
if num_gpus > 1:
|
|
|
|
model = apply_gradient_allreduce(model)
|
|
|
|
|
2018-11-05 16:05:04 +03:00
|
|
|
if c.lr_decay:
|
2018-11-26 16:09:42 +03:00
|
|
|
scheduler = NoamLR(
|
2018-11-05 16:05:04 +03:00
|
|
|
optimizer,
|
|
|
|
warmup_steps=c.warmup_steps,
|
|
|
|
last_epoch=args.restore_step - 1)
|
|
|
|
else:
|
|
|
|
scheduler = None
|
|
|
|
|
2018-02-23 17:20:22 +03:00
|
|
|
num_params = count_parameters(model)
|
2019-02-27 11:50:52 +03:00
|
|
|
print("\n > Model has {} parameters".format(num_params), flush=True)
|
2018-04-03 13:24:57 +03:00
|
|
|
|
2018-02-27 17:25:28 +03:00
|
|
|
if 'best_loss' not in locals():
|
|
|
|
best_loss = float('inf')
|
2018-04-03 13:24:57 +03:00
|
|
|
|
2018-02-08 16:57:43 +03:00
|
|
|
for epoch in range(0, c.epochs):
|
2018-08-02 17:34:17 +03:00
|
|
|
train_loss, current_step = train(model, criterion, criterion_st,
|
2019-02-27 11:50:52 +03:00
|
|
|
optimizer, optimizer_st, scheduler,
|
|
|
|
ap, epoch)
|
|
|
|
val_loss = evaluate(model, criterion, criterion_st, ap, current_step, epoch)
|
2018-08-02 17:34:17 +03:00
|
|
|
print(
|
2019-02-27 11:50:52 +03:00
|
|
|
" | > Training Loss: {:.5f} Validation Loss: {:.5f}".format(
|
2018-08-02 17:34:17 +03:00
|
|
|
train_loss, val_loss),
|
|
|
|
flush=True)
|
2019-02-05 13:55:41 +03:00
|
|
|
target_loss = train_loss
|
|
|
|
if c.run_eval:
|
|
|
|
target_loss = val_loss
|
|
|
|
best_loss = save_best_model(model, optimizer, target_loss, best_loss,
|
2018-08-02 17:34:17 +03:00
|
|
|
OUT_PATH, current_step, epoch)
|
2018-02-13 12:45:52 +03:00
|
|
|
|
2018-04-03 13:24:57 +03:00
|
|
|
|
2018-01-22 12:48:59 +03:00
|
|
|
if __name__ == '__main__':
|
2018-07-17 16:59:31 +03:00
|
|
|
parser = argparse.ArgumentParser()
|
2018-08-02 17:34:17 +03:00
|
|
|
parser.add_argument(
|
|
|
|
'--restore_path',
|
|
|
|
type=str,
|
2018-12-11 17:50:58 +03:00
|
|
|
help='Path to model outputs (checkpoint, tensorboard etc.).',
|
2018-08-02 17:34:17 +03:00
|
|
|
default=0)
|
|
|
|
parser.add_argument(
|
|
|
|
'--config_path',
|
|
|
|
type=str,
|
2018-12-11 17:50:58 +03:00
|
|
|
help='Path to config file for training.',
|
2018-08-02 17:34:17 +03:00
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
'--debug',
|
|
|
|
type=bool,
|
|
|
|
default=False,
|
2018-12-11 17:50:58 +03:00
|
|
|
help='Do not verify commit integrity to run training.')
|
2018-10-25 15:05:27 +03:00
|
|
|
parser.add_argument(
|
2019-02-27 11:50:52 +03:00
|
|
|
'--data_path',
|
|
|
|
type=str,
|
|
|
|
default='',
|
|
|
|
help='Defines the data path. It overwrites config.json.')
|
|
|
|
parser.add_argument(
|
|
|
|
'--output_path',
|
|
|
|
type=str,
|
|
|
|
help='path for training outputs.',
|
|
|
|
default='')
|
|
|
|
|
|
|
|
# DISTRUBUTED
|
|
|
|
parser.add_argument(
|
|
|
|
'--rank',
|
|
|
|
type=int,
|
|
|
|
default=0,
|
|
|
|
help='DISTRIBUTED: process rank for distributed training.')
|
|
|
|
parser.add_argument(
|
|
|
|
'--group_id',
|
|
|
|
type=str,
|
|
|
|
default="",
|
|
|
|
help='DISTRIBUTED: process group id.')
|
2018-07-17 16:59:31 +03:00
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
# setup output paths and read configs
|
|
|
|
c = load_config(args.config_path)
|
|
|
|
_ = os.path.dirname(os.path.realpath(__file__))
|
2018-11-02 18:13:51 +03:00
|
|
|
if args.data_path != '':
|
2018-10-25 15:05:27 +03:00
|
|
|
c.data_path = args.data_path
|
|
|
|
|
2019-02-27 11:50:52 +03:00
|
|
|
if args.output_path == '':
|
|
|
|
OUT_PATH = os.path.join(_, c.output_path)
|
|
|
|
else:
|
|
|
|
OUT_PATH = args.output_path
|
|
|
|
|
|
|
|
if args.group_id == '':
|
|
|
|
OUT_PATH = create_experiment_folder(OUT_PATH, c.model_name, args.debug)
|
|
|
|
|
|
|
|
AUDIO_PATH = os.path.join(OUT_PATH, 'test_audios')
|
|
|
|
|
|
|
|
if args.rank == 0:
|
|
|
|
os.makedirs(AUDIO_PATH, exist_ok=True)
|
|
|
|
shutil.copyfile(args.config_path, os.path.join(OUT_PATH,
|
|
|
|
'config.json'))
|
|
|
|
os.chmod(AUDIO_PATH, 0o775)
|
|
|
|
os.chmod(OUT_PATH, 0o775)
|
|
|
|
|
|
|
|
if args.rank==0:
|
|
|
|
LOG_DIR = OUT_PATH
|
|
|
|
tb_logger = Logger(LOG_DIR)
|
2018-07-17 16:59:31 +03:00
|
|
|
|
2018-12-11 19:52:43 +03:00
|
|
|
# Conditional imports
|
|
|
|
preprocessor = importlib.import_module('datasets.preprocess')
|
|
|
|
preprocessor = getattr(preprocessor, c.dataset.lower())
|
|
|
|
|
|
|
|
# Audio processor
|
|
|
|
ap = AudioProcessor(**c.audio)
|
|
|
|
|
2018-05-11 02:13:05 +03:00
|
|
|
try:
|
|
|
|
main(args)
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
remove_experiment_folder(OUT_PATH)
|
|
|
|
try:
|
|
|
|
sys.exit(0)
|
|
|
|
except SystemExit:
|
|
|
|
os._exit(0)
|
|
|
|
except Exception:
|
|
|
|
remove_experiment_folder(OUT_PATH)
|
|
|
|
traceback.print_exc()
|
|
|
|
sys.exit(1)
|