Download code/module/models_zzzzzz.py from rcell233/magvits_data: direct link, hf CLI and curl.
- Browser
- Download file 29.5 kB
-
https://huggingface.co/datasets/rcell233/magvits_data/resolve/main/code/module/models_zzzzzz.py
- Command line
-
hf download hf://datasets/rcell233/magvits_data/code/module/models_zzzzzz.py
-
curl -L -o models_zzzzzz.py https://huggingface.co/datasets/rcell233/magvits_data/resolve/main/code/module/models_zzzzzz.py
29.5 kB
| import math | |
| from module.aligner import AlignmentEncoder | |
| import numpy as np | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| from module import commons | |
| from module import modules | |
| from module import attentions | |
| import monotonic_align | |
| from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d | |
| from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm | |
| from module.commons import init_weights, get_padding | |
| from text import symbols | |
| from torch.autograd.function import InplaceFunction | |
| from numba import jit, prange | |
| from module.mrte_model import MRTE | |
| def mas_width1(attn_map): | |
| """mas with hardcoded width=1""" | |
| # assumes mel x text | |
| opt = np.zeros_like(attn_map) | |
| attn_map = np.log(attn_map) | |
| attn_map[0, 1:] = -np.inf | |
| log_p = np.zeros_like(attn_map) | |
| log_p[0, :] = attn_map[0, :] | |
| prev_ind = np.zeros_like(attn_map, dtype=np.int64) | |
| for i in range(1, attn_map.shape[0]): | |
| for j in range(attn_map.shape[1]): # for each text dim | |
| prev_log = log_p[i - 1, j] | |
| prev_j = j | |
| if j - 1 >= 0 and log_p[i - 1, j - 1] >= log_p[i - 1, j]: | |
| prev_log = log_p[i - 1, j - 1] | |
| prev_j = j - 1 | |
| log_p[i, j] = attn_map[i, j] + prev_log | |
| prev_ind[i, j] = prev_j | |
| # now backtrack | |
| curr_text_idx = attn_map.shape[1] - 1 | |
| for i in range(attn_map.shape[0] - 1, -1, -1): | |
| opt[i, curr_text_idx] = 1 | |
| curr_text_idx = prev_ind[i, curr_text_idx] | |
| opt[0, curr_text_idx] = 1 | |
| return opt | |
| def b_mas(b_attn_map, in_lens, out_lens, width=1): | |
| assert width == 1 | |
| attn_out = np.zeros_like(b_attn_map) | |
| for b in prange(b_attn_map.shape[0]): | |
| out = mas_width1(b_attn_map[b, 0, : out_lens[b], : in_lens[b]]) | |
| attn_out[b, 0, : out_lens[b], : in_lens[b]] = out | |
| return attn_out | |
| def binarize_attention_parallel(attn, in_lens, out_lens): | |
| """For training purposes only. Binarizes attention with MAS. | |
| These will no longer recieve a gradient. | |
| Args: | |
| attn: B x 1 x max_mel_len x max_text_len | |
| """ | |
| with torch.no_grad(): | |
| attn_cpu = attn.data.cpu().numpy() | |
| attn_out = b_mas(attn_cpu, in_lens.cpu().numpy(), out_lens.cpu().numpy(), width=1) | |
| return torch.from_numpy(attn_out).to(attn.device) | |
| class scalar_func9(InplaceFunction): | |
| def forward(ctx, input): | |
| ctx.input = input | |
| return torch.round(9*input)/9 | |
| def backward(ctx, grad_output): | |
| grad_input = grad_output.clone() | |
| return grad_input | |
| class TextEncoder(nn.Module): | |
| def __init__(self, | |
| out_channels, | |
| hidden_channels, | |
| filter_channels, | |
| n_heads, | |
| n_layers, | |
| kernel_size, | |
| p_dropout): | |
| super().__init__() | |
| self.out_channels = out_channels | |
| self.hidden_channels = hidden_channels | |
| self.filter_channels = filter_channels | |
| self.n_heads = n_heads | |
| self.n_layers = n_layers | |
| self.kernel_size = kernel_size | |
| self.p_dropout = p_dropout | |
| self.text_emb = nn.Embedding(len(symbols), hidden_channels) | |
| nn.init.normal_(self.text_emb.weight, 0.0, hidden_channels ** -0.5) | |
| # self.ssl_proj = nn.Conv1d(768, hidden_channels, 1) | |
| # self.encoder_ssl = attentions.Encoder( | |
| # hidden_channels, | |
| # filter_channels, | |
| # n_heads, | |
| # n_layers//2, | |
| # kernel_size, | |
| # p_dropout) | |
| self.encoder_text = attentions.Encoder( | |
| hidden_channels, | |
| filter_channels, | |
| n_heads, | |
| n_layers, | |
| kernel_size, | |
| p_dropout) | |
| # self.mrte = MRTE() | |
| # self.vq_dim = 8 | |
| # self.vq_down = nn.Conv1d(hidden_channels, self.vq_dim, 1) | |
| # self.vq = scalar_func9() | |
| # self.vq_up = nn.Conv1d(self.vq_dim, hidden_channels, 1) | |
| self.encoder2 = attentions.Encoder( | |
| hidden_channels, | |
| filter_channels, | |
| n_heads, | |
| n_layers//2, | |
| kernel_size, | |
| p_dropout) | |
| self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) | |
| def forward(self,y, y_mask, x, x_mask): | |
| # y = self.ssl_proj(y * y_mask) * y_mask | |
| # y = self.encoder_ssl(y * y_mask, y_mask) | |
| x = (self.text_emb(x)) * math.sqrt(self.hidden_channels) # [b, t, h] | |
| x = torch.transpose(x, 1, -1) # [b, h, t] | |
| x = self.encoder_text(x * x_mask, x_mask) | |
| # prosody = self.mrte(x, x_mask, y, y_mask) | |
| # prosody = self.vq_down(prosody) | |
| # prosody = F.tanh(prosody) | |
| # prosody_code = self.vq.apply(prosody) | |
| # z_q = self.vq_up(prosody_code) | |
| prosody_code = torch.zeros_like(x) | |
| # x = x + z_q | |
| x = self.encoder2(x * x_mask, x_mask) | |
| stats = self.proj(x) * x_mask | |
| m, logs = torch.split(stats, self.out_channels, dim=1) | |
| return x, m, logs, prosody_code | |
| class ResidualCouplingBlock(nn.Module): | |
| def __init__( | |
| self, | |
| channels, | |
| hidden_channels, | |
| kernel_size, | |
| dilation_rate, | |
| n_layers, | |
| n_flows=4, | |
| gin_channels=0, | |
| ): | |
| super(ResidualCouplingBlock, self).__init__() | |
| self.channels = channels | |
| self.hidden_channels = hidden_channels | |
| self.kernel_size = kernel_size | |
| self.dilation_rate = dilation_rate | |
| self.n_layers = n_layers | |
| self.n_flows = n_flows | |
| self.gin_channels = gin_channels | |
| self.flows = nn.ModuleList() | |
| for i in range(n_flows): | |
| self.flows.append( | |
| modules.ResidualCouplingLayer( | |
| channels, | |
| hidden_channels, | |
| kernel_size, | |
| dilation_rate, | |
| n_layers, | |
| gin_channels=gin_channels, | |
| mean_only=True, | |
| ) | |
| ) | |
| self.flows.append(modules.Flip()) | |
| def forward( | |
| self, | |
| x: torch.Tensor, | |
| x_mask: torch.Tensor, | |
| g=None, | |
| reverse: bool = False, | |
| ): | |
| if not reverse: | |
| for flow in self.flows: | |
| x, _ = flow(x, x_mask, g=g, reverse=reverse) | |
| else: | |
| for flow in self.flows[::-1]: | |
| x, _ = flow.forward(x, x_mask, g=g, reverse=reverse) | |
| return x | |
| def remove_weight_norm(self): | |
| for i in range(self.n_flows): | |
| self.flows[i * 2].remove_weight_norm() | |
| def __prepare_scriptable__(self): | |
| for i in range(self.n_flows): | |
| for hook in self.flows[i * 2]._forward_pre_hooks.values(): | |
| if ( | |
| hook.__module__ == "torch.nn.utils.weight_norm" | |
| and hook.__class__.__name__ == "WeightNorm" | |
| ): | |
| torch.nn.utils.remove_weight_norm(self.flows[i * 2]) | |
| return self | |
| class PosteriorEncoder(nn.Module): | |
| def __init__(self, | |
| in_channels, | |
| out_channels, | |
| hidden_channels, | |
| kernel_size, | |
| dilation_rate, | |
| n_layers, | |
| gin_channels=0): | |
| super().__init__() | |
| self.in_channels = in_channels | |
| self.out_channels = out_channels | |
| self.hidden_channels = hidden_channels | |
| self.kernel_size = kernel_size | |
| self.dilation_rate = dilation_rate | |
| self.n_layers = n_layers | |
| self.gin_channels = gin_channels | |
| self.pre = nn.Conv1d(in_channels, hidden_channels, 1) | |
| self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels) | |
| self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) | |
| def forward(self, x, x_lengths, g=None): | |
| x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) | |
| x = self.pre(x) * x_mask | |
| x = self.enc(x, x_mask, g=g) | |
| stats = self.proj(x) * x_mask | |
| m, logs = torch.split(stats, self.out_channels, dim=1) | |
| z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask | |
| return z, m, logs, x_mask | |
| class Generator(torch.nn.Module): | |
| def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, | |
| upsample_initial_channel, upsample_kernel_sizes, gin_channels=0): | |
| super(Generator, self).__init__() | |
| self.num_kernels = len(resblock_kernel_sizes) | |
| self.num_upsamples = len(upsample_rates) | |
| self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3) | |
| resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2 | |
| self.ups = nn.ModuleList() | |
| for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): | |
| self.ups.append(weight_norm( | |
| ConvTranspose1d(upsample_initial_channel // (2 ** i), upsample_initial_channel // (2 ** (i + 1)), | |
| k, u, padding=(k - u) // 2))) | |
| self.resblocks = nn.ModuleList() | |
| for i in range(len(self.ups)): | |
| ch = upsample_initial_channel // (2 ** (i + 1)) | |
| for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)): | |
| self.resblocks.append(resblock(ch, k, d)) | |
| self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) | |
| self.ups.apply(init_weights) | |
| if gin_channels != 0: | |
| self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) | |
| def forward(self, x, g=None): | |
| x = self.conv_pre(x) | |
| if g is not None: | |
| x = x + self.cond(g) | |
| for i in range(self.num_upsamples): | |
| x = F.leaky_relu(x, modules.LRELU_SLOPE) | |
| x = self.ups[i](x) | |
| xs = None | |
| for j in range(self.num_kernels): | |
| if xs is None: | |
| xs = self.resblocks[i * self.num_kernels + j](x) | |
| else: | |
| xs += self.resblocks[i * self.num_kernels + j](x) | |
| x = xs / self.num_kernels | |
| x = F.leaky_relu(x) | |
| x = self.conv_post(x) | |
| x = torch.tanh(x) | |
| return x | |
| def remove_weight_norm(self): | |
| print('Removing weight norm...') | |
| for l in self.ups: | |
| remove_weight_norm(l) | |
| for l in self.resblocks: | |
| l.remove_weight_norm() | |
| class DiscriminatorP(torch.nn.Module): | |
| def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): | |
| super(DiscriminatorP, self).__init__() | |
| self.period = period | |
| self.use_spectral_norm = use_spectral_norm | |
| norm_f = weight_norm if use_spectral_norm == False else spectral_norm | |
| self.convs = nn.ModuleList([ | |
| norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), | |
| norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), | |
| norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), | |
| norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), | |
| norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))), | |
| ]) | |
| self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) | |
| def forward(self, x): | |
| fmap = [] | |
| # 1d to 2d | |
| b, c, t = x.shape | |
| if t % self.period != 0: # pad first | |
| n_pad = self.period - (t % self.period) | |
| x = F.pad(x, (0, n_pad), "reflect") | |
| t = t + n_pad | |
| x = x.view(b, c, t // self.period, self.period) | |
| for l in self.convs: | |
| x = l(x) | |
| x = F.leaky_relu(x, modules.LRELU_SLOPE) | |
| fmap.append(x) | |
| x = self.conv_post(x) | |
| fmap.append(x) | |
| x = torch.flatten(x, 1, -1) | |
| return x, fmap | |
| class DiscriminatorS(torch.nn.Module): | |
| def __init__(self, use_spectral_norm=False): | |
| super(DiscriminatorS, self).__init__() | |
| norm_f = weight_norm if use_spectral_norm == False else spectral_norm | |
| self.convs = nn.ModuleList([ | |
| norm_f(Conv1d(1, 16, 15, 1, padding=7)), | |
| norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), | |
| norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), | |
| norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), | |
| norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), | |
| norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), | |
| ]) | |
| self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) | |
| def forward(self, x): | |
| fmap = [] | |
| for l in self.convs: | |
| x = l(x) | |
| x = F.leaky_relu(x, modules.LRELU_SLOPE) | |
| fmap.append(x) | |
| x = self.conv_post(x) | |
| fmap.append(x) | |
| x = torch.flatten(x, 1, -1) | |
| return x, fmap | |
| class MultiPeriodDiscriminator(torch.nn.Module): | |
| def __init__(self, use_spectral_norm=False): | |
| super(MultiPeriodDiscriminator, self).__init__() | |
| periods = [2, 3, 5, 7, 11] | |
| discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] | |
| discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods] | |
| self.discriminators = nn.ModuleList(discs) | |
| def forward(self, y, y_hat): | |
| y_d_rs = [] | |
| y_d_gs = [] | |
| fmap_rs = [] | |
| fmap_gs = [] | |
| for i, d in enumerate(self.discriminators): | |
| y_d_r, fmap_r = d(y) | |
| y_d_g, fmap_g = d(y_hat) | |
| y_d_rs.append(y_d_r) | |
| y_d_gs.append(y_d_g) | |
| fmap_rs.append(fmap_r) | |
| fmap_gs.append(fmap_g) | |
| return y_d_rs, y_d_gs, fmap_rs, fmap_gs | |
| class ReferenceEncoder(nn.Module): | |
| ''' | |
| inputs --- [N, Ty/r, n_mels*r] mels | |
| outputs --- [N, ref_enc_gru_size] | |
| ''' | |
| def __init__(self, spec_channels, gin_channels=0): | |
| super().__init__() | |
| self.spec_channels = spec_channels | |
| ref_enc_filters = [32, 32, 64, 64, 128, 128] | |
| K = len(ref_enc_filters) | |
| filters = [1] + ref_enc_filters | |
| convs = [weight_norm(nn.Conv2d(in_channels=filters[i], | |
| out_channels=filters[i + 1], | |
| kernel_size=(3, 3), | |
| stride=(2, 2), | |
| padding=(1, 1))) for i in range(K)] | |
| self.convs = nn.ModuleList(convs) | |
| # self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)]) | |
| out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K) | |
| self.gru = nn.GRU(input_size=ref_enc_filters[-1] * out_channels, | |
| hidden_size=256 // 2, | |
| batch_first=True) | |
| self.proj = nn.Linear(128, gin_channels) | |
| def forward(self, inputs, mask=None): | |
| N = inputs.size(0) | |
| out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs] | |
| for conv in self.convs: | |
| out = conv(out) | |
| # out = wn(out) | |
| out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K] | |
| out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K] | |
| T = out.size(1) | |
| N = out.size(0) | |
| out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K] | |
| self.gru.flatten_parameters() | |
| memory, out = self.gru(out) # out --- [1, N, 128] | |
| return self.proj(out.squeeze(0)).unsqueeze(-1) | |
| def calculate_channels(self, L, kernel_size, stride, pad, n_convs): | |
| for i in range(n_convs): | |
| L = (L - kernel_size + 2 * pad) // stride + 1 | |
| return L | |
| class FramePriorNet(nn.Module): | |
| def __init__(self, | |
| out_channels, | |
| hidden_channels, | |
| filter_channels, | |
| n_heads, | |
| n_layers, | |
| kernel_size, | |
| p_dropout): | |
| super().__init__() | |
| self.enc = attentions.Encoder( | |
| hidden_channels, | |
| filter_channels, | |
| n_heads, | |
| 6, | |
| kernel_size, | |
| p_dropout) | |
| self.out_proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) | |
| self.out_channels = out_channels | |
| def forward(self, x, x_mask): | |
| x = self.enc(x, x_mask) | |
| stats = self.out_proj(x) * x_mask | |
| m, logs = torch.split(stats, self.out_channels, dim=1) | |
| return m, logs | |
| class ProsodyEncoder(nn.Module): | |
| def __init__(self, | |
| in_channels, | |
| hidden_channels, | |
| kernel_size, | |
| dilation_rate, | |
| n_layers, | |
| gin_channels, | |
| vq_dim=16, | |
| ): | |
| super().__init__() | |
| self.in_proj = nn.Conv1d(in_channels, hidden_channels, 1) | |
| self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0) | |
| # from dac | |
| self.duration_dec = modules.WN(hidden_channels, kernel_size, dilation_rate, 3, gin_channels=0) | |
| self.duration_proj = nn.Linear(hidden_channels, 512, False) | |
| self.vq_dim = vq_dim | |
| self.vq_down = nn.Conv1d(hidden_channels, self.vq_dim, 1) | |
| self.vq = scalar_func9() | |
| self.vq_up = nn.Conv1d(self.vq_dim, hidden_channels, 1) | |
| def calc_dur_loss(self, x, x_mask, dur): | |
| dur = dur.clamp(0, 509) | |
| x = self.duration_dec(x, x_mask) | |
| logits = self.duration_proj(x.transpose(1, 2)) | |
| assert logits.shape[:2] == dur.shape[:2], (logits.shape, dur.shape) | |
| x_mask_bool = x_mask.squeeze(1).bool() | |
| dur = dur[x_mask_bool].view(-1) | |
| logits = logits[x_mask_bool].view(-1, 512) | |
| dur_loss = F.cross_entropy(logits, dur, reduction='mean') | |
| acc = (logits.argmax(-1) == dur).float().mean() * 100 | |
| # print('dur acc', acc.item()) | |
| pred_dur = logits.argmax(-1) | |
| return dur_loss, pred_dur | |
| def decode_dur(self, x, x_mask): | |
| x = self.duration_dec(x, x_mask) | |
| logits = self.duration_proj(x.transpose(1, 2)) | |
| logits = logits.view(-1, 512) | |
| pred_dur = logits.argmax(-1).reshape(-1, x.size(2)) | |
| return pred_dur | |
| def forward(self, y, x_mask, attn, dur): | |
| y = self.in_proj(y) | |
| s = attn.sum(axis=2).unsqueeze(2) | |
| s[s == 0] = 1 | |
| attn_pool = attn / s | |
| x = torch.matmul(attn_pool.squeeze(1).transpose(1, 2), y.transpose(1, 2)).transpose(1, 2) | |
| x = self.enc(x, x_mask, g=None) | |
| x = self.vq_down(x) | |
| x = F.tanh(x) | |
| z = self.vq.apply(x) | |
| # print('z.std', z.std()) | |
| z_q = self.vq_up(z) | |
| quantize_loss = torch.tensor(0.) | |
| dur_loss, pred_dur = self.calc_dur_loss(z_q, x_mask, dur) | |
| return z_q, quantize_loss, z, dur_loss, pred_dur | |
| def decode(self, z_pred, x_mask): | |
| z = self.vq.apply(z_pred) | |
| z_q = self.vq_up(z) | |
| dur = self.decode_dur(z_q, x_mask) | |
| return z_q, dur | |
| class DP(nn.Module): | |
| def __init__(self, | |
| hidden_channels, | |
| kernel_size, | |
| dilation_rate, | |
| ): | |
| super().__init__() | |
| self.duration_dec = modules.WN(hidden_channels, kernel_size, dilation_rate, 3, gin_channels=0) | |
| self.duration_proj = nn.Linear(hidden_channels, 512, False) | |
| def forward(self, x, x_mask, dur): | |
| dur = dur.clamp(0, 509) | |
| x = self.duration_dec(x, x_mask) | |
| logits = self.duration_proj(x.transpose(1, 2)) | |
| assert logits.shape[:2] == dur.shape[:2], (logits.shape, dur.shape) | |
| x_mask_bool = x_mask.squeeze(1).bool() | |
| dur = dur[x_mask_bool].view(-1) | |
| logits = logits[x_mask_bool].view(-1, 512) | |
| dur_loss = F.cross_entropy(logits, dur, reduction='mean') | |
| acc = (logits.argmax(-1) == dur).float().mean() * 100 | |
| print('dur acc', acc.item()) | |
| pred_dur = logits.argmax(-1) | |
| return dur_loss, pred_dur | |
| def decode_dur(self, x, x_mask): | |
| x = self.duration_dec(x, x_mask) | |
| logits = self.duration_proj(x.transpose(1, 2)) | |
| logits = logits.view(-1, 512) | |
| pred_dur = logits.argmax(-1).reshape(-1, x.size(2)) | |
| return pred_dur | |
| def mono_align_and_get_loss(m_p, logs_p, z_p,x_mask,y_mask): | |
| with torch.no_grad(): | |
| # negative cross-entropy | |
| s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t] | |
| neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True) # [b, 1, t_s] | |
| neg_cent2 = torch.matmul(-0.5 * (z_p ** 2).transpose(1, 2), s_p_sq_r) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s] | |
| neg_cent3 = torch.matmul(z_p.transpose(1, 2), (m_p * s_p_sq_r)) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s] | |
| neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s] | |
| neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4 | |
| attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1) | |
| attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach() | |
| w = attn.sum(2).squeeze(1).long() | |
| # print('w', w.shape, 'attn_hard', attn_hard.shape, 'g', g.shape) | |
| return attn, w | |
| class SynthesizerTrn(nn.Module): | |
| """ | |
| Synthesizer for Training | |
| """ | |
| def __init__(self, | |
| spec_channels, | |
| segment_size, | |
| inter_channels, | |
| hidden_channels, | |
| filter_channels, | |
| n_heads, | |
| n_layers, | |
| kernel_size, | |
| p_dropout, | |
| resblock, | |
| resblock_kernel_sizes, | |
| resblock_dilation_sizes, | |
| upsample_rates, | |
| upsample_initial_channel, | |
| upsample_kernel_sizes, | |
| n_speakers=0, | |
| gin_channels=0, | |
| use_sdp=True, | |
| freeze_quantizer=False, | |
| **kwargs): | |
| super().__init__() | |
| self.spec_channels = spec_channels | |
| self.inter_channels = inter_channels | |
| self.hidden_channels = hidden_channels | |
| self.filter_channels = filter_channels | |
| self.n_heads = n_heads | |
| self.n_layers = n_layers | |
| self.kernel_size = kernel_size | |
| self.p_dropout = p_dropout | |
| self.resblock = resblock | |
| self.resblock_kernel_sizes = resblock_kernel_sizes | |
| self.resblock_dilation_sizes = resblock_dilation_sizes | |
| self.upsample_rates = upsample_rates | |
| self.upsample_initial_channel = upsample_initial_channel | |
| self.upsample_kernel_sizes = upsample_kernel_sizes | |
| self.segment_size = segment_size | |
| self.n_speakers = n_speakers | |
| gin_channels = hidden_channels | |
| self.gin_channels = gin_channels | |
| self.use_sdp = use_sdp | |
| self.enc_p = TextEncoder(inter_channels, | |
| hidden_channels, | |
| filter_channels, | |
| n_heads, | |
| n_layers, | |
| kernel_size, | |
| p_dropout) | |
| print('n_param of enc_p', sum(p.numel() for p in self.enc_p.parameters() if p.requires_grad) / 1e6, 'M') | |
| self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, | |
| upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels) | |
| self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, | |
| gin_channels=gin_channels) | |
| self.flow = ResidualCouplingBlock( | |
| inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels | |
| ) | |
| self.ref_enc = modules.MelStyleEncoder(spec_channels, style_vector_dim=gin_channels) | |
| # self.dp = DP(hidden_channels, 5, 1) | |
| # def get_codes(self, x, x_lengths, y, y_lengths, ssl, attn_priors): | |
| # ph = x.clone() | |
| # y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(-1)), 1).to(y.dtype) | |
| # g = self.ref_enc(y * y_mask, y_mask) | |
| # x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(-1)), 1).to(y.dtype) | |
| # x, x_align = self.enc_p(x, x_mask) | |
| # z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) | |
| # attn_out, attn, duration = mono_align_and_get_loss(self.aligner, x_align, z.detach(), x_mask, y_mask, attn_priors, x_lengths, y_lengths, g) | |
| # _, _, pred_prosody_codes,_ , _ = self.prosody_encoder(ssl, x_mask, attn, duration) | |
| # return pred_prosody_codes | |
| def forward(self, x, x_lengths, y, y_lengths, mel, ssl, attn_priors, bert, spk_emb, ): | |
| y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(-1)), 1).to(y.dtype) | |
| g = self.ref_enc(y * y_mask, y_mask) | |
| x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(-1)), 1).to(y.dtype) | |
| x, m_p, logs_p, prosody = self.enc_p(ssl, y_mask, x, x_mask) | |
| assert not torch.isnan(x).any(), 'x nan' | |
| z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) | |
| z_p = self.flow(z, y_mask, g=g) | |
| assert not torch.isnan(z_p).any(), 'z_p nan' | |
| attn, duration = mono_align_and_get_loss(m_p, logs_p, z_p, x_mask, y_mask) | |
| assert not torch.isnan(attn).any(), 'attn nan' | |
| assert not torch.isnan(duration).any(), 'duration nan' | |
| # dur_loss, pred_dur = self.dp(x, x_mask, duration) | |
| dur_loss = torch.tensor(0.).to(x.device) | |
| print('dur loss', dur_loss.item()) | |
| m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) | |
| logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) | |
| assert not torch.isnan(m_p).any(), 'm_p nan' | |
| z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size) | |
| o = self.dec(z_slice, g=g) | |
| return o, attn, ids_slice, x_mask, y_mask, ( | |
| z, z_p, m_p, logs_p, m_q, logs_q), prosody, dur_loss | |
| def reconstruct(self, x, x_lengths, y, y_lengths,mel, ssl, attn_priors, bert, spk_emb, noise_scale=.4): | |
| y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(-1)), 1).to(y.dtype) | |
| g = self.ref_enc(y * y_mask, y_mask) | |
| x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(-1)), 1).to(y.dtype) | |
| x, m_p, logs_p, prosody = self.enc_p(ssl, y_mask, x, x_mask) | |
| duration = self.dp.decode_dur(x, x_mask) | |
| total_duration = torch.sum(duration, dim=1) | |
| y_lengths = total_duration.long() | |
| print('y_lengths', y_lengths, 'duration', duration) | |
| y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y_lengths.max()), 1).float() | |
| attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1) | |
| attn = commons.generate_path(duration.unsqueeze(1), attn_mask) | |
| m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) | |
| logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2) | |
| z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale | |
| z = self.flow(z_p, y_mask, g=g, reverse=True) | |
| o = self.dec((z * y_mask), g=g) | |
| return o, attn, y_mask, (z, z_p, m_p, logs_p) | |
| # def encode(self, x, x_lengths, y, y_lengths,ssl, attn_priors, bert, spk_emb): | |
| # y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(-1)), 1).to(y.dtype) | |
| # g = self.ref_enc(y * y_mask, y_mask) | |
| # x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(-1)), 1).to(y.dtype) | |
| # x, x_align = self.enc_p(x, x_mask) | |
| # z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) | |
| # attn_out, attn, duration = mono_align_and_get_loss(self.aligner, x_align, z.detach(), x_mask, y_mask, attn_priors, x_lengths, y_lengths, g) | |
| # _, _, pred_prosody_codes,_ , _ = self.prosody_encoder(ssl, x_mask, attn, duration) | |
| # return pred_prosody_codes, x, x_mask | |
| # def decode(self,pred_prosody_codes, x, x_lengths, y, y_lengths, noise_scale=.4): | |
| # y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(-1)), 1).to(y.dtype) | |
| # g = self.ref_enc(y * y_mask, y_mask) | |
| # x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(-1)), 1).to(y.dtype) | |
| # x, x_align = self.enc_p(x, x_mask) | |
| # z_q, duration = self.prosody_encoder.decode(pred_prosody_codes, x_mask) | |
| # total_duration = torch.sum(duration, dim=1) | |
| # y_lengths = total_duration.long() | |
| # y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y_lengths.max()), 1).float() | |
| # attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1) | |
| # attn = commons.generate_path(duration.unsqueeze(1), attn_mask) | |
| # x = x + z_q | |
| # frame_x = torch.matmul(attn.squeeze(1), x.transpose(1, 2)).transpose(1, 2) | |
| # m_p, logs_p = self.frame_prior_net(frame_x, y_mask) | |
| # z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale | |
| # z = self.flow(z_p, y_mask, g=g, reverse=True) | |
| # o = self.dec((z * y_mask), g=g) | |
| # return o | |