https://huggingface.co/Dionyssos/_TTS075B
Browse files
tts.py
CHANGED
|
@@ -1,847 +1,740 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import
|
| 3 |
-
nltk.download('punkt', download_dir='./') # COMMENT IF DOWNLOADED
|
| 4 |
-
nltk.download('punkt_tab', download_dir='./') # COMMENT IF DOWNLOADED
|
| 5 |
-
nltk.data.path.append('.')
|
| 6 |
-
import librosa
|
| 7 |
-
import audiofile
|
| 8 |
import torch.nn.functional as F
|
| 9 |
-
import
|
| 10 |
-
import numpy as np
|
| 11 |
-
import torch.nn as nn
|
| 12 |
-
import string
|
| 13 |
-
import textwrap
|
| 14 |
-
import phonemizer
|
| 15 |
-
from espeak_util import set_espeak_library
|
| 16 |
-
from transformers import AlbertConfig, AlbertModel
|
| 17 |
from huggingface_hub import hf_hub_download
|
| 18 |
-
|
| 19 |
-
from
|
| 20 |
-
from torch.nn.utils.parametrizations import weight_norm
|
| 21 |
-
from torch.nn.utils import spectral_norm
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
_letters_ipa = "ɑɐɒæɓʙβɔɕçɗɖðʤəɘɚɛɜɝɞɟʄɡɠɢʛɦɧħɥʜɨɪʝɭɬɫɮʟɱɯɰŋɳɲɴøɵɸθœɶʘɹɺɾɻʀʁɽʂʃʈʧʉʊʋⱱʌɣɤʍχʎʏʑʐʒʔʡʕʢǀǁǂǃˈˌːˑʼʴʰʱʲʷˠˤ˞↓↑→↗↘'̩'ᵻ"
|
| 27 |
-
MAX_PHONEMES = 424 # For OOM is the max length of single (non-split) sentence for StyleTTS2 inference
|
| 28 |
|
| 29 |
-
symbols = [_pad] + list(_punctuation) + list(_letters) + list(_letters_ipa)
|
| 30 |
|
| 31 |
-
dicts = {}
|
| 32 |
-
for i in range(len((symbols))):
|
| 33 |
-
dicts[symbols[i]] = i
|
| 34 |
|
|
|
|
| 35 |
|
| 36 |
-
|
| 37 |
-
def __init__(self, dummy=None):
|
| 38 |
-
self.word_index_dictionary = dicts
|
| 39 |
-
print(len(dicts))
|
| 40 |
-
|
| 41 |
-
def __call__(self, text):
|
| 42 |
-
indexes = []
|
| 43 |
-
for char in text:
|
| 44 |
-
try:
|
| 45 |
-
indexes.append(self.word_index_dictionary[char])
|
| 46 |
-
except KeyError:
|
| 47 |
-
# `=NONVOCAL == \x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f
|
| 48 |
-
# print(f'NonVOCAL {char}', end='\r')
|
| 49 |
-
pass
|
| 50 |
-
return indexes
|
| 51 |
-
|
| 52 |
-
set_espeak_library()
|
| 53 |
-
|
| 54 |
-
textclenaer = TextCleaner()
|
| 55 |
-
|
| 56 |
-
global_phonemizer = phonemizer.backend.EspeakBackend(language="en-us", preserve_punctuation=True, with_stress=True)
|
| 57 |
-
|
| 58 |
-
def _del_prefix(d):
|
| 59 |
-
# del ".module"
|
| 60 |
-
out = {}
|
| 61 |
-
for k, v in d.items():
|
| 62 |
-
out[k[7:]] = v
|
| 63 |
-
return out
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
class StyleTTS2(nn.Module):
|
| 69 |
-
|
| 70 |
-
def __init__(self):
|
| 71 |
super().__init__()
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
intermediate_size=2048,
|
| 76 |
-
max_position_embeddings=512,
|
| 77 |
-
num_hidden_layers=12,
|
| 78 |
-
dropout=0.1)
|
| 79 |
-
self.bert = AlbertModel(albert_base_configuration)
|
| 80 |
-
state_dict = torch.load(hf_hub_download(repo_id='dkounadis/artificial-styletts2',
|
| 81 |
-
filename='Utils/PLBERT/step_1000000.pth'),
|
| 82 |
-
map_location='cpu')['net']
|
| 83 |
-
new_state_dict = {}
|
| 84 |
-
for k, v in state_dict.items():
|
| 85 |
-
name = k[7:] # remove `module.`
|
| 86 |
-
if name.startswith('encoder.'):
|
| 87 |
-
name = name[8:] # remove `encoder.`
|
| 88 |
-
new_state_dict[name] = v
|
| 89 |
-
del new_state_dict["embeddings.position_ids"]
|
| 90 |
-
self.bert.load_state_dict(new_state_dict, strict=True)
|
| 91 |
-
self.decoder = Decoder(dim_in=512,
|
| 92 |
-
style_dim=128,
|
| 93 |
-
dim_out=80, # n_mels
|
| 94 |
-
resblock_kernel_sizes=[3, 7, 11],
|
| 95 |
-
upsample_rates=[10, 5, 3, 2],
|
| 96 |
-
upsample_initial_channel=512,
|
| 97 |
-
resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],
|
| 98 |
-
upsample_kernel_sizes=[20, 10, 6, 4])
|
| 99 |
-
self.text_encoder = TextEncoder(channels=512,
|
| 100 |
-
kernel_size=5,
|
| 101 |
-
depth=3, # args['model_params']['n_layer'],
|
| 102 |
-
n_symbols=178, # args['model_params']['n_token']
|
| 103 |
-
)
|
| 104 |
-
self.predictor = ProsodyPredictor(style_dim=128,
|
| 105 |
-
d_hid=512,
|
| 106 |
-
nlayers=3, # OFFICIAL config.nlayers=5;
|
| 107 |
-
max_dur=50)
|
| 108 |
-
self.style_encoder = StyleEncoder()
|
| 109 |
-
self.predictor_encoder = StyleEncoder()
|
| 110 |
-
self.bert_encoder = torch.nn.Linear(self.bert.config.hidden_size, 512)
|
| 111 |
-
self.mel_spec = MelSpec()
|
| 112 |
-
params = torch.load(hf_hub_download(repo_id='yl4579/StyleTTS2-LibriTTS',
|
| 113 |
-
filename='Models/LibriTTS/epochs_2nd_00020.pth'),
|
| 114 |
-
map_location='cpu')['net']
|
| 115 |
-
self.bert.load_state_dict(_del_prefix(params['bert']), strict=True)
|
| 116 |
-
self.bert_encoder.load_state_dict(_del_prefix(params['bert_encoder']), strict=True)
|
| 117 |
-
self.predictor.load_state_dict(_del_prefix(params['predictor']), strict=True)
|
| 118 |
-
self.decoder.load_state_dict(_del_prefix(params['decoder']), strict=True)
|
| 119 |
-
self.text_encoder.load_state_dict(_del_prefix(params['text_encoder']), strict=True)
|
| 120 |
-
self.predictor_encoder.load_state_dict(_del_prefix(params['predictor_encoder']), strict=True)
|
| 121 |
-
self.style_encoder.load_state_dict(_del_prefix(params['style_encoder']), strict=True)
|
| 122 |
-
|
| 123 |
-
# FOR LSTM
|
| 124 |
-
for n, p in self.named_parameters():
|
| 125 |
-
p.requires_grad = False
|
| 126 |
-
self.eval()
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
def device(self):
|
| 130 |
-
return self.style_encoder.unshared.weight.device
|
| 131 |
-
|
| 132 |
-
def compute_style(self, wav_file=None):
|
| 133 |
-
|
| 134 |
-
x, sr = librosa.load(wav_file, sr=24000)
|
| 135 |
-
x, _ = librosa.effects.trim(x, top_db=30)
|
| 136 |
-
if sr != 24000:
|
| 137 |
-
x = librosa.resample(x, sr, 24000)
|
| 138 |
-
# LOGMEL - Has 16KHz default basisc - Called on 24KHz .wav
|
| 139 |
-
x = torch.from_numpy(x[None, :]).to(device=self.device(),
|
| 140 |
-
dtype=torch.float)
|
| 141 |
-
mel_tensor = (torch.log(1e-5 + self.mel_spec(x)) + 4) / 4
|
| 142 |
-
#mel_tensor = preprocess(audio).to(device)
|
| 143 |
-
ref_s = self.style_encoder(mel_tensor)
|
| 144 |
-
ref_p = self.predictor_encoder(mel_tensor) # [bs, 11, 1, 128]
|
| 145 |
-
s = torch.cat([ref_s, ref_p], dim=3) # [bs, 11, 1, 256]
|
| 146 |
-
s = s[:, :, 0, :].transpose(1, 2) # [1, 128, 11]
|
| 147 |
-
return s # [1, 128, 11]
|
| 148 |
-
|
| 149 |
-
def inference(self,
|
| 150 |
-
text,
|
| 151 |
-
ref_s=None):
|
| 152 |
-
'''text may become too long when phonemized'''
|
| 153 |
-
|
| 154 |
-
if isinstance(ref_s, str):
|
| 155 |
-
ref_s = self.compute_style(ref_s)
|
| 156 |
-
else:
|
| 157 |
-
pass # assume ref_s = precomputed style vector
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
# text = transliterate_number(text, lang='en').strip()
|
| 161 |
-
# as we are in english transliteration is already done by the text cleaner?
|
| 162 |
-
# somehow we have phonemes in text that try to be rephonemized
|
| 163 |
-
# The ds txt should be only ascii
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
if isinstance(text, str):
|
| 167 |
-
|
| 168 |
-
_translator = str.maketrans('', '', string.punctuation)
|
| 169 |
-
|
| 170 |
-
text = [sub_sent.translate(_translator) + '.' for sub_sent in textwrap.wrap(text, 74)]
|
| 171 |
-
|
| 172 |
-
# # text = nltk.sent_tokenize(text)
|
| 173 |
-
# # text = [i for sent in sentences for i in textwrap.wrap(sent, width=120)]
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
# # text = textwrap.wrap(text, width=MAX_PHONEMES) # phonemes thus sent_tokenize() can't split them in sentences
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
device = ref_s.device
|
| 180 |
-
total = []
|
| 181 |
-
for _t in text:
|
| 182 |
-
|
| 183 |
-
_t = global_phonemizer.phonemize([_t])
|
| 184 |
-
_t = word_tokenize(_t[0])
|
| 185 |
-
_t = ' '.join(_t)
|
| 186 |
-
|
| 187 |
-
tokens = textclenaer(_t)[:MAX_PHONEMES] + [4] # textclenaer('.;?!') = [4,1,6,5] # append . punctuation to assure proper sound termination (pulse Issue)
|
| 188 |
-
|
| 189 |
-
# After filter we should assure is terminating as a sentence
|
| 190 |
-
# print(len(_t), len(tokens), 'Msi')#, textclenaer('.;?!'))
|
| 191 |
-
# ================================= Delete Phonemes If len(phonemes) > len(text) === OOM during training
|
| 192 |
-
tokens.insert(0, 0)
|
| 193 |
-
tokens = torch.LongTensor(tokens).to(device).unsqueeze(0)
|
| 194 |
-
with torch.no_grad():
|
| 195 |
-
hidden_states = self.text_encoder(tokens)
|
| 196 |
-
bert_dur = self.bert(tokens, attention_mask=torch.ones_like(tokens)
|
| 197 |
-
).last_hidden_state
|
| 198 |
-
d_en = self.bert_encoder(bert_dur).transpose(-1, -2)
|
| 199 |
-
aln_trg, F0_pred, N_pred = self.predictor(d_en=d_en, s=ref_s[:, 128:, :])
|
| 200 |
-
asr = torch.bmm(aln_trg, hidden_states)
|
| 201 |
-
asr = asr.transpose(1, 2)
|
| 202 |
-
asr_new = torch.zeros_like(asr)
|
| 203 |
-
asr_new[:, :, 0] = asr[:, :, 0]
|
| 204 |
-
asr_new[:, :, 1:] = asr[:, :, 0:-1]
|
| 205 |
-
asr = asr_new
|
| 206 |
-
x = self.decoder(asr=asr,
|
| 207 |
-
F0_curve=F0_pred,
|
| 208 |
-
N=N_pred,
|
| 209 |
-
s=ref_s[:, :128, :]) # different part of ref_s
|
| 210 |
-
# print(x.shape, 'TTS TTS TTS TTS')
|
| 211 |
-
if x.shape[2] < 100:
|
| 212 |
-
x = torch.zeros(1, 1, 1000, device=self.device()) # silence if this sentence was empty
|
| 213 |
-
|
| 214 |
-
# NORMALIS / Crop Scratch at end (The endingscratch sound is not solved even with nltk.sentence split & punctuation)
|
| 215 |
-
x = x[..., 40:-4000]
|
| 216 |
-
# x /= x.abs().max() + 1e-7 # preserve as torch
|
| 217 |
-
# return x
|
| 218 |
-
if x.shape[2] == 0:
|
| 219 |
-
# nohing to vocode
|
| 220 |
-
x = torch.zeros(1, 1, 1000, device=self.device())
|
| 221 |
-
total.append(x)
|
| 222 |
-
|
| 223 |
-
# --
|
| 224 |
-
total = 1.94 * torch.cat(total, 2) # 1.94 * Perhaps exceeding -1,1 affects MIMI encode
|
| 225 |
-
total /= 1.02 * total.abs().max() + 1e-7
|
| 226 |
-
# --
|
| 227 |
-
return total
|
| 228 |
-
|
| 229 |
-
|
| 230 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
|
| 232 |
-
def get_padding(kernel_size, dilation=1):
|
| 233 |
-
return int((kernel_size*dilation - dilation)/2)
|
| 234 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
return x
|
| 240 |
|
|
|
|
| 241 |
|
| 242 |
-
|
|
|
|
| 243 |
|
| 244 |
-
|
|
|
|
| 245 |
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
def forward(self, x, s):
|
| 252 |
-
|
| 253 |
-
# x = torch.Size([1, 512, 248]) same as output
|
| 254 |
-
# s = torch.Size([1, 7, 1, 128])
|
| 255 |
-
|
| 256 |
-
s = self.fc(s.transpose(1, 2)).transpose(1, 2)
|
| 257 |
-
|
| 258 |
-
s = _tile(s, length=x.shape[2])
|
| 259 |
-
|
| 260 |
-
gamma, beta = torch.chunk(s, chunks=2, dim=1)
|
| 261 |
-
return (1+gamma) * self.norm(x) + beta
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
class AdaINResBlock1(torch.nn.Module):
|
| 265 |
-
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5), style_dim=64):
|
| 266 |
-
super(AdaINResBlock1, self).__init__()
|
| 267 |
-
self.convs1 = nn.ModuleList([
|
| 268 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
|
| 269 |
-
padding=get_padding(kernel_size, dilation[0]))),
|
| 270 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
|
| 271 |
-
padding=get_padding(kernel_size, dilation[1]))),
|
| 272 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
|
| 273 |
-
padding=get_padding(kernel_size, dilation[2])))
|
| 274 |
-
])
|
| 275 |
-
# self.convs1.apply(init_weights)
|
| 276 |
-
|
| 277 |
-
self.convs2 = nn.ModuleList([
|
| 278 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
| 279 |
-
padding=get_padding(kernel_size, 1))),
|
| 280 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
| 281 |
-
padding=get_padding(kernel_size, 1))),
|
| 282 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
| 283 |
-
padding=get_padding(kernel_size, 1)))
|
| 284 |
-
])
|
| 285 |
-
# self.convs2.apply(init_weights)
|
| 286 |
-
|
| 287 |
-
self.adain1 = nn.ModuleList([
|
| 288 |
-
AdaIN1d(style_dim, channels),
|
| 289 |
-
AdaIN1d(style_dim, channels),
|
| 290 |
-
AdaIN1d(style_dim, channels),
|
| 291 |
-
])
|
| 292 |
-
|
| 293 |
-
self.adain2 = nn.ModuleList([
|
| 294 |
-
AdaIN1d(style_dim, channels),
|
| 295 |
-
AdaIN1d(style_dim, channels),
|
| 296 |
-
AdaIN1d(style_dim, channels),
|
| 297 |
-
])
|
| 298 |
-
|
| 299 |
-
self.alpha1 = nn.ParameterList(
|
| 300 |
-
[nn.Parameter(torch.ones(1, channels, 1)) for i in range(len(self.convs1))])
|
| 301 |
-
self.alpha2 = nn.ParameterList(
|
| 302 |
-
[nn.Parameter(torch.ones(1, channels, 1)) for i in range(len(self.convs2))])
|
| 303 |
-
|
| 304 |
-
def forward(self, x, s):
|
| 305 |
-
for c1, c2, n1, n2, a1, a2 in zip(self.convs1, self.convs2, self.adain1, self.adain2, self.alpha1, self.alpha2):
|
| 306 |
-
xt = n1(x, s) # THIS IS ADAIN - EXPECTS conv1d dims
|
| 307 |
-
xt = xt + (1 / a1) * (torch.sin(a1 * xt) ** 2) # Snake1D
|
| 308 |
-
xt = c1(xt)
|
| 309 |
-
xt = n2(xt, s) # THIS IS ADAIN - EXPECTS conv1d dims
|
| 310 |
-
xt = xt + (1 / a2) * (torch.sin(a2 * xt) ** 2) # Snake1D
|
| 311 |
-
xt = c2(xt)
|
| 312 |
-
x = xt + x
|
| 313 |
-
return x
|
| 314 |
|
|
|
|
|
|
|
| 315 |
|
| 316 |
-
|
| 317 |
|
| 318 |
-
def __init__(self):
|
| 319 |
|
|
|
|
|
|
|
| 320 |
super().__init__()
|
| 321 |
-
self.
|
| 322 |
-
self.l_linear = torch.nn.Linear(self.harmonic_num + 1, 1)
|
| 323 |
-
self.upsample_scale = 300
|
| 324 |
-
|
| 325 |
|
| 326 |
def forward(self, x):
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
# modulo of negative f0_values => -21 % 10 = 9 as -3*10 + 9 = 21 NOTICE THAT f0_values IS SIGNED
|
| 332 |
-
rad_values = x / 25647 #).clamp(0, 1)
|
| 333 |
-
# rad_values = torch.where(torch.logical_or(rad_values < 0, rad_values > 1), 0.5, rad_values)
|
| 334 |
-
rad_values = rad_values % 1 # % of neg values
|
| 335 |
-
rad_values = F.interpolate(rad_values.transpose(1, 2),
|
| 336 |
-
scale_factor=1/self.upsample_scale,
|
| 337 |
-
mode='linear').transpose(1, 2)
|
| 338 |
-
|
| 339 |
-
# 1.89 sounds also nice has woofer at punctuation
|
| 340 |
-
phase = torch.cumsum(rad_values, dim=1) * 1.84 * np.pi
|
| 341 |
-
phase = F.interpolate(phase.transpose(1, 2) * self.upsample_scale,
|
| 342 |
-
scale_factor=self.upsample_scale, mode='linear').transpose(1, 2)
|
| 343 |
-
x = .009 * phase.sin()
|
| 344 |
-
# --
|
| 345 |
-
x = self.l_linear(x).tanh()
|
| 346 |
-
return x
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
class Generator(torch.nn.Module):
|
| 350 |
-
def __init__(self,
|
| 351 |
-
style_dim,
|
| 352 |
-
resblock_kernel_sizes,
|
| 353 |
-
upsample_rates,
|
| 354 |
-
upsample_initial_channel,
|
| 355 |
-
resblock_dilation_sizes,
|
| 356 |
-
upsample_kernel_sizes):
|
| 357 |
-
super(Generator, self).__init__()
|
| 358 |
-
self.num_kernels = len(resblock_kernel_sizes)
|
| 359 |
-
self.num_upsamples = len(upsample_rates)
|
| 360 |
-
self.m_source = SourceModuleHnNSF()
|
| 361 |
-
self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates))
|
| 362 |
-
self.noise_convs = nn.ModuleList()
|
| 363 |
-
self.ups = nn.ModuleList()
|
| 364 |
-
self.noise_res = nn.ModuleList()
|
| 365 |
-
|
| 366 |
-
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
| 367 |
-
c_cur = upsample_initial_channel // (2 ** (i + 1))
|
| 368 |
-
|
| 369 |
-
self.ups.append(weight_norm(ConvTranspose1d(upsample_initial_channel//(2**i),
|
| 370 |
-
upsample_initial_channel//(
|
| 371 |
-
2**(i+1)),
|
| 372 |
-
k, u, padding=(u//2 + u % 2), output_padding=u % 2)))
|
| 373 |
-
|
| 374 |
-
if i + 1 < len(upsample_rates):
|
| 375 |
-
stride_f0 = np.prod(upsample_rates[i + 1:])
|
| 376 |
-
self.noise_convs.append(Conv1d(
|
| 377 |
-
1, c_cur, kernel_size=stride_f0 * 2, stride=stride_f0, padding=(stride_f0+1) // 2))
|
| 378 |
-
self.noise_res.append(AdaINResBlock1(
|
| 379 |
-
c_cur, 7, [1, 3, 5], style_dim))
|
| 380 |
-
else:
|
| 381 |
-
self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1))
|
| 382 |
-
self.noise_res.append(AdaINResBlock1(
|
| 383 |
-
c_cur, 11, [1, 3, 5], style_dim))
|
| 384 |
-
|
| 385 |
-
self.resblocks = nn.ModuleList()
|
| 386 |
|
| 387 |
-
self.alphas = nn.ParameterList()
|
| 388 |
-
self.alphas.append(nn.Parameter(
|
| 389 |
-
torch.ones(1, upsample_initial_channel, 1)))
|
| 390 |
|
| 391 |
-
|
| 392 |
-
ch = upsample_initial_channel//(2**(i+1))
|
| 393 |
-
self.alphas.append(nn.Parameter(torch.ones(1, ch, 1)))
|
| 394 |
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
|
| 400 |
-
def forward(self,
|
| 401 |
|
| 402 |
-
|
| 403 |
-
f0 = self.f0_upsamp(f0).transpose(1, 2)
|
| 404 |
|
| 405 |
-
|
|
|
|
|
|
|
|
|
|
| 406 |
|
| 407 |
-
|
| 408 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 409 |
|
| 410 |
-
har_source = har_source.transpose(1, 2)
|
| 411 |
|
| 412 |
-
|
| 413 |
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 417 |
|
| 418 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
|
| 420 |
-
x = x + x_source
|
| 421 |
|
| 422 |
-
|
| 423 |
-
for j in range(self.num_kernels):
|
| 424 |
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
|
|
|
|
|
|
| 433 |
|
|
|
|
|
|
|
|
|
|
| 434 |
return x
|
| 435 |
|
| 436 |
-
class AdainResBlk1d(nn.Module):
|
| 437 |
-
|
| 438 |
-
# also used in ProsodyPredictor()
|
| 439 |
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
self.
|
| 448 |
-
|
| 449 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 450 |
else:
|
| 451 |
-
self.
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
x = self.actv(x)
|
| 472 |
-
x = self.pool(x)
|
| 473 |
-
x = self.conv1(x)
|
| 474 |
-
x = self.norm2(x, s)
|
| 475 |
-
x = self.actv(x)
|
| 476 |
-
x = self.conv2(x)
|
| 477 |
-
return x
|
| 478 |
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 483 |
|
|
|
|
| 484 |
|
| 485 |
-
|
| 486 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 487 |
super().__init__()
|
| 488 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
|
| 490 |
def forward(self, x):
|
| 491 |
-
|
| 492 |
-
return x
|
| 493 |
-
else:
|
| 494 |
-
return F.interpolate(x, scale_factor=2, mode='nearest-exact')
|
| 495 |
-
|
| 496 |
|
| 497 |
-
class Decoder(nn.Module):
|
| 498 |
-
def __init__(self, dim_in=512, F0_channel=512, style_dim=64, dim_out=80,
|
| 499 |
-
resblock_kernel_sizes=[3, 7, 11],
|
| 500 |
-
upsample_rates=[10, 5, 3, 2],
|
| 501 |
-
upsample_initial_channel=512,
|
| 502 |
-
resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],
|
| 503 |
-
upsample_kernel_sizes=[20, 10, 6, 4]):
|
| 504 |
-
super().__init__()
|
| 505 |
|
| 506 |
-
|
| 507 |
|
| 508 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 509 |
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 515 |
|
| 516 |
-
|
| 517 |
-
|
| 518 |
|
| 519 |
-
self.N_conv = weight_norm(
|
| 520 |
-
nn.Conv1d(1, 1, kernel_size=3, stride=2, groups=1, padding=1))
|
| 521 |
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
|
|
|
|
|
|
|
|
|
| 525 |
|
| 526 |
-
|
| 527 |
-
|
| 528 |
|
| 529 |
-
|
| 530 |
|
|
|
|
| 531 |
|
| 532 |
-
|
| 533 |
-
N = self.N_conv(N)
|
| 534 |
|
|
|
|
| 535 |
|
| 536 |
-
|
|
|
|
| 537 |
|
| 538 |
-
|
| 539 |
|
| 540 |
-
|
|
|
|
| 541 |
|
| 542 |
-
|
| 543 |
-
for block in self.decode:
|
| 544 |
-
if res:
|
| 545 |
|
| 546 |
-
|
|
|
|
| 547 |
|
| 548 |
-
|
| 549 |
-
if block.upsample_type != "none":
|
| 550 |
-
res = False
|
| 551 |
|
| 552 |
-
|
| 553 |
-
|
| 554 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 555 |
|
| 556 |
-
class MelSpec(torch.nn.Module):
|
| 557 |
|
|
|
|
|
|
|
|
|
|
| 558 |
def __init__(self,
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
):
|
| 565 |
-
'''avoids dependency on torchaudio'''
|
| 566 |
-
super().__init__()
|
| 567 |
-
self.n_fft = n_fft
|
| 568 |
-
self.win_length = win_length if win_length is not None else n_fft
|
| 569 |
-
self.hop_length = hop_length if hop_length is not None else self.win_length // 2
|
| 570 |
-
# --
|
| 571 |
-
f_min = 0.0
|
| 572 |
-
f_max = float(sample_rate // 2)
|
| 573 |
-
all_freqs = torch.linspace(0, sample_rate // 2, n_fft//2+1)
|
| 574 |
-
m_min = 2595.0 * math.log10(1.0 + (f_min / 700.0))
|
| 575 |
-
m_max = 2595.0 * math.log10(1.0 + (f_max / 700.0))
|
| 576 |
-
m_pts = torch.linspace(m_min, m_max, n_mels + 2)
|
| 577 |
-
f_pts = 700.0 * (10 ** (m_pts / 2595.0) - 1.0)
|
| 578 |
-
f_diff = f_pts[1:] - f_pts[:-1] # (n_mels + 1)
|
| 579 |
-
slopes = f_pts.unsqueeze(0) - all_freqs.unsqueeze(1)
|
| 580 |
-
zero = torch.zeros(1)
|
| 581 |
-
down_slopes = (-1.0 * slopes[:, :-2]) / f_diff[:-1] # (n_freqs, n_mels)
|
| 582 |
-
up_slopes = slopes[:, 2:] / f_diff[1:] # (n_freqs, n_mels)
|
| 583 |
-
fb = torch.max(zero, torch.min(down_slopes, up_slopes))
|
| 584 |
-
# --
|
| 585 |
-
self.register_buffer('fb', fb, persistent=False)
|
| 586 |
-
window = torch.hann_window(self.win_length)
|
| 587 |
-
self.register_buffer('window', window, persistent=False)
|
| 588 |
-
|
| 589 |
-
def forward(self, x):
|
| 590 |
-
spec_f = torch.stft(x,
|
| 591 |
-
self.n_fft,
|
| 592 |
-
self.hop_length,
|
| 593 |
-
self.win_length,
|
| 594 |
-
self.window,
|
| 595 |
-
center=True,
|
| 596 |
-
pad_mode="reflect",
|
| 597 |
-
normalized=False,
|
| 598 |
-
onesided=True,
|
| 599 |
-
return_complex=True) # [bs, 1025, 56]
|
| 600 |
-
mel_specgram = torch.matmul(spec_f.abs().pow(2).transpose(1, 2), self.fb).transpose(1, 2)
|
| 601 |
-
return mel_specgram[:, None, :, :] # [bs, 1, 80, time]
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
class LearnedDownSample(nn.Module):
|
| 605 |
-
def __init__(self, dim_in):
|
| 606 |
-
super().__init__()
|
| 607 |
-
self.conv = spectral_norm(nn.Conv2d(dim_in, dim_in, kernel_size=(
|
| 608 |
-
3, 3), stride=(2, 2), groups=dim_in, padding=1))
|
| 609 |
|
| 610 |
def forward(self, x):
|
| 611 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 612 |
|
| 613 |
|
| 614 |
-
class
|
| 615 |
-
def __init__(self,
|
| 616 |
-
dim_in, dim_out):
|
| 617 |
super().__init__()
|
| 618 |
-
self.
|
| 619 |
-
self.downsample_res = LearnedDownSample(dim_in)
|
| 620 |
-
self.learned_sc = dim_in != dim_out
|
| 621 |
-
self.conv1 = spectral_norm(nn.Conv2d(dim_in, dim_in, 3, 1, 1))
|
| 622 |
-
self.conv2 = spectral_norm(nn.Conv2d(dim_in, dim_out, 3, 1, 1))
|
| 623 |
-
if self.learned_sc:
|
| 624 |
-
self.conv1x1 = spectral_norm(
|
| 625 |
-
nn.Conv2d(dim_in, dim_out, 1, 1, 0, bias=False))
|
| 626 |
-
|
| 627 |
-
def _shortcut(self, x):
|
| 628 |
-
if self.learned_sc:
|
| 629 |
-
x = self.conv1x1(x)
|
| 630 |
-
if x.shape[3] % 2 != 0: # [bs, 128, Freq, Time]
|
| 631 |
-
x = torch.cat([x, x[:, :, :, -1:]], dim=3)
|
| 632 |
-
return F.interpolate(x, scale_factor=.5, mode='nearest-exact') # F.avg_pool2d(x, 2)
|
| 633 |
-
|
| 634 |
-
def _residual(self, x):
|
| 635 |
-
x = self.actv(x)
|
| 636 |
-
x = self.conv1(x)
|
| 637 |
-
x = self.downsample_res(x)
|
| 638 |
-
x = self.actv(x)
|
| 639 |
-
x = self.conv2(x)
|
| 640 |
-
return x
|
| 641 |
|
| 642 |
-
def
|
| 643 |
-
|
| 644 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 645 |
|
|
|
|
|
|
|
|
|
|
| 646 |
|
| 647 |
-
class StyleEncoder(nn.Module):
|
| 648 |
|
| 649 |
-
|
| 650 |
|
| 651 |
def __init__(self,
|
| 652 |
-
|
| 653 |
-
style_dim=128,
|
| 654 |
-
max_conv_dim=512):
|
| 655 |
super().__init__()
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
x = self.
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 675 |
|
|
|
|
|
|
|
| 676 |
|
| 677 |
-
class LinearNorm(torch.nn.Module):
|
| 678 |
-
def __init__(self, in_dim, out_dim, bias=True):
|
| 679 |
super().__init__()
|
| 680 |
-
self.
|
| 681 |
|
| 682 |
def forward(self, x):
|
| 683 |
-
|
| 684 |
-
|
|
|
|
|
|
|
|
|
|
| 685 |
|
| 686 |
-
class LayerNorm(nn.Module):
|
| 687 |
-
def __init__(self, channels, eps=1e-5):
|
| 688 |
-
super().__init__()
|
| 689 |
-
self.channels = channels
|
| 690 |
-
self.eps = eps
|
| 691 |
-
|
| 692 |
-
self.gamma = nn.Parameter(torch.ones(channels))
|
| 693 |
-
self.beta = nn.Parameter(torch.zeros(channels))
|
| 694 |
-
|
| 695 |
-
def forward(self, x):
|
| 696 |
-
x = x.transpose(1, -1)
|
| 697 |
-
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
|
| 698 |
-
return x.transpose(1, -1)
|
| 699 |
|
|
|
|
| 700 |
|
| 701 |
-
|
| 702 |
-
def __init__(self, channels, kernel_size, depth, n_symbols):
|
| 703 |
super().__init__()
|
| 704 |
-
self.
|
| 705 |
-
|
| 706 |
-
self.
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
weight_norm(nn.Conv1d(channels, channels, kernel_size=kernel_size, padding=padding)),
|
| 710 |
-
LayerNorm(channels),
|
| 711 |
-
nn.LeakyReLU(0.24))
|
| 712 |
-
)
|
| 713 |
-
self.lstm = nn.LSTM(channels, channels//2, 1,
|
| 714 |
-
batch_first=True, bidirectional=True)
|
| 715 |
|
| 716 |
def forward(self, x):
|
| 717 |
-
x = self.
|
| 718 |
-
x
|
| 719 |
-
for c in self.cnn:
|
| 720 |
-
x = c(x)
|
| 721 |
-
x = x.transpose(1, 2)
|
| 722 |
-
x, _ = self.lstm(x)
|
| 723 |
-
return x
|
| 724 |
|
| 725 |
|
| 726 |
-
class
|
| 727 |
|
| 728 |
-
def __init__(self
|
| 729 |
-
super().__init__()
|
| 730 |
-
self.eps = eps
|
| 731 |
-
self.fc = nn.Linear(style_dim, 1024)
|
| 732 |
-
|
| 733 |
-
def forward(self, x, s):
|
| 734 |
-
h = self.fc(s)
|
| 735 |
-
gamma = h[:, :, :512]
|
| 736 |
-
beta = h[:, :, 512:1024]
|
| 737 |
-
x = F.layer_norm(x, (512, ), eps=self.eps)
|
| 738 |
-
x = (1 + gamma) * x + beta
|
| 739 |
-
return x # [1, 75, 512]
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
class ProsodyPredictor(nn.Module):
|
| 743 |
-
|
| 744 |
-
def __init__(self, style_dim, d_hid, nlayers, max_dur=50):
|
| 745 |
-
super().__init__()
|
| 746 |
|
| 747 |
-
self.text_encoder = DurationEncoder(sty_dim=style_dim,
|
| 748 |
-
d_model=d_hid,
|
| 749 |
-
nlayers=nlayers) # called outside forward
|
| 750 |
-
self.lstm = nn.LSTM(d_hid + style_dim, d_hid // 2,
|
| 751 |
-
1, batch_first=True, bidirectional=True)
|
| 752 |
-
self.duration_proj = LinearNorm(d_hid, max_dur)
|
| 753 |
-
self.shared = nn.LSTM(d_hid + style_dim, d_hid //
|
| 754 |
-
2, 1, batch_first=True, bidirectional=True)
|
| 755 |
-
self.F0 = nn.ModuleList([
|
| 756 |
-
AdainResBlk1d(d_hid, d_hid, style_dim),
|
| 757 |
-
AdainResBlk1d(d_hid, d_hid // 2, style_dim, upsample=True),
|
| 758 |
-
AdainResBlk1d(d_hid // 2, d_hid // 2, style_dim),
|
| 759 |
-
])
|
| 760 |
-
self.N = nn.ModuleList([
|
| 761 |
-
AdainResBlk1d(d_hid, d_hid, style_dim),
|
| 762 |
-
AdainResBlk1d(d_hid, d_hid // 2, style_dim, upsample=True),
|
| 763 |
-
AdainResBlk1d(d_hid // 2, d_hid // 2, style_dim)
|
| 764 |
-
])
|
| 765 |
-
self.F0_proj = nn.Conv1d(d_hid // 2, 1, 1, 1, 0)
|
| 766 |
-
self.N_proj = nn.Conv1d(d_hid // 2, 1, 1, 1, 0)
|
| 767 |
-
|
| 768 |
-
def F0Ntrain(self, x, s):
|
| 769 |
-
|
| 770 |
-
x, _ = self.shared(x) # [bs, time, ch] LSTM
|
| 771 |
-
|
| 772 |
-
x = x.transpose(1, 2) # [bs, ch, time]
|
| 773 |
-
|
| 774 |
-
F0 = x
|
| 775 |
-
|
| 776 |
-
for block in self.F0:
|
| 777 |
-
# print(f'LOOP {F0.shape=} {s.shape=}\n')
|
| 778 |
-
# )N F0.shape=torch.Size([1, 512, 147]) s.shape=torch.Size([1, 128])
|
| 779 |
-
# This is an AdainResBlk1d expects conv1d dimensions
|
| 780 |
-
F0 = block(F0, s)
|
| 781 |
-
F0 = self.F0_proj(F0)
|
| 782 |
-
|
| 783 |
-
N = x
|
| 784 |
-
|
| 785 |
-
for block in self.N:
|
| 786 |
-
N = block(N, s)
|
| 787 |
-
N = self.N_proj(N)
|
| 788 |
-
|
| 789 |
-
return F0, N
|
| 790 |
-
|
| 791 |
-
def forward(self, d_en=None, s=None):
|
| 792 |
-
blend = self.text_encoder(d_en, s)
|
| 793 |
-
x, _ = self.lstm(blend)
|
| 794 |
-
dur = self.duration_proj(x) # [bs, 150, 50]
|
| 795 |
-
|
| 796 |
-
_, input_length, classifier_50 = dur.shape
|
| 797 |
-
|
| 798 |
-
dur = dur[0, :, :]
|
| 799 |
-
dur = torch.sigmoid(dur).sum(1)
|
| 800 |
-
dur = dur.round().clamp(min=1).to(torch.int64)
|
| 801 |
-
aln_trg = torch.zeros(1,
|
| 802 |
-
dur.sum(),
|
| 803 |
-
input_length,
|
| 804 |
-
device=s.device)
|
| 805 |
-
c_frame = 0
|
| 806 |
-
for i in range(input_length):
|
| 807 |
-
aln_trg[:, c_frame:c_frame + dur[i], i] = 1
|
| 808 |
-
c_frame += dur[i]
|
| 809 |
-
en = torch.bmm(aln_trg, blend)
|
| 810 |
-
F0_pred, N_pred = self.F0Ntrain(en, s)
|
| 811 |
-
return aln_trg, F0_pred, N_pred
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
class DurationEncoder(nn.Module):
|
| 815 |
-
|
| 816 |
-
def __init__(self, sty_dim=128, d_model=512, nlayers=3):
|
| 817 |
super().__init__()
|
| 818 |
-
self.
|
| 819 |
-
for _ in range(nlayers):
|
| 820 |
-
self.lstms.append(nn.LSTM(d_model + sty_dim,
|
| 821 |
-
d_model // 2,
|
| 822 |
-
num_layers=1,
|
| 823 |
-
batch_first=True,
|
| 824 |
-
bidirectional=True
|
| 825 |
-
))
|
| 826 |
-
self.lstms.append(AdaLayerNorm(sty_dim, d_model))
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
def forward(self, x, style):
|
| 830 |
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
style = _tile(style, length=x.shape[2]).transpose(1, 2)
|
| 834 |
x = x.transpose(1, 2)
|
|
|
|
|
|
|
|
|
|
| 835 |
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
|
| 841 |
-
|
| 842 |
-
x = torch.cat([x, style], axis=2)
|
| 843 |
-
# LSTM
|
| 844 |
|
| 845 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 846 |
|
| 847 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch#2.9.0 cu126
|
| 2 |
+
from torch import nn
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import torch.nn.functional as F
|
| 4 |
+
from transformers import Wav2Vec2PreTrainedModel, PretrainedConfig#4.49.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from huggingface_hub import hf_hub_download
|
| 6 |
+
import re
|
| 7 |
+
from collections import deque
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
from safetensors.torch import load_file
|
| 10 |
+
from sentencepiece import SentencePieceProcessor
|
| 11 |
+
from einops import rearrange
|
|
|
|
|
|
|
| 12 |
|
|
|
|
| 13 |
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
class ActivationGating(nn.Module):
|
| 16 |
|
| 17 |
+
def __init__(self, dim_feedforward=4224):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
super().__init__()
|
| 19 |
+
d = 2816 if dim_feedforward == 4224 else 2048
|
| 20 |
+
self.linear_in = nn.Linear(1024, 2 * d, bias=False)
|
| 21 |
+
self.linear_out = nn.Linear(d, 1024, bias=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
def forward(self, x):
|
| 24 |
+
x = F.linear(x, self.linear_in.weight)
|
| 25 |
+
B, T, _ = x.shape
|
| 26 |
+
x = x.view(B, T, 2, -1)
|
| 27 |
+
x = F.silu(x[:, :, 0, :]) * x[:, :, 1, :]
|
| 28 |
+
x = F.linear(x, self.linear_out.weight)
|
| 29 |
+
return x
|
| 30 |
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
def apply_rope(q, k, offset=0):
|
| 33 |
+
q_type = q.dtype
|
| 34 |
+
q = q.to(torch.float)
|
| 35 |
+
k = k.to(torch.float)
|
| 36 |
+
bs, h, _1, d = k.shape
|
| 37 |
|
| 38 |
+
# fr = torch.exp(-18.420680743952367 / d * torch.arange(d // 2, device=q.device, dtype=torch.float))
|
| 39 |
+
# fr = torch.exp(-18.42068099975586 / d * torch.arange(d // 2, device=q.device, dtype=torch.float))
|
| 40 |
+
fr = torch.exp(-18.4206809997 / d * torch.arange(d // 2, device=q.device, dtype=torch.float))
|
|
|
|
| 41 |
|
| 42 |
+
t = offset * fr[None, None, :, None]
|
| 43 |
|
| 44 |
+
r = torch.cos(t)
|
| 45 |
+
i = torch.sin(t)
|
| 46 |
|
| 47 |
+
q = q.view(bs, h, d // 2, 2) # interleave
|
| 48 |
+
k = k.view(bs, h, d // 2, 2)
|
| 49 |
|
| 50 |
+
qor = q[:, :, :, :1] * r - q[:, :, :, 1:] * i
|
| 51 |
+
qoi = q[:, :, :, :1] * i + q[:, :, :, 1:] * r
|
| 52 |
+
kor = k[:, :, :, :1] * r - k[:, :, :, 1:] * i
|
| 53 |
+
koi = k[:, :, :, :1] * i + k[:, :, :, 1:] * r
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
+
qo = torch.cat([qor.to(dtype=q_type), qoi.to(dtype=q_type)], dim=3)
|
| 56 |
+
ko = torch.cat([kor.to(dtype=q_type), koi.to(dtype=q_type)], dim=3)
|
| 57 |
|
| 58 |
+
return qo.view(bs, h, 1, d), ko.view(bs, h, 1, d)
|
| 59 |
|
|
|
|
| 60 |
|
| 61 |
+
class RMSNorm(nn.Module):
|
| 62 |
+
def __init__(self, d=1024):
|
| 63 |
super().__init__()
|
| 64 |
+
self.alpha = nn.Parameter(torch.full((1, 1, d), 1.0, dtype=torch.float64))
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
def forward(self, x):
|
| 67 |
+
x = x.to(torch.float64)
|
| 68 |
+
v = 9e-9 + torch.mean(x * x, dim=2, keepdim=True)
|
| 69 |
+
return (x * (self.alpha * torch.rsqrt(v))).to(torch.bfloat16)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
+
class LLMAttention(nn.Module):
|
|
|
|
|
|
|
| 73 |
|
| 74 |
+
def __init__(self, weights_per_step):
|
| 75 |
+
super().__init__()
|
| 76 |
+
self.weights_per_step = weights_per_step
|
| 77 |
+
self.k_history = None
|
| 78 |
+
self.v_history = None
|
| 79 |
+
p = 9 if weights_per_step else 1
|
| 80 |
+
self.out_projs = nn.ModuleList([nn.Linear(1024, 1024, bias=False) for _ in range(p)])
|
| 81 |
+
self.in_projs = nn.ModuleList([nn.Linear(1024, 3 * 1024, bias=False) for _ in range(p)])
|
| 82 |
|
| 83 |
+
def forward(self, query):
|
| 84 |
|
| 85 |
+
offset = 0 if self.k_history is None else self.k_history.shape[2] # if overpass RoPE untrained or DPF 16x
|
|
|
|
| 86 |
|
| 87 |
+
if (self.weights_per_step and offset % self.weights_per_step == 0) or (offset % 473 == 0):
|
| 88 |
+
self.k_history = None
|
| 89 |
+
self.v_history = None
|
| 90 |
+
offset = 0
|
| 91 |
|
| 92 |
+
if self.weights_per_step:
|
| 93 |
+
x = self.in_projs[offset if offset < 9 else 8](query)
|
| 94 |
+
else:
|
| 95 |
+
x = self.in_projs[0](query)
|
| 96 |
+
q, k, v = rearrange(x, "b t (p h d) -> p b h t d", p=3, h=16)
|
| 97 |
+
q, k = apply_rope(q, k, offset=offset)
|
| 98 |
+
# KVCACHE
|
| 99 |
+
if self.k_history is not None:
|
| 100 |
+
self.k_history = torch.cat([self.k_history, k], 2)
|
| 101 |
+
self.v_history = torch.cat([self.v_history, v], 2)
|
| 102 |
+
else:
|
| 103 |
+
self.k_history = k
|
| 104 |
+
self.v_history = v
|
| 105 |
+
k = self.k_history
|
| 106 |
+
v = self.v_history
|
| 107 |
+
# ones-bool attn mask sounds better than passing no mask argument
|
| 108 |
+
x = F.scaled_dot_product_attention(q, k, v, torch.ones(k.shape[0], 1, 1, k.shape[2],dtype=torch.bool, device=k.device))
|
| 109 |
+
x = rearrange(x, "b h t d -> b t (h d)")
|
| 110 |
+
if self.weights_per_step:
|
| 111 |
+
return self.out_projs[offset if offset < 9 else 8](x)
|
| 112 |
+
return self.out_projs[0](x)
|
| 113 |
|
|
|
|
| 114 |
|
| 115 |
+
class LLMTransformerLayer(nn.Module):
|
| 116 |
|
| 117 |
+
def __init__(self, weights_per_step=None):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.self_attn = LLMAttention(weights_per_step=weights_per_step)
|
| 120 |
+
self.norm1 = RMSNorm()
|
| 121 |
+
self.norm2 = RMSNorm()
|
| 122 |
+
self.weights_per_step = weights_per_step
|
| 123 |
+
if self.weights_per_step:
|
| 124 |
+
self.gating = nn.ModuleList([ActivationGating(3072) for _ in range(9)])
|
| 125 |
+
else:
|
| 126 |
+
self.gating = ActivationGating()
|
| 127 |
|
| 128 |
+
def forward(self, x):
|
| 129 |
+
x = self.self_attn(self.norm1(x)) + x
|
| 130 |
+
if self.weights_per_step:
|
| 131 |
+
p = self.self_attn.k_history.shape[2] - 1
|
| 132 |
+
return x + self.gating[p if p < 9 else 8](self.norm2(x))
|
| 133 |
+
return x + self.gating(self.norm2(x))
|
| 134 |
|
|
|
|
| 135 |
|
| 136 |
+
class LLMTransformer(nn.Module):
|
|
|
|
| 137 |
|
| 138 |
+
def __init__(
|
| 139 |
+
self,
|
| 140 |
+
num_layers=24,
|
| 141 |
+
weights_per_step=False):
|
| 142 |
+
super().__init__()
|
| 143 |
+
self.layers = nn.ModuleList(
|
| 144 |
+
[
|
| 145 |
+
LLMTransformerLayer(weights_per_step=weights_per_step)
|
| 146 |
+
for _ in range(num_layers)
|
| 147 |
+
])
|
| 148 |
|
| 149 |
+
def forward(self, x):
|
| 150 |
+
for lay in self.layers:
|
| 151 |
+
x = lay(x)
|
| 152 |
return x
|
| 153 |
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
+
class Voc(Wav2Vec2PreTrainedModel):
|
| 156 |
+
|
| 157 |
+
'''For using different batch_siz -> Voc._flush()
|
| 158 |
+
'''
|
| 159 |
+
|
| 160 |
+
def __init__(self, config=PretrainedConfig()):
|
| 161 |
+
super().__init__(config=config)
|
| 162 |
+
self.encoder_transformer = VocTransformer()
|
| 163 |
+
self.decoder_transformer = VocTransformer()
|
| 164 |
+
self.encoder = SEANetEncoder()
|
| 165 |
+
self.decoder = SEANetDecoder()
|
| 166 |
+
self.sample_rate = 24000
|
| 167 |
+
self.quantizer = SplitResidualVectorQuantizer()
|
| 168 |
+
self.downsample = BufferConv1d(512, 512, kernel_size=4, stride=2, groups=1, bias=False)
|
| 169 |
+
upsample_channel_wise_bug = True
|
| 170 |
+
self.upsample = BufferConvTranspose1d(512, 512, kernel_size=4,
|
| 171 |
+
groups=512 if upsample_channel_wise_bug else 1,
|
| 172 |
+
stride=2, bias=False)
|
| 173 |
+
self.frame_rate = 12.5
|
| 174 |
+
self.encode_buffer = None
|
| 175 |
+
|
| 176 |
+
def _flush(self):
|
| 177 |
+
'''stream buffers have tensors of old batch size! Voc()._flush() to clean buffers
|
| 178 |
+
'''
|
| 179 |
+
self.encode_buffer = None # holds unused (incomplete windows of len < 1920) - we need 1920 to produce 1 token
|
| 180 |
+
if self.downsample.previous is not None:
|
| 181 |
+
self.downsample.previous = None
|
| 182 |
+
if self.upsample.partial is not None:
|
| 183 |
+
self.upsample.partial = None
|
| 184 |
+
for arch in [self.encoder, self.decoder]:
|
| 185 |
+
for _m in arch.model:
|
| 186 |
+
if type(_m) is SEANetResnetBlock:
|
| 187 |
+
for _b in _m.block:
|
| 188 |
+
if type(_b) is BufferConv1d:
|
| 189 |
+
if _b.previous is not None:
|
| 190 |
+
_b.previous = None
|
| 191 |
+
if type(_m) is BufferConv1d:
|
| 192 |
+
if _m.previous is not None:
|
| 193 |
+
_m.previous = None
|
| 194 |
+
if type(_m) is BufferConvTranspose1d:
|
| 195 |
+
if _m.partial is not None:
|
| 196 |
+
_m.partial = None
|
| 197 |
+
|
| 198 |
+
@torch.no_grad()
|
| 199 |
+
def encode(self, x):
|
| 200 |
+
'''24KHz audio to codes
|
| 201 |
+
x : [bs, 1, 24 KHz]
|
| 202 |
+
c : [bs, 8, time] = 1920 audio samples produce 1 time frame (of n_q codebooks)
|
| 203 |
+
'''
|
| 204 |
+
if self.encode_buffer is not None:
|
| 205 |
+
x = torch.cat([self.encode_buffer, x], 2)
|
| 206 |
+
_bs, _1, _len = x.shape
|
| 207 |
+
num_frames = int(_len / 1920)
|
| 208 |
+
leftover = x[:, :, (num_frames+1) * 1920:]
|
| 209 |
+
if leftover.shape[2] > 0:
|
| 210 |
+
self.encode_buffer = leftover
|
| 211 |
else:
|
| 212 |
+
self.encode_buffer = None
|
| 213 |
+
torch.cuda.empty_cache()
|
| 214 |
+
if num_frames > 0:
|
| 215 |
+
c = []
|
| 216 |
+
for n in range(num_frames):
|
| 217 |
+
e = self.encoder(x[:, :, n * 1920:(n + 1) * 1920])
|
| 218 |
+
e = self.encoder_transformer(e)
|
| 219 |
+
e = self.downsample(e)
|
| 220 |
+
_c = self.quantizer.encode(e)
|
| 221 |
+
c.append(_c)
|
| 222 |
+
c = torch.cat(c, 2)
|
| 223 |
+
else:
|
| 224 |
+
# num_frames = 0 Early exit -> for x.shape[2]<1920 fill conv buffers but can't output token
|
| 225 |
+
c = torch.empty(_bs, 16, 0)
|
| 226 |
+
return c
|
| 227 |
+
|
| 228 |
+
@torch.no_grad()
|
| 229 |
+
def decode(self, c):
|
| 230 |
+
'''codes to 24kHZ audio
|
| 231 |
+
c: [bs, 8, n_tokens]
|
| 232 |
+
x: [bs, 1, n_tokens * 1920]
|
| 233 |
+
'''
|
| 234 |
+
_hidden = []
|
| 235 |
+
for i in range(c.shape[2]):
|
| 236 |
+
x = self.quantizer.decode(c[:, :, i:i+1])
|
| 237 |
+
x = self.upsample(x)
|
| 238 |
+
x = self.decoder_transformer(x)
|
| 239 |
+
x = self.decoder(x)
|
| 240 |
+
_hidden.append(x)
|
| 241 |
+
return torch.cat(_hidden, 2) # [bs, 1, 24KHz]
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
class SEANetResnetBlock(nn.Module):
|
| 245 |
+
def __init__(
|
| 246 |
+
self,
|
| 247 |
+
dim,
|
| 248 |
+
kernel_sizes=[3, 1],
|
| 249 |
+
):
|
| 250 |
+
super().__init__()
|
| 251 |
|
| 252 |
+
block = []
|
| 253 |
+
for i, kernel_size in enumerate(kernel_sizes):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
|
| 255 |
+
block += [
|
| 256 |
+
nn.ELU(),
|
| 257 |
+
BufferConv1d(
|
| 258 |
+
dim if i == 0 else dim // 2,
|
| 259 |
+
dim // 2 if i == 0 else dim,
|
| 260 |
+
kernel_size=kernel_size,
|
| 261 |
+
bias=True,
|
| 262 |
+
),
|
| 263 |
+
]
|
| 264 |
|
| 265 |
+
self.block = nn.Sequential(*block)
|
| 266 |
|
| 267 |
+
def forward(self, x):
|
| 268 |
+
return x + self.block(x)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
class SEANetEncoder(nn.Module):
|
| 272 |
+
def __init__(
|
| 273 |
+
self,
|
| 274 |
+
channels=1, # DOES NOT SUPPORT STEREO
|
| 275 |
+
dimension=512,
|
| 276 |
+
n_filters=64,
|
| 277 |
+
ratios=[8, 6, 5, 4],
|
| 278 |
+
kernel_size=7,
|
| 279 |
+
last_kernel_size=3,
|
| 280 |
+
):
|
| 281 |
super().__init__()
|
| 282 |
+
self.ratios = list(reversed(ratios))
|
| 283 |
+
del ratios
|
| 284 |
+
mult = 1
|
| 285 |
+
model=[
|
| 286 |
+
BufferConv1d(
|
| 287 |
+
channels,
|
| 288 |
+
mult * n_filters,
|
| 289 |
+
kernel_size,
|
| 290 |
+
bias=True
|
| 291 |
+
)
|
| 292 |
+
]
|
| 293 |
+
for i, ratio in enumerate(self.ratios):
|
| 294 |
+
model += [SEANetResnetBlock(mult * n_filters),
|
| 295 |
+
nn.ELU(),
|
| 296 |
+
BufferConv1d(mult * n_filters,
|
| 297 |
+
mult * n_filters * 2,
|
| 298 |
+
kernel_size=ratio * 2,
|
| 299 |
+
stride=ratio,
|
| 300 |
+
bias=True)]
|
| 301 |
+
mult *= 2
|
| 302 |
+
# ENDFOR
|
| 303 |
+
model += [nn.ELU(),
|
| 304 |
+
BufferConv1d(mult * n_filters,
|
| 305 |
+
dimension,
|
| 306 |
+
last_kernel_size,
|
| 307 |
+
bias=True)]
|
| 308 |
+
self.model = nn.Sequential(*model)
|
| 309 |
|
| 310 |
def forward(self, x):
|
| 311 |
+
return self.model(x)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
+
class SEANetDecoder(nn.Module):
|
| 315 |
|
| 316 |
+
def __init__(
|
| 317 |
+
self,
|
| 318 |
+
channels=1,
|
| 319 |
+
dimension=512,
|
| 320 |
+
n_filters=64,
|
| 321 |
+
ratios=[8, 6, 5, 4],
|
| 322 |
+
kernel_size=7,
|
| 323 |
+
last_kernel_size=3):
|
| 324 |
|
| 325 |
+
super().__init__()
|
| 326 |
+
mult = int(2 ** len(ratios))
|
| 327 |
+
model = [BufferConv1d(dimension,
|
| 328 |
+
mult * n_filters,
|
| 329 |
+
kernel_size,
|
| 330 |
+
bias=True)]
|
| 331 |
+
#UP
|
| 332 |
+
for i, ratio in enumerate(ratios):
|
| 333 |
+
model += [nn.ELU(),
|
| 334 |
+
BufferConvTranspose1d(mult * n_filters,
|
| 335 |
+
mult * n_filters // 2,
|
| 336 |
+
kernel_size=ratio * 2,
|
| 337 |
+
stride=ratio,
|
| 338 |
+
bias=True),
|
| 339 |
+
SEANetResnetBlock(mult * n_filters // 2)]
|
| 340 |
+
mult //= 2
|
| 341 |
+
# LAST
|
| 342 |
+
model += [
|
| 343 |
+
nn.ELU(),
|
| 344 |
+
BufferConv1d(
|
| 345 |
+
n_filters,
|
| 346 |
+
channels,
|
| 347 |
+
last_kernel_size,
|
| 348 |
+
bias=True
|
| 349 |
+
),
|
| 350 |
+
]
|
| 351 |
+
self.model = nn.Sequential(*model)
|
| 352 |
|
| 353 |
+
def forward(self, x):
|
| 354 |
+
return self.model(x)
|
| 355 |
|
|
|
|
|
|
|
| 356 |
|
| 357 |
+
class BufferConv1d(nn.Conv1d):
|
| 358 |
+
def __init__(self,
|
| 359 |
+
*args,
|
| 360 |
+
**kwargs):
|
| 361 |
+
super().__init__(*args, **kwargs)
|
| 362 |
+
self.previous = None
|
| 363 |
|
| 364 |
+
def forward(self, x):
|
| 365 |
+
k = self.kernel_size[0]
|
| 366 |
|
| 367 |
+
if self.previous is not None:
|
| 368 |
|
| 369 |
+
x = torch.cat([self.previous, x], 2)
|
| 370 |
|
| 371 |
+
else: # If self.previous is None => Use zero pad
|
|
|
|
| 372 |
|
| 373 |
+
if k == 3:
|
| 374 |
|
| 375 |
+
p = (2, 0)
|
| 376 |
+
x = F.pad(x, p, mode='replicate', value=0.0) # skip connections SeaNetResBlk
|
| 377 |
|
| 378 |
+
elif k == 4: # ConvTrUpsample is the first conv encountered by decode replicate solves pulse
|
| 379 |
|
| 380 |
+
p = (3, 0)
|
| 381 |
+
x = F.pad(x, p, mode='replicate', value=0.0)
|
| 382 |
|
| 383 |
+
elif k == 7:
|
|
|
|
|
|
|
| 384 |
|
| 385 |
+
p = (6, 0)
|
| 386 |
+
x = F.pad(x, p, mode='replicate', value=0.0)
|
| 387 |
|
| 388 |
+
elif k == 16:
|
|
|
|
|
|
|
| 389 |
|
| 390 |
+
p = (2, 0)
|
| 391 |
+
x = F.pad(x, p, mode='replicate', value=0.0) # THis can be also constant w/o pulse occur
|
| 392 |
|
| 393 |
+
num_frames = int( (x.shape[2] - self.kernel_size[0]) / self.stride[0] ) + 1 # +1 is: k starts at left of x and doing (I-k)/s jumps
|
| 394 |
+
offset = num_frames * self.stride[0]
|
| 395 |
+
self.previous = x[..., offset:]
|
| 396 |
+
return super().forward(x)
|
| 397 |
|
|
|
|
| 398 |
|
| 399 |
+
class BufferConvTranspose1d(nn.ConvTranspose1d):
|
| 400 |
+
# kernel 5 has only 1 pixel for input (cloned)
|
| 401 |
+
# https://distill.pub/2016/deconv-checkerboard/
|
| 402 |
def __init__(self,
|
| 403 |
+
*args,
|
| 404 |
+
**kwargs):
|
| 405 |
+
super().__init__(*args,
|
| 406 |
+
**kwargs)
|
| 407 |
+
self.partial = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 408 |
|
| 409 |
def forward(self, x):
|
| 410 |
+
out = super().forward(x)
|
| 411 |
+
OT = out.shape[2]
|
| 412 |
+
invalid_steps = self.kernel_size[0] - self.stride[0]
|
| 413 |
+
if self.partial is not None:
|
| 414 |
+
PT = self.partial.shape[-1]
|
| 415 |
+
if self.bias is not None:
|
| 416 |
+
out[..., :PT] += self.partial - self.bias[:, None]
|
| 417 |
+
else:
|
| 418 |
+
out[..., :PT] += self.partial # for ConvTrUpsample1d
|
| 419 |
+
invalid_steps = self.kernel_size[0] - self.stride[0]
|
| 420 |
+
self.partial = out[..., OT - invalid_steps :]
|
| 421 |
+
out = out[...,:OT - invalid_steps]
|
| 422 |
+
return out
|
| 423 |
|
| 424 |
|
| 425 |
+
class CodeBook(nn.Module):
|
| 426 |
+
def __init__(self, dim, codebook_size):
|
|
|
|
| 427 |
super().__init__()
|
| 428 |
+
self.register_buffer('_e', torch.zeros(codebook_size, dim))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
|
| 430 |
+
def encode(self, x):
|
| 431 |
+
dist = torch.cdist(
|
| 432 |
+
x.transpose(1, 2), # [bs, time, 256]
|
| 433 |
+
self._e[None, :, :] # [1, 2048, 256]
|
| 434 |
+
)
|
| 435 |
+
codes = dist.argmin(2)
|
| 436 |
+
return codes
|
| 437 |
|
| 438 |
+
def decode(self, codes):
|
| 439 |
+
quantized = F.embedding(codes, self._e)
|
| 440 |
+
return quantized.transpose(1, 2) # [1, 256, time]
|
| 441 |
|
|
|
|
| 442 |
|
| 443 |
+
class SplitResidualVectorQuantizer(nn.Module):
|
| 444 |
|
| 445 |
def __init__(self,
|
| 446 |
+
n_q=None):
|
|
|
|
|
|
|
| 447 |
super().__init__()
|
| 448 |
+
self.in_proj_s = torch.nn.Conv1d(512, 256, 1, bias=False)
|
| 449 |
+
self.in_proj_a = torch.nn.Conv1d(512, 256, 1, bias=False)
|
| 450 |
+
self.out_proj_s = torch.nn.Conv1d(256, 512, 1, bias=False) # reused for all _acoustic_books
|
| 451 |
+
self.out_proj_a = torch.nn.Conv1d(256, 512, 1, bias=False)
|
| 452 |
+
self.layers = nn.ModuleList([CodeBook(dim=256, codebook_size=2048) for _ in range(18)])
|
| 453 |
+
self._acoustic_books = range(1, 16) # Official Mimi
|
| 454 |
+
# CODEBOOKS
|
| 455 |
+
# Here we re use RVQ codebooks for higher fidelity!
|
| 456 |
+
# Exclude 0 here as it has different proj (in_proj_s)
|
| 457 |
+
# self._acoustic_books = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 17, 17, 17, 17]
|
| 458 |
+
|
| 459 |
+
def encode(self, x):
|
| 460 |
+
indices = self.layers[0].encode(self.in_proj_s(x)) # integers
|
| 461 |
+
all_indices = [ indices[:, None, :], ]
|
| 462 |
+
x = self.in_proj_a(x)
|
| 463 |
+
for _cb in self._acoustic_books:
|
| 464 |
+
indices = self.layers[_cb].encode(x)
|
| 465 |
+
x = x - self.layers[_cb].decode(indices)
|
| 466 |
+
all_indices.append(indices[:, None, :])
|
| 467 |
+
codes = torch.cat(all_indices, 1)
|
| 468 |
+
return codes
|
| 469 |
+
|
| 470 |
+
def decode(self, codes):
|
| 471 |
+
_s = self.layers[0].decode(codes[:, 0, :])
|
| 472 |
+
_a = torch.zeros([1, 1], device=codes.device)
|
| 473 |
+
for i, _cb in enumerate(self._acoustic_books):
|
| 474 |
+
_a = _a + self.layers[_cb].decode(codes[:, i+1, :])
|
| 475 |
+
return self.out_proj_s(_s) + self.out_proj_a(_a) # [bs, 512, time]
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
class VocAttention(nn.Module):
|
| 479 |
|
| 480 |
+
def __init__(self,
|
| 481 |
+
embed_dim):
|
| 482 |
|
|
|
|
|
|
|
| 483 |
super().__init__()
|
| 484 |
+
self.fused_proj = nn.Parameter(torch.zeros(embed_dim, embed_dim))
|
| 485 |
|
| 486 |
def forward(self, x):
|
| 487 |
+
'''bypass of streaming training'''
|
| 488 |
+
if x.shape[1] > 1:
|
| 489 |
+
x = x.mean(1, keepdims=True)
|
| 490 |
+
x = torch.matmul(x, self.fused_proj)
|
| 491 |
+
return x # FFN broadcasts to x.shape[1]=2
|
| 492 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 493 |
|
| 494 |
+
class VocTransformerLayer(nn.Module):
|
| 495 |
|
| 496 |
+
def __init__(self, d_model=512, dim_feedforward=2048):
|
|
|
|
| 497 |
super().__init__()
|
| 498 |
+
self.self_attn = VocAttention(embed_dim=d_model)
|
| 499 |
+
self.norm1 = nn.LayerNorm(d_model, eps=1e-5)
|
| 500 |
+
self.norm2 = nn.LayerNorm(d_model, eps=1e-5)
|
| 501 |
+
self.linear1 = nn.Linear(d_model, dim_feedforward, bias=False)
|
| 502 |
+
self.linear2 = nn.Linear(dim_feedforward, d_model, bias=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 503 |
|
| 504 |
def forward(self, x):
|
| 505 |
+
x = x + self.self_attn(self.norm1(x))
|
| 506 |
+
return x + self.linear2(F.gelu(self.linear1(self.norm2(x))))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
|
| 508 |
|
| 509 |
+
class VocTransformer(nn.Module):
|
| 510 |
|
| 511 |
+
def __init__(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 512 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 513 |
super().__init__()
|
| 514 |
+
self.layers = nn.ModuleList(VocTransformerLayer() for _ in range(8))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 515 |
|
| 516 |
+
def forward(self, x):
|
|
|
|
|
|
|
| 517 |
x = x.transpose(1, 2)
|
| 518 |
+
for la in self.layers:
|
| 519 |
+
x = la(x)
|
| 520 |
+
return x.transpose(1, 2)
|
| 521 |
|
| 522 |
+
class Entry():
|
| 523 |
+
def __init__(self, tokens=None):
|
| 524 |
+
self.tokens = tokens
|
| 525 |
+
self.padding = len(tokens) + 2 - 1
|
| 526 |
|
| 527 |
+
class TokenState:
|
|
|
|
|
|
|
| 528 |
|
| 529 |
+
def __init__(self, entries = None):
|
| 530 |
+
self.entries = entries
|
| 531 |
+
self.queued = deque([])
|
| 532 |
+
self.lookahead_queued = deque()
|
| 533 |
+
self.end_step = None
|
| 534 |
+
self.forced_padding = 2
|
| 535 |
|
| 536 |
+
class TTSModel(nn.Module):
|
| 537 |
+
|
| 538 |
+
def __init__(self):
|
| 539 |
+
super().__init__()
|
| 540 |
+
self.tokenizer = SentencePieceProcessor(str(hf_hub_download(repo_id='kyutai/tts-0.75b-en-public',
|
| 541 |
+
filename='tokenizer_spm_8k_en_fr_audio.model')))
|
| 542 |
+
with torch.device("meta"):
|
| 543 |
+
self.emb = nn.ModuleList([ScaledEmbedding(2049, 1024) for _ in range(16)])
|
| 544 |
+
self.text_emb = ScaledEmbedding(8001, 1024, demux_second_stream=True)
|
| 545 |
+
self.transformer = LLMTransformer()
|
| 546 |
+
self.out_norm = RMSNorm()
|
| 547 |
+
self.depformer_in = nn.ModuleList([nn.Linear(1024, 1024, bias=False) for _ in range(9)])
|
| 548 |
+
self.depformer_emb = nn.ModuleList([ScaledEmbedding(2049, 128) for _ in range(16 - 1)])
|
| 549 |
+
self.depformer_text_emb = ScaledEmbedding(8001, 128, demux_second_stream=True)
|
| 550 |
+
self.depformer = LLMTransformer(num_layers=4, weights_per_step=16)
|
| 551 |
+
self.linears = nn.ModuleList([nn.Linear(1024, 2048, bias=False) for _ in range(16)]) # DPF heads
|
| 552 |
+
|
| 553 |
+
state_d = load_file(hf_hub_download(repo_id='Dionyssos/_TTS075B', filename='tts_075B.safetensors'))
|
| 554 |
+
self.load_state_dict(state_d, assign=True, strict=True) #overwrite devices of rand init params
|
| 555 |
+
self.to(dtype=torch.bfloat16).eval()
|
| 556 |
+
|
| 557 |
+
def prepare_script(self, script='Type your text here.'):
|
| 558 |
+
entries = []
|
| 559 |
+
# break is indicated as e.g. <break time="3s"/>
|
| 560 |
+
event_re = re.compile(r"(?:<break\s+time=\"([0-9]+(?:.[0-9]*)?)s\"\s*/?>)|(?:\s+)")
|
| 561 |
+
line = script.replace('’', "'").replace(':', " ").replace('(', "").replace(')', "")
|
| 562 |
+
while line:
|
| 563 |
+
match = event_re.search(line)
|
| 564 |
+
if match is None:
|
| 565 |
+
break
|
| 566 |
+
word = line[:match.start()]
|
| 567 |
+
line = line[match.end():]
|
| 568 |
+
if word:
|
| 569 |
+
entries.append(Entry(tokens=self.tokenizer.encode(word)))
|
| 570 |
+
if match.group(1):
|
| 571 |
+
raise ValueError
|
| 572 |
+
# break_duration = float(match.group(1))
|
| 573 |
+
# padding = int(round(break_duration * frame_rate))
|
| 574 |
+
# entry = Entry(tokens=[], text='', padding=padding)
|
| 575 |
+
# entries.append(entry)
|
| 576 |
+
if line:
|
| 577 |
+
entries.append(Entry(tokens=self.tokenizer.encode(line)))
|
| 578 |
+
return entries
|
| 579 |
+
|
| 580 |
+
@property
|
| 581 |
+
def device(self):
|
| 582 |
+
return next(iter(self.parameters())).device
|
| 583 |
+
|
| 584 |
+
@torch.no_grad()
|
| 585 |
+
def generate(self, text=None,
|
| 586 |
+
_wav=None, mimi=None,
|
| 587 |
+
play=16):
|
| 588 |
+
|
| 589 |
+
state = TokenState(entries=deque(self.prepare_script(script=text)))
|
| 590 |
+
upper_lim = 9999
|
| 591 |
+
self.cache = torch.full((2,17, 4), -1, device=self.device, dtype=torch.long)
|
| 592 |
+
pcms = []#final audio to return
|
| 593 |
+
for offset in range(upper_lim):
|
| 594 |
+
print(f'{offset=} of {upper_lim=}',end='\r')
|
| 595 |
+
if state.end_step is not None:
|
| 596 |
+
if offset >= state.end_step + 16 + 4:
|
| 597 |
+
break
|
| 598 |
+
|
| 599 |
+
input_ = self.cache[:, :, offset % self.cache.shape[2]].clone()
|
| 600 |
+
|
| 601 |
+
if offset == 0:
|
| 602 |
+
input_[:, 0] = 8000 # so we dont have to reset cfg txr = -1 for offset >0
|
| 603 |
+
input_[:, 1:] = 2048
|
| 604 |
+
|
| 605 |
+
if offset < 3:
|
| 606 |
+
input_[:, 2:] = 2048
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
x = self.text_emb(input_[:, :1])
|
| 610 |
+
for cb_ in range(16):
|
| 611 |
+
x = self.emb[cb_](input_[:, cb_ + 1 : cb_ + 2]) + x
|
| 612 |
+
x = self.out_norm(self.transformer(x))
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
token = -1
|
| 616 |
+
if offset > _wav.shape[1]:
|
| 617 |
+
token = 0
|
| 618 |
+
# START
|
| 619 |
+
if state.queued:
|
| 620 |
+
token = 3
|
| 621 |
+
if state.forced_padding > 0:
|
| 622 |
+
token = 3
|
| 623 |
+
#===================================
|
| 624 |
+
if token == 0:
|
| 625 |
+
if state.entries:
|
| 626 |
+
e = state.entries.popleft()
|
| 627 |
+
if e.tokens:
|
| 628 |
+
state.queued.extend(e.tokens)
|
| 629 |
+
lookahead =2
|
| 630 |
+
for e2 in state.entries:
|
| 631 |
+
if e2.tokens:
|
| 632 |
+
lookahead -= 1
|
| 633 |
+
if lookahead == 0:
|
| 634 |
+
state.lookahead_queued.extend(e2.tokens)
|
| 635 |
+
break
|
| 636 |
+
# print('\neeee',e2,'\n\n')
|
| 637 |
+
# raise ValueError
|
| 638 |
+
else:
|
| 639 |
+
token = 3
|
| 640 |
+
state.forced_padding = e.padding
|
| 641 |
+
# print(f'\n\n=========o=============\n{state.lookahead_queued=} {state.queued=}===================\n\n')
|
| 642 |
+
else:
|
| 643 |
+
token = 3
|
| 644 |
+
if state.end_step is None:
|
| 645 |
+
token = 0
|
| 646 |
+
if state.end_step is None:
|
| 647 |
+
state.end_step = offset
|
| 648 |
+
#==============================================
|
| 649 |
+
output=0
|
| 650 |
+
if token == 3:
|
| 651 |
+
if state.forced_padding > 0:
|
| 652 |
+
state.forced_padding -= 1
|
| 653 |
+
if state.queued:
|
| 654 |
+
output = state.queued.popleft()
|
| 655 |
+
else:
|
| 656 |
+
output = 3
|
| 657 |
+
# ==========================
|
| 658 |
+
second = -1
|
| 659 |
+
if output == 0:
|
| 660 |
+
second = 0
|
| 661 |
+
if state.queued:
|
| 662 |
+
output = state.queued.popleft()
|
| 663 |
+
else:
|
| 664 |
+
output = 3
|
| 665 |
+
elif state.lookahead_queued:
|
| 666 |
+
second = state.lookahead_queued.popleft() # Difference of queued and lookahead_queued?
|
| 667 |
+
token = (second + 1) * 8001 + output
|
| 668 |
+
|
| 669 |
+
# audio tokens
|
| 670 |
+
ac = (offset + 1) % self.cache.shape[2]
|
| 671 |
+
self.cache[0, 0, ac] = token
|
| 672 |
+
audio_tokens = torch.ones([1, 16], device=x.device, dtype=torch.long)
|
| 673 |
+
if offset > play:
|
| 674 |
+
prev_token = torch.tensor([[token]], device=x.device, dtype=torch.long)
|
| 675 |
+
for _cb in range(16):
|
| 676 |
+
last_token_input = None
|
| 677 |
+
if _cb == 0:
|
| 678 |
+
last_token_input = self.depformer_text_emb(prev_token.repeat(2, 1))
|
| 679 |
+
else:
|
| 680 |
+
last_token_input = self.depformer_emb[_cb - 1](prev_token)
|
| 681 |
+
dep_output = self.depformer(self.depformer_in[_cb if _cb < 9 else 8](x) + last_token_input)
|
| 682 |
+
logits = self.linears[_cb](dep_output)
|
| 683 |
+
prev_token = (2.0 * logits[0, :, :] - logits[1, :, :]).argmax(1)
|
| 684 |
+
audio_tokens[0, _cb] = prev_token
|
| 685 |
+
if offset > play and offset < play + 1 + _wav.shape[1]:
|
| 686 |
+
audio_tokens[:, :5] = _wav[:5, offset - play - 3]
|
| 687 |
+
audio_tokens[:, 11:] = _wav[11:, offset - play - 3]
|
| 688 |
+
# next turn
|
| 689 |
+
self.cache[0, 1:, ac] = audio_tokens
|
| 690 |
+
# cfg
|
| 691 |
+
if offset > 16 + 2 + _wav.shape[1]:
|
| 692 |
+
if offset > 16 + 4 + _wav.shape[1]:
|
| 693 |
+
self.cache[1, 1:, ac] = self.cache[0, 1:, ac]
|
| 694 |
+
else:
|
| 695 |
+
self.cache[1, 1, ac] = self.cache[0, 1, ac]
|
| 696 |
+
# ivao0/voc
|
| 697 |
+
if offset > 20 + _wav.shape[1]:
|
| 698 |
+
audio_tokens[:, 0] = self.cache[0, 1, (offset - 1) % self.cache.shape[2]] # previous
|
| 699 |
+
pcms.append(mimi.decode(audio_tokens[:, :, None])) # [1,1,1920]
|
| 700 |
+
x = torch.cat(pcms, dim=2)[0, 0, :]
|
| 701 |
+
return x.cpu().numpy()
|
| 702 |
+
|
| 703 |
+
def _flush(self):
|
| 704 |
+
for lay in self.transformer.layers:
|
| 705 |
+
lay.self_attn.k_history = None
|
| 706 |
+
lay.self_attn.v_history = None
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
class ScaledEmbedding(nn.Embedding):
|
| 710 |
+
def __init__(self, num_embeddings=None, embedding_dim=None, demux_second_stream=False):
|
| 711 |
+
super().__init__(num_embeddings, embedding_dim)
|
| 712 |
+
self.zero_idx = -1
|
| 713 |
+
self.low_rank = None
|
| 714 |
+
self.demux_second_stream = demux_second_stream
|
| 715 |
+
if self.demux_second_stream:
|
| 716 |
+
self.out1 = nn.Linear(embedding_dim, 1024, bias=False)
|
| 717 |
+
self.out2 = nn.Linear(embedding_dim, 1024, bias=False)
|
| 718 |
+
else:
|
| 719 |
+
if embedding_dim != 1024:
|
| 720 |
+
self.low_rank = nn.Linear(embedding_dim, 1024, bias=False)
|
| 721 |
+
|
| 722 |
+
def forward(self, input):
|
| 723 |
+
is_zero = input == self.zero_idx
|
| 724 |
+
zero = torch.zeros(1, dtype=input.dtype, device=input.device)
|
| 725 |
+
input = input.clamp(min=0)
|
| 726 |
+
if self.demux_second_stream:
|
| 727 |
+
left = super().forward(input % self.num_embeddings)
|
| 728 |
+
right = input // self.num_embeddings - 1
|
| 729 |
+
right_zero = (right < 0)[..., None]
|
| 730 |
+
right.clamp_(min=0)
|
| 731 |
+
right = super().forward(right)
|
| 732 |
+
y = self.out1(left) + torch.where(right_zero, zero, self.out2(right))
|
| 733 |
+
y = torch.where(is_zero[..., None], zero, y)
|
| 734 |
+
else:
|
| 735 |
+
y = super().forward(input)
|
| 736 |
+
y = torch.where(is_zero[..., None], zero, y)
|
| 737 |
+
if self.low_rank is not None:
|
| 738 |
+
# Can only see low_rank if no demux second stream
|
| 739 |
+
y = self.low_rank(y) # applies after
|
| 740 |
+
return y
|