"""Tiny TTS: standalone inference. Needs: torch, numpy, safetensors (+ soundfile for the CLI).""" import json, os, re, sys import numpy as np import torch, torch.nn as nn, torch.nn.functional as F from safetensors.torch import load_file from torch.nn.utils.parametrizations import weight_norm def sinusoids(T, d, device): pos = torch.arange(T, device=device)[:, None].float() i = torch.arange(0, d, 2, device=device).float() ang = pos / (10000 ** (i / d)) return torch.cat([ang.sin(), ang.cos()], dim=-1) def durations_to_attn(dur, T): ends = dur.cumsum(1) starts = ends - dur t = torch.arange(T, device=dur.device)[None, :, None] return ((t >= starts[:, None, :]) & (t < ends[:, None, :])).float() class FFTBlock(nn.Module): def __init__(self, d, heads, ff, p, k=3): super().__init__() self.h = heads self.n1 = nn.LayerNorm(d) self.qkv = nn.Linear(d, 3 * d) self.o = nn.Linear(d, d) self.n2 = nn.LayerNorm(d) self.c1 = nn.Conv1d(d, ff, k, padding=k // 2) self.c2 = nn.Conv1d(ff, d, 1) self.drop = nn.Dropout(p) def forward(self, x, m, am): B, T, D = x.shape q, kk, v = self.qkv(self.n1(x)).view(B, T, 3, self.h, D // self.h).permute(2, 0, 3, 1, 4) a = F.scaled_dot_product_attention(q, kk, v, attn_mask=am) x = x + self.drop(self.o(a.transpose(1, 2).reshape(B, T, D))) y = (self.n2(x) * m).transpose(1, 2) y = self.c2(F.gelu(self.c1(y))).transpose(1, 2) return (x + self.drop(y)) * m class Stack(nn.Module): def __init__(self, d, heads, n, ff, p): super().__init__() self.blocks = nn.ModuleList([FFTBlock(d, heads, ff, p) for _ in range(n)]) self.norm = nn.LayerNorm(d) self.drop = nn.Dropout(p) def forward(self, x, mask): m = mask[:, :, None].to(x.dtype) am = mask[:, None, None, :] x = self.drop(x + sinusoids(x.shape[1], x.shape[2], x.device)) * m for blk in self.blocks: x = blk(x, m, am) return self.norm(x) * m class DurationPredictor(nn.Module): def __init__(self, d, p, k=3): super().__init__() self.c1 = nn.Conv1d(d, d, k, padding=k // 2); self.n1 = nn.LayerNorm(d) self.c2 = nn.Conv1d(d, d, k, padding=k // 2); self.n2 = nn.LayerNorm(d) self.lin = nn.Linear(d, 1) self.drop = nn.Dropout(p) def forward(self, x, m): h = (x * m).transpose(1, 2) h = self.drop(self.n1(F.relu(self.c1(h)).transpose(1, 2))) * m h = self.drop(self.n2(F.relu(self.c2(h.transpose(1, 2))).transpose(1, 2))) * m return self.lin(h).squeeze(-1) class TinyTTS(nn.Module): """Acoustic model (inference only): text -> normalized log-mel.""" def __init__(self, vocab, d, heads, n_enc, n_dec, ff, n_mels): super().__init__() self.emb = nn.Embedding(vocab, d, padding_idx=0) self.encoder = Stack(d, heads, n_enc, ff, 0.0) self.decoder = Stack(d, heads, n_dec, ff, 0.0) self.dur = DurationPredictor(d, 0.0) self.out = nn.Linear(d, n_mels) @torch.no_grad() def infer(self, text, text_len, speed=1.0): B, L = text.shape tmask = torch.arange(L, device=text.device)[None] < text_len[:, None] enc = self.encoder(self.emb(text), tmask) logd = self.dur(enc, tmask[..., None].to(enc.dtype)).float() dur = ((torch.expm1(logd) / speed).round().clamp(min=1) * tmask).long() mel_len = dur.sum(1) T = int(mel_len.max()) mmask = torch.arange(T, device=text.device)[None] < mel_len[:, None] x = torch.bmm(durations_to_attn(dur, T).to(enc.dtype), enc) return self.out(self.decoder(x, mmask)).transpose(1, 2), mel_len class ResBlock2(nn.Module): def __init__(self, ch, k, dil): super().__init__() self.convs = nn.ModuleList([weight_norm(nn.Conv1d(ch, ch, k, 1, d * (k - 1) // 2, dilation=d)) for d in dil]) def forward(self, x): for c in self.convs: x = x + c(F.leaky_relu(x, 0.1)) return x class VGen(nn.Module): """HiFi-GAN-style generator: normalized log-mel (B,80,T) -> waveform (B, T*256).""" def __init__(self, n_mels=80, ch=256, rates=(8, 8, 2, 2), ks=(16, 16, 4, 4), rk=(3, 7, 11), rd=(1, 3)): super().__init__() self.pre = weight_norm(nn.Conv1d(n_mels, ch, 7, 1, 3)) self.ups, self.res = nn.ModuleList(), nn.ModuleList() c = ch for r, k in zip(rates, ks): self.ups.append(weight_norm(nn.ConvTranspose1d(c, c // 2, k, r, (k - r) // 2))) c //= 2 self.res.append(nn.ModuleList([ResBlock2(c, kk, rd) for kk in rk])) self.post = weight_norm(nn.Conv1d(c, 1, 7, 1, 3)) def forward(self, x): x = self.pre(x) for up, rs in zip(self.ups, self.res): x = up(F.leaky_relu(x, 0.1)) x = sum(r(x) for r in rs) / len(rs) return torch.tanh(self.post(F.leaky_relu(x))).squeeze(1) class TinyTTSPipeline: def __init__(self, path=".", device=None, vocoder="default"): if not os.path.isdir(path): # treat as a Hub repo id from huggingface_hub import snapshot_download path = snapshot_download(path) c = json.load(open(os.path.join(path, "config.json"))) self.cfg, self.sr = c, c["sr"] self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu")) self.symbols = c["symbols"] self.char2id = {s: i for i, s in enumerate(self.symbols) if i >= 3} m = c["model"] self.tts = TinyTTS(len(self.symbols), m["d_model"], m["n_heads"], m["n_enc_layers"], m["n_dec_layers"], m["ff"], m["n_mels"]) self.tts.load_state_dict(load_file(os.path.join(path, "tts.safetensors"))) self.voc = VGen(m["n_mels"], c["vocoder"]["ch"]) vf = "vocoder_original.safetensors" if vocoder == "original" else "vocoder.safetensors" self.voc.load_state_dict(load_file(os.path.join(path, vf))) self.tts.to(self.device).eval() self.voc.to(self.device).eval() def encode(self, text): text = re.sub(r"\s+", " ", text.lower()).strip() ids = [self.char2id.get(ch, 2) for ch in text] # 2 = out = [1] * (2 * len(ids) + 1) # 1 = , interspersed out[1::2] = ids return out @torch.no_grad() def text_to_mel(self, text, speed=None): speed = self.cfg["speed"] if speed is None else speed ids = torch.tensor([self.encode(text)], device=self.device) ln = torch.tensor([ids.shape[1]], device=self.device) mel, mlen = self.tts.infer(ids, ln, speed) return mel[:, :, :int(mlen[0])] @torch.no_grad() def __call__(self, text, speed=None): """text -> float32 numpy waveform at self.sr""" if not re.sub(r"\s+", "", text): raise ValueError("empty text") w = self.voc(self.text_to_mel(text, speed))[0].clamp(-1, 1).cpu().numpy() return (w / max(1e-6, float(np.abs(w).max())) * 0.9).astype(np.float32) if __name__ == "__main__": import soundfile as sf here = os.path.dirname(os.path.abspath(__file__)) text = sys.argv[1] if len(sys.argv) > 1 else "Hello, how are you today?" out = sys.argv[2] if len(sys.argv) > 2 else "out.wav" tts = TinyTTSPipeline(here) sf.write(out, tts(text), tts.sr) print("wrote", out)