jbetker commited on
Commit
a578697
1 Parent(s): 8e94abd

clear out new_autoregressive api

Browse files
Files changed (1) hide show
  1. api_new_autoregressive.py +0 -245
api_new_autoregressive.py DELETED
@@ -1,245 +0,0 @@
1
- import argparse
2
- import os
3
- import random
4
- from urllib import request
5
-
6
- import torch
7
- import torch.nn.functional as F
8
- import torchaudio
9
- import progressbar
10
- import ocotillo
11
-
12
- from models.diffusion_decoder import DiffusionTts
13
- from models.autoregressive import UnifiedVoice
14
- from tqdm import tqdm
15
-
16
- from models.arch_util import TorchMelSpectrogram
17
- from models.new_autoregressive import AutoregressiveCodegen
18
- from models.text_voice_clip import VoiceCLIP
19
- from models.vocoder import UnivNetGenerator
20
- from utils.audio import load_audio, wav_to_univnet_mel, denormalize_tacotron_mel
21
- from utils.diffusion import SpacedDiffusion, space_timesteps, get_named_beta_schedule
22
- from utils.tokenizer import VoiceBpeTokenizer, lev_distance
23
-
24
-
25
- pbar = None
26
- def download_models():
27
- MODELS = {
28
- 'clip.pth': 'https://huggingface.co/jbetker/tortoise-tts-clip/resolve/main/pytorch-model.bin',
29
- 'diffusion.pth': 'https://huggingface.co/jbetker/tortoise-tts-diffusion-v1/resolve/main/pytorch-model.bin',
30
- 'autoregressive.pth': 'https://huggingface.co/jbetker/tortoise-tts-autoregressive/resolve/main/pytorch-model.bin'
31
- }
32
- os.makedirs('.models', exist_ok=True)
33
- def show_progress(block_num, block_size, total_size):
34
- global pbar
35
- if pbar is None:
36
- pbar = progressbar.ProgressBar(maxval=total_size)
37
- pbar.start()
38
-
39
- downloaded = block_num * block_size
40
- if downloaded < total_size:
41
- pbar.update(downloaded)
42
- else:
43
- pbar.finish()
44
- pbar = None
45
- for model_name, url in MODELS.items():
46
- if os.path.exists(f'.models/{model_name}'):
47
- continue
48
- print(f'Downloading {model_name} from {url}...')
49
- request.urlretrieve(url, f'.models/{model_name}', show_progress)
50
- print('Done.')
51
-
52
-
53
- def pad_or_truncate(t, length):
54
- if t.shape[-1] == length:
55
- return t
56
- elif t.shape[-1] < length:
57
- return F.pad(t, (0, length-t.shape[-1]))
58
- else:
59
- return t[..., :length]
60
-
61
-
62
- def load_discrete_vocoder_diffuser(trained_diffusion_steps=4000, desired_diffusion_steps=200, cond_free=True, cond_free_k=1):
63
- """
64
- Helper function to load a GaussianDiffusion instance configured for use as a vocoder.
65
- """
66
- return SpacedDiffusion(use_timesteps=space_timesteps(trained_diffusion_steps, [desired_diffusion_steps]), model_mean_type='epsilon',
67
- model_var_type='learned_range', loss_type='mse', betas=get_named_beta_schedule('linear', trained_diffusion_steps),
68
- conditioning_free=cond_free, conditioning_free_k=cond_free_k)
69
-
70
-
71
- def load_conditioning(clip, cond_length=132300):
72
- gap = clip.shape[-1] - cond_length
73
- if gap < 0:
74
- clip = F.pad(clip, pad=(0, abs(gap)))
75
- elif gap > 0:
76
- rand_start = random.randint(0, gap)
77
- clip = clip[:, rand_start:rand_start + cond_length]
78
- mel_clip = TorchMelSpectrogram()(clip.unsqueeze(0)).squeeze(0)
79
- return mel_clip.unsqueeze(0).cuda()
80
-
81
-
82
- def fix_autoregressive_output(codes, stop_token):
83
- """
84
- This function performs some padding on coded audio that fixes a mismatch issue between what the diffusion model was
85
- trained on and what the autoregressive code generator creates (which has no padding or end).
86
- This is highly specific to the DVAE being used, so this particular coding will not necessarily work if used with
87
- a different DVAE. This can be inferred by feeding a audio clip padded with lots of zeros on the end through the DVAE
88
- and copying out the last few codes.
89
-
90
- Failing to do this padding will produce speech with a harsh end that sounds like "BLAH" or similar.
91
- """
92
- # Strip off the autoregressive stop token and add padding.
93
- stop_token_indices = (codes == stop_token).nonzero()
94
- if len(stop_token_indices) == 0:
95
- print("No stop tokens found, enjoy that output of yours!")
96
- return codes
97
- else:
98
- codes[stop_token_indices] = 83
99
- stm = stop_token_indices.min().item()
100
- codes[stm:] = 83
101
- if stm - 3 < codes.shape[0]:
102
- codes[-3] = 45
103
- codes[-2] = 45
104
- codes[-1] = 248
105
-
106
- return codes
107
-
108
-
109
- def do_spectrogram_diffusion(diffusion_model, diffuser, mel_codes, conditioning_samples, temperature=1):
110
- """
111
- Uses the specified diffusion model to convert discrete codes into a spectrogram.
112
- """
113
- with torch.no_grad():
114
- cond_mels = []
115
- for sample in conditioning_samples:
116
- sample = pad_or_truncate(sample, 102400)
117
- cond_mel = wav_to_univnet_mel(sample.to(mel_codes.device), do_normalization=False)
118
- cond_mels.append(cond_mel)
119
- cond_mels = torch.stack(cond_mels, dim=1)
120
-
121
- output_seq_len = mel_codes.shape[-1]*4*24000//22050 # This diffusion model converts from 22kHz spectrogram codes to a 24kHz spectrogram signal.
122
- output_shape = (mel_codes.shape[0], 100, output_seq_len)
123
- precomputed_embeddings = diffusion_model.timestep_independent(mel_codes, cond_mels, output_seq_len, False)
124
-
125
- noise = torch.randn(output_shape, device=mel_codes.device) * temperature
126
- mel = diffuser.p_sample_loop(diffusion_model, output_shape, noise=noise,
127
- model_kwargs={'precomputed_aligned_embeddings': precomputed_embeddings})
128
- return denormalize_tacotron_mel(mel)[:,:,:output_seq_len]
129
-
130
-
131
- class TextToSpeech:
132
- def __init__(self, autoregressive_batch_size=32):
133
- self.autoregressive_batch_size = autoregressive_batch_size
134
- self.tokenizer = VoiceBpeTokenizer()
135
- download_models()
136
-
137
- self.autoregressive = AutoregressiveCodegen(1024, 16).cpu().eval()
138
- self.autoregressive.load_state_dict(torch.load('X:\\dlas\\experiments\\train_autoregressive_codegen\\models\\20750_codegen_ema.pth'))
139
-
140
- self.clip = VoiceCLIP(dim_text=512, dim_speech=512, dim_latent=512, num_text_tokens=256, text_enc_depth=12,
141
- text_seq_len=350, text_heads=8,
142
- num_speech_tokens=8192, speech_enc_depth=12, speech_heads=8, speech_seq_len=430,
143
- use_xformers=True).cpu().eval()
144
- self.clip.load_state_dict(torch.load('.models/clip.pth'))
145
-
146
- self.diffusion = DiffusionTts(model_channels=1024, num_layers=10, in_channels=100, out_channels=200,
147
- in_latent_channels=1024, in_tokens=8193, dropout=0, use_fp16=False, num_heads=16,
148
- layer_drop=0, unconditioned_percentage=0).cpu().eval()
149
- self.diffusion.load_state_dict(torch.load('.models/diffusion.pth'))
150
-
151
- self.vocoder = UnivNetGenerator().cpu()
152
- self.vocoder.load_state_dict(torch.load('.models/vocoder.pth')['model_g'])
153
- self.vocoder.eval(inference=True)
154
-
155
- def tts(self, text, voice_samples, k=1,
156
- # autoregressive generation parameters follow
157
- num_autoregressive_samples=512, temperature=.5, length_penalty=2, repetition_penalty=2.0, top_p=.5,
158
- typical_sampling=False, typical_mass=.9,
159
- # diffusion generation parameters follow
160
- diffusion_iterations=100, cond_free=True, cond_free_k=2, diffusion_temperature=.7,):
161
- text = torch.IntTensor(self.tokenizer.encode(text)).unsqueeze(0).cuda()
162
- text = F.pad(text, (0, 1)) # This may not be necessary.
163
-
164
- conds = []
165
- if not isinstance(voice_samples, list):
166
- voice_samples = [voice_samples]
167
- for vs in voice_samples:
168
- conds.append(load_conditioning(vs))
169
- conds = torch.stack(conds, dim=1)
170
-
171
- diffuser = load_discrete_vocoder_diffuser(desired_diffusion_steps=diffusion_iterations, cond_free=cond_free, cond_free_k=cond_free_k)
172
-
173
- with torch.no_grad():
174
- samples = []
175
- num_batches = num_autoregressive_samples // self.autoregressive_batch_size
176
- stop_mel_token = self.autoregressive.STOP_TOKEN
177
- self.autoregressive = self.autoregressive.cuda()
178
- for _ in tqdm(range(num_batches)):
179
- codes = self.autoregressive.generate(conds, text,
180
- do_sample=True,
181
- top_p=top_p,
182
- temperature=temperature,
183
- num_return_sequences=self.autoregressive_batch_size,
184
- length_penalty=length_penalty,
185
- repetition_penalty=repetition_penalty,
186
- typical_sampling=typical_sampling,
187
- typical_mass=typical_mass)
188
- padding_needed = 250 - codes.shape[1]
189
- codes = F.pad(codes, (0, padding_needed), value=stop_mel_token)
190
- samples.append(codes)
191
- #self.autoregressive = self.autoregressive.cpu()
192
-
193
- clip_results = []
194
- self.clip = self.clip.cuda()
195
- for batch in samples:
196
- for i in range(batch.shape[0]):
197
- batch[i] = fix_autoregressive_output(batch[i], stop_mel_token)
198
- bad_toks = batch >= 8192
199
- batch = batch * bad_toks.logical_not()
200
- clip_results.append(self.clip(text.repeat(batch.shape[0], 1), batch, return_loss=False))
201
- clip_results = torch.cat(clip_results, dim=0)
202
- samples = torch.cat(samples, dim=0)
203
- best_results = samples[torch.topk(clip_results, k=k).indices]
204
- self.clip = self.clip.cpu()
205
- del samples
206
-
207
- print("Performing vocoding..")
208
- wav_candidates = []
209
- self.diffusion = self.diffusion.cuda()
210
- self.vocoder = self.vocoder.cuda()
211
- for b in range(best_results.shape[0]):
212
- code = best_results[b].unsqueeze(0)
213
- mel = do_spectrogram_diffusion(self.diffusion, diffuser, code, voice_samples, temperature=diffusion_temperature)
214
- wav = self.vocoder.inference(mel)
215
- wav_candidates.append(wav.cpu())
216
- self.diffusion = self.diffusion.cpu()
217
- self.vocoder = self.vocoder.cpu()
218
-
219
- if len(wav_candidates) > 1:
220
- return wav_candidates
221
- return wav_candidates[0]
222
-
223
- def refine_for_intellibility(self, wav_candidates, corresponding_codes, output_path):
224
- """
225
- Further refine the remaining candidates using a ASR model to pick out the ones that are the most understandable.
226
- TODO: finish this function
227
- :param wav_candidates:
228
- :return:
229
- """
230
- transcriber = ocotillo.Transcriber(on_cuda=True)
231
- transcriptions = transcriber.transcribe_batch(torch.cat(wav_candidates, dim=0).squeeze(1), 24000)
232
- best = 99999999
233
- for i, transcription in enumerate(transcriptions):
234
- dist = lev_distance(transcription, args.text.lower())
235
- if dist < best:
236
- best = dist
237
- best_codes = corresponding_codes[i].unsqueeze(0)
238
- best_wav = wav_candidates[i]
239
- del transcriber
240
- torchaudio.save(os.path.join(output_path, f'{voice}_poor.wav'), best_wav.squeeze(0).cpu(), 24000)
241
-
242
- # Perform diffusion again with the high-quality diffuser.
243
- mel = do_spectrogram_diffusion(diffusion, final_diffuser, best_codes, cond_diffusion, mean=False)
244
- wav = vocoder.inference(mel)
245
- torchaudio.save(os.path.join(args.output_path, f'{voice}.wav'), wav.squeeze(0).cpu(), 24000)