magvits_data / code /module /models_s1.py
arcadiaaaaa
Add files using upload-large-folder tool
11b4f27 verified
Raw History Blame Contribute Delete
4.98 kB
import math
from omegaconf import OmegaConf
from tqdm import tqdm
from module.aligner import AlignmentEncoder
from text import symbols
from transformer.embedding import SinePositionalEmbedding
from transformer.transformer import LayerNorm, TransformerEncoder, TransformerEncoderLayer
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from module.models import TextEncoder, PosteriorEncoder, FramePriorNet, Generator, ProsodyEncoder, ResidualCouplingBlock, mono_align_and_get_loss
from module import commons
from module import modules
import random
import random
from tqdm import tqdm
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__()
self.in_proj = nn.Linear(io_channels+cond_channels, 512)
norm_first = False
self.position = SinePositionalEmbedding(
512, dropout=0.1, scale=False, alpha=True)
self.encoder = TransformerEncoder(
TransformerEncoderLayer(
d_model=512,
nhead=16,
dim_feedforward=2048,
dropout=0.1,
batch_first=True,
norm_first=False, ),
num_layers=12,
norm=LayerNorm(512) if norm_first else None, )
self.proj = nn.Linear(512, io_channels)
self.diffusion_embedding = SinusoidalPosEmb(512)
def forward(self, x, t, cond, mask=None):
if mask is None:
mask = torch.ones(x.shape[0], x.shape[-1], device=x.device).long()
mask_bool = ~mask.bool()
diffusion_step = self.diffusion_embedding(t).unsqueeze(1)
x = torch.cat([x, cond], dim=1).transpose(1, 2)
x = self.in_proj(x)
x = torch.cat([diffusion_step, x], dim=1)
mask_bool = torch.cat([torch.zeros([mask_bool.shape[0], 1], device=mask_bool.device).bool(), mask_bool], dim=1)
x = self.position(x)
x, _ = self.encoder(
(x, None), src_key_padding_mask=mask_bool)
x = x[:, 1:, :]
x = self.proj(x).transpose(1, 2)
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.unsqueeze(1)
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.Linear(192, 192)
self.g_emb = nn.Linear(256, 192)
self.reflow = ReFlow(latent_dim, 192)
def forward(self, x, bert, spk_emb, diffusion_input, mask):
g = self.g_emb(spk_emb).unsqueeze(1)
bert = self.bert_proj(bert.transpose(1, 2))
x = self.x_emb(x.transpose(1,2))
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, spk_emb, step, guidance):
g = self.g_emb(spk_emb).unsqueeze(1)
bert = self.bert_proj(bert.transpose(1, 2))
x = self.x_emb(x.transpose(1,2))
cond = (x + bert + g).transpose(1, 2)
fakes = self.reflow.sample(cond, step)
return fakes