"""IndexTTS-2.5 voice cloning with ONNX Runtime. Follows the official `IndexTTS2.infer_generator(spk_audio_prompt, text, lang, text_normalization=False)` (index-tts @d9e41aa, infer_v2_5.py): w2v-BERT 2.0 features and CAM++ style of the reference, the emotion vector taken from the reference itself, the GPT-2 speech-token model with the official beam sampling (3 beams, top-p 0.8, top-k 30, temperature 0.8, repetition penalty 10 on the log-probabilities, length penalty 0, at most 1500 tokens), the semantic codec decoder, the s2mel flow (25 Euler steps, classifier-free guidance 0.7) with the reference mel as prompt, BigVGAN v2. 22.05 kHz output. Needs numpy, onnxruntime (or onnxruntime-gpu), tiktoken, soundfile and soxr. python fp16/pipeline.py "Text to say." out.wav --ref voice.wav --lang en [--cuda] [--seed 0] Not included: the official text normalisation (wetext; pass written-out text), Japanese / Spanish frontends, emotion control by vector, text or a second reference (the reference's own emotion is used, as by default), and the duration factor. Sampling uses numpy's generator, so a seed gives the same speech every run here, not the same as PyTorch with that seed. """ from __future__ import annotations import json import math import re from pathlib import Path import numpy as np SR, HOP, N_FFT = 22050, 256, 1024 LAYERS, HEADS, HEAD_DIM = 24, 20, 64 START_TEXT, STOP_TEXT, START_MEL, STOP_MEL = 0, 1, 8192, 8193 MAX_TEXT_POS = 602 # gpt.text_pos_embedding size: max_text_tokens + 2 CHAR_REP = {":": ",", ";": ",", ";": ",", ",": ",", "。": ".", "!": "!", "?": "?", "\n": " ", "·": "-", "、": ",", "...": "…", ",,,": "…", ",,,": "…", "……": "…", "“": "'", "”": "'", '"': "'", "‘": "'", "’": "'", "(": "'", ")": "'", "(": "'", ")": "'", "《": "'", "》": "'", "【": "'", "】": "'", "[": "'", "]": "'", "—": "-", "~": "-", "~": "-", "「": "'", "」": "'", ":": ","} CLEAN = re.compile("|".join(re.escape(p) for p in CHAR_REP)) ANNOT = re.compile(r'<([^|>\n]+)\|([^>\n]+)>') PROTECTED = re.compile(r'<\|SPECIAL_TOKEN_\d+\|>.*?<\|SPECIAL_TOKEN_\d+\|>') # -- features ---------------------------------------------------------------------------------------------------- def resample(x, orig, new, lowpass_filter_width=6, rolloff=0.99): """torchaudio.transforms.Resample(orig, new) (sinc_interp_hann), which the official code uses for 16 kHz.""" g = math.gcd(int(orig), int(new)) o, n = int(orig) // g, int(new) // g if o == n: return np.asarray(x, np.float32) base = min(o, n) * rolloff width = math.ceil(lowpass_filter_width * o / base) idx = np.arange(-width, width + o, dtype=np.float64)[None, :] / o t = (np.arange(0, -n, -1, dtype=np.float64)[:, None] / n + idx) * base t = np.clip(t, -lowpass_filter_width, lowpass_filter_width) win = np.cos(t * math.pi / lowpass_filter_width / 2) ** 2 t = t * math.pi with np.errstate(invalid="ignore", divide="ignore"): k = np.where(t == 0, 1.0, np.sin(t) / t) k = (k * win * base / o).astype(np.float32) xp = np.pad(np.asarray(x, np.float32), (width, width + o)) frames = np.lib.stride_tricks.sliding_window_view(xp, k.shape[1])[::o] y = (frames @ k.T).reshape(-1) return y[: math.ceil(n * len(x) / o)].astype(np.float32) def _kaldi_bank(): melf = lambda hz: 1127.0 * np.log(1.0 + hz / 700.0) centers = np.linspace(melf(20.0), melf(8000.0), 82) fft_mel = melf(np.arange(256) * 16000.0 / 512) bank = np.zeros((80, 257)) for m in range(80): l, c, r = centers[m], centers[m + 1], centers[m + 2] bank[m, :256] = np.maximum(0, np.minimum((fft_mel - l) / (c - l), (r - fft_mel) / (r - c))) return bank def _povey_power(x): """25 / 10 ms frames (snip edges), DC removal, pre-emphasis 0.97, povey window, 512-point power spectrum.""" fl, fs = 400, 160 n = 1 + (len(x) - fl) // fs f = x[np.arange(fl)[None, :] + fs * np.arange(n)[:, None]] f = f - f.mean(1, keepdims=True) f = np.concatenate([f[:, :1] - 0.97 * f[:, :1], f[:, 1:] - 0.97 * f[:, :-1]], 1) win = (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(fl) / (fl - 1))) ** 0.85 return np.abs(np.fft.rfft(f * win, 512, axis=1)) ** 2 def kaldi_fbank(wav16): """torchaudio.compliance.kaldi.fbank(num_mel_bins=80, dither=0, sample_frequency=16000). Returns [T, 80].""" e = _povey_power(np.asarray(wav16, np.float64)) @ _kaldi_bank().T return np.log(np.maximum(e, np.finfo(np.float32).eps)).astype(np.float32) def w2v_features(wav16): """SeamlessM4TFeatureExtractor (w2v-bert-2.0's preprocessor): Kaldi fbank of the 16-bit-scaled audio, each bin normalised over time (ddof 1), padded to an even frame count with 1.0, frame pairs stacked -> [1, T, 160], and the attention mask [1, T] (the padded pair is masked).""" x = np.asarray(wav16, np.float32).astype(np.float64) * 32768.0 e = _povey_power(x) @ _kaldi_bank().T f = np.log(np.maximum(e, 1.192092955078125e-07)).astype(np.float32) f = (f - f.mean(0, keepdims=True)) / np.sqrt(f.var(0, ddof=1, keepdims=True) + 1e-7) mask = np.ones(len(f), np.int64) if len(f) % 2: f = np.concatenate([f, np.ones((1, 80), np.float32)]) mask = np.concatenate([mask, [0]]) return f.reshape(1, -1, 160).astype(np.float32), mask[1::2][None].astype(np.int64) def mel(wav22, basis): """s2mel mel_spectrogram(n_fft 1024, 80 mels, hop 256, win 1024, center=False): reflect padding of 384 each side, periodic Hann, magnitude, log of the clamp at 1e-5. Returns [1, 80, T].""" x = np.pad(np.asarray(wav22, np.float32), ((N_FFT - HOP) // 2, (N_FFT - HOP) // 2), mode="reflect") win = (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(N_FFT) / N_FFT)).astype(np.float32) n = 1 + (len(x) - N_FFT) // HOP s = np.fft.rfft(x[np.arange(N_FFT)[None, :] + HOP * np.arange(n)[:, None]] * win, axis=1) mag = np.sqrt(s.real.astype(np.float64) ** 2 + s.imag.astype(np.float64) ** 2 + 1e-9).astype(np.float32) return np.log(np.maximum(basis @ mag.T, 1e-5))[None].astype(np.float32) def mel_basis(): """librosa.filters.mel(sr=22050, n_fft=1024, n_mels=80, fmin=0, fmax=None): Slaney scale and norm.""" def hz2mel(f): f = np.asarray(f, np.float64) lin = f / (200.0 / 3) return np.where(f >= 1000.0, 15.0 + np.log(np.maximum(f, 1e-10) / 1000.0) / (np.log(6.4) / 27.0), lin) def mel2hz(m): m = np.asarray(m, np.float64) return np.where(m >= 15.0, 1000.0 * np.exp((np.log(6.4) / 27.0) * (m - 15.0)), (200.0 / 3) * m) fft = np.linspace(0, SR / 2, N_FFT // 2 + 1) pts = mel2hz(np.linspace(hz2mel(0.0), hz2mel(SR / 2), 82)) fd = np.diff(pts) ramps = pts[:, None] - fft[None, :] w = np.zeros((80, len(fft))) for i in range(80): w[i] = np.maximum(0, np.minimum(-ramps[i] / fd[i], ramps[i + 2] / fd[i + 1])) w *= (2.0 / (pts[2:82] - pts[:80]))[:, None] return w.astype(np.float32) def nearest(x, n): """F.interpolate(mode='nearest') along time of [1, T, C] to length n.""" t = x.shape[1] src = np.minimum(np.floor(np.arange(n, dtype=np.float32) * (np.float32(t) / np.float32(n))).astype(np.int64), t - 1) return np.ascontiguousarray(x[:, src]) # -- text ---------------------------------------------------------------------------------------------------------- def prepare_text(text, lang): """The official clean-up with text_normalization off: punctuation map, lower case (zh / en), pronunciation annotations -> special-token-wrapped pronunciations, tags upper-cased.""" text = CLEAN.sub(lambda m: CHAR_REP[m.group()], text) if lang in ("ja", "zh", "zhen", "en"): text = text.lower() if lang == "es": text = text.upper() def rep(m): word, pron = m.group(1), m.group(2).upper() if re.fullmatch(r'[぀-ゟ]+', pron) or re.fullmatch(r'[゠-ヿ]+', pron): return f' {pron} ' tok = 'SPECIAL_TOKEN_2' if re.search(r"[一-鿿]", word) else 'SPECIAL_TOKEN_1' return f'<|{tok}|>{pron}<|{tok}|>' text = ANNOT.sub(rep, text) return re.sub(r'<\|([^|]+)\|>', lambda m: f'<|{m.group(1).upper()}|>', text) class Tokenizer: def __init__(self, folder): import base64 import tiktoken cfg = json.loads((folder / "tokenizer.json").read_text(encoding="utf-8")) ranks = {base64.b64decode(t): int(r) for t, r in (l.split() for l in (folder / "tokenizer.tiktoken").read_text().splitlines() if l)} self.enc = tiktoken.Encoding(name="multilingual_zh_ja_yue_char_del", explicit_n_vocab=cfg["n_vocab"], pat_str=cfg["pat_str"], mergeable_ranks=ranks, special_tokens=cfg["special_tokens"]) self.lang = cfg["languages"] def encode(self, text): return self.enc.encode(text, allowed_special="all") def split(self, text, prefix, max_tokens=120): """split_text_by_tokens: segments of at most max_tokens (with the language prefix), at punctuation.""" n = lambda t: len(self.encode(t)) budget = max(1, min(max_tokens, MAX_TEXT_POS - 2) - n(prefix)) if n(text) <= budget: return [text] pieces, pos = [], 0 for m in PROTECTED.finditer(text): if m.start() > pos: pieces.append((text[pos:m.start()], False)) pieces.append((m.group(0), True)); pos = m.end() if pos < len(text): pieces.append((text[pos:], False)) chunks = [] for piece, atomic in pieces: if atomic: chunks.append(piece); continue for part in re.split(r'(?<=[,。!?、;:,\.!\?;:\n])', piece): if not part: continue if n(part) <= budget: chunks.append(part); continue cur = "" for ch in part: if cur and n(cur + ch) > budget: chunks.append(cur); cur = ch else: cur += ch if cur: chunks.append(cur) segs, cur = [], "" for c in chunks: if cur and n(cur + c) > budget: segs.append(cur); cur = c else: cur += c if cur: segs.append(cur) return segs or [text] # -- the speech-token model ---------------------------------------------------------------------------------------- def log_softmax(x): m = x.max(-1, keepdims=True) return x - m - np.log(np.exp(x - m).sum(-1, keepdims=True)) def warp(scores, ids, penalty=10.0, temperature=0.8, top_k=30, top_p=0.8, keep=2): """The processors HF's beam sampling applies to the log-probabilities, in its order: repetition penalty on every token already in the sequence (the prompt's placeholder ids 1 and the start token included), temperature, top-k, top-p (both keeping at least 2).""" s = scores.copy() for b in range(len(s)): u = np.unique(ids[b]) v = s[b, u] s[b, u] = np.where(v < 0, v * penalty, v / penalty) s = s / temperature kth = np.sort(s, -1)[:, -top_k][:, None] s = np.where(s < kth, -np.inf, s) order = np.argsort(s, -1, kind="stable") srt = np.take_along_axis(s, order, -1) e = np.exp(srt - srt.max(-1, keepdims=True)) cum = np.cumsum(e / e.sum(-1, keepdims=True), -1) remove = cum <= 1 - top_p remove[:, -keep:] = False out = np.full_like(s, -np.inf) np.put_along_axis(out, order, np.where(remove, -np.inf, srt), -1) return out class Beams: """BeamSearchScorer (num_beams 3, length_penalty 0 so a hypothesis scores its summed log-probability, early_stopping off).""" def __init__(self, n=3): self.n, self.hyps, self.done = n, [], False def add(self, seq, score): if len(self.hyps) < self.n or score > min(h[0] for h in self.hyps): self.hyps.append((score, seq)) if len(self.hyps) > self.n: self.hyps.remove(min(self.hyps, key=lambda h: h[0])) def is_done(self, best): return len(self.hyps) >= self.n and min(h[0] for h in self.hyps) >= best class IndexTTS25: def __init__(self, folder, provider="cpu", threads=4): import onnxruntime as ort folder = Path(folder) if provider != "cpu" and hasattr(ort, "preload_dlls"): try: ort.preload_dlls() except Exception: pass self.ort = ort so = ort.SessionOptions() so.intra_op_num_threads = threads so.log_severity_level = 3 # host memory: no CPU arena (it would keep the initializers' staging copies) and initializers allocated # with the device allocator; ten sessions of ~1-2.5 GB otherwise hold about twice their size so.enable_cpu_mem_arena = False so.add_session_config_entry("session.use_device_allocator_for_initializers", "1") cuda = ("CUDAExecutionProvider", {"arena_extend_strategy": "kSameAsRequested", "cudnn_conv_algo_search": "HEURISTIC"}) prov = ["CPUExecutionProvider"] if provider == "cpu" else [cuda, "CPUExecutionProvider"] self.s = {n: ort.InferenceSession(str(folder / f"{n}.onnx"), so, providers=prov) for n in ("semantic", "emovec", "campplus", "prefix", "embed", "decoder", "codec", "regulator", "estimator", "vocoder")} self.device = "cuda" if "CUDAExecutionProvider" in self.s["decoder"].get_providers() else "cpu" p = {i.name: i for i in self.s["decoder"].get_inputs()} self.kv_dtype = np.float16 if "float16" in p["past_key_values.0.key"].type else np.float32 self.emb_dtype = np.float16 if "float16" in p["inputs_embeds"].type else np.float32 self.out_names = [o.name for o in self.s["decoder"].get_outputs()] # every input length differs (the KV cache grows by one position per step), so the GPU arena could rarely # reuse a block: shrink it after each run (on Windows device allocations count against the process's commit) self.ro = ort.RunOptions() if self.device == "cuda": self.ro.add_run_config_entry("memory.enable_memory_arena_shrinkage", "gpu:0") self.tok = Tokenizer(folder) self.basis = mel_basis() self.cache = None def run(self, name, **feeds): return self.s[name].run(None, feeds, self.ro)[0] # reference ------------------------------------------------------------------------------------------------ def reference(self, wav, sr): """The official prompt features: 22.05 kHz and (torchaudio-resampled from it) 16 kHz copies of the first 15 s for the s2mel prompt, CAM++ style and mel; a direct 16 kHz load of the first 15 s for the emotion vector.""" import soxr key = (id(wav), len(wav), sr) if self.cache and self.cache[0] == key: return self.cache[1] wav = np.asarray(wav, np.float32) rs = lambda r: soxr.resample(wav, sr, r, quality="HQ").astype(np.float32) if sr != r else wav a22 = rs(SR)[: int(15 * SR)] a16 = resample(a22, SR, 16000) e16 = rs(16000)[: int(15 * 16000)] f, m = w2v_features(a16) spk = self.run("semantic", feats=f, mask=m) f, m = w2v_features(e16) emo = self.run("semantic", feats=f, mask=m) ref_mel = mel(a22, self.basis) fb = kaldi_fbank(a16) style = self.run("campplus", feat=(fb - fb.mean(0, keepdims=True))[None].astype(np.float32)) prompt_cond = self.run("regulator", feat=nearest(spk, ref_mel.shape[2])) emovec = self.run("emovec", feat=emo) out = dict(style=style, emovec=emovec, ref_mel=ref_mel, prompt_cond=prompt_cond) self.cache = (key, out) return out # GPT ---------------------------------------------------------------------------------------------------------- def _decode_step(self, embeds, beam_idx, past): s = self.s["decoder"] if self.device == "cpu": feeds = {"inputs_embeds": embeds.astype(self.emb_dtype), "beam_idx": beam_idx} feeds.update({f"past_key_values.{i // 2}.{'key' if i % 2 == 0 else 'value'}": past[i] for i in range(2 * LAYERS)}) outs = s.run(self.out_names, feeds, self.ro) return outs[0], outs[1:] io = s.io_binding() # a fresh binding per step; the cache stays on the GPU io.bind_cpu_input("inputs_embeds", embeds.astype(self.emb_dtype)) io.bind_cpu_input("beam_idx", beam_idx) for i in range(2 * LAYERS): io.bind_ortvalue_input(f"past_key_values.{i // 2}.{'key' if i % 2 == 0 else 'value'}", past[i]) io.bind_output("logits", "cpu") for n in self.out_names[1:]: io.bind_output(n, "cuda") s.run_with_iobinding(io, self.ro) outs = io.get_outputs() return outs[0].numpy(), outs[1:] def speech_tokens(self, ref, text_ids, lang, rng, max_new=1500, n_beams=3): ids = [t for t in text_ids if t not in (START_TEXT, STOP_TEXT)] text = np.array([[START_TEXT, *ids, STOP_TEXT]], np.int64) prefix = self.run("prefix", style=ref["style"], emovec=ref["emovec"], text=text, lang=np.array([lang], np.int64)) # [1, mel_len + 1, 1280] mel_len = prefix.shape[1] - 1 empty = np.zeros((1, HEADS, 0, HEAD_DIM), self.kv_dtype) if self.device == "cuda": empty = self.ort.OrtValue.ortvalue_from_numpy(empty, "cuda", 0) logits, past = self._decode_step(prefix, np.zeros(1, np.int64), [empty] * (2 * LAYERS)) logits = np.repeat(logits.astype(np.float32), n_beams, 0) seqs = np.tile(np.array([[1] * mel_len + [START_MEL]], np.int64), (n_beams, 1)) beam_scores = np.array([0.0] + [-1e9] * (n_beams - 1), np.float32) beams = Beams(n_beams) beam_idx = np.zeros(n_beams, np.int64) # the prefill cache has batch 1 V = logits.shape[1] for step in range(max_new): scores = warp(log_softmax(logits), seqs) + beam_scores[:, None] flat = scores.reshape(-1) p = np.exp(flat - flat[np.isfinite(flat)].max()) p = np.where(np.isfinite(flat), p, 0.0) p = p / p.sum() k = min(2 * n_beams, int((p > 0).sum())) pick = rng.choice(len(p), size=k, replace=False, p=p) sc = flat[pick] order = np.argsort(-sc, kind="stable") pick, sc = pick[order], sc[order] nxt_score, nxt_tok, nxt_beam = [], [], [] for rank, (tok_flat, s_) in enumerate(zip(pick, sc)): b, t = divmod(int(tok_flat), V) if t == STOP_MEL: if rank >= n_beams: continue beams.add(seqs[b, mel_len + 1:].tolist(), float(s_)) else: nxt_score.append(s_); nxt_tok.append(t); nxt_beam.append(b) if len(nxt_tok) == n_beams: break if beams.is_done(float(sc.max())): beams.done = True break beam_idx = np.array(nxt_beam, np.int64) beam_scores = np.array(nxt_score, np.float32) seqs = np.concatenate([seqs[beam_idx], np.array(nxt_tok, np.int64)[:, None]], 1) if step == max_new - 1: break n_gen = seqs.shape[1] - (mel_len + 1) # GPT2InferenceModel embeds a step's token at attention-mask length - mel_len: position n_gen + 1 emb = self.run("embed", tokens=np.array(nxt_tok, np.int64)[:, None], pos=np.array([n_gen + 1], np.int64)) logits, past = self._decode_step(emb, beam_idx, past) logits = logits.astype(np.float32) if not beams.done: # finalize: running beams join for b in range(n_beams): beams.add(seqs[b, mel_len + 1:].tolist(), float(beam_scores[b])) return max(beams.hyps, key=lambda h: h[0])[1] # s2mel + vocoder ---------------------------------------------------------------------------------------------- def flow(self, cond, prompt, style, rng, steps=25, cfg=0.7): T, pl = cond.shape[1], prompt.shape[2] x = rng.standard_normal((1, 80, T)).astype(np.float32) ts = np.linspace(0, 1, steps + 1, dtype=np.float32) t = ts[0] px = np.zeros_like(x) px[..., :pl] = prompt[..., :pl] x[..., :pl] = 0 z = np.zeros_like for step in range(1, len(ts)): dt = ts[step] - ts[step - 1] v = self.run("estimator", x=np.concatenate([x, x]), prompt_x=np.concatenate([px, z(px)]), t=np.full(2, t, np.float32), style=np.concatenate([style, z(style)]), cond=np.concatenate([cond, z(cond)])) d = (1.0 + cfg) * v[0:1] - cfg * v[1:2] x = (x + dt * d).astype(np.float32) t = np.float32(t + dt) x[:, :, :pl] = 0 return x def __call__(self, text, ref_wav, ref_sr, lang="en", seed=0, interval_silence_ms=200): rng = np.random.default_rng(seed) lang = lang.lower() ref = self.reference(ref_wav, ref_sr) prefix = f"<|{lang}|> " text = prepare_text(text, lang) lang_id = self.tok.lang.get(lang, self.tok.lang["common"]) wavs = [] for seg in self.tok.split(text, prefix): ids = self.tok.encode(prefix + seg) + [STOP_TEXT] codes = self.speech_tokens(ref, ids, lang_id, rng) if STOP_MEL in codes: codes = codes[: codes.index(STOP_MEL)] S = self.run("codec", codes=np.array([codes], np.int64)) # [1, 2 N, 1024] cond = self.run("regulator", feat=nearest(S, int(S.shape[1] * 1.72))) cat = np.concatenate([ref["prompt_cond"], cond], 1) m = self.flow(cat, ref["ref_mel"], ref["style"], rng)[:, :, ref["ref_mel"].shape[2]:] w = self.run("vocoder", mel=np.ascontiguousarray(m)).reshape(-1) wavs.append(np.clip(32767 * w, -32767.0, 32767.0)) out = [] for i, w in enumerate(wavs): # insert_interval_silence out.append(w) if i < len(wavs) - 1: out.append(np.zeros(int(SR * interval_silence_ms / 1000), np.float32)) wav = np.concatenate(out) n = min(int(SR * 20 / 1000), len(wav)) # fade_out_tail, 20 ms if n > 1: wav[-n:] = wav[-n:] * (0.5 * (1.0 + np.cos(np.linspace(0.0, math.pi, n)))).astype(np.float32) return (wav / 32767.0).astype(np.float32), SR 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(Path(__file__).resolve().parent)) ap.add_argument("--cuda", action="store_true"); ap.add_argument("--seed", type=int, default=0) a = ap.parse_args() r, rsr = sf.read(a.ref, dtype="float32", always_2d=True) tts = IndexTTS25(a.dir, "cuda" if a.cuda else "cpu") y, sr = tts(a.text, r.mean(1), rsr, a.lang, seed=a.seed) sf.write(a.output, y, sr)