Download code/module/models_s1_stable.py from rcell233/magvits_data: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/datasets/rcell233/magvits_data/resolve/main/code/module/models_s1_stable.py
- Command line
-
hf download hf://datasets/rcell233/magvits_data/code/module/models_s1_stable.py
-
curl -L -o models_s1_stable.py https://huggingface.co/datasets/rcell233/magvits_data/resolve/main/code/module/models_s1_stable.py
13.1 kB
| from module.wavenet import SinusoidalPosEmb, WaveNet | |
| 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 | |
| from module import commons | |
| from module import modules | |
| import math | |
| import random | |
| from tqdm import tqdm | |
| class NARPredictor(nn.Module): | |
| def __init__(self, codebook_size=128, gin_channels=0): | |
| super().__init__() | |
| norm_first = False | |
| self.encoder = TransformerEncoder( | |
| TransformerEncoderLayer( | |
| d_model=512, | |
| nhead=16, | |
| dim_feedforward=2048, | |
| dropout=0.1, | |
| batch_first=True, | |
| norm_first=False, ), | |
| num_layers=6, | |
| norm=LayerNorm(512) if norm_first else None, ) | |
| self.num_head = 16 | |
| self.position = SinePositionalEmbedding( | |
| 512, dropout=0.1, scale=False, alpha=True) | |
| self.bert_proj = nn.Linear(1024, 512) | |
| self.x_proj = nn.Linear(192, 512) | |
| self.g_emb = nn.Linear(256, 512) | |
| self.proj = nn.Linear(512, codebook_size, bias=False) | |
| self.quantize_embedding = nn.Embedding(codebook_size + 1, 512) | |
| self.n_codes = codebook_size | |
| def forward_encoder(self, x, mask=None): | |
| if mask is not None: | |
| mask = ~mask.squeeze(1).bool() | |
| x = self.position(x) | |
| x, _ = self.encoder( | |
| (x, None), src_key_padding_mask=mask) | |
| audio_output = self.proj(x) | |
| return audio_output | |
| def forward(self, x, x_mask, bert, spk_emb, tgt_code): | |
| g = self.g_emb(spk_emb).unsqueeze(1) | |
| bert = self.bert_proj(bert.transpose(1, 2)) | |
| x = self.x_proj(x.transpose(1, 2)) | |
| cond = x + bert + g | |
| cfg_dropout_prob = 0.1 | |
| null_embed = torch.zeros_like(cond, device=cond.device) | |
| dropout_mask = torch.bernoulli(torch.full((cond.shape[0], 1, 1), cfg_dropout_prob, device=cond.device)).to(torch.bool) | |
| cond = torch.where(dropout_mask, null_embed, cond) | |
| # make mask | |
| quantization = tgt_code.clone() | |
| mask_ratio = random.uniform(0, 1) | |
| mask = torch.bernoulli(mask_ratio * torch.ones_like(quantization)).bool() | |
| quantization[mask] = self.n_codes | |
| quantization_emb = self.quantize_embedding(quantization) | |
| inp = cond + quantization_emb | |
| audio_output = self.forward_encoder(inp, mask=x_mask) | |
| tgt_mask = x_mask.squeeze(1).bool() | |
| audio_output = audio_output[tgt_mask] | |
| tgt_code = tgt_code[tgt_mask].view(-1) | |
| predict_loss = F.cross_entropy(audio_output, tgt_code, reduction='mean') | |
| acc = (audio_output.argmax(-1) == tgt_code).float().mean() * 100 | |
| print('prosody acc', acc.item()) | |
| return predict_loss | |
| def infer(self, x, x_mask, bert, spk_emb, step=5, sched_mode="square", temp=30, randomize="None", r_temp=30, cfg_scale=1.5): | |
| g = self.g_emb(spk_emb).unsqueeze(1) | |
| bert = self.bert_proj(bert.transpose(1, 2)) | |
| x = self.x_proj(x.transpose(1, 2)) | |
| cond = x + bert + g | |
| uncond = torch.zeros_like(cond) | |
| nb_sample = x.size(0) | |
| tgt_length = x.size(1) | |
| code = torch.full((nb_sample, tgt_length), self.n_codes).long().to(x.device) | |
| mask = torch.ones((nb_sample, tgt_length)).to(x.device) | |
| scheduler = self.adap_sche(step, mode=sched_mode, tgt_length=tgt_length) | |
| for indice, t in enumerate(scheduler): | |
| # print('step:', indice, '\nmask:', mask, '\nt:', t, '\ncode', code, '\n\n') | |
| if mask.sum() < t: # Cannot predict more token than 16*16 or 32*32 | |
| t = int(mask.sum().item()) | |
| print(f"Warning: cannot predict {t} tokens, only {mask.sum().item()} tokens left") | |
| if mask.sum() == 0: # Break if code is fully predicted | |
| break | |
| quantization_emb = self.quantize_embedding(code.clone()) | |
| inp = cond + quantization_emb | |
| logit = self.forward_encoder(inp) | |
| inp_uncond = uncond + quantization_emb | |
| logit_uncond = self.forward_encoder(inp_uncond) | |
| logit = cfg_scale * logit + (1 - cfg_scale) * logit_uncond | |
| prob = torch.softmax(logit * temp, -1) | |
| distri = torch.distributions.Categorical(probs=prob) | |
| pred_code = distri.sample() | |
| conf = torch.gather(prob, 2, pred_code.view(nb_sample, tgt_length, 1)) | |
| if randomize == "linear": # add gumbel noise decreasing over the sampling process | |
| ratio = (indice / (len(scheduler) - 1)) | |
| rand = r_temp * np.random.gumbel(size=(nb_sample, tgt_length)) * (1 - ratio) | |
| conf = torch.log(conf.squeeze()) + torch.from_numpy(rand).to(x.device) | |
| elif randomize == "warm_up": # chose random sample for the 2 first steps | |
| conf = torch.rand_like(conf) if indice < 2 else conf | |
| elif randomize == "random": # chose random prediction at each step | |
| conf = torch.rand_like(conf) | |
| # do not predict on already predicted tokens | |
| conf[~mask.bool()] = -math.inf | |
| # chose the predicted token with the highest confidence | |
| tresh_conf, indice_mask = torch.topk(conf.view(nb_sample, -1), k=t, dim=-1) | |
| tresh_conf = tresh_conf[:, -1] | |
| # replace the chosen tokens | |
| conf = (conf >= tresh_conf.unsqueeze(-1)).view(nb_sample, tgt_length) | |
| f_mask = (mask.float() * conf.float()).bool() | |
| code[f_mask] = pred_code[f_mask] | |
| # update the mask | |
| for i_mask, ind_mask in enumerate(indice_mask): | |
| mask[i_mask, ind_mask] = 0 | |
| return code | |
| def adap_sche(self, step, mode="arccos", leave=False, tgt_length=None): | |
| """ Create a sampling scheduler | |
| :param | |
| step -> int: number of prediction during inference | |
| mode -> str: the rate of value to unmask | |
| leave -> bool: tqdm arg on either to keep the bar or not | |
| :return | |
| scheduler -> torch.LongTensor(): the list of token to predict at each step | |
| """ | |
| r = torch.linspace(1, 0, step) | |
| if mode == "root": # root scheduler | |
| val_to_mask = 1 - (r ** .5) | |
| elif mode == "linear": # linear scheduler | |
| val_to_mask = 1 - r | |
| elif mode == "square": # square scheduler | |
| val_to_mask = 1 - (r ** 2) | |
| elif mode == "cosine": # cosine scheduler | |
| val_to_mask = torch.cos(r * math.pi * 0.5) | |
| elif mode == "arccos": # arc cosine scheduler | |
| val_to_mask = torch.arccos(r) / (math.pi * 0.5) | |
| else: | |
| return | |
| # fill the scheduler by the ratio of tokens to predict at each step | |
| sche = (val_to_mask / val_to_mask.sum()) * tgt_length | |
| sche = sche.round() | |
| sche[sche == 0] = 1 # add 1 to predict a least 1 token / step | |
| sche[-1] += tgt_length - sche.sum() # need to sum up nb of code | |
| return tqdm(sche.int(), leave=leave) | |
| 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.frame_prior_net = FramePriorNet(inter_channels, | |
| hidden_channels, | |
| filter_channels, | |
| n_heads, | |
| n_layers, | |
| kernel_size, | |
| p_dropout) | |
| 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) | |
| vq_dim = 512 | |
| self.prosody_encoder = ProsodyEncoder(768, hidden_channels, 5, 1, 6, gin_channels, vq_dim) | |
| self.prosody_predictor = NARPredictor(vq_dim, gin_channels=gin_channels) | |
| def forward(self, x, x_lengths, y, y_lengths, ssl, duration, bert, spk_emb, prosody_predict_only=False): | |
| y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y.size(-1)), 1).to(y.dtype) | |
| text_long = x.clone() | |
| 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) | |
| attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1) | |
| attn = commons.generate_path(duration.unsqueeze(1), attn_mask) | |
| v_mask = (x > 0).float() | |
| z_q, quantize_loss, indices, dur_loss, pred_dur = self.prosody_encoder(ssl, x_mask, attn, duration, v_mask) | |
| x = self.enc_p(x, x_mask, bert) | |
| prosody_predict_loss = self.prosody_predictor(x, x_mask, bert, spk_emb, indices) | |
| return prosody_predict_loss, indices | |
| def reconstruct(self, x, x_lengths, y, y_lengths, ssl, duration, 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) | |
| # attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1) | |
| # attn = commons.generate_path(duration.unsqueeze(1), attn_mask) | |
| # v_mask = (x > 0).float() | |
| # _, _, pred_prosody_codes, _, _ = self.prosody_encoder(ssl, x_mask, attn, duration,v_mask) | |
| x = self.enc_p(x, x_mask, bert) | |
| pred_prosody_codes = self.prosody_predictor.infer(x, x_mask, bert, spk_emb) | |
| 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, attn, y_mask, (z, z_p, m_p, logs_p) | |