TTS/tests/tts_tests/test_tacotron2_model.py

325 lines
15 KiB
Python
Raw Normal View History

import copy
2020-07-16 13:05:36 +00:00
import os
import unittest
2020-07-16 13:05:36 +00:00
import torch
from torch import nn, optim
2021-04-12 09:47:39 +00:00
from tests import get_tests_input_path
2021-05-10 21:03:21 +00:00
from TTS.tts.configs import Tacotron2Config
2021-06-18 11:27:19 +00:00
from TTS.tts.configs.shared_configs import GSTConfig
2020-09-09 10:27:23 +00:00
from TTS.tts.layers.losses import MSELossMasked
from TTS.tts.models.tacotron2 import Tacotron2
from TTS.utils.audio import AudioProcessor
2021-04-12 09:47:39 +00:00
# pylint: disable=unused-variable
2019-07-19 09:48:12 +00:00
torch.manual_seed(1)
use_cuda = torch.cuda.is_available()
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
2021-06-18 11:27:19 +00:00
config_global = Tacotron2Config(num_chars=32, num_speakers=5, out_channels=80, decoder_output_dim=80)
2021-06-18 11:27:19 +00:00
ap = AudioProcessor(**config_global.audio)
WAV_FILE = os.path.join(get_tests_input_path(), "example_1.wav")
class TacotronTrainTest(unittest.TestCase):
"""Test vanilla Tacotron2 model."""
2020-08-04 12:07:47 +00:00
def test_train_step(self): # pylint: disable=no-self-use
2021-06-18 11:27:19 +00:00
config = config_global.copy()
config.use_speaker_embedding = False
config.num_speakers = 1
2020-08-04 12:07:47 +00:00
input_dummy = torch.randint(0, 24, (8, 128)).long().to(device)
2021-04-12 09:47:39 +00:00
input_lengths = torch.randint(100, 128, (8,)).long().to(device)
input_lengths = torch.sort(input_lengths, descending=True)[0]
2021-06-18 11:27:19 +00:00
mel_spec = torch.rand(8, 30, config.audio["num_mels"]).to(device)
mel_postnet_spec = torch.rand(8, 30, config.audio["num_mels"]).to(device)
2021-04-12 09:47:39 +00:00
mel_lengths = torch.randint(20, 30, (8,)).long().to(device)
2020-07-08 08:21:45 +00:00
mel_lengths[0] = 30
stop_targets = torch.zeros(8, 30, 1).float().to(device)
for idx in mel_lengths:
2021-04-12 09:47:39 +00:00
stop_targets[:, int(idx.item()) :, 0] = 1.0
2021-06-18 11:27:19 +00:00
stop_targets = stop_targets.view(input_dummy.shape[0], stop_targets.size(1) // config.r, -1)
stop_targets = (stop_targets.sum(2) > 0.0).unsqueeze(2).float().squeeze()
2020-01-15 22:10:11 +00:00
criterion = MSELossMasked(seq_len_norm=False).to(device)
criterion_st = nn.BCEWithLogitsLoss().to(device)
2021-06-18 11:27:19 +00:00
model = Tacotron2(config).to(device)
model.train()
model_ref = copy.deepcopy(model)
count = 0
2021-04-12 09:47:39 +00:00
for param, param_ref in zip(model.parameters(), model_ref.parameters()):
2020-07-12 12:07:44 +00:00
assert (param - param_ref).sum() == 0, param
count += 1
2021-06-18 11:27:19 +00:00
optimizer = optim.Adam(model.parameters(), lr=config.lr)
2020-07-12 12:07:44 +00:00
for i in range(5):
outputs = model.forward(input_dummy, input_lengths, mel_spec, mel_lengths)
assert torch.sigmoid(outputs["stop_tokens"]).data.max() <= 1.0
assert torch.sigmoid(outputs["stop_tokens"]).data.min() >= 0.0
2020-07-12 12:07:44 +00:00
optimizer.zero_grad()
loss = criterion(outputs["decoder_outputs"], mel_spec, mel_lengths)
stop_loss = criterion_st(outputs["stop_tokens"], stop_targets)
loss = loss + criterion(outputs["model_outputs"], mel_postnet_spec, mel_lengths) + stop_loss
2020-07-12 12:07:44 +00:00
loss.backward()
optimizer.step()
# check parameter changes
count = 0
2021-04-12 09:47:39 +00:00
for param, param_ref in zip(model.parameters(), model_ref.parameters()):
2020-07-12 12:07:44 +00:00
# ignore pre-higway layer since it works conditional
# if count not in [145, 59]:
2021-04-12 09:47:39 +00:00
assert (param != param_ref).any(), "param {} with shape {} not updated!! \n{}\n{}".format(
count, param.shape, param, param_ref
)
2020-07-12 12:07:44 +00:00
count += 1
class MultiSpeakerTacotronTrainTest(unittest.TestCase):
"""Test multi-speaker Tacotron2 with speaker embedding layer"""
@staticmethod
def test_train_step():
2021-06-18 11:27:19 +00:00
config = config_global.copy()
config.use_speaker_embedding = True
config.num_speakers = 5
input_dummy = torch.randint(0, 24, (8, 128)).long().to(device)
2021-04-12 09:47:39 +00:00
input_lengths = torch.randint(100, 128, (8,)).long().to(device)
input_lengths = torch.sort(input_lengths, descending=True)[0]
2021-06-18 11:27:19 +00:00
mel_spec = torch.rand(8, 30, config.audio["num_mels"]).to(device)
mel_postnet_spec = torch.rand(8, 30, config.audio["num_mels"]).to(device)
2021-04-12 09:47:39 +00:00
mel_lengths = torch.randint(20, 30, (8,)).long().to(device)
mel_lengths[0] = 30
stop_targets = torch.zeros(8, 30, 1).float().to(device)
speaker_ids = torch.randint(0, 5, (8,)).long().to(device)
for idx in mel_lengths:
2021-04-12 09:47:39 +00:00
stop_targets[:, int(idx.item()) :, 0] = 1.0
2021-06-18 11:27:19 +00:00
stop_targets = stop_targets.view(input_dummy.shape[0], stop_targets.size(1) // config.r, -1)
stop_targets = (stop_targets.sum(2) > 0.0).unsqueeze(2).float().squeeze()
criterion = MSELossMasked(seq_len_norm=False).to(device)
criterion_st = nn.BCEWithLogitsLoss().to(device)
2021-06-18 11:27:19 +00:00
config.d_vector_dim = 55
model = Tacotron2(config).to(device)
model.train()
model_ref = copy.deepcopy(model)
count = 0
2021-04-12 09:47:39 +00:00
for param, param_ref in zip(model.parameters(), model_ref.parameters()):
assert (param - param_ref).sum() == 0, param
count += 1
2021-06-18 11:27:19 +00:00
optimizer = optim.Adam(model.parameters(), lr=config.lr)
for i in range(5):
outputs = model.forward(
input_dummy, input_lengths, mel_spec, mel_lengths, aux_input={"speaker_ids": speaker_ids}
2021-04-12 09:47:39 +00:00
)
assert torch.sigmoid(outputs["stop_tokens"]).data.max() <= 1.0
assert torch.sigmoid(outputs["stop_tokens"]).data.min() >= 0.0
optimizer.zero_grad()
loss = criterion(outputs["decoder_outputs"], mel_spec, mel_lengths)
stop_loss = criterion_st(outputs["stop_tokens"], stop_targets)
loss = loss + criterion(outputs["model_outputs"], mel_postnet_spec, mel_lengths) + stop_loss
loss.backward()
optimizer.step()
# check parameter changes
count = 0
2021-04-12 09:47:39 +00:00
for param, param_ref in zip(model.parameters(), model_ref.parameters()):
# ignore pre-higway layer since it works conditional
# if count not in [145, 59]:
2021-04-12 09:47:39 +00:00
assert (param != param_ref).any(), "param {} with shape {} not updated!! \n{}\n{}".format(
count, param.shape, param, param_ref
)
2019-03-12 08:52:01 +00:00
count += 1
2021-04-12 09:47:39 +00:00
class TacotronGSTTrainTest(unittest.TestCase):
"""Test multi-speaker Tacotron2 with Global Style Token and Speaker Embedding"""
2021-04-12 09:47:39 +00:00
# pylint: disable=no-self-use
2020-08-05 18:19:23 +00:00
def test_train_step(self):
# with random gst mel style
2021-06-18 11:27:19 +00:00
config = config_global.copy()
config.use_speaker_embedding = True
config.num_speakers = 10
config.use_gst = True
config.gst = GSTConfig()
input_dummy = torch.randint(0, 24, (8, 128)).long().to(device)
2021-04-12 09:47:39 +00:00
input_lengths = torch.randint(100, 128, (8,)).long().to(device)
input_lengths = torch.sort(input_lengths, descending=True)[0]
2021-06-18 11:27:19 +00:00
mel_spec = torch.rand(8, 30, config.audio["num_mels"]).to(device)
mel_postnet_spec = torch.rand(8, 30, config.audio["num_mels"]).to(device)
2021-04-12 09:47:39 +00:00
mel_lengths = torch.randint(20, 30, (8,)).long().to(device)
mel_lengths[0] = 30
stop_targets = torch.zeros(8, 30, 1).float().to(device)
2021-04-12 09:47:39 +00:00
speaker_ids = torch.randint(0, 5, (8,)).long().to(device)
for idx in mel_lengths:
2021-04-12 09:47:39 +00:00
stop_targets[:, int(idx.item()) :, 0] = 1.0
2021-06-18 11:27:19 +00:00
stop_targets = stop_targets.view(input_dummy.shape[0], stop_targets.size(1) // config.r, -1)
stop_targets = (stop_targets.sum(2) > 0.0).unsqueeze(2).float().squeeze()
criterion = MSELossMasked(seq_len_norm=False).to(device)
criterion_st = nn.BCEWithLogitsLoss().to(device)
2021-06-18 11:27:19 +00:00
config.use_gst = True
config.gst = GSTConfig()
model = Tacotron2(config).to(device)
model.train()
model_ref = copy.deepcopy(model)
count = 0
for param, param_ref in zip(model.parameters(), model_ref.parameters()):
assert (param - param_ref).sum() == 0, param
count += 1
2021-06-18 11:27:19 +00:00
optimizer = optim.Adam(model.parameters(), lr=config.lr)
for i in range(10):
outputs = model.forward(
2021-06-07 14:08:56 +00:00
input_dummy, input_lengths, mel_spec, mel_lengths, aux_input={"speaker_ids": speaker_ids}
2021-04-12 09:47:39 +00:00
)
assert torch.sigmoid(outputs["stop_tokens"]).data.max() <= 1.0
assert torch.sigmoid(outputs["stop_tokens"]).data.min() >= 0.0
optimizer.zero_grad()
loss = criterion(outputs["decoder_outputs"], mel_spec, mel_lengths)
stop_loss = criterion_st(outputs["stop_tokens"], stop_targets)
loss = loss + criterion(outputs["model_outputs"], mel_postnet_spec, mel_lengths) + stop_loss
loss.backward()
optimizer.step()
# check parameter changes
count = 0
for name_param, param_ref in zip(model.named_parameters(), model_ref.parameters()):
# ignore pre-higway layer since it works conditional
# if count not in [145, 59]:
name, param = name_param
2021-04-12 09:47:39 +00:00
if name == "gst_layer.encoder.recurrence.weight_hh_l0":
# print(param.grad)
continue
2021-04-12 09:47:39 +00:00
assert (param != param_ref).any(), "param {} {} with shape {} not updated!! \n{}\n{}".format(
name, count, param.shape, param, param_ref
)
count += 1
# with file gst style
2021-04-12 09:47:39 +00:00
mel_spec = (
torch.FloatTensor(ap.melspectrogram(ap.load_wav(WAV_FILE)))[:, :30].unsqueeze(0).transpose(1, 2).to(device)
)
mel_spec = mel_spec.repeat(8, 1, 1)
input_dummy = torch.randint(0, 24, (8, 128)).long().to(device)
2021-04-12 09:47:39 +00:00
input_lengths = torch.randint(100, 128, (8,)).long().to(device)
input_lengths = torch.sort(input_lengths, descending=True)[0]
2021-06-18 11:27:19 +00:00
mel_postnet_spec = torch.rand(8, 30, config.audio["num_mels"]).to(device)
2021-04-12 09:47:39 +00:00
mel_lengths = torch.randint(20, 30, (8,)).long().to(device)
mel_lengths[0] = 30
stop_targets = torch.zeros(8, 30, 1).float().to(device)
2021-04-12 09:47:39 +00:00
speaker_ids = torch.randint(0, 5, (8,)).long().to(device)
for idx in mel_lengths:
2021-04-12 09:47:39 +00:00
stop_targets[:, int(idx.item()) :, 0] = 1.0
2021-06-18 11:27:19 +00:00
stop_targets = stop_targets.view(input_dummy.shape[0], stop_targets.size(1) // config.r, -1)
stop_targets = (stop_targets.sum(2) > 0.0).unsqueeze(2).float().squeeze()
criterion = MSELossMasked(seq_len_norm=False).to(device)
criterion_st = nn.BCEWithLogitsLoss().to(device)
2021-06-18 11:27:19 +00:00
model = Tacotron2(config).to(device)
model.train()
model_ref = copy.deepcopy(model)
count = 0
for param, param_ref in zip(model.parameters(), model_ref.parameters()):
assert (param - param_ref).sum() == 0, param
count += 1
2021-06-18 11:27:19 +00:00
optimizer = optim.Adam(model.parameters(), lr=config.lr)
for i in range(10):
outputs = model.forward(
2021-06-07 14:08:56 +00:00
input_dummy, input_lengths, mel_spec, mel_lengths, aux_input={"speaker_ids": speaker_ids}
2021-04-12 09:47:39 +00:00
)
assert torch.sigmoid(outputs["stop_tokens"]).data.max() <= 1.0
assert torch.sigmoid(outputs["stop_tokens"]).data.min() >= 0.0
optimizer.zero_grad()
loss = criterion(outputs["decoder_outputs"], mel_spec, mel_lengths)
stop_loss = criterion_st(outputs["stop_tokens"], stop_targets)
loss = loss + criterion(outputs["model_outputs"], mel_postnet_spec, mel_lengths) + stop_loss
loss.backward()
optimizer.step()
# check parameter changes
count = 0
for name_param, param_ref in zip(model.named_parameters(), model_ref.parameters()):
# ignore pre-higway layer since it works conditional
# if count not in [145, 59]:
name, param = name_param
2021-04-12 09:47:39 +00:00
if name == "gst_layer.encoder.recurrence.weight_hh_l0":
# print(param.grad)
continue
2021-04-12 09:47:39 +00:00
assert (param != param_ref).any(), "param {} {} with shape {} not updated!! \n{}\n{}".format(
name, count, param.shape, param, param_ref
)
2020-07-13 06:51:37 +00:00
count += 1
2020-09-29 20:03:25 +00:00
2021-04-12 09:47:39 +00:00
2020-09-29 20:03:25 +00:00
class SCGSTMultiSpeakeTacotronTrainTest(unittest.TestCase):
"""Test multi-speaker Tacotron2 with Global Style Tokens and d-vector inputs."""
2020-09-29 20:03:25 +00:00
@staticmethod
def test_train_step():
2021-06-18 11:27:19 +00:00
config = config_global.copy()
config.use_d_vector_file = True
config.use_gst = True
config.gst = GSTConfig()
2020-09-29 20:03:25 +00:00
input_dummy = torch.randint(0, 24, (8, 128)).long().to(device)
2021-04-12 09:47:39 +00:00
input_lengths = torch.randint(100, 128, (8,)).long().to(device)
2020-09-29 20:03:25 +00:00
input_lengths = torch.sort(input_lengths, descending=True)[0]
2021-06-18 11:27:19 +00:00
mel_spec = torch.rand(8, 30, config.audio["num_mels"]).to(device)
mel_postnet_spec = torch.rand(8, 30, config.audio["num_mels"]).to(device)
2021-04-12 09:47:39 +00:00
mel_lengths = torch.randint(20, 30, (8,)).long().to(device)
2020-09-29 20:03:25 +00:00
mel_lengths[0] = 30
stop_targets = torch.zeros(8, 30, 1).float().to(device)
speaker_embeddings = torch.rand(8, 55).to(device)
for idx in mel_lengths:
2021-04-12 09:47:39 +00:00
stop_targets[:, int(idx.item()) :, 0] = 1.0
2020-09-29 20:03:25 +00:00
2021-06-18 11:27:19 +00:00
stop_targets = stop_targets.view(input_dummy.shape[0], stop_targets.size(1) // config.r, -1)
2020-09-29 20:03:25 +00:00
stop_targets = (stop_targets.sum(2) > 0.0).unsqueeze(2).float().squeeze()
criterion = MSELossMasked(seq_len_norm=False).to(device)
criterion_st = nn.BCEWithLogitsLoss().to(device)
2021-06-18 11:27:19 +00:00
config.d_vector_dim = 55
model = Tacotron2(config).to(device)
2020-09-29 20:03:25 +00:00
model.train()
model_ref = copy.deepcopy(model)
count = 0
2021-04-12 09:47:39 +00:00
for param, param_ref in zip(model.parameters(), model_ref.parameters()):
2020-09-29 20:03:25 +00:00
assert (param - param_ref).sum() == 0, param
count += 1
2021-06-18 11:27:19 +00:00
optimizer = optim.Adam(model.parameters(), lr=config.lr)
2020-09-29 20:03:25 +00:00
for i in range(5):
outputs = model.forward(
2021-06-07 14:08:56 +00:00
input_dummy, input_lengths, mel_spec, mel_lengths, aux_input={"d_vectors": speaker_embeddings}
2021-04-12 09:47:39 +00:00
)
assert torch.sigmoid(outputs["stop_tokens"]).data.max() <= 1.0
assert torch.sigmoid(outputs["stop_tokens"]).data.min() >= 0.0
2020-09-29 20:03:25 +00:00
optimizer.zero_grad()
loss = criterion(outputs["decoder_outputs"], mel_spec, mel_lengths)
stop_loss = criterion_st(outputs["stop_tokens"], stop_targets)
loss = loss + criterion(outputs["model_outputs"], mel_postnet_spec, mel_lengths) + stop_loss
2020-09-29 20:03:25 +00:00
loss.backward()
optimizer.step()
# check parameter changes
count = 0
2021-04-12 09:47:39 +00:00
for name_param, param_ref in zip(model.named_parameters(), model_ref.parameters()):
2020-09-29 20:03:25 +00:00
# ignore pre-higway layer since it works conditional
# if count not in [145, 59]:
name, param = name_param
2021-04-12 09:47:39 +00:00
if name == "gst_layer.encoder.recurrence.weight_hh_l0":
2020-09-29 20:03:25 +00:00
continue
2021-04-12 09:47:39 +00:00
assert (param != param_ref).any(), "param {} with shape {} not updated!! \n{}\n{}".format(
count, param.shape, param, param_ref
)
2021-03-08 04:06:54 +00:00
count += 1