MasonCrinr commited on
Commit
6860da7
1 Parent(s): 3d99ca3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +599 -0
app.py ADDED
@@ -0,0 +1,599 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import random
4
+ import uuid
5
+ from time import time
6
+ from urllib import request
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import progressbar
11
+ import torchaudio
12
+
13
+ from tortoise.models.classifier import AudioMiniEncoderWithClassifierHead
14
+ from tortoise.models.diffusion_decoder import DiffusionTts
15
+ from tortoise.models.autoregressive import UnifiedVoice
16
+ from tqdm import tqdm
17
+ from tortoise.models.arch_util import TorchMelSpectrogram
18
+ from tortoise.models.clvp import CLVP
19
+ from tortoise.models.cvvp import CVVP
20
+ from tortoise.models.random_latent_generator import RandomLatentConverter
21
+ from tortoise.models.vocoder import UnivNetGenerator
22
+ from tortoise.utils.audio import wav_to_univnet_mel, denormalize_tacotron_mel
23
+ from tortoise.utils.diffusion import SpacedDiffusion, space_timesteps, get_named_beta_schedule
24
+ from tortoise.utils.tokenizer import VoiceBpeTokenizer
25
+ from tortoise.utils.wav2vec_alignment import Wav2VecAlignment
26
+ from contextlib import contextmanager
27
+ from huggingface_hub import hf_hub_download
28
+ pbar = None
29
+
30
+ DEFAULT_MODELS_DIR = os.path.join(os.path.expanduser('~'), '.cache', 'tortoise', 'models')
31
+ MODELS_DIR = os.environ.get('TORTOISE_MODELS_DIR', DEFAULT_MODELS_DIR)
32
+ MODELS = {
33
+ 'autoregressive.pth': 'https://huggingface.co/jbetker/tortoise-tts-v2/resolve/main/.models/autoregressive.pth',
34
+ 'classifier.pth': 'https://huggingface.co/jbetker/tortoise-tts-v2/resolve/main/.models/classifier.pth',
35
+ 'clvp2.pth': 'https://huggingface.co/jbetker/tortoise-tts-v2/resolve/main/.models/clvp2.pth',
36
+ 'cvvp.pth': 'https://huggingface.co/jbetker/tortoise-tts-v2/resolve/main/.models/cvvp.pth',
37
+ 'diffusion_decoder.pth': 'https://huggingface.co/jbetker/tortoise-tts-v2/resolve/main/.models/diffusion_decoder.pth',
38
+ 'vocoder.pth': 'https://huggingface.co/jbetker/tortoise-tts-v2/resolve/main/.models/vocoder.pth',
39
+ 'rlg_auto.pth': 'https://huggingface.co/jbetker/tortoise-tts-v2/resolve/main/.models/rlg_auto.pth',
40
+ 'rlg_diffuser.pth': 'https://huggingface.co/jbetker/tortoise-tts-v2/resolve/main/.models/rlg_diffuser.pth',
41
+ }
42
+
43
+ def get_model_path(model_name, models_dir=MODELS_DIR):
44
+ """
45
+ Get path to given model, download it if it doesn't exist.
46
+ """
47
+ if model_name not in MODELS:
48
+ raise ValueError(f'Model {model_name} not found in available models.')
49
+ model_path = hf_hub_download(repo_id="Manmay/tortoise-tts", filename=model_name, cache_dir=models_dir)
50
+ return model_path
51
+
52
+
53
+ def pad_or_truncate(t, length):
54
+ """
55
+ Utility function for forcing <t> to have the specified sequence length, whether by clipping it or padding it with 0s.
56
+ """
57
+ if t.shape[-1] == length:
58
+ return t
59
+ elif t.shape[-1] < length:
60
+ return F.pad(t, (0, length-t.shape[-1]))
61
+ else:
62
+ return t[..., :length]
63
+
64
+
65
+ def load_discrete_vocoder_diffuser(trained_diffusion_steps=4000, desired_diffusion_steps=200, cond_free=True, cond_free_k=1):
66
+ """
67
+ Helper function to load a GaussianDiffusion instance configured for use as a vocoder.
68
+ """
69
+ return SpacedDiffusion(use_timesteps=space_timesteps(trained_diffusion_steps, [desired_diffusion_steps]), model_mean_type='epsilon',
70
+ model_var_type='learned_range', loss_type='mse', betas=get_named_beta_schedule('linear', trained_diffusion_steps),
71
+ conditioning_free=cond_free, conditioning_free_k=cond_free_k)
72
+
73
+
74
+ def format_conditioning(clip, cond_length=132300, device="cuda" if not torch.backends.mps.is_available() else 'mps'):
75
+ """
76
+ Converts the given conditioning signal to a MEL spectrogram and clips it as expected by the models.
77
+ """
78
+ gap = clip.shape[-1] - cond_length
79
+ if gap < 0:
80
+ clip = F.pad(clip, pad=(0, abs(gap)))
81
+ elif gap > 0:
82
+ rand_start = random.randint(0, gap)
83
+ clip = clip[:, rand_start:rand_start + cond_length]
84
+ mel_clip = TorchMelSpectrogram()(clip.unsqueeze(0)).squeeze(0)
85
+ return mel_clip.unsqueeze(0).to(device)
86
+
87
+
88
+ def fix_autoregressive_output(codes, stop_token, complain=True):
89
+ """
90
+ This function performs some padding on coded audio that fixes a mismatch issue between what the diffusion model was
91
+ trained on and what the autoregressive code generator creates (which has no padding or end).
92
+ This is highly specific to the DVAE being used, so this particular coding will not necessarily work if used with
93
+ a different DVAE. This can be inferred by feeding a audio clip padded with lots of zeros on the end through the DVAE
94
+ and copying out the last few codes.
95
+
96
+ Failing to do this padding will produce speech with a harsh end that sounds like "BLAH" or similar.
97
+ """
98
+ # Strip off the autoregressive stop token and add padding.
99
+ stop_token_indices = (codes == stop_token).nonzero()
100
+ if len(stop_token_indices) == 0:
101
+ if complain:
102
+ print("No stop tokens found in one of the generated voice clips. This typically means the spoken audio is "
103
+ "too long. In some cases, the output will still be good, though. Listen to it and if it is missing words, "
104
+ "try breaking up your input text.")
105
+ return codes
106
+ else:
107
+ codes[stop_token_indices] = 83
108
+ stm = stop_token_indices.min().item()
109
+ codes[stm:] = 83
110
+ if stm - 3 < codes.shape[0]:
111
+ codes[-3] = 45
112
+ codes[-2] = 45
113
+ codes[-1] = 248
114
+
115
+ return codes
116
+
117
+
118
+ def do_spectrogram_diffusion(diffusion_model, diffuser, latents, conditioning_latents, temperature=1, verbose=True):
119
+ """
120
+ Uses the specified diffusion model to convert discrete codes into a spectrogram.
121
+ """
122
+ with torch.no_grad():
123
+ output_seq_len = latents.shape[1] * 4 * 24000 // 22050 # This diffusion model converts from 22kHz spectrogram codes to a 24kHz spectrogram signal.
124
+ output_shape = (latents.shape[0], 100, output_seq_len)
125
+ precomputed_embeddings = diffusion_model.timestep_independent(latents, conditioning_latents, output_seq_len, False)
126
+
127
+ noise = torch.randn(output_shape, device=latents.device) * temperature
128
+ mel = diffuser.p_sample_loop(diffusion_model, output_shape, noise=noise,
129
+ model_kwargs={'precomputed_aligned_embeddings': precomputed_embeddings},
130
+ progress=verbose)
131
+ return denormalize_tacotron_mel(mel)[:,:,:output_seq_len]
132
+
133
+
134
+ def classify_audio_clip(clip):
135
+ """
136
+ Returns whether or not Tortoises' classifier thinks the given clip came from Tortoise.
137
+ :param clip: torch tensor containing audio waveform data (get it from load_audio)
138
+ :return: True if the clip was classified as coming from Tortoise and false if it was classified as real.
139
+ """
140
+ classifier = AudioMiniEncoderWithClassifierHead(2, spec_dim=1, embedding_dim=512, depth=5, downsample_factor=4,
141
+ resnet_blocks=2, attn_blocks=4, num_attn_heads=4, base_channels=32,
142
+ dropout=0, kernel_size=5, distribute_zero_label=False)
143
+ classifier.load_state_dict(torch.load(get_model_path('classifier.pth'), map_location=torch.device('cpu')))
144
+ clip = clip.cpu().unsqueeze(0)
145
+ results = F.softmax(classifier(clip), dim=-1)
146
+ return results[0][0]
147
+
148
+
149
+ def pick_best_batch_size_for_gpu():
150
+ """
151
+ Tries to pick a batch size that will fit in your GPU. These sizes aren't guaranteed to work, but they should give
152
+ you a good shot.
153
+ """
154
+ if torch.cuda.is_available():
155
+ _, available = torch.cuda.mem_get_info()
156
+ availableGb = available / (1024 ** 3)
157
+ if availableGb > 14:
158
+ return 16
159
+ elif availableGb > 10:
160
+ return 8
161
+ elif availableGb > 7:
162
+ return 4
163
+ if torch.backends.mps.is_available():
164
+ import psutil
165
+ available = psutil.virtual_memory().total
166
+ availableGb = available / (1024 ** 3)
167
+ if availableGb > 14:
168
+ return 16
169
+ elif availableGb > 10:
170
+ return 8
171
+ elif availableGb > 7:
172
+ return 4
173
+ return 1
174
+
175
+ class TextToSpeech:
176
+ """
177
+ Main entry point into Tortoise.
178
+ """
179
+
180
+ def __init__(self, autoregressive_batch_size=None, models_dir=MODELS_DIR,
181
+ enable_redaction=True, kv_cache=False, use_deepspeed=False, half=False, device=None,
182
+ tokenizer_vocab_file=None, tokenizer_basic=False):
183
+
184
+ """
185
+ Constructor
186
+ :param autoregressive_batch_size: Specifies how many samples to generate per batch. Lower this if you are seeing
187
+ GPU OOM errors. Larger numbers generates slightly faster.
188
+ :param models_dir: Where model weights are stored. This should only be specified if you are providing your own
189
+ models, otherwise use the defaults.
190
+ :param enable_redaction: When true, text enclosed in brackets are automatically redacted from the spoken output
191
+ (but are still rendered by the model). This can be used for prompt engineering.
192
+ Default is true.
193
+ :param device: Device to use when running the model. If omitted, the device will be automatically chosen.
194
+ """
195
+ self.models_dir = models_dir
196
+ self.autoregressive_batch_size = pick_best_batch_size_for_gpu() if autoregressive_batch_size is None else autoregressive_batch_size
197
+ self.enable_redaction = enable_redaction
198
+ self.device = torch.device('cuda' if torch.cuda.is_available() else'cpu')
199
+ if torch.backends.mps.is_available():
200
+ self.device = torch.device('mps')
201
+ if self.enable_redaction:
202
+ self.aligner = Wav2VecAlignment()
203
+
204
+ self.tokenizer = VoiceBpeTokenizer(
205
+ vocab_file=tokenizer_vocab_file,
206
+ use_basic_cleaners=tokenizer_basic,
207
+ )
208
+ self.half = half
209
+ if os.path.exists(f'{models_dir}/autoregressive.ptt'):
210
+ # Assume this is a traced directory.
211
+ self.autoregressive = torch.jit.load(f'{models_dir}/autoregressive.ptt')
212
+ self.diffusion = torch.jit.load(f'{models_dir}/diffusion_decoder.ptt')
213
+ else:
214
+ self.autoregressive = UnifiedVoice(max_mel_tokens=604, max_text_tokens=402, max_conditioning_inputs=2, layers=30,
215
+ model_dim=1024,
216
+ heads=16, number_text_tokens=255, start_text_token=255, checkpointing=False,
217
+ train_solo_embeddings=False).cpu().eval()
218
+ self.autoregressive.load_state_dict(torch.load(get_model_path('autoregressive.pth', models_dir)), strict=False)
219
+ self.autoregressive.post_init_gpt2_config(use_deepspeed=use_deepspeed, kv_cache=kv_cache, half=self.half)
220
+
221
+ self.diffusion = DiffusionTts(model_channels=1024, num_layers=10, in_channels=100, out_channels=200,
222
+ in_latent_channels=1024, in_tokens=8193, dropout=0, use_fp16=False, num_heads=16,
223
+ layer_drop=0, unconditioned_percentage=0).cpu().eval()
224
+ self.diffusion.load_state_dict(torch.load(get_model_path('diffusion_decoder.pth', models_dir)))
225
+
226
+ self.clvp = CLVP(dim_text=768, dim_speech=768, dim_latent=768, num_text_tokens=256, text_enc_depth=20,
227
+ text_seq_len=350, text_heads=12,
228
+ num_speech_tokens=8192, speech_enc_depth=20, speech_heads=12, speech_seq_len=430,
229
+ use_xformers=True).cpu().eval()
230
+ self.clvp.load_state_dict(torch.load(get_model_path('clvp2.pth', models_dir)))
231
+ self.cvvp = None # CVVP model is only loaded if used.
232
+
233
+ self.vocoder = UnivNetGenerator().cpu()
234
+ self.vocoder.load_state_dict(torch.load(get_model_path('vocoder.pth', models_dir), map_location=torch.device('cpu'))['model_g'])
235
+ self.vocoder.eval(inference=True)
236
+
237
+ # Random latent generators (RLGs) are loaded lazily.
238
+ self.rlg_auto = None
239
+ self.rlg_diffusion = None
240
+ @contextmanager
241
+ def temporary_cuda(self, model):
242
+ m = model.to(self.device)
243
+ yield m
244
+ m = model.cpu()
245
+
246
+
247
+ def load_cvvp(self):
248
+ """Load CVVP model."""
249
+ self.cvvp = CVVP(model_dim=512, transformer_heads=8, dropout=0, mel_codes=8192, conditioning_enc_depth=8, cond_mask_percentage=0,
250
+ speech_enc_depth=8, speech_mask_percentage=0, latent_multiplier=1).cpu().eval()
251
+ self.cvvp.load_state_dict(torch.load(get_model_path('cvvp.pth', self.models_dir)))
252
+
253
+ def get_conditioning_latents(self, voice_samples, return_mels=False):
254
+ """
255
+ Transforms one or more voice_samples into a tuple (autoregressive_conditioning_latent, diffusion_conditioning_latent).
256
+ These are expressive learned latents that encode aspects of the provided clips like voice, intonation, and acoustic
257
+ properties.
258
+ :param voice_samples: List of 2 or more ~10 second reference clips, which should be torch tensors containing 22.05kHz waveform data.
259
+ """
260
+ with torch.no_grad():
261
+ voice_samples = [v.to(self.device) for v in voice_samples]
262
+
263
+ auto_conds = []
264
+ if not isinstance(voice_samples, list):
265
+ voice_samples = [voice_samples]
266
+ for vs in voice_samples:
267
+ auto_conds.append(format_conditioning(vs, device=self.device))
268
+ auto_conds = torch.stack(auto_conds, dim=1)
269
+ self.autoregressive = self.autoregressive.to(self.device)
270
+ auto_latent = self.autoregressive.get_conditioning(auto_conds)
271
+ self.autoregressive = self.autoregressive.cpu()
272
+
273
+ diffusion_conds = []
274
+ for sample in voice_samples:
275
+ # The diffuser operates at a sample rate of 24000 (except for the latent inputs)
276
+ sample = torchaudio.functional.resample(sample, 22050, 24000)
277
+ sample = pad_or_truncate(sample, 102400)
278
+ cond_mel = wav_to_univnet_mel(sample.to(self.device), do_normalization=False, device=self.device)
279
+ diffusion_conds.append(cond_mel)
280
+ diffusion_conds = torch.stack(diffusion_conds, dim=1)
281
+
282
+ self.diffusion = self.diffusion.to(self.device)
283
+ diffusion_latent = self.diffusion.get_conditioning(diffusion_conds)
284
+ self.diffusion = self.diffusion.cpu()
285
+
286
+ if return_mels:
287
+ return auto_latent, diffusion_latent, auto_conds, diffusion_conds
288
+ else:
289
+ return auto_latent, diffusion_latent
290
+
291
+ def get_random_conditioning_latents(self):
292
+ # Lazy-load the RLG models.
293
+ if self.rlg_auto is None:
294
+ self.rlg_auto = RandomLatentConverter(1024).eval()
295
+ self.rlg_auto.load_state_dict(torch.load(get_model_path('rlg_auto.pth', self.models_dir), map_location=torch.device('cpu')))
296
+ self.rlg_diffusion = RandomLatentConverter(2048).eval()
297
+ self.rlg_diffusion.load_state_dict(torch.load(get_model_path('rlg_diffuser.pth', self.models_dir), map_location=torch.device('cpu')))
298
+ with torch.no_grad():
299
+ return self.rlg_auto(torch.tensor([0.0])), self.rlg_diffusion(torch.tensor([0.0]))
300
+
301
+ def tts_with_preset(self, text, preset='fast', **kwargs):
302
+ """
303
+ Calls TTS with one of a set of preset generation parameters. Options:
304
+ 'ultra_fast': Produces speech at a speed which belies the name of this repo. (Not really, but it's definitely fastest).
305
+ 'fast': Decent quality speech at a decent inference rate. A good choice for mass inference.
306
+ 'standard': Very good quality. This is generally about as good as you are going to get.
307
+ 'high_quality': Use if you want the absolute best. This is not really worth the compute, though.
308
+ """
309
+ # Use generally found best tuning knobs for generation.
310
+ settings = {'temperature': .8, 'length_penalty': 1.0, 'repetition_penalty': 2.0,
311
+ 'top_p': .8,
312
+ 'cond_free_k': 2.0, 'diffusion_temperature': 1.0}
313
+ # Presets are defined here.
314
+ presets = {
315
+ 'ultra_fast': {'num_autoregressive_samples': 16, 'diffusion_iterations': 30, 'cond_free': False},
316
+ 'fast': {'num_autoregressive_samples': 96, 'diffusion_iterations': 80},
317
+ 'standard': {'num_autoregressive_samples': 256, 'diffusion_iterations': 200},
318
+ 'high_quality': {'num_autoregressive_samples': 256, 'diffusion_iterations': 400},
319
+ }
320
+ settings.update(presets[preset])
321
+ settings.update(kwargs) # allow overriding of preset settings with kwargs
322
+ return self.tts(text, **settings)
323
+
324
+ def tts(self, text, voice_samples=None, conditioning_latents=None, k=1, verbose=True, use_deterministic_seed=None,
325
+ return_deterministic_state=False,
326
+ # autoregressive generation parameters follow
327
+ num_autoregressive_samples=512, temperature=.8, length_penalty=1, repetition_penalty=2.0, top_p=.8, max_mel_tokens=500,
328
+ # CVVP parameters follow
329
+ cvvp_amount=.0,
330
+ # diffusion generation parameters follow
331
+ diffusion_iterations=100, cond_free=True, cond_free_k=2, diffusion_temperature=1.0,
332
+ **hf_generate_kwargs):
333
+ """
334
+ Produces an audio clip of the given text being spoken with the given reference voice.
335
+ :param text: Text to be spoken.
336
+ :param voice_samples: List of 2 or more ~10 second reference clips which should be torch tensors containing 22.05kHz waveform data.
337
+ :param conditioning_latents: A tuple of (autoregressive_conditioning_latent, diffusion_conditioning_latent), which
338
+ can be provided in lieu of voice_samples. This is ignored unless voice_samples=None.
339
+ Conditioning latents can be retrieved via get_conditioning_latents().
340
+ :param k: The number of returned clips. The most likely (as determined by Tortoises' CLVP model) clips are returned.
341
+ :param verbose: Whether or not to print log messages indicating the progress of creating a clip. Default=true.
342
+ ~~AUTOREGRESSIVE KNOBS~~
343
+ :param num_autoregressive_samples: Number of samples taken from the autoregressive model, all of which are filtered using CLVP.
344
+ As Tortoise is a probabilistic model, more samples means a higher probability of creating something "great".
345
+ :param temperature: The softmax temperature of the autoregressive model.
346
+ :param length_penalty: A length penalty applied to the autoregressive decoder. Higher settings causes the model to produce more terse outputs.
347
+ :param repetition_penalty: A penalty that prevents the autoregressive decoder from repeating itself during decoding. Can be used to reduce the incidence
348
+ of long silences or "uhhhhhhs", etc.
349
+ :param top_p: P value used in nucleus sampling. (0,1]. Lower values mean the decoder produces more "likely" (aka boring) outputs.
350
+ :param max_mel_tokens: Restricts the output length. (0,600] integer. Each unit is 1/20 of a second.
351
+ :param typical_sampling: Turns typical sampling on or off. This sampling mode is discussed in this paper: https://arxiv.org/abs/2202.00666
352
+ I was interested in the premise, but the results were not as good as I was hoping. This is off by default, but
353
+ could use some tuning.
354
+ :param typical_mass: The typical_mass parameter from the typical_sampling algorithm.
355
+ ~~CLVP-CVVP KNOBS~~
356
+ :param cvvp_amount: Controls the influence of the CVVP model in selecting the best output from the autoregressive model.
357
+ [0,1]. Values closer to 1 mean the CVVP model is more important, 0 disables the CVVP model.
358
+ ~~DIFFUSION KNOBS~~
359
+ :param diffusion_iterations: Number of diffusion steps to perform. [0,4000]. More steps means the network has more chances to iteratively refine
360
+ the output, which should theoretically mean a higher quality output. Generally a value above 250 is not noticeably better,
361
+ however.
362
+ :param cond_free: Whether or not to perform conditioning-free diffusion. Conditioning-free diffusion performs two forward passes for
363
+ each diffusion step: one with the outputs of the autoregressive model and one with no conditioning priors. The output
364
+ of the two is blended according to the cond_free_k value below. Conditioning-free diffusion is the real deal, and
365
+ dramatically improves realism.
366
+ :param cond_free_k: Knob that determines how to balance the conditioning free signal with the conditioning-present signal. [0,inf].
367
+ As cond_free_k increases, the output becomes dominated by the conditioning-free signal.
368
+ Formula is: output=cond_present_output*(cond_free_k+1)-cond_absenct_output*cond_free_k
369
+ :param diffusion_temperature: Controls the variance of the noise fed into the diffusion model. [0,1]. Values at 0
370
+ are the "mean" prediction of the diffusion network and will sound bland and smeared.
371
+ ~~OTHER STUFF~~
372
+ :param hf_generate_kwargs: The huggingface Transformers generate API is used for the autoregressive transformer.
373
+ Extra keyword args fed to this function get forwarded directly to that API. Documentation
374
+ here: https://huggingface.co/docs/transformers/internal/generation_utils
375
+ :return: Generated audio clip(s) as a torch tensor. Shape 1,S if k=1 else, (k,1,S) where S is the sample length.
376
+ Sample rate is 24kHz.
377
+ """
378
+ deterministic_seed = self.deterministic_state(seed=use_deterministic_seed)
379
+
380
+ text_tokens = torch.IntTensor(self.tokenizer.encode(text)).unsqueeze(0).to(self.device)
381
+ text_tokens = F.pad(text_tokens, (0, 1)) # This may not be necessary.
382
+ assert text_tokens.shape[-1] < 400, 'Too much text provided. Break the text up into separate segments and re-try inference.'
383
+ auto_conds = None
384
+ if voice_samples is not None:
385
+ auto_conditioning, diffusion_conditioning, auto_conds, _ = self.get_conditioning_latents(voice_samples, return_mels=True)
386
+ elif conditioning_latents is not None:
387
+ auto_conditioning, diffusion_conditioning = conditioning_latents
388
+ else:
389
+ auto_conditioning, diffusion_conditioning = self.get_random_conditioning_latents()
390
+ auto_conditioning = auto_conditioning.to(self.device)
391
+ diffusion_conditioning = diffusion_conditioning.to(self.device)
392
+
393
+ diffuser = load_discrete_vocoder_diffuser(desired_diffusion_steps=diffusion_iterations, cond_free=cond_free, cond_free_k=cond_free_k)
394
+
395
+ with torch.no_grad():
396
+ samples = []
397
+ num_batches = num_autoregressive_samples // self.autoregressive_batch_size
398
+ stop_mel_token = self.autoregressive.stop_mel_token
399
+ calm_token = 83 # This is the token for coding silence, which is fixed in place with "fix_autoregressive_output"
400
+ if verbose:
401
+ print("Generating autoregressive samples..")
402
+ if not torch.backends.mps.is_available():
403
+ with self.temporary_cuda(self.autoregressive
404
+ ) as autoregressive, torch.autocast(device_type="cuda", dtype=torch.float16, enabled=self.half):
405
+ for b in tqdm(range(num_batches), disable=not verbose):
406
+ codes = autoregressive.inference_speech(auto_conditioning, text_tokens,
407
+ do_sample=True,
408
+ top_p=top_p,
409
+ temperature=temperature,
410
+ num_return_sequences=self.autoregressive_batch_size,
411
+ length_penalty=length_penalty,
412
+ repetition_penalty=repetition_penalty,
413
+ max_generate_length=max_mel_tokens,
414
+ **hf_generate_kwargs)
415
+ padding_needed = max_mel_tokens - codes.shape[1]
416
+ codes = F.pad(codes, (0, padding_needed), value=stop_mel_token)
417
+ samples.append(codes)
418
+ else:
419
+ with self.temporary_cuda(self.autoregressive) as autoregressive:
420
+ for b in tqdm(range(num_batches), disable=not verbose):
421
+ codes = autoregressive.inference_speech(auto_conditioning, text_tokens,
422
+ do_sample=True,
423
+ top_p=top_p,
424
+ temperature=temperature,
425
+ num_return_sequences=self.autoregressive_batch_size,
426
+ length_penalty=length_penalty,
427
+ repetition_penalty=repetition_penalty,
428
+ max_generate_length=max_mel_tokens,
429
+ **hf_generate_kwargs)
430
+ padding_needed = max_mel_tokens - codes.shape[1]
431
+ codes = F.pad(codes, (0, padding_needed), value=stop_mel_token)
432
+ samples.append(codes)
433
+
434
+ clip_results = []
435
+
436
+ if not torch.backends.mps.is_available():
437
+ with self.temporary_cuda(self.clvp) as clvp, torch.autocast(
438
+ device_type="cuda" if not torch.backends.mps.is_available() else 'mps', dtype=torch.float16, enabled=self.half
439
+ ):
440
+ if cvvp_amount > 0:
441
+ if self.cvvp is None:
442
+ self.load_cvvp()
443
+ self.cvvp = self.cvvp.to(self.device)
444
+ if verbose:
445
+ if self.cvvp is None:
446
+ print("Computing best candidates using CLVP")
447
+ else:
448
+ print(f"Computing best candidates using CLVP {((1-cvvp_amount) * 100):2.0f}% and CVVP {(cvvp_amount * 100):2.0f}%")
449
+ for batch in tqdm(samples, disable=not verbose):
450
+ for i in range(batch.shape[0]):
451
+ batch[i] = fix_autoregressive_output(batch[i], stop_mel_token)
452
+ if cvvp_amount != 1:
453
+ clvp_out = clvp(text_tokens.repeat(batch.shape[0], 1), batch, return_loss=False)
454
+ if auto_conds is not None and cvvp_amount > 0:
455
+ cvvp_accumulator = 0
456
+ for cl in range(auto_conds.shape[1]):
457
+ cvvp_accumulator = cvvp_accumulator + self.cvvp(auto_conds[:, cl].repeat(batch.shape[0], 1, 1), batch, return_loss=False)
458
+ cvvp = cvvp_accumulator / auto_conds.shape[1]
459
+ if cvvp_amount == 1:
460
+ clip_results.append(cvvp)
461
+ else:
462
+ clip_results.append(cvvp * cvvp_amount + clvp_out * (1-cvvp_amount))
463
+ else:
464
+ clip_results.append(clvp_out)
465
+ clip_results = torch.cat(clip_results, dim=0)
466
+ samples = torch.cat(samples, dim=0)
467
+ best_results = samples[torch.topk(clip_results, k=k).indices]
468
+ else:
469
+ with self.temporary_cuda(self.clvp) as clvp:
470
+ if cvvp_amount > 0:
471
+ if self.cvvp is None:
472
+ self.load_cvvp()
473
+ self.cvvp = self.cvvp.to(self.device)
474
+ if verbose:
475
+ if self.cvvp is None:
476
+ print("Computing best candidates using CLVP")
477
+ else:
478
+ print(f"Computing best candidates using CLVP {((1-cvvp_amount) * 100):2.0f}% and CVVP {(cvvp_amount * 100):2.0f}%")
479
+ for batch in tqdm(samples, disable=not verbose):
480
+ for i in range(batch.shape[0]):
481
+ batch[i] = fix_autoregressive_output(batch[i], stop_mel_token)
482
+ if cvvp_amount != 1:
483
+ clvp_out = clvp(text_tokens.repeat(batch.shape[0], 1), batch, return_loss=False)
484
+ if auto_conds is not None and cvvp_amount > 0:
485
+ cvvp_accumulator = 0
486
+ for cl in range(auto_conds.shape[1]):
487
+ cvvp_accumulator = cvvp_accumulator + self.cvvp(auto_conds[:, cl].repeat(batch.shape[0], 1, 1), batch, return_loss=False)
488
+ cvvp = cvvp_accumulator / auto_conds.shape[1]
489
+ if cvvp_amount == 1:
490
+ clip_results.append(cvvp)
491
+ else:
492
+ clip_results.append(cvvp * cvvp_amount + clvp_out * (1-cvvp_amount))
493
+ else:
494
+ clip_results.append(clvp_out)
495
+ clip_results = torch.cat(clip_results, dim=0)
496
+ samples = torch.cat(samples, dim=0)
497
+ best_results = samples[torch.topk(clip_results, k=k).indices]
498
+ if self.cvvp is not None:
499
+ self.cvvp = self.cvvp.cpu()
500
+ del samples
501
+
502
+ # The diffusion model actually wants the last hidden layer from the autoregressive model as conditioning
503
+ # inputs. Re-produce those for the top results. This could be made more efficient by storing all of these
504
+ # results, but will increase memory usage.
505
+ if not torch.backends.mps.is_available():
506
+ with self.temporary_cuda(
507
+ self.autoregressive
508
+ ) as autoregressive, torch.autocast(
509
+ device_type="cuda" if not torch.backends.mps.is_available() else 'mps', dtype=torch.float16, enabled=self.half
510
+ ):
511
+ best_latents = autoregressive(auto_conditioning.repeat(k, 1), text_tokens.repeat(k, 1),
512
+ torch.tensor([text_tokens.shape[-1]], device=text_tokens.device), best_results,
513
+ torch.tensor([best_results.shape[-1]*self.autoregressive.mel_length_compression], device=text_tokens.device),
514
+ return_latent=True, clip_inputs=False)
515
+ del auto_conditioning
516
+ else:
517
+ with self.temporary_cuda(
518
+ self.autoregressive
519
+ ) as autoregressive:
520
+ best_latents = autoregressive(auto_conditioning.repeat(k, 1), text_tokens.repeat(k, 1),
521
+ torch.tensor([text_tokens.shape[-1]], device=text_tokens.device), best_results,
522
+ torch.tensor([best_results.shape[-1]*self.autoregressive.mel_length_compression], device=text_tokens.device),
523
+ return_latent=True, clip_inputs=False)
524
+ del auto_conditioning
525
+
526
+ if verbose:
527
+ print("Transforming autoregressive outputs into audio..")
528
+ wav_candidates = []
529
+ if not torch.backends.mps.is_available():
530
+ with self.temporary_cuda(self.diffusion) as diffusion, self.temporary_cuda(
531
+ self.vocoder
532
+ ) as vocoder:
533
+ for b in range(best_results.shape[0]):
534
+ codes = best_results[b].unsqueeze(0)
535
+ latents = best_latents[b].unsqueeze(0)
536
+
537
+ # Find the first occurrence of the "calm" token and trim the codes to that.
538
+ ctokens = 0
539
+ for k in range(codes.shape[-1]):
540
+ if codes[0, k] == calm_token:
541
+ ctokens += 1
542
+ else:
543
+ ctokens = 0
544
+ if ctokens > 8: # 8 tokens gives the diffusion model some "breathing room" to terminate speech.
545
+ latents = latents[:, :k]
546
+ break
547
+ mel = do_spectrogram_diffusion(diffusion, diffuser, latents, diffusion_conditioning, temperature=diffusion_temperature,
548
+ verbose=verbose)
549
+ wav = vocoder.inference(mel)
550
+ wav_candidates.append(wav.cpu())
551
+ else:
552
+ diffusion, vocoder = self.diffusion, self.vocoder
553
+ diffusion_conditioning = diffusion_conditioning.cpu()
554
+ for b in range(best_results.shape[0]):
555
+ codes = best_results[b].unsqueeze(0).cpu()
556
+ latents = best_latents[b].unsqueeze(0).cpu()
557
+
558
+ # Find the first occurrence of the "calm" token and trim the codes to that.
559
+ ctokens = 0
560
+ for k in range(codes.shape[-1]):
561
+ if codes[0, k] == calm_token:
562
+ ctokens += 1
563
+ else:
564
+ ctokens = 0
565
+ if ctokens > 8: # 8 tokens gives the diffusion model some "breathing room" to terminate speech.
566
+ latents = latents[:, :k]
567
+ break
568
+ mel = do_spectrogram_diffusion(diffusion, diffuser, latents, diffusion_conditioning, temperature=diffusion_temperature,
569
+ verbose=verbose)
570
+ wav = vocoder.inference(mel)
571
+ wav_candidates.append(wav.cpu())
572
+
573
+ def potentially_redact(clip, text):
574
+ if self.enable_redaction:
575
+ return self.aligner.redact(clip.squeeze(1), text).unsqueeze(1)
576
+ return clip
577
+ wav_candidates = [potentially_redact(wav_candidate, text) for wav_candidate in wav_candidates]
578
+
579
+ if len(wav_candidates) > 1:
580
+ res = wav_candidates
581
+ else:
582
+ res = wav_candidates[0]
583
+
584
+ if return_deterministic_state:
585
+ return res, (deterministic_seed, text, voice_samples, conditioning_latents)
586
+ else:
587
+ return res
588
+ def deterministic_state(self, seed=None):
589
+ """
590
+ Sets the random seeds that tortoise uses to the current time() and returns that seed so results can be
591
+ reproduced.
592
+ """
593
+ seed = int(time()) if seed is None else seed
594
+ torch.manual_seed(seed)
595
+ random.seed(seed)
596
+ # Can't currently set this because of CUBLAS. TODO: potentially enable it if necessary.
597
+ # torch.use_deterministic_algorithms(True)
598
+
599
+ return seed