# Сеть Kokoro-82M / Kitten TTS 2 Mini (одна архитектура) для экспорта в Core ML: # веса, обратный STFT свёртками (= torch.istft), полный генератор и графы # длительностей и интонации Kitten. Модель — переменная KOKORO=1 (иначе Kitten). # Окружение: torch 2.7, coremltools 9.0, transformers 4.55, # `pip install --no-deps kittenml==0.9.8` (код сетей, Apache 2.0). import sys, os, json, glob, numpy as np, torch, torch.nn as nn, torch.nn.functional as F, coremltools as ct from scipy.signal import get_window from kittenml.kittentts2_tiny.networks.modules import build_modules, AdaLayerNorm from safetensors.torch import load_file from coremltools.converters.mil.frontend.torch import ops as _ctops from coremltools.converters.mil import Builder as _mb def _cast_fixed(context, node, dtype, dtype_name): x = _ctops._get_inputs(context, node, expected=1)[0] if x.can_be_folded_to_const(): v = np.asarray(x.val).reshape(-1)[0] res = _mb.const(val=dtype(v), name=node.name) elif len(x.shape) > 0: res = _mb.cast(x=_mb.squeeze(x=x, name=node.name + "_item"), dtype=dtype_name, name=node.name) else: res = _mb.cast(x=x, dtype=dtype_name, name=node.name) context.add(res, node.name) _ctops._cast = _cast_fixed SNAP = glob.glob(os.path.expanduser('~/.cache/huggingface/hub/models--KittenML--kitten-tts-2-mini/snapshots/8e89ae2a718ee4bb893c67d67657e520e6112faf'))[0] cfg = json.load(open(f'{SNAP}/config.json'))['models']['kitten_tts_2_mini']['architecture'] net = nn.ModuleDict(build_modules(cfg)) KOKORO = bool(os.environ.get('KOKORO')) if KOKORO: # Kokoro-82M v1.0: the same architecture and config, its own weights _pth = glob.glob(os.path.expanduser('~/.cache/huggingface/hub/models--hexgrad--Kokoro-82M/snapshots/f3ff3571791e39611d31c381e3a41a3af07b4987/kokoro-v1_0.pth'))[0] _sd = torch.load(_pth, map_location='cpu', weights_only=True) for _k in net: net[_k].load_state_dict({k.replace('module.', '', 1): v for k, v in _sd[_k].items()}, strict=True) else: net.load_state_dict(load_file(f'{SNAP}/kitten_tts_2_mini.safetensors'), strict=True) SPEC = torch.exp if KOKORO else F.softplus # Kokoro's generator takes exp of the magnitude, Kitten's softplus net.eval(); net.requires_grad_(False) for m in net.modules(): # fold weight norm if hasattr(m, 'weight_g'): torch.nn.utils.remove_weight_norm(m) net.requires_grad_(False) class Duration(nn.Module): def forward(self, input_ids, ref_s, speed): ids = input_ids.long(); T = ids.shape[1]; sp = ref_s[:, 128:] te = net['text_encoder'] x = te.embedding(ids).transpose(1, 2) for c in te.cnn: x = c(x) x, _ = te.lstm(x.transpose(1, 2)) t_en = x.transpose(-1, -2) bd = net['bert'](ids, attention_mask=torch.ones_like(ids)) x = net['bert_encoder'](bd).transpose(-1, -2) s = sp.unsqueeze(-1).expand(-1, -1, T) x = torch.cat([x, s], 1) for block in net['predictor'].text_encoder.lstms: if isinstance(block, AdaLayerNorm): x = block(x.transpose(-1, -2), sp).transpose(-1, -2) x = torch.cat([x, s], 1) else: x, _ = block(x.transpose(-1, -2)); x = x.transpose(-1, -2) d = x.transpose(-1, -2) h, _ = net['predictor'].lstm(d) dur = torch.sigmoid(net['predictor'].duration_proj(h)).sum(-1) / speed return dur, d, t_en class Prosody(nn.Module): def forward(self, en, asr, ref_s): sa, sp = ref_s[:, :128], ref_s[:, 128:] f0, n = net['predictor'].F0Ntrain(en, sp) dec = net['decoder'] F0 = dec.F0_conv(f0.unsqueeze(1)); N = dec.N_conv(n.unsqueeze(1)) x = dec.encode(torch.cat([asr, F0, N], 1), sa) asr_res = dec.asr_res(asr); res = True for block in dec.decode: if res: x = torch.cat([x, asr_res, F0, N], 1) x = block(x, sa) if block.upsample_type != 'none': res = False return f0, x NFFT, HOP = cfg['decoder']['gen_istft_n_fft'], cfg['decoder']['gen_istft_hop_size'] win = torch.from_numpy(get_window('hann', NFFT, fftbins=True).astype(np.float32)) K = NFFT // 2 + 1 n = torch.arange(NFFT, dtype=torch.float64); k = torch.arange(K, dtype=torch.float64) wk = torch.full((K,), 2.0, dtype=torch.float64); wk[0] = 1; wk[-1] = 1 ang = 2 * np.pi * k[:, None] * n[None, :] / NFFT basis_re = (wk[:, None] * torch.cos(ang) / NFFT * win.double()[None]).float() # [K, NFFT] basis_im = (-wk[:, None] * torch.sin(ang) / NFFT * win.double()[None]).float() ISTFT_W = torch.cat([basis_re, basis_im], 0).unsqueeze(1) # [2K, 1, NFFT] ENV_W = (win ** 2).view(1, 1, NFFT) def istft(spec, phase): # == torch.istft(center=True, hann) of spec * exp(i phase) z = torch.cat([spec * torch.cos(phase), spec * torch.sin(phase)], 1) y = F.conv_transpose1d(z, ISTFT_W, stride=HOP) env = F.conv_transpose1d(torch.ones_like(z[:, :1]), ENV_W, stride=HOP) y = y / env.clamp(min=1e-8) return y[:, :, NFFT // 2: -(NFFT // 2)] class Generator(nn.Module): def forward(self, x_pre, ref_s, har): g = net['decoder'].generator; s = ref_s[:, :128]; x = x_pre for i in range(g.num_upsamples): x = F.leaky_relu(x, negative_slope=0.1) x_source = g.noise_res[i](g.noise_convs[i](har), s) x = g.ups[i](x) if i == g.num_upsamples - 1: x = g.reflection_pad(x) x = x + x_source xs = None for j in range(g.num_kernels): y = g.resblocks[i * g.num_kernels + j](x, s); xs = y if xs is None else xs + y x = xs / g.num_kernels x = g.conv_post(F.leaky_relu(x)) spec = SPEC(x[:, :K, :]); phase = torch.sin(x[:, K:, :]) return istft(spec, phase)