import torch import torch.nn as nn import torch.optim as optim import pytorch_lightning.core.module as pl import matplotlib.pyplot as plt from module import commons from transformer.embedding import SinePositionalEmbedding from transformer.transformer import LayerNorm, TransformerEncoder, TransformerEncoderLayer plt.switch_backend('agg') import math import torch.nn.functional as F from tqdm import tqdm from module import attentions from module.modules import MelStyleEncoder class SinusoidalPosEmb(nn.Module): def __init__(self, dim): super().__init__() self.dim = dim def forward(self, x): device = x.device half_dim = self.dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, device=device) * -emb) emb = x[:, None] * emb[None, :] emb = torch.cat((emb.sin(), emb.cos()), dim=-1) return emb class DiT(nn.Module): def __init__(self, io_channels, cond_channels): super().__init__() hidden_channels = 512 filter_channels = 768 n_heads = 16 n_layers = 6 kernel_size = 3 p_dropout = 0.1 self.in_proj = nn.Conv1d(io_channels+cond_channels, hidden_channels, 1) self.encoder = attentions.Encoder( hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout) self.proj = nn.Conv1d(hidden_channels, io_channels, 1) self.diffusion_embedding = SinusoidalPosEmb(hidden_channels) def forward(self, x, t, cond, mask=None): if mask is None: mask = torch.ones(x.shape[0], 1, x.shape[-1], device=x.device) diffusion_step = self.diffusion_embedding(t).unsqueeze(-1) x = torch.cat([x, cond], dim=1) x = self.in_proj(x) x = x + diffusion_step x = self.encoder(x*mask, mask) x = self.proj(x)*mask return x class ReFlow(nn.Module): def __init__(self, io_channels, cond_channels, ): super().__init__() self.model = DiT(io_channels, cond_channels) self.io_channels = io_channels self.rng = torch.quasirandom.SobolEngine(1, scramble=True) def forward(self, reals, cond, mask): # reals : [B, 128, T] # cond : [B, 192, T] # mask : [B, 1, T] t = self.rng.draw(reals.shape[0])[:, 0].to(reals.device) alphas, sigmas = 1 - t, t alphas = alphas[:, None, None] sigmas = sigmas[:, None, None] noise = torch.randn_like(reals) noised_inputs = reals * alphas + noise * sigmas targets = noise - reals output = self.model(noised_inputs, t, cond, mask) # mse loss with mask loss = F.mse_loss(output, targets, reduction='none') loss = loss * mask return loss.mean() def sample(self, cond, steps, sigma_max=1): x = torch.randn(cond.shape[0], self.io_channels, cond.shape[2]).to(cond.device) t = torch.linspace(sigma_max, 0, steps + 1) for t_curr, t_prev in tqdm(zip(t[:-1], t[1:])): t_curr_tensor = t_curr * torch.ones( (x.shape[0],), dtype=x.dtype, device=x.device ) dt = t_prev - t_curr x = x + dt * self.model(x, t_curr_tensor, cond) return x class NARPredictor(nn.Module): def __init__(self, latent_dim=16): super().__init__() self.latent_dim = latent_dim self.bert_proj = nn.Linear(1024, 192) self.x_emb = nn.Embedding(1024, 192) self.ref_enc = MelStyleEncoder(latent_dim, style_vector_dim=192) self.reflow = ReFlow(latent_dim, 192) def forward(self, x, bert, diffusion_input, mask): g = self.ref_enc(diffusion_input, mask).transpose(1, 2) bert = self.bert_proj(bert.transpose(1, 2)) x = self.x_emb(x) cond = (x + bert + g).transpose(1, 2) loss = self.reflow(diffusion_input, cond, mask) return loss @torch.inference_mode() @torch.no_grad() def infer(self, x, bert, prompt, step, guidance): print('prompt shape:', prompt.shape) g = self.ref_enc(prompt).transpose(1, 2) bert = self.bert_proj(bert.transpose(1, 2)) x = self.x_emb(x) cond = (x + bert + g).transpose(1, 2) fakes = self.reflow.sample(cond, step) return fakes class Wav2TTS(pl.LightningModule): def __init__(self, hp, **kwargs): super().__init__() self.model = NARPredictor(latent_dim=4) self.lr = hp.lr def configure_optimizers(self): print('train with lr ', self.lr) optimizer = optim.AdamW([*self.parameters()], lr=self.lr, betas=(0.9, 0.95), weight_decay=0.1) return optimizer def training_step(self, batch, batch_idx): loss = self.step(batch) self.log("train/loss", loss, on_step=True, prog_bar=True) # self.log("train/quantize_loss", quantize_loss, on_step=True, prog_bar=True) return loss def validation_step(self, batch, batch_idx): loss = self.step(batch) self.log("val/loss", loss, on_step=True, prog_bar=True) def step(self, batch): # speaker_embedding = self.spk_proj(batch['spk_emb']) # speaker_embedding, commitment_loss, codebook_loss, indices, z_e = self.spk_vq(speaker_embedding.unsqueeze(-1)) # quantize_loss = codebook_loss + 0.25*commitment_loss # speaker_embedding = speaker_embedding.squeeze(-1) # speaker_embedding = self.spk_emb(batch['spk_emb']) # Deal with phone segments phone_features = batch['phone'] lengths = batch['length'] bert_feature = batch['bert_feature'] speaker_embedding = batch['spk_emb'] latent = batch['latent'] mask = commons.sequence_mask(lengths, latent.size(-1)).unsqueeze(1) loss = self.model(phone_features, bert_feature, latent, mask) return loss @torch.inference_mode() @torch.no_grad() def inference(self, phonemes, bert_feature, ref_latent, n_steps=32, guidance=4): # speaker_embedding = self.spk_proj(spk_emb) # speaker_embedding, commitment_loss, codebook_loss, indices, z_e = self.spk_vq(speaker_embedding.unsqueeze(-1)) # speaker_embedding = speaker_embedding.squeeze(-1) # print('quantized spk code:', indices) output = self.model.infer(phonemes, bert_feature, ref_latent, n_steps, guidance) return output