magvits_data / code /s1 /maskgit_v1.py
arcadiaaaaa
Add files using upload-large-folder tool
11b4f27 verified
Raw History Blame Contribute Delete
6.61 kB
from transformer.transformer import LayerNorm, TransformerEncoder, TransformerEncoderLayer
from transformer.embedding import SinePositionalEmbedding
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
import math
import numpy as np
from tqdm import tqdm
class NARPredictor(nn.Module):
def __init__(self, codebook_size=128):
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=12,
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_emb = nn.Embedding(1024, 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_emb(x)
x = x + bert + g
# 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 = x + quantization_emb
audio_output = self.forward_encoder(inp, mask=x_mask)
x_mask_bool = x_mask.squeeze(1).bool()
tgt_mask = x_mask_bool & mask
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()
return {
'loss': predict_loss,
'acc': acc,
}
@torch.inference_mode()
@torch.no_grad()
def infer(self, x, bert, spk_emb, step=12, sched_mode="square", temp=30, randomize="None", r_temp=30):
g = self.g_emb(spk_emb).unsqueeze(1)
bert = self.bert_proj(bert.transpose(1, 2))
x = self.x_emb(x)
x = x + bert + g
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 = x + quantization_emb
logit = self.forward_encoder(inp)
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)