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
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import time
|
| 4 |
+
from subprocess import CalledProcessError
|
| 5 |
+
from typing import Dict, List, Tuple
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torchaudio
|
| 9 |
+
from torch.nn.utils.rnn import pad_sequence
|
| 10 |
+
from omegaconf import OmegaConf
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
|
| 13 |
+
import warnings
|
| 14 |
+
|
| 15 |
+
warnings.filterwarnings("ignore", category=FutureWarning)
|
| 16 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
| 17 |
+
|
| 18 |
+
from indextts.BigVGAN.models import BigVGAN as Generator
|
| 19 |
+
from indextts.gpt.model import UnifiedVoice
|
| 20 |
+
from indextts.utils.checkpoint import load_checkpoint
|
| 21 |
+
from indextts.utils.feature_extractors import MelSpectrogramFeatures
|
| 22 |
+
|
| 23 |
+
from indextts.utils.front import TextNormalizer, TextTokenizer
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class IndexTTS:
|
| 27 |
+
def __init__(
|
| 28 |
+
self, cfg_path="checkpoints/config.yaml", model_dir="checkpoints", is_fp16=True, device=None, use_cuda_kernel=None,
|
| 29 |
+
):
|
| 30 |
+
"""
|
| 31 |
+
Args:
|
| 32 |
+
cfg_path (str): path to the config file.
|
| 33 |
+
model_dir (str): path to the model directory.
|
| 34 |
+
is_fp16 (bool): whether to use fp16.
|
| 35 |
+
device (str): device to use (e.g., 'cuda:0', 'cpu'). If None, it will be set automatically based on the availability of CUDA or MPS.
|
| 36 |
+
use_cuda_kernel (None | bool): whether to use BigVGan custom fused activation CUDA kernel, only for CUDA device.
|
| 37 |
+
"""
|
| 38 |
+
if device is not None:
|
| 39 |
+
self.device = device
|
| 40 |
+
self.is_fp16 = False if device == "cpu" else is_fp16
|
| 41 |
+
self.use_cuda_kernel = use_cuda_kernel is not None and use_cuda_kernel and device.startswith("cuda")
|
| 42 |
+
elif torch.cuda.is_available():
|
| 43 |
+
self.device = "cuda:0"
|
| 44 |
+
self.is_fp16 = is_fp16
|
| 45 |
+
self.use_cuda_kernel = use_cuda_kernel is None or use_cuda_kernel
|
| 46 |
+
elif hasattr(torch, "mps") and torch.backends.mps.is_available():
|
| 47 |
+
self.device = "mps"
|
| 48 |
+
self.is_fp16 = False # Use float16 on MPS is overhead than float32
|
| 49 |
+
self.use_cuda_kernel = False
|
| 50 |
+
else:
|
| 51 |
+
self.device = "cpu"
|
| 52 |
+
self.is_fp16 = False
|
| 53 |
+
self.use_cuda_kernel = False
|
| 54 |
+
print(">> Be patient, it may take a while to run in CPU mode.")
|
| 55 |
+
|
| 56 |
+
self.cfg = OmegaConf.load(cfg_path)
|
| 57 |
+
self.model_dir = model_dir
|
| 58 |
+
self.dtype = torch.float16 if self.is_fp16 else None
|
| 59 |
+
self.stop_mel_token = self.cfg.gpt.stop_mel_token
|
| 60 |
+
|
| 61 |
+
# Comment-off to load the VQ-VAE model for debugging tokenizer
|
| 62 |
+
# https://github.com/index-tts/index-tts/issues/34
|
| 63 |
+
#
|
| 64 |
+
# from indextts.vqvae.xtts_dvae import DiscreteVAE
|
| 65 |
+
# self.dvae = DiscreteVAE(**self.cfg.vqvae)
|
| 66 |
+
# self.dvae_path = os.path.join(self.model_dir, self.cfg.dvae_checkpoint)
|
| 67 |
+
# load_checkpoint(self.dvae, self.dvae_path)
|
| 68 |
+
# self.dvae = self.dvae.to(self.device)
|
| 69 |
+
# if self.is_fp16:
|
| 70 |
+
# self.dvae.eval().half()
|
| 71 |
+
# else:
|
| 72 |
+
# self.dvae.eval()
|
| 73 |
+
# print(">> vqvae weights restored from:", self.dvae_path)
|
| 74 |
+
self.gpt = UnifiedVoice(**self.cfg.gpt)
|
| 75 |
+
self.gpt_path = os.path.join(self.model_dir, self.cfg.gpt_checkpoint)
|
| 76 |
+
load_checkpoint(self.gpt, self.gpt_path)
|
| 77 |
+
self.gpt = self.gpt.to(self.device)
|
| 78 |
+
if self.is_fp16:
|
| 79 |
+
self.gpt.eval().half()
|
| 80 |
+
else:
|
| 81 |
+
self.gpt.eval()
|
| 82 |
+
print(">> GPT weights restored from:", self.gpt_path)
|
| 83 |
+
if self.is_fp16:
|
| 84 |
+
try:
|
| 85 |
+
import deepspeed
|
| 86 |
+
|
| 87 |
+
use_deepspeed = True
|
| 88 |
+
except (ImportError, OSError, CalledProcessError) as e:
|
| 89 |
+
use_deepspeed = False
|
| 90 |
+
print(f">> DeepSpeed加载失败,回退到标准推理: {e}")
|
| 91 |
+
print("See more details https://www.deepspeed.ai/tutorials/advanced-install/")
|
| 92 |
+
|
| 93 |
+
self.gpt.post_init_gpt2_config(use_deepspeed=use_deepspeed, kv_cache=True, half=True)
|
| 94 |
+
else:
|
| 95 |
+
self.gpt.post_init_gpt2_config(use_deepspeed=False, kv_cache=True, half=False)
|
| 96 |
+
|
| 97 |
+
if self.use_cuda_kernel:
|
| 98 |
+
# preload the CUDA kernel for BigVGAN
|
| 99 |
+
try:
|
| 100 |
+
from indextts.BigVGAN.alias_free_activation.cuda import load as anti_alias_activation_loader
|
| 101 |
+
anti_alias_activation_cuda = anti_alias_activation_loader.load()
|
| 102 |
+
print(">> Preload custom CUDA kernel for BigVGAN", anti_alias_activation_cuda)
|
| 103 |
+
except Exception as e:
|
| 104 |
+
print(">> Failed to load custom CUDA kernel for BigVGAN. Falling back to torch.", e, file=sys.stderr)
|
| 105 |
+
print(" Reinstall with `pip install -e . --no-deps --no-build-isolation` to prebuild `anti_alias_activation_cuda` kernel.", file=sys.stderr)
|
| 106 |
+
print(
|
| 107 |
+
"See more details: https://github.com/index-tts/index-tts/issues/164#issuecomment-2903453206", file=sys.stderr
|
| 108 |
+
)
|
| 109 |
+
self.use_cuda_kernel = False
|
| 110 |
+
self.bigvgan = Generator(self.cfg.bigvgan, use_cuda_kernel=self.use_cuda_kernel)
|
| 111 |
+
self.bigvgan_path = os.path.join(self.model_dir, self.cfg.bigvgan_checkpoint)
|
| 112 |
+
vocoder_dict = torch.load(self.bigvgan_path, map_location="cpu")
|
| 113 |
+
self.bigvgan.load_state_dict(vocoder_dict["generator"])
|
| 114 |
+
self.bigvgan = self.bigvgan.to(self.device)
|
| 115 |
+
# remove weight norm on eval mode
|
| 116 |
+
self.bigvgan.remove_weight_norm()
|
| 117 |
+
self.bigvgan.eval()
|
| 118 |
+
print(">> bigvgan weights restored from:", self.bigvgan_path)
|
| 119 |
+
self.bpe_path = os.path.join(self.model_dir, self.cfg.dataset["bpe_model"])
|
| 120 |
+
self.normalizer = TextNormalizer()
|
| 121 |
+
self.normalizer.load()
|
| 122 |
+
print(">> TextNormalizer loaded")
|
| 123 |
+
self.tokenizer = TextTokenizer(self.bpe_path, self.normalizer)
|
| 124 |
+
print(">> bpe model loaded from:", self.bpe_path)
|
| 125 |
+
# 缓存参考音频mel:
|
| 126 |
+
self.cache_audio_prompt = None
|
| 127 |
+
self.cache_cond_mel = None
|
| 128 |
+
# 进度引用显示(可选)
|
| 129 |
+
self.gr_progress = None
|
| 130 |
+
self.model_version = self.cfg.version if hasattr(self.cfg, "version") else None
|
| 131 |
+
|
| 132 |
+
def remove_long_silence(self, codes: torch.Tensor, silent_token=52, max_consecutive=30):
|
| 133 |
+
"""
|
| 134 |
+
Shrink special tokens (silent_token and stop_mel_token) in codes
|
| 135 |
+
codes: [B, T]
|
| 136 |
+
"""
|
| 137 |
+
code_lens = []
|
| 138 |
+
codes_list = []
|
| 139 |
+
device = codes.device
|
| 140 |
+
dtype = codes.dtype
|
| 141 |
+
isfix = False
|
| 142 |
+
for i in range(0, codes.shape[0]):
|
| 143 |
+
code = codes[i]
|
| 144 |
+
if not torch.any(code == self.stop_mel_token).item():
|
| 145 |
+
len_ = code.size(0)
|
| 146 |
+
else:
|
| 147 |
+
stop_mel_idx = (code == self.stop_mel_token).nonzero(as_tuple=False)
|
| 148 |
+
len_ = stop_mel_idx[0].item() if len(stop_mel_idx) > 0 else code.size(0)
|
| 149 |
+
|
| 150 |
+
count = torch.sum(code == silent_token).item()
|
| 151 |
+
if count > max_consecutive:
|
| 152 |
+
# code = code.cpu().tolist()
|
| 153 |
+
ncode_idx = []
|
| 154 |
+
n = 0
|
| 155 |
+
for k in range(len_):
|
| 156 |
+
assert code[k] != self.stop_mel_token, f"stop_mel_token {self.stop_mel_token} should be shrinked here"
|
| 157 |
+
if code[k] != silent_token:
|
| 158 |
+
ncode_idx.append(k)
|
| 159 |
+
n = 0
|
| 160 |
+
elif code[k] == silent_token and n < 10:
|
| 161 |
+
ncode_idx.append(k)
|
| 162 |
+
n += 1
|
| 163 |
+
# if (k == 0 and code[k] == 52) or (code[k] == 52 and code[k-1] == 52):
|
| 164 |
+
# n += 1
|
| 165 |
+
# new code
|
| 166 |
+
len_ = len(ncode_idx)
|
| 167 |
+
codes_list.append(code[ncode_idx])
|
| 168 |
+
isfix = True
|
| 169 |
+
else:
|
| 170 |
+
# shrink to len_
|
| 171 |
+
codes_list.append(code[:len_])
|
| 172 |
+
code_lens.append(len_)
|
| 173 |
+
if isfix:
|
| 174 |
+
if len(codes_list) > 1:
|
| 175 |
+
codes = pad_sequence(codes_list, batch_first=True, padding_value=self.stop_mel_token)
|
| 176 |
+
else:
|
| 177 |
+
codes = codes_list[0].unsqueeze(0)
|
| 178 |
+
else:
|
| 179 |
+
# unchanged
|
| 180 |
+
pass
|
| 181 |
+
# clip codes to max length
|
| 182 |
+
max_len = max(code_lens)
|
| 183 |
+
if max_len < codes.shape[1]:
|
| 184 |
+
codes = codes[:, :max_len]
|
| 185 |
+
code_lens = torch.tensor(code_lens, dtype=torch.long, device=device)
|
| 186 |
+
return codes, code_lens
|
| 187 |
+
|
| 188 |
+
def bucket_sentences(self, sentences, bucket_max_size=4) -> List[List[Dict]]:
|
| 189 |
+
"""
|
| 190 |
+
Sentence data bucketing.
|
| 191 |
+
if ``bucket_max_size=1``, return all sentences in one bucket.
|
| 192 |
+
"""
|
| 193 |
+
outputs: List[Dict] = []
|
| 194 |
+
for idx, sent in enumerate(sentences):
|
| 195 |
+
outputs.append({"idx": idx, "sent": sent, "len": len(sent)})
|
| 196 |
+
|
| 197 |
+
if len(outputs) > bucket_max_size:
|
| 198 |
+
# split sentences into buckets by sentence length
|
| 199 |
+
buckets: List[List[Dict]] = []
|
| 200 |
+
factor = 1.5
|
| 201 |
+
last_bucket = None
|
| 202 |
+
last_bucket_sent_len_median = 0
|
| 203 |
+
|
| 204 |
+
for sent in sorted(outputs, key=lambda x: x["len"]):
|
| 205 |
+
current_sent_len = sent["len"]
|
| 206 |
+
if current_sent_len == 0:
|
| 207 |
+
print(">> skip empty sentence")
|
| 208 |
+
continue
|
| 209 |
+
if last_bucket is None \
|
| 210 |
+
or current_sent_len >= int(last_bucket_sent_len_median * factor) \
|
| 211 |
+
or len(last_bucket) >= bucket_max_size:
|
| 212 |
+
# new bucket
|
| 213 |
+
buckets.append([sent])
|
| 214 |
+
last_bucket = buckets[-1]
|
| 215 |
+
last_bucket_sent_len_median = current_sent_len
|
| 216 |
+
else:
|
| 217 |
+
# current bucket can hold more sentences
|
| 218 |
+
last_bucket.append(sent) # sorted
|
| 219 |
+
mid = len(last_bucket) // 2
|
| 220 |
+
last_bucket_sent_len_median = last_bucket[mid]["len"]
|
| 221 |
+
last_bucket=None
|
| 222 |
+
# merge all buckets with size 1
|
| 223 |
+
out_buckets: List[List[Dict]] = []
|
| 224 |
+
only_ones: List[Dict] = []
|
| 225 |
+
for b in buckets:
|
| 226 |
+
if len(b) == 1:
|
| 227 |
+
only_ones.append(b[0])
|
| 228 |
+
else:
|
| 229 |
+
out_buckets.append(b)
|
| 230 |
+
if len(only_ones) > 0:
|
| 231 |
+
# merge into previous buckets if possible
|
| 232 |
+
# print("only_ones:", [(o["idx"], o["len"]) for o in only_ones])
|
| 233 |
+
for i in range(len(out_buckets)):
|
| 234 |
+
b = out_buckets[i]
|
| 235 |
+
if len(b) < bucket_max_size:
|
| 236 |
+
b.append(only_ones.pop(0))
|
| 237 |
+
if len(only_ones) == 0:
|
| 238 |
+
break
|
| 239 |
+
# combined all remaining sized 1 buckets
|
| 240 |
+
if len(only_ones) > 0:
|
| 241 |
+
out_buckets.extend([only_ones[i:i+bucket_max_size] for i in range(0, len(only_ones), bucket_max_size)])
|
| 242 |
+
return out_buckets
|
| 243 |
+
return [outputs]
|
| 244 |
+
|
| 245 |
+
def pad_tokens_cat(self, tokens: List[torch.Tensor]) -> torch.Tensor:
|
| 246 |
+
if self.model_version and self.model_version >= 1.5:
|
| 247 |
+
# 1.5版本以上,直接使用stop_text_token 右侧填充,填充到最大长度
|
| 248 |
+
# [1, N] -> [N,]
|
| 249 |
+
tokens = [t.squeeze(0) for t in tokens]
|
| 250 |
+
return pad_sequence(tokens, batch_first=True, padding_value=self.cfg.gpt.stop_text_token, padding_side="right")
|
| 251 |
+
max_len = max(t.size(1) for t in tokens)
|
| 252 |
+
outputs = []
|
| 253 |
+
for tensor in tokens:
|
| 254 |
+
pad_len = max_len - tensor.size(1)
|
| 255 |
+
if pad_len > 0:
|
| 256 |
+
n = min(8, pad_len)
|
| 257 |
+
tensor = torch.nn.functional.pad(tensor, (0, n), value=self.cfg.gpt.stop_text_token)
|
| 258 |
+
tensor = torch.nn.functional.pad(tensor, (0, pad_len - n), value=self.cfg.gpt.start_text_token)
|
| 259 |
+
tensor = tensor[:, :max_len]
|
| 260 |
+
outputs.append(tensor)
|
| 261 |
+
tokens = torch.cat(outputs, dim=0)
|
| 262 |
+
return tokens
|
| 263 |
+
|
| 264 |
+
def torch_empty_cache(self):
|
| 265 |
+
try:
|
| 266 |
+
if "cuda" in str(self.device):
|
| 267 |
+
torch.cuda.empty_cache()
|
| 268 |
+
elif "mps" in str(self.device):
|
| 269 |
+
torch.mps.empty_cache()
|
| 270 |
+
except Exception as e:
|
| 271 |
+
pass
|
| 272 |
+
|
| 273 |
+
def _set_gr_progress(self, value, desc):
|
| 274 |
+
if self.gr_progress is not None:
|
| 275 |
+
self.gr_progress(value, desc=desc)
|
| 276 |
+
|
| 277 |
+
# 快速推理:对于“多句长文本”,可实现至少 2~10 倍以上的速度提升~ (First modified by sunnyboxs 2025-04-16)
|
| 278 |
+
def infer_fast(self, audio_prompt, text, output_path, verbose=False, max_text_tokens_per_sentence=100, sentences_bucket_max_size=4, **generation_kwargs):
|
| 279 |
+
"""
|
| 280 |
+
Args:
|
| 281 |
+
``max_text_tokens_per_sentence``: 分句的最大token数,默认``100``,可以根据GPU硬件情况调整
|
| 282 |
+
- 越小,batch 越多,推理速度越*快*,占用内存更多,可能影响质量
|
| 283 |
+
- 越大,batch 越少,推理速度越*慢*,占用内存和质量更接近于非快速推理
|
| 284 |
+
``sentences_bucket_max_size``: 分句分桶的最大容量,默认``4``,可以根据GPU内存调整
|
| 285 |
+
- 越大,bucket数量越少,batch越多,推理速度越*快*,占用内存更多,可能影响质量
|
| 286 |
+
- 越小,bucket数量越多,batch越少,推理速度越*慢*,占用内存和质量更接近于非快速推理
|
| 287 |
+
"""
|
| 288 |
+
print(">> start fast inference...")
|
| 289 |
+
|
| 290 |
+
self._set_gr_progress(0, "start fast inference...")
|
| 291 |
+
if verbose:
|
| 292 |
+
print(f"origin text:{text}")
|
| 293 |
+
start_time = time.perf_counter()
|
| 294 |
+
|
| 295 |
+
# 如果参考音频改变了,才需要重新生成 cond_mel, 提升速度
|
| 296 |
+
if self.cache_cond_mel is None or self.cache_audio_prompt != audio_prompt:
|
| 297 |
+
audio, sr = torchaudio.load(audio_prompt)
|
| 298 |
+
audio = torch.mean(audio, dim=0, keepdim=True)
|
| 299 |
+
if audio.shape[0] > 1:
|
| 300 |
+
audio = audio[0].unsqueeze(0)
|
| 301 |
+
audio = torchaudio.transforms.Resample(sr, 24000)(audio)
|
| 302 |
+
cond_mel = MelSpectrogramFeatures()(audio).to(self.device)
|
| 303 |
+
cond_mel_frame = cond_mel.shape[-1]
|
| 304 |
+
if verbose:
|
| 305 |
+
print(f"cond_mel shape: {cond_mel.shape}", "dtype:", cond_mel.dtype)
|
| 306 |
+
|
| 307 |
+
self.cache_audio_prompt = audio_prompt
|
| 308 |
+
self.cache_cond_mel = cond_mel
|
| 309 |
+
else:
|
| 310 |
+
cond_mel = self.cache_cond_mel
|
| 311 |
+
cond_mel_frame = cond_mel.shape[-1]
|
| 312 |
+
pass
|
| 313 |
+
|
| 314 |
+
auto_conditioning = cond_mel
|
| 315 |
+
cond_mel_lengths = torch.tensor([cond_mel_frame], device=self.device)
|
| 316 |
+
|
| 317 |
+
# text_tokens
|
| 318 |
+
text_tokens_list = self.tokenizer.tokenize(text)
|
| 319 |
+
|
| 320 |
+
sentences = self.tokenizer.split_sentences(text_tokens_list, max_tokens_per_sentence=max_text_tokens_per_sentence)
|
| 321 |
+
if verbose:
|
| 322 |
+
print(">> text token count:", len(text_tokens_list))
|
| 323 |
+
print(" splited sentences count:", len(sentences))
|
| 324 |
+
print(" max_text_tokens_per_sentence:", max_text_tokens_per_sentence)
|
| 325 |
+
print(*sentences, sep="\n")
|
| 326 |
+
do_sample = generation_kwargs.pop("do_sample", True)
|
| 327 |
+
top_p = generation_kwargs.pop("top_p", 0.8)
|
| 328 |
+
top_k = generation_kwargs.pop("top_k", 30)
|
| 329 |
+
temperature = generation_kwargs.pop("temperature", 1.0)
|
| 330 |
+
autoregressive_batch_size = 1
|
| 331 |
+
length_penalty = generation_kwargs.pop("length_penalty", 0.0)
|
| 332 |
+
num_beams = generation_kwargs.pop("num_beams", 3)
|
| 333 |
+
repetition_penalty = generation_kwargs.pop("repetition_penalty", 10.0)
|
| 334 |
+
max_mel_tokens = generation_kwargs.pop("max_mel_tokens", 600)
|
| 335 |
+
sampling_rate = 24000
|
| 336 |
+
# lang = "EN"
|
| 337 |
+
# lang = "ZH"
|
| 338 |
+
wavs = []
|
| 339 |
+
gpt_gen_time = 0
|
| 340 |
+
gpt_forward_time = 0
|
| 341 |
+
bigvgan_time = 0
|
| 342 |
+
|
| 343 |
+
# text processing
|
| 344 |
+
all_text_tokens: List[List[torch.Tensor]] = []
|
| 345 |
+
self._set_gr_progress(0.1, "text processing...")
|
| 346 |
+
bucket_max_size = sentences_bucket_max_size if self.device != "cpu" else 1
|
| 347 |
+
all_sentences = self.bucket_sentences(sentences, bucket_max_size=bucket_max_size)
|
| 348 |
+
bucket_count = len(all_sentences)
|
| 349 |
+
if verbose:
|
| 350 |
+
print(">> sentences bucket_count:", bucket_count,
|
| 351 |
+
"bucket sizes:", [(len(s), [t["idx"] for t in s]) for s in all_sentences],
|
| 352 |
+
"bucket_max_size:", bucket_max_size)
|
| 353 |
+
for sentences in all_sentences:
|
| 354 |
+
temp_tokens: List[torch.Tensor] = []
|
| 355 |
+
all_text_tokens.append(temp_tokens)
|
| 356 |
+
for item in sentences:
|
| 357 |
+
sent = item["sent"]
|
| 358 |
+
text_tokens = self.tokenizer.convert_tokens_to_ids(sent)
|
| 359 |
+
text_tokens = torch.tensor(text_tokens, dtype=torch.int32, device=self.device).unsqueeze(0)
|
| 360 |
+
if verbose:
|
| 361 |
+
print(text_tokens)
|
| 362 |
+
print(f"text_tokens shape: {text_tokens.shape}, text_tokens type: {text_tokens.dtype}")
|
| 363 |
+
# debug tokenizer
|
| 364 |
+
text_token_syms = self.tokenizer.convert_ids_to_tokens(text_tokens[0].tolist())
|
| 365 |
+
print("text_token_syms is same as sentence tokens", text_token_syms == sent)
|
| 366 |
+
temp_tokens.append(text_tokens)
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
# Sequential processing of bucketing data
|
| 370 |
+
all_batch_num = sum(len(s) for s in all_sentences)
|
| 371 |
+
all_batch_codes = []
|
| 372 |
+
processed_num = 0
|
| 373 |
+
for item_tokens in all_text_tokens:
|
| 374 |
+
batch_num = len(item_tokens)
|
| 375 |
+
if batch_num > 1:
|
| 376 |
+
batch_text_tokens = self.pad_tokens_cat(item_tokens)
|
| 377 |
+
else:
|
| 378 |
+
batch_text_tokens = item_tokens[0]
|
| 379 |
+
processed_num += batch_num
|
| 380 |
+
# gpt speech
|
| 381 |
+
self._set_gr_progress(0.2 + 0.3 * processed_num/all_batch_num, f"gpt inference speech... {processed_num}/{all_batch_num}")
|
| 382 |
+
m_start_time = time.perf_counter()
|
| 383 |
+
with torch.no_grad():
|
| 384 |
+
with torch.amp.autocast(batch_text_tokens.device.type, enabled=self.dtype is not None, dtype=self.dtype):
|
| 385 |
+
temp_codes = self.gpt.inference_speech(auto_conditioning, batch_text_tokens,
|
| 386 |
+
cond_mel_lengths=cond_mel_lengths,
|
| 387 |
+
# text_lengths=text_len,
|
| 388 |
+
do_sample=do_sample,
|
| 389 |
+
top_p=top_p,
|
| 390 |
+
top_k=top_k,
|
| 391 |
+
temperature=temperature,
|
| 392 |
+
num_return_sequences=autoregressive_batch_size,
|
| 393 |
+
length_penalty=length_penalty,
|
| 394 |
+
num_beams=num_beams,
|
| 395 |
+
repetition_penalty=repetition_penalty,
|
| 396 |
+
max_generate_length=max_mel_tokens,
|
| 397 |
+
**generation_kwargs)
|
| 398 |
+
all_batch_codes.append(temp_codes)
|
| 399 |
+
gpt_gen_time += time.perf_counter() - m_start_time
|
| 400 |
+
|
| 401 |
+
# gpt latent
|
| 402 |
+
self._set_gr_progress(0.5, "gpt inference latents...")
|
| 403 |
+
all_idxs = []
|
| 404 |
+
all_latents = []
|
| 405 |
+
has_warned = False
|
| 406 |
+
for batch_codes, batch_tokens, batch_sentences in zip(all_batch_codes, all_text_tokens, all_sentences):
|
| 407 |
+
for i in range(batch_codes.shape[0]):
|
| 408 |
+
codes = batch_codes[i] # [x]
|
| 409 |
+
if not has_warned and codes[-1] != self.stop_mel_token:
|
| 410 |
+
warnings.warn(
|
| 411 |
+
f"WARN: generation stopped due to exceeding `max_mel_tokens` ({max_mel_tokens}). "
|
| 412 |
+
f"Consider reducing `max_text_tokens_per_sentence`({max_text_tokens_per_sentence}) or increasing `max_mel_tokens`.",
|
| 413 |
+
category=RuntimeWarning
|
| 414 |
+
)
|
| 415 |
+
has_warned = True
|
| 416 |
+
codes = codes.unsqueeze(0) # [x] -> [1, x]
|
| 417 |
+
if verbose:
|
| 418 |
+
print("codes:", codes.shape)
|
| 419 |
+
print(codes)
|
| 420 |
+
codes, code_lens = self.remove_long_silence(codes, silent_token=52, max_consecutive=30)
|
| 421 |
+
if verbose:
|
| 422 |
+
print("fix codes:", codes.shape)
|
| 423 |
+
print(codes)
|
| 424 |
+
print("code_lens:", code_lens)
|
| 425 |
+
text_tokens = batch_tokens[i]
|
| 426 |
+
all_idxs.append(batch_sentences[i]["idx"])
|
| 427 |
+
m_start_time = time.perf_counter()
|
| 428 |
+
with torch.no_grad():
|
| 429 |
+
with torch.amp.autocast(text_tokens.device.type, enabled=self.dtype is not None, dtype=self.dtype):
|
| 430 |
+
latent = \
|
| 431 |
+
self.gpt(auto_conditioning, text_tokens,
|
| 432 |
+
torch.tensor([text_tokens.shape[-1]], device=text_tokens.device), codes,
|
| 433 |
+
code_lens*self.gpt.mel_length_compression,
|
| 434 |
+
cond_mel_lengths=torch.tensor([auto_conditioning.shape[-1]], device=text_tokens.device),
|
| 435 |
+
return_latent=True, clip_inputs=False)
|
| 436 |
+
gpt_forward_time += time.perf_counter() - m_start_time
|
| 437 |
+
all_latents.append(latent)
|
| 438 |
+
del all_batch_codes, all_text_tokens, all_sentences
|
| 439 |
+
# bigvgan chunk
|
| 440 |
+
chunk_size = 2
|
| 441 |
+
all_latents = [all_latents[all_idxs.index(i)] for i in range(len(all_latents))]
|
| 442 |
+
if verbose:
|
| 443 |
+
print(">> all_latents:", len(all_latents))
|
| 444 |
+
print(" latents length:", [l.shape[1] for l in all_latents])
|
| 445 |
+
chunk_latents = [all_latents[i : i + chunk_size] for i in range(0, len(all_latents), chunk_size)]
|
| 446 |
+
chunk_length = len(chunk_latents)
|
| 447 |
+
latent_length = len(all_latents)
|
| 448 |
+
|
| 449 |
+
# bigvgan chunk decode
|
| 450 |
+
self._set_gr_progress(0.7, "bigvgan decode...")
|
| 451 |
+
tqdm_progress = tqdm(total=latent_length, desc="bigvgan")
|
| 452 |
+
for items in chunk_latents:
|
| 453 |
+
tqdm_progress.update(len(items))
|
| 454 |
+
latent = torch.cat(items, dim=1)
|
| 455 |
+
with torch.no_grad():
|
| 456 |
+
with torch.amp.autocast(latent.device.type, enabled=self.dtype is not None, dtype=self.dtype):
|
| 457 |
+
m_start_time = time.perf_counter()
|
| 458 |
+
wav, _ = self.bigvgan(latent, auto_conditioning.transpose(1, 2))
|
| 459 |
+
bigvgan_time += time.perf_counter() - m_start_time
|
| 460 |
+
wav = wav.squeeze(1)
|
| 461 |
+
pass
|
| 462 |
+
wav = torch.clamp(32767 * wav, -32767.0, 32767.0)
|
| 463 |
+
wavs.append(wav.cpu()) # to cpu before saving
|
| 464 |
+
|
| 465 |
+
# clear cache
|
| 466 |
+
tqdm_progress.close() # 确保进度条被关闭
|
| 467 |
+
del all_latents, chunk_latents
|
| 468 |
+
end_time = time.perf_counter()
|
| 469 |
+
self.torch_empty_cache()
|
| 470 |
+
|
| 471 |
+
# wav audio output
|
| 472 |
+
self._set_gr_progress(0.9, "save audio...")
|
| 473 |
+
wav = torch.cat(wavs, dim=1)
|
| 474 |
+
wav_length = wav.shape[-1] / sampling_rate
|
| 475 |
+
print(f">> Reference audio length: {cond_mel_frame * 256 / sampling_rate:.2f} seconds")
|
| 476 |
+
print(f">> gpt_gen_time: {gpt_gen_time:.2f} seconds")
|
| 477 |
+
print(f">> gpt_forward_time: {gpt_forward_time:.2f} seconds")
|
| 478 |
+
print(f">> bigvgan_time: {bigvgan_time:.2f} seconds")
|
| 479 |
+
print(f">> Total fast inference time: {end_time - start_time:.2f} seconds")
|
| 480 |
+
print(f">> Generated audio length: {wav_length:.2f} seconds")
|
| 481 |
+
print(f">> [fast] bigvgan chunk_length: {chunk_length}")
|
| 482 |
+
print(f">> [fast] batch_num: {all_batch_num} bucket_max_size: {bucket_max_size}", f"bucket_count: {bucket_count}" if bucket_max_size > 1 else "")
|
| 483 |
+
print(f">> [fast] RTF: {(end_time - start_time) / wav_length:.4f}")
|
| 484 |
+
|
| 485 |
+
# save audio
|
| 486 |
+
wav = wav.cpu() # to cpu
|
| 487 |
+
if output_path:
|
| 488 |
+
# 直接保存音频到指定路径中
|
| 489 |
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
| 490 |
+
torchaudio.save(output_path, wav.type(torch.int16), sampling_rate)
|
| 491 |
+
print(">> wav file saved to:", output_path)
|
| 492 |
+
return output_path
|
| 493 |
+
else:
|
| 494 |
+
# 返回以符合Gradio的格式要求
|
| 495 |
+
wav_data = wav.type(torch.int16)
|
| 496 |
+
wav_data = wav_data.numpy().T
|
| 497 |
+
return (sampling_rate, wav_data)
|
| 498 |
+
|
| 499 |
+
# 原始推理模式
|
| 500 |
+
def infer(self, audio_prompt, text, output_path, verbose=False, max_text_tokens_per_sentence=120, **generation_kwargs):
|
| 501 |
+
print(">> start inference...")
|
| 502 |
+
self._set_gr_progress(0, "start inference...")
|
| 503 |
+
if verbose:
|
| 504 |
+
print(f"origin text:{text}")
|
| 505 |
+
start_time = time.perf_counter()
|
| 506 |
+
|
| 507 |
+
# 如果参考音频改变了,才需要重新生成 cond_mel, 提升速度
|
| 508 |
+
if self.cache_cond_mel is None or self.cache_audio_prompt != audio_prompt:
|
| 509 |
+
audio, sr = torchaudio.load(audio_prompt)
|
| 510 |
+
audio = torch.mean(audio, dim=0, keepdim=True)
|
| 511 |
+
if audio.shape[0] > 1:
|
| 512 |
+
audio = audio[0].unsqueeze(0)
|
| 513 |
+
audio = torchaudio.transforms.Resample(sr, 24000)(audio)
|
| 514 |
+
cond_mel = MelSpectrogramFeatures()(audio).to(self.device)
|
| 515 |
+
cond_mel_frame = cond_mel.shape[-1]
|
| 516 |
+
if verbose:
|
| 517 |
+
print(f"cond_mel shape: {cond_mel.shape}", "dtype:", cond_mel.dtype)
|
| 518 |
+
|
| 519 |
+
self.cache_audio_prompt = audio_prompt
|
| 520 |
+
self.cache_cond_mel = cond_mel
|
| 521 |
+
else:
|
| 522 |
+
cond_mel = self.cache_cond_mel
|
| 523 |
+
cond_mel_frame = cond_mel.shape[-1]
|
| 524 |
+
pass
|
| 525 |
+
|
| 526 |
+
self._set_gr_progress(0.1, "text processing...")
|
| 527 |
+
auto_conditioning = cond_mel
|
| 528 |
+
text_tokens_list = self.tokenizer.tokenize(text)
|
| 529 |
+
sentences = self.tokenizer.split_sentences(text_tokens_list, max_text_tokens_per_sentence)
|
| 530 |
+
if verbose:
|
| 531 |
+
print("text token count:", len(text_tokens_list))
|
| 532 |
+
print("sentences count:", len(sentences))
|
| 533 |
+
print("max_text_tokens_per_sentence:", max_text_tokens_per_sentence)
|
| 534 |
+
print(*sentences, sep="\n")
|
| 535 |
+
do_sample = generation_kwargs.pop("do_sample", True)
|
| 536 |
+
top_p = generation_kwargs.pop("top_p", 0.8)
|
| 537 |
+
top_k = generation_kwargs.pop("top_k", 30)
|
| 538 |
+
temperature = generation_kwargs.pop("temperature", 1.0)
|
| 539 |
+
autoregressive_batch_size = 1
|
| 540 |
+
length_penalty = generation_kwargs.pop("length_penalty", 0.0)
|
| 541 |
+
num_beams = generation_kwargs.pop("num_beams", 3)
|
| 542 |
+
repetition_penalty = generation_kwargs.pop("repetition_penalty", 10.0)
|
| 543 |
+
max_mel_tokens = generation_kwargs.pop("max_mel_tokens", 600)
|
| 544 |
+
sampling_rate = 24000
|
| 545 |
+
# lang = "EN"
|
| 546 |
+
# lang = "ZH"
|
| 547 |
+
wavs = []
|
| 548 |
+
gpt_gen_time = 0
|
| 549 |
+
gpt_forward_time = 0
|
| 550 |
+
bigvgan_time = 0
|
| 551 |
+
progress = 0
|
| 552 |
+
has_warned = False
|
| 553 |
+
for sent in sentences:
|
| 554 |
+
text_tokens = self.tokenizer.convert_tokens_to_ids(sent)
|
| 555 |
+
text_tokens = torch.tensor(text_tokens, dtype=torch.int32, device=self.device).unsqueeze(0)
|
| 556 |
+
# text_tokens = F.pad(text_tokens, (0, 1)) # This may not be necessary.
|
| 557 |
+
# text_tokens = F.pad(text_tokens, (1, 0), value=0)
|
| 558 |
+
# text_tokens = F.pad(text_tokens, (0, 1), value=1)
|
| 559 |
+
if verbose:
|
| 560 |
+
print(text_tokens)
|
| 561 |
+
print(f"text_tokens shape: {text_tokens.shape}, text_tokens type: {text_tokens.dtype}")
|
| 562 |
+
# debug tokenizer
|
| 563 |
+
text_token_syms = self.tokenizer.convert_ids_to_tokens(text_tokens[0].tolist())
|
| 564 |
+
print("text_token_syms is same as sentence tokens", text_token_syms == sent)
|
| 565 |
+
|
| 566 |
+
# text_len = torch.IntTensor([text_tokens.size(1)], device=text_tokens.device)
|
| 567 |
+
# print(text_len)
|
| 568 |
+
progress += 1
|
| 569 |
+
self._set_gr_progress(0.2 + 0.4 * (progress-1) / len(sentences), f"gpt inference latent... {progress}/{len(sentences)}")
|
| 570 |
+
m_start_time = time.perf_counter()
|
| 571 |
+
with torch.no_grad():
|
| 572 |
+
with torch.amp.autocast(text_tokens.device.type, enabled=self.dtype is not None, dtype=self.dtype):
|
| 573 |
+
codes = self.gpt.inference_speech(auto_conditioning, text_tokens,
|
| 574 |
+
cond_mel_lengths=torch.tensor([auto_conditioning.shape[-1]],
|
| 575 |
+
device=text_tokens.device),
|
| 576 |
+
# text_lengths=text_len,
|
| 577 |
+
do_sample=do_sample,
|
| 578 |
+
top_p=top_p,
|
| 579 |
+
top_k=top_k,
|
| 580 |
+
temperature=temperature,
|
| 581 |
+
num_return_sequences=autoregressive_batch_size,
|
| 582 |
+
length_penalty=length_penalty,
|
| 583 |
+
num_beams=num_beams,
|
| 584 |
+
repetition_penalty=repetition_penalty,
|
| 585 |
+
max_generate_length=max_mel_tokens,
|
| 586 |
+
**generation_kwargs)
|
| 587 |
+
gpt_gen_time += time.perf_counter() - m_start_time
|
| 588 |
+
if not has_warned and (codes[:, -1] != self.stop_mel_token).any():
|
| 589 |
+
warnings.warn(
|
| 590 |
+
f"WARN: generation stopped due to exceeding `max_mel_tokens` ({max_mel_tokens}). "
|
| 591 |
+
f"Input text tokens: {text_tokens.shape[1]}. "
|
| 592 |
+
f"Consider reducing `max_text_tokens_per_sentence`({max_text_tokens_per_sentence}) or increasing `max_mel_tokens`.",
|
| 593 |
+
category=RuntimeWarning
|
| 594 |
+
)
|
| 595 |
+
has_warned = True
|
| 596 |
+
|
| 597 |
+
code_lens = torch.tensor([codes.shape[-1]], device=codes.device, dtype=codes.dtype)
|
| 598 |
+
if verbose:
|
| 599 |
+
print(codes, type(codes))
|
| 600 |
+
print(f"codes shape: {codes.shape}, codes type: {codes.dtype}")
|
| 601 |
+
print(f"code len: {code_lens}")
|
| 602 |
+
|
| 603 |
+
# remove ultra-long silence if exits
|
| 604 |
+
# temporarily fix the long silence bug.
|
| 605 |
+
codes, code_lens = self.remove_long_silence(codes, silent_token=52, max_consecutive=30)
|
| 606 |
+
if verbose:
|
| 607 |
+
print(codes, type(codes))
|
| 608 |
+
print(f"fix codes shape: {codes.shape}, codes type: {codes.dtype}")
|
| 609 |
+
print(f"code len: {code_lens}")
|
| 610 |
+
self._set_gr_progress(0.2 + 0.4 * progress / len(sentences), f"gpt inference speech... {progress}/{len(sentences)}")
|
| 611 |
+
m_start_time = time.perf_counter()
|
| 612 |
+
# latent, text_lens_out, code_lens_out = \
|
| 613 |
+
with torch.amp.autocast(text_tokens.device.type, enabled=self.dtype is not None, dtype=self.dtype):
|
| 614 |
+
latent = \
|
| 615 |
+
self.gpt(auto_conditioning, text_tokens,
|
| 616 |
+
torch.tensor([text_tokens.shape[-1]], device=text_tokens.device), codes,
|
| 617 |
+
code_lens*self.gpt.mel_length_compression,
|
| 618 |
+
cond_mel_lengths=torch.tensor([auto_conditioning.shape[-1]], device=text_tokens.device),
|
| 619 |
+
return_latent=True, clip_inputs=False)
|
| 620 |
+
gpt_forward_time += time.perf_counter() - m_start_time
|
| 621 |
+
|
| 622 |
+
m_start_time = time.perf_counter()
|
| 623 |
+
wav, _ = self.bigvgan(latent, auto_conditioning.transpose(1, 2))
|
| 624 |
+
bigvgan_time += time.perf_counter() - m_start_time
|
| 625 |
+
wav = wav.squeeze(1)
|
| 626 |
+
|
| 627 |
+
wav = torch.clamp(32767 * wav, -32767.0, 32767.0)
|
| 628 |
+
if verbose:
|
| 629 |
+
print(f"wav shape: {wav.shape}", "min:", wav.min(), "max:", wav.max())
|
| 630 |
+
# wavs.append(wav[:, :-512])
|
| 631 |
+
wavs.append(wav.cpu()) # to cpu before saving
|
| 632 |
+
end_time = time.perf_counter()
|
| 633 |
+
self._set_gr_progress(0.9, "save audio...")
|
| 634 |
+
wav = torch.cat(wavs, dim=1)
|
| 635 |
+
wav_length = wav.shape[-1] / sampling_rate
|
| 636 |
+
print(f">> Reference audio length: {cond_mel_frame * 256 / sampling_rate:.2f} seconds")
|
| 637 |
+
print(f">> gpt_gen_time: {gpt_gen_time:.2f} seconds")
|
| 638 |
+
print(f">> gpt_forward_time: {gpt_forward_time:.2f} seconds")
|
| 639 |
+
print(f">> bigvgan_time: {bigvgan_time:.2f} seconds")
|
| 640 |
+
print(f">> Total inference time: {end_time - start_time:.2f} seconds")
|
| 641 |
+
print(f">> Generated audio length: {wav_length:.2f} seconds")
|
| 642 |
+
print(f">> RTF: {(end_time - start_time) / wav_length:.4f}")
|
| 643 |
+
|
| 644 |
+
# save audio
|
| 645 |
+
wav = wav.cpu() # to cpu
|
| 646 |
+
if output_path:
|
| 647 |
+
# 直接保存音频到指定路径中
|
| 648 |
+
if os.path.isfile(output_path):
|
| 649 |
+
os.remove(output_path)
|
| 650 |
+
print(">> remove old wav file:", output_path)
|
| 651 |
+
if os.path.dirname(output_path) != "":
|
| 652 |
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
| 653 |
+
torchaudio.save(output_path, wav.type(torch.int16), sampling_rate)
|
| 654 |
+
print(">> wav file saved to:", output_path)
|
| 655 |
+
return output_path
|
| 656 |
+
else:
|
| 657 |
+
# 返回以符合Gradio的格式要求
|
| 658 |
+
wav_data = wav.type(torch.int16)
|
| 659 |
+
wav_data = wav_data.numpy().T
|
| 660 |
+
return (sampling_rate, wav_data)
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
if __name__ == "__main__":
|
| 664 |
+
prompt_wav="test_data/input.wav"
|
| 665 |
+
#text="晕 XUAN4 是 一 种 GAN3 觉"
|
| 666 |
+
#text='大家好,我现在正在bilibili 体验 ai 科技,说实话,来之前我绝对想不到!AI技术已经发展到这样匪夷所思的地步了!'
|
| 667 |
+
text="There is a vehicle arriving in dock number 7?"
|
| 668 |
+
|
| 669 |
+
tts = IndexTTS(cfg_path="checkpoints/config.yaml", model_dir="checkpoints", is_fp16=True, use_cuda_kernel=False)
|
| 670 |
+
tts.infer(audio_prompt=prompt_wav, text=text, output_path="gen.wav", verbose=True)
|