Download code/s1/trainer.py from rcell233/magvits_data: direct link, hf CLI and curl.
- Browser
- Download file 8.55 kB
-
https://huggingface.co/datasets/rcell233/magvits_data/resolve/main/code/s1/trainer.py
- Command line
-
hf download hf://datasets/rcell233/magvits_data/code/s1/trainer.py
-
curl -L -o trainer.py https://huggingface.co/datasets/rcell233/magvits_data/resolve/main/code/s1/trainer.py
8.55 kB
| 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') | |
| from module.models import SynthesizerTrn | |
| from module.modules import MelStyleEncoder | |
| def init_vits_s2(config_path, cpt_path): | |
| import utils | |
| hps = utils.get_hparams_from_file(config_path) | |
| vits_s2 = SynthesizerTrn( | |
| hps.data.filter_length // 2 + 1, | |
| hps.train.segment_size // hps.data.hop_length, | |
| n_speakers=hps.data.n_speakers, | |
| **hps.model) | |
| ckpt = torch.load(cpt_path, map_location='cpu')['model'] | |
| vits_s2.load_state_dict(ckpt) | |
| vits_s2.eval() | |
| return vits_s2 | |
| import math | |
| import torch.nn.functional as F | |
| 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, uncond, steps, guidance, 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 | |
| v_cond = self.model(x, t_curr_tensor, cond) | |
| v_uncond = self.model(x, t_curr_tensor, uncond) | |
| v = guidance * v_cond + (1 - guidance) * v_uncond | |
| x = x + dt * v | |
| 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.ref_enc = MelStyleEncoder(latent_dim, style_vector_dim=192) | |
| self.null_emb = nn.Parameter(torch.randn(192)) | |
| self.reflow = ReFlow(latent_dim, 192) | |
| def forward(self, x, bert, spk_emb, diffusion_input, mask): | |
| g = self.ref_enc(diffusion_input, mask.float().unsqueeze(1)).transpose(1, 2) | |
| bert = self.bert_proj(bert.transpose(1, 2)) | |
| x = self.x_emb(x.transpose(1,2)) | |
| cond = (x + bert + g).transpose(1, 2) # [B, 192, T] | |
| # dropout prob 0.1 | |
| for b in range(cond.shape[0]): | |
| if torch.rand(1) < 0.1: | |
| cond[b, :, :] = self.null_emb.unsqueeze(1).expand(-1, cond.shape[2]) | |
| loss = self.reflow(diffusion_input, cond, mask) | |
| return loss | |
| def infer(self, x, bert, prompt, step, guidance): | |
| g = self.ref_enc(prompt).transpose(1, 2) | |
| bert = self.bert_proj(bert.transpose(1, 2)) | |
| x = self.x_emb(x.transpose(1,2)) | |
| cond = (x + bert + g).transpose(1, 2) | |
| uncond = self.null_emb.unsqueeze(1).expand(-1, cond.shape[2]).unsqueeze(0) | |
| fakes = self.reflow.sample(cond,uncond, step, guidance) | |
| return fakes | |
| class Wav2TTS(pl.LightningModule): | |
| def __init__(self, hp, vits_s2=None): | |
| super().__init__() | |
| self.model = NARPredictor(latent_dim=4) | |
| self.lr = hp.lr | |
| if vits_s2 is None: | |
| vits_s2 = init_vits_s2('configs/vits.json', 'logs/vits/G_38100.pth') | |
| self.s2 = [vits_s2] | |
| self.inited = False | |
| 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 = 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)).long() # [1,1,1,1,0...] | |
| if not self.inited: | |
| self.s2 = [self.s2[0].to(phone.device)] | |
| self.inited = True | |
| s2 = self.s2[0] | |
| phone_features, _ = s2.enc_p(phone, mask.unsqueeze(1)) | |
| loss = self.model(phone_features, bert_feature, speaker_embedding, latent, mask) | |
| return loss | |
| def inference(self, phonemes, bert_feature, prompt, 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) | |
| mask = torch.ones(phonemes.shape[0],1, phonemes.shape[1]).to(phonemes.device).float() | |
| s2 = self.s2[0] | |
| phone_features, _ = s2.enc_p(phonemes, mask) | |
| output = self.model.infer(phone_features, bert_feature, prompt, n_steps, guidance) | |
| return output |