TTS/train.py

401 строка
15 KiB
Python
Исходник Обычный вид История

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
import pickle
import traceback
2018-01-22 12:48:59 +03:00
import numpy as np
import torch.nn as nn
from torch import optim
from torch import onnx
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,
2018-04-06 13:53:49 +03:00
count_parameters, check_update, get_commit_hash)
2018-01-22 12:48:59 +03:00
from utils.model import get_param_size
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-03-23 00:35:02 +03:00
from layers.losses import L1LossMasked
2018-01-22 12:48:59 +03:00
2018-05-11 13:47:30 +03:00
torch.manual_seed(1)
2018-01-22 12:48:59 +03:00
use_cuda = torch.cuda.is_available()
2018-03-02 18:54:35 +03:00
parser = argparse.ArgumentParser()
parser.add_argument('--restore_path', type=str,
help='Folder path to checkpoints', default=0)
parser.add_argument('--config_path', type=str,
2018-04-03 13:24:57 +03:00
help='path to config file for training',)
2018-05-11 13:49:55 +03:00
parser.add_argument('--debug', type=bool, default=False,
help='do not ask for git has before run.')
2018-03-02 18:54:35 +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__))
OUT_PATH = os.path.join(_, c.output_path)
2018-05-11 13:49:55 +03:00
OUT_PATH = create_experiment_folder(OUT_PATH, c.model_name, args.debug)
2018-03-02 18:54:35 +03:00
CHECKPOINT_PATH = os.path.join(OUT_PATH, 'checkpoints')
shutil.copyfile(args.config_path, os.path.join(OUT_PATH, 'config.json'))
2018-03-09 15:06:36 +03:00
parser.add_argument('--finetine_path', type=str)
2018-03-02 18:54:35 +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"))
# setup tensorboard
LOG_DIR = OUT_PATH
tb = SummaryWriter(LOG_DIR)
def train(model, criterion, criterion_st, data_loader, optimizer, epoch):
2018-03-02 18:54:35 +03:00
model = model.train()
epoch_time = 0
2018-03-06 16:39:54 +03:00
avg_linear_loss = 0
avg_mel_loss = 0
avg_stop_loss = 0
2018-03-02 18:54:35 +03:00
print(" | > Epoch {}/{}".format(epoch, c.epochs))
progbar = Progbar(len(data_loader.dataset) / c.batch_size)
n_priority_freq = int(3000 / (c.sample_rate * 0.5) * c.num_freq)
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]
2018-03-22 23:46:52 +03:00
mel_lengths = data[4]
2018-05-11 14:24:57 +03:00
stop_targets = data[5]
# set stop targets view, we predict a single stop token per r frames prediction
stop_targets = stop_targets.view(text_input.shape[0], stop_targets.size(1) // c.r, -1)
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
current_lr = lr_decay(c.lr, current_step, c.warmup_steps)
for params_group in optimizer.param_groups:
params_group['lr'] = current_lr
optimizer.zero_grad()
# dispatch data to GPU
if use_cuda:
2018-05-11 02:05:03 +03:00
text_input = text_input.cuda()
mel_input = mel_input.cuda()
mel_lengths = mel_lengths.cuda()
linear_input = linear_input.cuda()
2018-05-11 14:24:57 +03:00
stop_targets = stop_targets.cuda()
2018-03-02 18:54:35 +03:00
# forward pass
mel_output, linear_output, alignments, stop_tokens =\
2018-05-11 02:05:03 +03:00
model.forward(text_input, mel_input)
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)
linear_loss = 0.5 * criterion(linear_output, linear_input, mel_lengths) \
2018-04-03 13:24:57 +03:00
+ 0.5 * criterion(linear_output[:, :, :n_priority_freq],
2018-05-11 02:05:03 +03:00
linear_input[:, :, :n_priority_freq],
mel_lengths)
loss = mel_loss + linear_loss + stop_loss
2018-03-02 18:54:35 +03:00
2018-04-03 13:24:57 +03:00
# backpass and check the grad norm
2018-03-02 18:54:35 +03:00
loss.backward()
grad_norm, skip_flag = check_update(model, 0.5, 100)
if skip_flag:
optimizer.zero_grad()
print(" | > Iteration skipped!!")
continue
optimizer.step()
step_time = time.time() - start_time
epoch_time += step_time
2018-04-03 13:24:57 +03:00
# update
2018-05-11 02:22:17 +03:00
progbar.update(num_iter+1, values=[('total_loss', loss.item()),
('linear_loss', linear_loss.item()),
('mel_loss', mel_loss.item()),
('stop_loss', stop_loss.item()),
2018-05-11 02:22:17 +03:00
('grad_norm', grad_norm.item())])
avg_linear_loss += linear_loss.item()
avg_mel_loss += mel_loss.item()
avg_stop_loss += stop_loss.item()
2018-03-02 18:54:35 +03:00
# Plot Training Iter Stats
2018-05-11 02:22:17 +03:00
tb.add_scalar('TrainIterLoss/TotalLoss', loss.item(), current_step)
tb.add_scalar('TrainIterLoss/LinearLoss', linear_loss.item(),
2018-03-02 18:54:35 +03:00
current_step)
2018-05-11 02:22:17 +03:00
tb.add_scalar('TrainIterLoss/MelLoss', mel_loss.item(), current_step)
2018-03-02 18:54:35 +03:00
tb.add_scalar('Params/LearningRate', optimizer.param_groups[0]['lr'],
current_step)
tb.add_scalar('Params/GradNorm', grad_norm, current_step)
tb.add_scalar('Time/StepTime', step_time, current_step)
if current_step % c.save_step == 0:
if c.checkpoint:
# save model
2018-05-11 02:22:17 +03:00
save_checkpoint(model, optimizer, linear_loss.item(),
2018-03-02 18:54:35 +03:00
OUT_PATH, current_step, epoch)
# Diagnostic visualizations
const_spec = linear_output[0].data.cpu().numpy()
2018-05-11 02:05:03 +03:00
gt_spec = linear_input[0].data.cpu().numpy()
2018-03-02 18:54:35 +03:00
2018-03-05 19:54:23 +03:00
const_spec = plot_spectrogram(const_spec, data_loader.dataset.ap)
gt_spec = plot_spectrogram(gt_spec, data_loader.dataset.ap)
2018-03-02 18:54:35 +03:00
tb.add_image('Visual/Reconstruction', const_spec, current_step)
tb.add_image('Visual/GroundTruth', gt_spec, current_step)
2018-01-22 12:48:59 +03:00
2018-03-02 18:54:35 +03:00
align_img = alignments[0].data.cpu().numpy()
align_img = plot_alignment(align_img)
tb.add_image('Visual/Alignment', align_img, current_step)
# Sample audio
audio_signal = linear_output[0].data.cpu().numpy()
2018-03-05 19:54:23 +03:00
data_loader.dataset.ap.griffin_lim_iters = 60
2018-04-03 13:24:57 +03:00
audio_signal = data_loader.dataset.ap.inv_spectrogram(
audio_signal.T)
2018-03-02 18:54:35 +03:00
try:
tb.add_audio('SampleAudio', audio_signal, current_step,
sample_rate=c.sample_rate)
except:
2018-03-10 02:37:58 +03:00
# print("\n > Error at audio signal on TB!!")
# print(audio_signal.max())
# print(audio_signal.min())
pass
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)
avg_stop_loss /= (num_iter + 1)
avg_total_loss = avg_mel_loss + avg_linear_loss + avg_stop_loss
2018-04-03 13:24:57 +03:00
2018-03-02 18:54:35 +03:00
# Plot Training Epoch Stats
tb.add_scalar('TrainEpochLoss/TotalLoss', avg_total_loss, current_step)
tb.add_scalar('TrainEpochLoss/LinearLoss', avg_linear_loss, current_step)
tb.add_scalar('TrainEpochLoss/MelLoss', avg_mel_loss, current_step)
tb.add_scalar('TrainEpochLoss/StopLoss', avg_stop_loss, current_step)
2018-03-02 18:54:35 +03:00
tb.add_scalar('Time/EpochTime', epoch_time, epoch)
epoch_time = 0
return avg_linear_loss, current_step
2018-04-03 13:24:57 +03:00
def evaluate(model, criterion, criterion_st, data_loader, current_step):
2018-03-10 02:37:58 +03:00
model = 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
avg_stop_loss = 0
print(" | > Validation")
progbar = Progbar(len(data_loader.dataset) / c.batch_size)
n_priority_freq = int(3000 / (c.sample_rate * 0.5) * c.num_freq)
2018-05-11 02:44:37 +03:00
with torch.no_grad():
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]
2018-05-11 14:24:57 +03:00
stop_targets = data[5]
# set stop targets view, we predict a single stop token per r frames prediction
2018-05-11 14:24:57 +03:00
stop_targets = stop_targets.view(text_input.shape[0], stop_targets.size(1) // c.r, -1)
stop_targets = (stop_targets.sum(2) > 0.0).unsqueeze(2).float()
2018-05-11 02:44:37 +03:00
# 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()
2018-05-11 14:24:57 +03:00
stop_targets = stop_targets.cuda()
2018-05-11 02:44:37 +03:00
# forward pass
mel_output, linear_output, alignments, stop_tokens =\
2018-05-11 14:24:57 +03:00
model.forward(text_input, mel_input)
2018-05-11 02:44:37 +03:00
# loss computation
2018-05-11 14:24:57 +03:00
stop_loss = criterion_st(stop_tokens, stop_targets)
2018-05-11 02:44:37 +03:00
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
2018-05-11 02:44:37 +03:00
step_time = time.time() - start_time
epoch_time += step_time
# update
progbar.update(num_iter+1, values=[('total_loss', loss.item()),
('linear_loss', linear_loss.item()),
('mel_loss', mel_loss.item()),
('stop_loss', stop_loss.item())])
2018-05-11 02:44:37 +03:00
avg_linear_loss += linear_loss.item()
avg_mel_loss += mel_loss.item()
avg_stop_loss += stop_loss.item()
2018-03-02 18:54:35 +03:00
# Diagnostic visualizations
2018-03-07 17:58:51 +03:00
idx = np.random.randint(mel_input.shape[0])
2018-03-02 18:54:35 +03:00
const_spec = linear_output[idx].data.cpu().numpy()
2018-05-11 02:05:03 +03:00
gt_spec = linear_input[idx].data.cpu().numpy()
2018-03-06 16:39:54 +03:00
align_img = alignments[idx].data.cpu().numpy()
2018-03-02 18:54:35 +03:00
const_spec = plot_spectrogram(const_spec, data_loader.dataset.ap)
gt_spec = plot_spectrogram(gt_spec, data_loader.dataset.ap)
2018-03-06 16:39:54 +03:00
align_img = plot_alignment(align_img)
2018-04-03 13:24:57 +03:00
2018-03-02 18:54:35 +03:00
tb.add_image('ValVisual/Reconstruction', const_spec, current_step)
tb.add_image('ValVisual/GroundTruth', gt_spec, current_step)
tb.add_image('ValVisual/ValidationAlignment', align_img, current_step)
# Sample audio
audio_signal = linear_output[idx].data.cpu().numpy()
data_loader.dataset.ap.griffin_lim_iters = 60
audio_signal = data_loader.dataset.ap.inv_spectrogram(audio_signal.T)
try:
tb.add_audio('ValSampleAudio', audio_signal, current_step,
sample_rate=c.sample_rate)
except:
2018-03-10 02:37:58 +03:00
# print(" | > Error at audio signal on TB!!")
# print(audio_signal.max())
# print(audio_signal.min())
pass
2018-04-03 13:24:57 +03:00
2018-03-02 18:54:35 +03:00
# compute average losses
2018-03-06 16:39:54 +03:00
avg_linear_loss /= (num_iter + 1)
avg_stop_loss /= (num_iter + 1)
avg_total_loss = avg_mel_loss + avg_linear_loss + stop_loss
2018-04-03 13:24:57 +03:00
2018-03-02 18:54:35 +03:00
# Plot Learning Stats
tb.add_scalar('ValEpochLoss/TotalLoss', avg_total_loss, current_step)
tb.add_scalar('ValEpochLoss/LinearLoss', avg_linear_loss, current_step)
tb.add_scalar('ValEpochLoss/MelLoss', avg_mel_loss, current_step)
tb.add_scalar('ValEpochLoss/Stop_loss', avg_stop_loss, current_step)
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):
2018-01-22 19:20:20 +03:00
2018-03-02 19:01:04 +03:00
# Setup the dataset
2018-03-02 18:54:35 +03:00
train_dataset = LJSpeechDataset(os.path.join(c.data_path, 'metadata_train.csv'),
2018-04-03 13:24:57 +03:00
os.path.join(c.data_path, 'wavs'),
c.r,
c.sample_rate,
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,
min_seq_len=c.min_seq_len
)
2018-01-22 12:48:59 +03:00
2018-03-02 18:54:35 +03:00
train_loader = DataLoader(train_dataset, batch_size=c.batch_size,
2018-03-10 02:37:58 +03:00
shuffle=False, collate_fn=train_dataset.collate_fn,
drop_last=False, num_workers=c.num_loader_workers,
pin_memory=True)
2018-04-03 13:24:57 +03:00
2018-03-02 18:54:35 +03:00
val_dataset = LJSpeechDataset(os.path.join(c.data_path, 'metadata_val.csv'),
2018-04-03 13:24:57 +03:00
os.path.join(c.data_path, 'wavs'),
c.r,
c.sample_rate,
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-03-02 18:54:35 +03:00
2018-03-09 20:55:15 +03:00
val_loader = DataLoader(val_dataset, batch_size=c.eval_batch_size,
2018-03-07 17:58:51 +03:00
shuffle=False, collate_fn=val_dataset.collate_fn,
2018-04-03 13:24:57 +03:00
drop_last=False, num_workers=4,
2018-03-02 18:54:35 +03:00
pin_memory=True)
2018-03-02 19:01:04 +03:00
model = Tacotron(c.embedding_size,
2018-01-22 12:48:59 +03:00
c.num_freq,
2018-03-28 19:43:29 +03:00
c.num_mels,
2018-03-19 18:26:16 +03:00
c.r)
2018-03-22 22:34:16 +03:00
2018-01-22 12:48:59 +03:00
optimizer = optim.Adam(model.parameters(), lr=c.lr)
2018-04-03 13:24:57 +03:00
criterion = L1LossMasked()
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)
model.load_state_dict(checkpoint['model'])
optimizer.load_state_dict(checkpoint['optimizer'])
print("\n > Model restored from step %d\n" % checkpoint['step'])
2018-03-05 19:48:17 +03:00
start_epoch = checkpoint['step'] // len(train_loader)
2018-02-26 16:33:54 +03:00
best_loss = checkpoint['linear_loss']
start_epoch = 0
2018-03-02 16:42:23 +03:00
args.restore_step = checkpoint['step']
2018-02-26 16:33:54 +03:00
else:
2018-03-07 17:58:51 +03:00
args.restore_step = 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-26 16:33:54 +03:00
if use_cuda:
model = nn.DataParallel(model.cuda())
criterion.cuda()
criterion_st.cuda()
2018-02-26 16:33:54 +03:00
2018-02-23 17:20:22 +03:00
num_params = count_parameters(model)
print(" | > Model has {} parameters".format(num_params))
2018-04-03 13:24:57 +03:00
2018-01-22 19:20:20 +03:00
if not os.path.exists(CHECKPOINT_PATH):
os.mkdir(CHECKPOINT_PATH)
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
for epoch in range(0, c.epochs):
2018-04-03 13:24:57 +03:00
train_loss, current_step = train(
model, criterion, criterion_st, train_loader, optimizer, epoch)
val_loss = evaluate(model, criterion, criterion_st, val_loader, current_step)
2018-03-02 18:54:35 +03:00
best_loss = save_best_model(model, optimizer, val_loss,
2018-02-13 12:45:52 +03:00
best_loss, OUT_PATH,
current_step, epoch)
2018-04-03 13:24:57 +03:00
2018-01-22 12:48:59 +03:00
if __name__ == '__main__':
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)