"""IndexTTS-2.5 voice cloning with TensorRT: the ONNX build's pipeline.py (the official `IndexTTS2.infer_generator(spk_audio_prompt, text, lang, text_normalization=False)`: beam sampling with 3 beams, 25 flow steps with CFG 0.7) with its graphs run as the engines in this folder: decoder_0..k.engine the 24-layer GPT-2 (decoder_split.json): inputs_embeds [B, S, 1280], beam_idx [B], past_key_values.{i}.key / .value [B', 20, P, 64] (fp16) -> logits [B, 8194], present.* semantic, emovec, campplus, prefix, embed, codec, regulator .engine estimator.engine the s2mel DiT for flows up to 2,048 mel frames; estimator_long.engine for 2,048-4,096 (loaded when a flow needs it: its attention keeps 3.5 GB of working memory) vocoder.engine BigVGAN in windows of 512 mel frames with 64 of context on each side (local: one whole pass's samples) The decoder's KV cache stays on the GPU (device_chain.py): two buffer sets, a step reading one (reordered by beam_idx inside the engine) and writing the longer cache into the other. Limits of the engines: a text segment up to 160 ids (pipeline.py splits text at 120 tokens), up to 800 speech tokens a segment (32 s), and the flow's mel (the reference's first 15 s plus the segment) up to 4,096 frames: a segment's speech tokens stop where its mel would pass that. 22.05 kHz output. Needs numpy, tiktoken, soundfile, soxr, tensorrt-cu12 / tensorrt-lean-cu12 10.13 and polygraphy. python pipeline_trt.py "Text to say." out.wav --ref voice.wav [--lang en] [--seed 0] """ from __future__ import annotations import sys from pathlib import Path import numpy as np HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) from device_chain import Buffers, Chain # noqa: E402 from pipeline import HEAD_DIM, HEADS, HOP, LAYERS, IndexTTS25, Tokenizer, mel_basis # noqa: E402 from trt_runner import OrtLike # noqa: E402 BEAMS, MAX_TEXT, MAX_TOKENS, MAX_MEL = 3, 160, 800, 4096 LONG = 2048 # flows over this many mel frames run on estimator_long.engine (loaded then) MAX_CACHE = 3 + MAX_TEXT + 1 + MAX_TOKENS + 1 VOC_WIN, VOC_CTX = 512, 64 # vocoder windows (mel frames): the engine takes up to 640 MEL_PER_TOKEN = 2 * 1.72 # pipeline.py: codec doubles the tokens, the regulator stretches by 1.72 OUTS = {"semantic": "feat", "emovec": "emovec", "campplus": "style", "prefix": "embeds", "embed": "embeds", "codec": "feat", "regulator": "cond", "estimator": "velocity", "vocoder": "wav"} STATIC = ("prefix", "embed", "regulator") # small profiles; the others take their memory per call's shapes class IndexTTS25Trt(IndexTTS25): def __init__(self, folder=HERE): folder = self.folder = Path(folder) self.s = {n: OrtLike(folder / f"{n}.engine", [o], allocation="static" if n in STATIC else "runtime") for n, o in OUTS.items()} self.chain = Chain.from_split(folder, "decoder") names = [f"{i}.{kv}" for i in range(LAYERS) for kv in ("key", "value")] self.kv = Buffers([f"past_key_values.{n}" for n in names], [f"present.{n}" for n in names], np.float16, (BEAMS, HEADS, MAX_CACHE, HEAD_DIM)) self.kv_len = 0 self.device = "trt" self.kv_dtype, self.emb_dtype = np.float16, np.float32 self.tok = Tokenizer(folder) self.basis = mel_basis() self.cache = None def run(self, name, **feeds): if name == "vocoder": return self.vocode(feeds["mel"]) if name == "estimator" and feeds["x"].shape[2] > LONG: # the long engine, loaded on first use if "estimator_long" not in self.s: self.s["estimator_long"] = OrtLike(self.folder / "estimator_long.engine", ["velocity"], "runtime") name = "estimator_long" return self.s[name].run(None, feeds)[0] def vocode(self, m): """BigVGAN over [1, 80, T] in windows of VOC_WIN frames with VOC_CTX frames of context on each side, whose audio is dropped: its output is local (on the CPU the windows give one whole pass's samples exactly).""" T, out = m.shape[2], [] for a in range(0, T, VOC_WIN): lo, hi = max(0, a - VOC_CTX), min(T, a + VOC_WIN + VOC_CTX) y = self.s["vocoder"].run(None, {"mel": np.ascontiguousarray(m[:, :, lo:hi])})[0] out.append(y[..., (a - lo) * HOP:(a - lo + min(VOC_WIN, T - a)) * HOP]) return np.concatenate(out, -1) def _decode_step(self, embeds, beam_idx, past): """past: pipeline.py's empty start (a list: a new prompt) or what the last step returned; the cache itself stays on the GPU.""" if isinstance(past, list): self.kv.reset((1, HEADS, 0, HEAD_DIM)) self.kv_len = 0 n = embeds.shape[1] if self.kv_len + n > MAX_CACHE: raise ValueError(f"decoder: {self.kv_len} cached + {n} new positions; the engines take up to {MAX_CACHE}") out = self.chain({"inputs_embeds": np.asarray(embeds, np.float32), "beam_idx": np.asarray(beam_idx, np.int64), **self.kv.reads()}, outputs=self.kv.writes(), fetch=["logits"]) self.kv.swap() self.kv_len += n return out["logits"], "gpu" def speech_tokens(self, ref, text_ids, lang, rng, max_new=1500, n_beams=3): if n_beams != BEAMS: raise ValueError(f"the engines are built for {BEAMS} beams") if len(text_ids) + 1 > MAX_TEXT: raise ValueError(f"a text segment of {len(text_ids) + 1} ids; the engines take up to {MAX_TEXT}") room = int((MAX_MEL - ref["ref_mel"].shape[2]) / MEL_PER_TOKEN) - 1 return super().speech_tokens(ref, text_ids, lang, rng, min(max_new, MAX_TOKENS, room), n_beams) def close(self): self.chain.close() self.kv.free() for s in self.s.values(): s.e.close() if __name__ == "__main__": import argparse import soundfile as sf ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("text"); ap.add_argument("output") ap.add_argument("--ref", required=True); ap.add_argument("--lang", default="en") ap.add_argument("--dir", default=str(HERE)) ap.add_argument("--seed", type=int, default=0) a = ap.parse_args() r, rsr = sf.read(a.ref, dtype="float32", always_2d=True) tts = IndexTTS25Trt(a.dir) y, sr = tts(a.text, r.mean(1), rsr, a.lang, seed=a.seed) sf.write(a.output, y, sr)