File size: 4,984 Bytes
11b4f27 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | 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
|