2018-01-22 12:48:59 +03:00
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
import time
|
2018-01-26 13:07:07 +03:00
|
|
|
import datetime
|
2018-01-22 19:20:20 +03:00
|
|
|
import shutil
|
2018-01-22 12:48:59 +03:00
|
|
|
import torch
|
|
|
|
import signal
|
|
|
|
import argparse
|
2018-01-22 19:20:20 +03:00
|
|
|
import importlib
|
2018-01-24 19:04:25 +03:00
|
|
|
import pickle
|
2018-01-22 12:48:59 +03:00
|
|
|
import numpy as np
|
|
|
|
|
|
|
|
import torch.nn as nn
|
|
|
|
from torch import optim
|
2018-02-02 18:18:16 +03:00
|
|
|
from torch import onnx
|
2018-01-22 17:58:12 +03:00
|
|
|
from torch.autograd import Variable
|
2018-01-22 12:48:59 +03:00
|
|
|
from torch.utils.data import DataLoader
|
2018-01-26 13:07:07 +03:00
|
|
|
from torch.optim.lr_scheduler import ReduceLROnPlateau
|
2018-01-25 18:07:46 +03:00
|
|
|
from tensorboardX import SummaryWriter
|
2018-01-22 12:48:59 +03:00
|
|
|
|
|
|
|
from utils.generic_utils import (Progbar, remove_experiment_folder,
|
2018-01-22 19:20:20 +03:00
|
|
|
create_experiment_folder, save_checkpoint,
|
2018-02-23 17:20:22 +03:00
|
|
|
save_best_model, load_config, lr_decay,
|
|
|
|
count_parameters)
|
2018-01-22 12:48:59 +03:00
|
|
|
from utils.model import get_param_size
|
2018-02-04 19:25:00 +03:00
|
|
|
from utils.visual import plot_alignment, plot_spectrogram
|
2018-01-22 12:48:59 +03:00
|
|
|
from datasets.LJSpeech import LJSpeechDataset
|
2018-01-22 17:58:12 +03:00
|
|
|
from models.tacotron import Tacotron
|
2018-01-22 12:48:59 +03:00
|
|
|
|
|
|
|
use_cuda = torch.cuda.is_available()
|
|
|
|
|
|
|
|
def main(args):
|
|
|
|
|
2018-01-22 19:20:20 +03:00
|
|
|
# setup output paths and read configs
|
|
|
|
c = load_config(args.config_path)
|
|
|
|
_ = os.path.dirname(os.path.realpath(__file__))
|
|
|
|
OUT_PATH = os.path.join(_, c.output_path)
|
|
|
|
OUT_PATH = create_experiment_folder(OUT_PATH)
|
|
|
|
CHECKPOINT_PATH = os.path.join(OUT_PATH, 'checkpoints')
|
|
|
|
shutil.copyfile(args.config_path, os.path.join(OUT_PATH, 'config.json'))
|
|
|
|
|
2018-01-24 19:04:25 +03:00
|
|
|
# save config to tmp place to be loaded by subsequent modules.
|
|
|
|
file_name = str(os.getpid())
|
|
|
|
tmp_path = os.path.join("/tmp/", file_name+'_tts')
|
|
|
|
pickle.dump(c, open(tmp_path, "wb"))
|
|
|
|
|
2018-01-25 18:07:46 +03:00
|
|
|
# setup tensorboard
|
2018-01-26 13:33:20 +03:00
|
|
|
LOG_DIR = OUT_PATH
|
2018-01-25 18:07:46 +03:00
|
|
|
tb = SummaryWriter(LOG_DIR)
|
|
|
|
|
2018-01-22 19:20:20 +03:00
|
|
|
# Ctrl+C handler to remove empty experiment folder
|
|
|
|
def signal_handler(signal, frame):
|
|
|
|
print(" !! Pressed Ctrl+C !!")
|
|
|
|
remove_experiment_folder(OUT_PATH)
|
2018-01-24 19:17:49 +03:00
|
|
|
sys.exit(1)
|
2018-01-22 19:20:20 +03:00
|
|
|
signal.signal(signal.SIGINT, signal_handler)
|
|
|
|
|
2018-02-02 18:18:16 +03:00
|
|
|
# Setup the dataset
|
2018-01-22 12:48:59 +03:00
|
|
|
dataset = LJSpeechDataset(os.path.join(c.data_path, 'metadata.csv'),
|
|
|
|
os.path.join(c.data_path, 'wavs'),
|
2018-01-22 19:29:27 +03:00
|
|
|
c.r,
|
|
|
|
c.sample_rate,
|
2018-01-24 19:04:25 +03:00
|
|
|
c.text_cleaner,
|
|
|
|
c.num_mels,
|
|
|
|
c.min_level_db,
|
|
|
|
c.frame_shift_ms,
|
|
|
|
c.frame_length_ms,
|
|
|
|
c.preemphasis,
|
|
|
|
c.ref_level_db,
|
|
|
|
c.num_freq,
|
|
|
|
c.power
|
2018-01-22 12:48:59 +03:00
|
|
|
)
|
|
|
|
|
2018-02-02 18:18:16 +03:00
|
|
|
dataloader = DataLoader(dataset, batch_size=c.batch_size,
|
2018-02-08 16:57:43 +03:00
|
|
|
shuffle=True, collate_fn=dataset.collate_fn,
|
|
|
|
drop_last=True, num_workers=c.num_loader_workers)
|
2018-02-02 18:18:16 +03:00
|
|
|
|
|
|
|
# setup the model
|
2018-01-22 12:48:59 +03:00
|
|
|
model = Tacotron(c.embedding_size,
|
|
|
|
c.hidden_size,
|
|
|
|
c.num_mels,
|
|
|
|
c.num_freq,
|
2018-01-22 19:20:20 +03:00
|
|
|
c.r)
|
2018-02-02 18:18:16 +03:00
|
|
|
|
|
|
|
# plot model on tensorboard
|
|
|
|
dummy_input = dataset.get_dummy_data()
|
|
|
|
|
|
|
|
## TODO: onnx does not support RNN fully yet
|
|
|
|
# model_proto_path = os.path.join(OUT_PATH, "model.proto")
|
|
|
|
# onnx.export(model, dummy_input, model_proto_path, verbose=True)
|
|
|
|
# tb.add_graph_onnx(model_proto_path)
|
|
|
|
|
2018-01-22 12:48:59 +03:00
|
|
|
if use_cuda:
|
|
|
|
model = nn.DataParallel(model.cuda())
|
|
|
|
|
|
|
|
optimizer = optim.Adam(model.parameters(), lr=c.lr)
|
|
|
|
|
2018-02-08 16:57:43 +03:00
|
|
|
if args.restore_step:
|
2018-01-22 12:48:59 +03:00
|
|
|
checkpoint = torch.load(os.path.join(
|
2018-02-08 16:57:43 +03:00
|
|
|
args.restore_path, 'checkpoint_%d.pth.tar' % args.restore_step))
|
2018-01-22 12:48:59 +03:00
|
|
|
model.load_state_dict(checkpoint['model'])
|
|
|
|
optimizer.load_state_dict(checkpoint['optimizer'])
|
|
|
|
print("\n > Model restored from step %d\n" % args.restore_step)
|
2018-02-08 16:57:43 +03:00
|
|
|
start_epoch = checkpoint['step'] // len(dataloader)
|
2018-02-13 12:45:52 +03:00
|
|
|
best_loss = checkpoint['linear_loss']
|
2018-02-08 16:57:43 +03:00
|
|
|
else:
|
|
|
|
start_epoch = 0
|
2018-01-25 18:07:46 +03:00
|
|
|
print("\n > Starting a new training")
|
2018-01-22 12:48:59 +03:00
|
|
|
|
2018-02-23 17:20:22 +03:00
|
|
|
num_params = count_parameters(model)
|
|
|
|
print(" | > Model has {} parameters".format(num_params))
|
|
|
|
|
2018-01-22 12:48:59 +03:00
|
|
|
model = model.train()
|
|
|
|
|
2018-01-22 19:20:20 +03:00
|
|
|
if not os.path.exists(CHECKPOINT_PATH):
|
|
|
|
os.mkdir(CHECKPOINT_PATH)
|
2018-01-22 12:48:59 +03:00
|
|
|
|
|
|
|
if use_cuda:
|
|
|
|
criterion = nn.L1Loss().cuda()
|
|
|
|
else:
|
|
|
|
criterion = nn.L1Loss()
|
|
|
|
|
2018-02-01 19:43:59 +03:00
|
|
|
n_priority_freq = int(3000 / (c.sample_rate * 0.5) * c.num_freq)
|
2018-01-22 12:48:59 +03:00
|
|
|
|
2018-02-01 19:26:40 +03:00
|
|
|
#lr_scheduler = ReduceLROnPlateau(optimizer, factor=c.lr_decay,
|
|
|
|
# patience=c.lr_patience, verbose=True)
|
2018-01-26 13:33:20 +03:00
|
|
|
epoch_time = 0
|
2018-02-09 16:39:58 +03:00
|
|
|
best_loss = float('inf')
|
2018-02-08 16:57:43 +03:00
|
|
|
for epoch in range(0, c.epochs):
|
2018-01-22 12:48:59 +03:00
|
|
|
|
2018-01-26 13:07:07 +03:00
|
|
|
print("\n | > Epoch {}/{}".format(epoch, c.epochs))
|
2018-01-22 19:20:20 +03:00
|
|
|
progbar = Progbar(len(dataset) / c.batch_size)
|
2018-01-22 12:48:59 +03:00
|
|
|
|
2018-02-05 17:27:02 +03:00
|
|
|
for num_iter, data in enumerate(dataloader):
|
2018-01-31 18:21:22 +03:00
|
|
|
start_time = time.time()
|
|
|
|
|
2018-01-22 17:58:12 +03:00
|
|
|
text_input = data[0]
|
2018-02-02 18:18:16 +03:00
|
|
|
text_lengths = data[1]
|
2018-02-09 16:39:58 +03:00
|
|
|
linear_input = data[2]
|
2018-02-02 18:18:16 +03:00
|
|
|
mel_input = data[3]
|
2018-01-22 12:48:59 +03:00
|
|
|
|
2018-02-05 17:27:02 +03:00
|
|
|
current_step = num_iter + args.restore_step + epoch * len(dataloader) + 1
|
2018-01-22 12:48:59 +03:00
|
|
|
|
2018-02-01 19:26:40 +03:00
|
|
|
# setup lr
|
2018-02-01 19:43:59 +03:00
|
|
|
current_lr = lr_decay(c.lr, current_step)
|
2018-02-01 19:26:40 +03:00
|
|
|
for params_group in optimizer.param_groups:
|
2018-02-02 16:37:09 +03:00
|
|
|
params_group['lr'] = current_lr
|
2018-02-01 19:26:40 +03:00
|
|
|
|
2018-01-22 12:48:59 +03:00
|
|
|
optimizer.zero_grad()
|
|
|
|
|
2018-02-13 12:45:52 +03:00
|
|
|
# Add a single frame of zeros to Mel Specs for better end detection
|
2018-02-01 19:26:40 +03:00
|
|
|
#try:
|
|
|
|
# mel_input = np.concatenate((np.zeros(
|
|
|
|
# [c.batch_size, 1, c.num_mels], dtype=np.float32),
|
|
|
|
# mel_input[:, 1:, :]), axis=1)
|
|
|
|
#except:
|
|
|
|
# raise TypeError("not same dimension")
|
2018-01-22 12:48:59 +03:00
|
|
|
|
2018-02-04 19:25:00 +03:00
|
|
|
# convert inputs to variables
|
|
|
|
text_input_var = Variable(text_input)
|
|
|
|
mel_spec_var = Variable(mel_input)
|
2018-02-09 16:39:58 +03:00
|
|
|
linear_spec_var = Variable(linear_input, volatile=True)
|
2018-02-04 19:25:00 +03:00
|
|
|
|
2018-02-09 16:39:58 +03:00
|
|
|
# sort sequence by length.
|
|
|
|
# TODO: might be unnecessary
|
2018-02-04 19:25:00 +03:00
|
|
|
sorted_lengths, indices = torch.sort(
|
|
|
|
text_lengths.view(-1), dim=0, descending=True)
|
|
|
|
sorted_lengths = sorted_lengths.long().numpy()
|
|
|
|
|
|
|
|
text_input_var = text_input_var[indices]
|
|
|
|
mel_spec_var = mel_spec_var[indices]
|
|
|
|
linear_spec_var = linear_spec_var[indices]
|
|
|
|
|
2018-01-22 12:48:59 +03:00
|
|
|
if use_cuda:
|
2018-02-04 19:25:00 +03:00
|
|
|
text_input_var = text_input_var.cuda()
|
|
|
|
mel_spec_var = mel_spec_var.cuda()
|
|
|
|
linear_spec_var = linear_spec_var.cuda()
|
2018-01-22 12:48:59 +03:00
|
|
|
|
2018-01-22 17:58:12 +03:00
|
|
|
mel_output, linear_output, alignments =\
|
2018-02-04 19:25:00 +03:00
|
|
|
model.forward(text_input_var, mel_spec_var,
|
|
|
|
input_lengths= torch.autograd.Variable(torch.cuda.LongTensor(sorted_lengths)))
|
2018-01-22 12:48:59 +03:00
|
|
|
|
2018-01-22 17:58:12 +03:00
|
|
|
mel_loss = criterion(mel_output, mel_spec_var)
|
2018-01-31 18:21:22 +03:00
|
|
|
#linear_loss = torch.abs(linear_output - linear_spec_var)
|
|
|
|
#linear_loss = 0.5 * \
|
|
|
|
#torch.mean(linear_loss) + 0.5 * \
|
|
|
|
#torch.mean(linear_loss[:, :n_priority_freq, :])
|
|
|
|
linear_loss = 0.5 * criterion(linear_output, linear_spec_var) \
|
|
|
|
+ 0.5 * criterion(linear_output[:, :, :n_priority_freq],
|
|
|
|
linear_spec_var[: ,: ,:n_priority_freq])
|
2018-01-22 12:48:59 +03:00
|
|
|
loss = mel_loss + linear_loss
|
2018-01-31 18:21:22 +03:00
|
|
|
# loss = loss.cuda()
|
2018-01-22 12:48:59 +03:00
|
|
|
|
|
|
|
loss.backward()
|
2018-02-02 18:18:16 +03:00
|
|
|
grad_norm = nn.utils.clip_grad_norm(model.parameters(), 1.) ## TODO: maybe no need
|
2018-01-22 12:48:59 +03:00
|
|
|
optimizer.step()
|
|
|
|
|
2018-01-26 13:33:20 +03:00
|
|
|
step_time = time.time() - start_time
|
|
|
|
epoch_time += step_time
|
|
|
|
|
2018-02-05 17:27:02 +03:00
|
|
|
progbar.update(num_iter+1, values=[('total_loss', loss.data[0]),
|
|
|
|
('linear_loss', linear_loss.data[0]),
|
|
|
|
('mel_loss', mel_loss.data[0]),
|
|
|
|
('grad_norm', grad_norm)])
|
2018-01-22 12:48:59 +03:00
|
|
|
|
2018-02-02 18:18:16 +03:00
|
|
|
# Plot Learning Stats
|
2018-02-01 18:39:35 +03:00
|
|
|
tb.add_scalar('Loss/TotalLoss', loss.data[0], current_step)
|
|
|
|
tb.add_scalar('Loss/LinearLoss', linear_loss.data[0],
|
2018-01-26 13:33:20 +03:00
|
|
|
current_step)
|
2018-02-01 18:39:35 +03:00
|
|
|
tb.add_scalar('Loss/MelLoss', mel_loss.data[0], current_step)
|
|
|
|
tb.add_scalar('Params/LearningRate', optimizer.param_groups[0]['lr'],
|
2018-01-26 13:33:20 +03:00
|
|
|
current_step)
|
2018-02-01 18:39:35 +03:00
|
|
|
tb.add_scalar('Params/GradNorm', grad_norm, current_step)
|
2018-01-26 13:33:20 +03:00
|
|
|
tb.add_scalar('Time/StepTime', step_time, current_step)
|
2018-01-25 18:07:46 +03:00
|
|
|
|
2018-02-04 19:25:00 +03:00
|
|
|
align_img = alignments[0].data.cpu().numpy()
|
|
|
|
align_img = plot_alignment(align_img)
|
|
|
|
tb.add_image('Attn/Alignment', align_img, current_step)
|
2018-01-31 19:38:46 +03:00
|
|
|
|
2018-01-22 12:48:59 +03:00
|
|
|
if current_step % c.save_step == 0:
|
2018-02-09 16:39:58 +03:00
|
|
|
|
2018-02-13 12:45:52 +03:00
|
|
|
if c.checkpoint:
|
|
|
|
# save model
|
|
|
|
save_checkpoint(model, optimizer, linear_loss.data[0],
|
2018-02-21 18:21:44 +03:00
|
|
|
OUT_PATH, current_step, epoch)
|
2018-01-31 19:38:46 +03:00
|
|
|
|
2018-02-02 16:37:09 +03:00
|
|
|
# Diagnostic visualizations
|
2018-02-04 19:25:00 +03:00
|
|
|
const_spec = linear_output[0].data.cpu().numpy()
|
|
|
|
gt_spec = linear_spec_var[0].data.cpu().numpy()
|
|
|
|
|
|
|
|
const_spec = plot_spectrogram(const_spec, dataset.ap)
|
|
|
|
gt_spec = plot_spectrogram(gt_spec, dataset.ap)
|
2018-01-31 19:38:46 +03:00
|
|
|
tb.add_image('Spec/Reconstruction', const_spec, current_step)
|
|
|
|
tb.add_image('Spec/GroundTruth', gt_spec, current_step)
|
2018-02-04 19:25:00 +03:00
|
|
|
|
|
|
|
align_img = alignments[0].data.cpu().numpy()
|
|
|
|
align_img = plot_alignment(align_img)
|
2018-02-02 16:37:09 +03:00
|
|
|
tb.add_image('Attn/Alignment', align_img, current_step)
|
|
|
|
|
2018-02-04 19:25:00 +03:00
|
|
|
# Sample audio
|
|
|
|
audio_signal = linear_output[0].data.cpu().numpy()
|
|
|
|
dataset.ap.griffin_lim_iters = 60
|
|
|
|
audio_signal = dataset.ap.inv_spectrogram(audio_signal.T)
|
2018-02-08 16:57:43 +03:00
|
|
|
try:
|
|
|
|
tb.add_audio('SampleAudio', audio_signal, current_step,
|
|
|
|
sample_rate=c.sample_rate)
|
|
|
|
except:
|
|
|
|
print("\n > Error at audio signal on TB!!")
|
|
|
|
print(audio_signal.max())
|
|
|
|
print(audio_signal.min())
|
2018-01-31 19:38:46 +03:00
|
|
|
|
2018-02-13 12:45:52 +03:00
|
|
|
|
|
|
|
# average loss after the epoch
|
|
|
|
avg_epoch_loss = np.mean(
|
|
|
|
progbar.sum_values['linear_loss'][0] / max(1, progbar.sum_values['linear_loss'][1]))
|
|
|
|
best_loss = save_best_model(model, optimizer, avg_epoch_loss,
|
|
|
|
best_loss, OUT_PATH,
|
|
|
|
current_step, epoch)
|
|
|
|
|
2018-02-01 19:26:40 +03:00
|
|
|
#lr_scheduler.step(loss.data[0])
|
2018-01-26 13:33:20 +03:00
|
|
|
tb.add_scalar('Time/EpochTime', epoch_time, epoch)
|
|
|
|
epoch_time = 0
|
2018-01-22 12:48:59 +03:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser.add_argument('--restore_step', type=int,
|
2018-02-04 19:25:00 +03:00
|
|
|
help='Global step to restore checkpoint', default=0)
|
2018-02-08 16:57:43 +03:00
|
|
|
parser.add_argument('--restore_path', type=str,
|
|
|
|
help='Folder path to checkpoints', default=0)
|
2018-01-22 19:20:20 +03:00
|
|
|
parser.add_argument('--config_path', type=str,
|
2018-01-22 12:48:59 +03:00
|
|
|
help='path to config file for training',)
|
|
|
|
args = parser.parse_args()
|
|
|
|
main(args)
|