# SPDX-License-Identifier: Apache-2.0 """Clean-room fp32 CPU reference of Kokoro-82M v1.0 (StyleTTS2 + iSTFTNet), batch 1, written from the graph in the port's architecture notes (no code of the ``kokoro`` package). It is the numerical contract of the device engines: every stage returns the tensors the device stages produce, under the same names as the goldens. Layout: channels-first ``[C, T]`` tensors (batch dim dropped). Noise is explicit (``reference/noise.py``), so the waveform is a pure function of (ids, style, speed, noise). """ from __future__ import annotations import math from dataclasses import dataclass from typing import Dict, Optional import torch import torch.nn.functional as F SR = 24000 HOP_FRAME = 600 # samples per predictor frame (40 Hz) N_FFT, HOP = 20, 5 UPSAMPLE = 300 # 80 Hz F0 curve -> 24 kHz HARMONICS = 9 SINE_AMP, NOISE_STD, VOICED_THRESHOLD = 0.1, 0.003, 10.0 RSQRT2 = float(torch.rsqrt(torch.tensor(2.0))) # the fp32 constant the model uses def _ln_channels(x, g, b, eps=1e-5): # x [C, T], LayerNorm over C return F.layer_norm(x.t(), (x.shape[0],), g, b, eps).t() def adain(x, gb, eps=1e-5): """AdaIN1d: gb = fc(style) [2C] (gamma first). InstanceNorm over time (biased var), affine = identity.""" C = x.shape[0] g, b = gb[:C, None], gb[C:, None] mu = x.mean(dim=1, keepdim=True) var = x.var(dim=1, unbiased=False, keepdim=True) return (1 + g) * ((x - mu) / torch.sqrt(var + eps)) + b def snake(x, alpha): # alpha [C] a = alpha[:, None] return x + (1 / a) * torch.sin(a * x) ** 2 def conv1d(x, w, b=None, stride=1, padding=0, dilation=1, groups=1): return F.conv1d(x[None], w, b, stride, padding, dilation, groups)[0] def conv_t1d(x, w, b=None, stride=1, padding=0, output_padding=0, groups=1): return F.conv_transpose1d(x[None], w, b, stride, padding, output_padding, groups)[0] def _lstm_module(P, prefix, din): m = torch.nn.LSTM(din, 256, 1, batch_first=True, bidirectional=True) sd = {k: P[f"{prefix}.{k}"] for k in m.state_dict()} m.load_state_dict(sd) return m.eval() def stft(x): """x [N] -> (magnitude [11, N/5 + 1], phase [11, N/5 + 1]); torch.stft, hann periodic, center reflect""" win = torch.hann_window(N_FFT, periodic=True, dtype=torch.float32) s = torch.stft(x[None], N_FFT, HOP, N_FFT, window=win, center=True, pad_mode="reflect", return_complex=True)[0] return s.abs(), s.angle() def istft(mag, phase): win = torch.hann_window(N_FFT, periodic=True, dtype=torch.float32) return torch.istft((mag * torch.exp(phase * 1j))[None], N_FFT, HOP, N_FFT, window=win)[0] @dataclass class Noise: """the random inputs of one chunk: ``rand_ini`` [9] (initial harmonic phases; provably unused, see ARCH 3.9), ``z`` [N, 9] standard normals (or ``z1`` [N]: one normal per sample, the folded form, ARCH 3.9)""" rand_ini: Optional[torch.Tensor] = None z: Optional[torch.Tensor] = None z1: Optional[torch.Tensor] = None class KokoroReference: def __init__(self, P: Dict[str, torch.Tensor], config: dict): self.P = P self.cfg = config self.vocab = config["vocab"] torch.set_grad_enabled(False) self.lstm = {name: _lstm_module(P, name, din) for name, din in [ ("predictor.text_encoder.lstms.0", 640), ("predictor.text_encoder.lstms.2", 640), ("predictor.text_encoder.lstms.4", 640), ("predictor.lstm", 640), ("predictor.shared", 640), ("text_encoder.lstm", 512)]} self.lin_w = P["decoder.generator.m_source.l_linear.weight"][0] # [9] self.lin_b = P["decoder.generator.m_source.l_linear.bias"][0] # ------------------------------------------------------------------ text side (T tokens incl. the 2 pads) def ids(self, phonemes: str): ids = [self.vocab[p] for p in phonemes if p in self.vocab] return torch.tensor([0, *ids, 0], dtype=torch.long) def albert(self, ids): P, p = self.P, "bert." T = ids.shape[0] x = P[p + "embeddings.word_embeddings.weight"][ids] + P[p + "embeddings.position_embeddings.weight"][:T] \ + P[p + "embeddings.token_type_embeddings.weight"][0] x = F.layer_norm(x, (128,), P[p + "embeddings.LayerNorm.weight"], P[p + "embeddings.LayerNorm.bias"], 1e-12) x = F.linear(x, P[p + "encoder.embedding_hidden_mapping_in.weight"], P[p + "encoder.embedding_hidden_mapping_in.bias"]) q = p + "encoder.albert_layer_groups.0.albert_layers.0." lin = lambda n, h: F.linear(h, P[q + n + ".weight"], P[q + n + ".bias"]) for _ in range(12): Q = lin("attention.query", x).view(T, 12, 64).transpose(0, 1) K = lin("attention.key", x).view(T, 12, 64).transpose(0, 1) V = lin("attention.value", x).view(T, 12, 64).transpose(0, 1) a = torch.softmax(Q @ K.transpose(1, 2) / 8.0, dim=-1) @ V a = lin("attention.dense", a.transpose(0, 1).reshape(T, 768)) a = F.layer_norm(x + a, (768,), P[q + "attention.LayerNorm.weight"], P[q + "attention.LayerNorm.bias"], 1e-12) h = F.gelu(lin("ffn", a), approximate="tanh") h = lin("ffn_output", h) x = F.layer_norm(h + a, (768,), P[q + "full_layer_layer_norm.weight"], P[q + "full_layer_layer_norm.bias"], 1e-12) return x # [T, 768] def bilstm(self, name, x): # x [T, Din] -> [T, 512] return self.lstm[name](x[None])[0][0] def duration_encoder(self, d_en, s): """d_en [512, T], s [128] -> d [T, 640] = [AdaLN(lstm) (512) | s (128)]""" P = self.P T = d_en.shape[1] sT = s[:, None].expand(128, T) x = torch.cat([d_en, sT], 0) # [640, T] for i in (0, 2, 4): h = self.bilstm(f"predictor.text_encoder.lstms.{i}", x.t()) # [T, 512] gb = F.linear(s, P[f"predictor.text_encoder.lstms.{i + 1}.fc.weight"], P[f"predictor.text_encoder.lstms.{i + 1}.fc.bias"]) h = F.layer_norm(h, (512,), eps=1e-5) h = (1 + gb[:512]) * h + gb[512:] x = torch.cat([h.t(), sT], 0) return x.t() def durations(self, d, speed): P = self.P x = self.bilstm("predictor.lstm", d) logits = F.linear(x, P["predictor.duration_proj.linear_layer.weight"], P["predictor.duration_proj.linear_layer.bias"]) dur = torch.sigmoid(logits).sum(-1) / speed return dur, torch.round(dur).clamp(min=1).long(), x, logits def text_encoder(self, ids): P, p = self.P, "text_encoder." x = P[p + "embedding.weight"][ids].t() # [512, T] for i in range(3): x = conv1d(x, P[p + f"cnn.{i}.0.weight"], P[p + f"cnn.{i}.0.bias"], padding=2) x = _ln_channels(x, P[p + f"cnn.{i}.1.gamma"], P[p + f"cnn.{i}.1.beta"]) x = F.leaky_relu(x, 0.2) return self.bilstm("text_encoder.lstm", x.t()).t() # [512, T] # ------------------------------------------------------------------ frame side (L frames at 40 Hz) @staticmethod def alignment(pred_dur): T = pred_dur.shape[0] idx = torch.repeat_interleave(torch.arange(T), pred_dur) aln = torch.zeros(T, idx.shape[0]) aln[idx, torch.arange(idx.shape[0])] = 1 return aln, idx def adain_resblk(self, name, x, s, upsample=False): """AdainResBlk1d (StyleTTS2): (residual + shortcut) / sqrt(2); lrelu 0.2; optional x2 upsample""" P = self.P w = lambda n: P.get(f"{name}.{n}") cin = x.shape[0] fc = lambda n: F.linear(s, w(f"{n}.fc.weight"), w(f"{n}.fc.bias")) h = F.leaky_relu(adain(x, fc("norm1")), 0.2) if upsample: h = conv_t1d(h, w("pool.weight"), w("pool.bias"), stride=2, padding=1, output_padding=1, groups=cin) h = conv1d(h, w("conv1.weight"), w("conv1.bias"), padding=1) h = F.leaky_relu(adain(h, fc("norm2")), 0.2) h = conv1d(h, w("conv2.weight"), w("conv2.bias"), padding=1) sc = F.interpolate(x[None], scale_factor=2, mode="nearest")[0] if upsample else x if w("conv1x1.weight") is not None: sc = conv1d(sc, w("conv1x1.weight")) return (h + sc) * RSQRT2 def prosody(self, en, s): """en [640, L] -> F0 [2L], N [2L] (+ the shared-LSTM output)""" P = self.P xs = self.bilstm("predictor.shared", en.t()).t() # [512, L] out = {"shared": xs.t()} for br in ("F0", "N"): h = xs for i in range(3): h = self.adain_resblk(f"predictor.{br}.{i}", h, s, upsample=(i == 1)) out[br] = conv1d(h, P[f"predictor.{br}_proj.weight"], P[f"predictor.{br}_proj.bias"])[0] return out def decoder(self, asr, F0, N, s): """asr [512, L], F0 / N [2L] -> generator input [512, 2L]""" P, p = self.P, "decoder." F0c = conv1d(F0[None], P[p + "F0_conv.weight"], P[p + "F0_conv.bias"], stride=2, padding=1) Nc = conv1d(N[None], P[p + "N_conv.weight"], P[p + "N_conv.bias"], stride=2, padding=1) x = self.adain_resblk(p + "encode", torch.cat([asr, F0c, Nc], 0), s) asr_res = conv1d(asr, P[p + "asr_res.0.weight"], P[p + "asr_res.0.bias"]) for i in range(4): x = torch.cat([x, asr_res, F0c, Nc], 0) x = self.adain_resblk(p + f"decode.{i}", x, s, upsample=(i == 3)) return x # ------------------------------------------------------------------ harmonic-plus-noise source def source(self, F0, noise: Noise): """F0 [2L] (80 Hz) -> har_source [N = 600 L]: hn-NSF with 9 harmonics (official op order, fp32)""" f0 = F.interpolate(F0[None, None], scale_factor=UPSAMPLE, mode="nearest")[0].t()[None] # [1, N, 1] fn = f0 * torch.arange(1, HARMONICS + 1, dtype=torch.float32)[None, None] rad = (fn / SR) % 1 if noise.rand_ini is not None: ri = noise.rand_ini.clone() ri[0] = 0 rad[:, 0, :] = rad[:, 0, :] + ri rad = F.interpolate(rad.transpose(1, 2), scale_factor=1 / UPSAMPLE, mode="linear").transpose(1, 2) phase = torch.cumsum(rad, dim=1) * 2 * torch.pi phase = F.interpolate(phase.transpose(1, 2) * UPSAMPLE, scale_factor=UPSAMPLE, mode="linear").transpose(1, 2) sines = torch.sin(phase) * SINE_AMP uv = (f0 > VOICED_THRESHOLD).float() amp = uv * NOISE_STD + (1 - uv) * SINE_AMP / 3 if noise.z is not None: sw = sines * uv + amp * noise.z[None] har = torch.tanh(sw @ self.lin_w + self.lin_b) else: # folded: sum_h w_h * amp * z_h == amp * ||w|| * z1 in distribution har = torch.tanh((sines * uv) @ self.lin_w + amp[..., 0] * self.lin_w.norm() * noise.z1[None] + self.lin_b) return har[0] # ------------------------------------------------------------------ iSTFTNet generator def resblock1(self, name, x, s, k): P = self.P for j, d in enumerate((1, 3, 5)): fc1 = F.linear(s, P[f"{name}.adain1.{j}.fc.weight"], P[f"{name}.adain1.{j}.fc.bias"]) fc2 = F.linear(s, P[f"{name}.adain2.{j}.fc.weight"], P[f"{name}.adain2.{j}.fc.bias"]) xt = snake(adain(x, fc1), P[f"{name}.alpha1.{j}"].view(-1)) xt = conv1d(xt, P[f"{name}.convs1.{j}.weight"], P[f"{name}.convs1.{j}.bias"], padding=d * (k - 1) // 2, dilation=d) xt = snake(adain(xt, fc2), P[f"{name}.alpha2.{j}"].view(-1)) xt = conv1d(xt, P[f"{name}.convs2.{j}.weight"], P[f"{name}.convs2.{j}.bias"], padding=(k - 1) // 2) x = xt + x return x def generator(self, x, s, har, cap=None): P, p = self.P, "decoder.generator." ks = (3, 7, 11) for i, (u, kk) in enumerate(((10, 20), (6, 12))): x = F.leaky_relu(x, 0.1) if i == 0: xs = conv1d(har, P[p + "noise_convs.0.weight"], P[p + "noise_convs.0.bias"], stride=6, padding=3) xs = self.resblock1(p + "noise_res.0", xs, s, 7) else: xs = conv1d(har, P[p + "noise_convs.1.weight"], P[p + "noise_convs.1.bias"]) xs = self.resblock1(p + "noise_res.1", xs, s, 11) x = conv_t1d(x, P[p + f"ups.{i}.weight"], P[p + f"ups.{i}.bias"], stride=u, padding=(kk - u) // 2) if i == 1: x = F.pad(x[None], (1, 0), mode="reflect")[0] x = x + xs acc = None for j in range(3): r = self.resblock1(p + f"resblocks.{i * 3 + j}", x, s, ks[j]) acc = r if acc is None else acc + r x = acc / 3 if cap is not None: cap[f"gen_x{i}"], cap[f"gen_src{i}"] = x, xs x = F.leaky_relu(x, 0.01) x = conv1d(x, P[p + "conv_post.weight"], P[p + "conv_post.bias"], padding=3) if cap is not None: cap["gen_post"] = x return istft(torch.exp(x[:11]), torch.sin(x[11:])) # ------------------------------------------------------------------ whole chunk def forward(self, ids, ref_s, speed=1.0, noise_fn=None, forced_dur=None, cap: Optional[dict] = None): """ids [T] (with pads), ref_s [256] -> audio [600 L]. ``noise_fn(nsamp) -> Noise``.""" cap = {} if cap is None else cap s_pro, s_dec = ref_s[128:], ref_s[:128] bert = self.albert(ids) d_en = F.linear(bert, self.P["bert_encoder.weight"], self.P["bert_encoder.bias"]).t() d = self.duration_encoder(d_en, s_pro) dur, pred_dur, x, logits = self.durations(d, speed) cap.update(bert_dur=bert, d_en=d_en, d=d, dur_lstm=x, dur_logits=logits, duration=dur, pred_dur_model=pred_dur) if forced_dur is not None: pred_dur = forced_dur.long() cap["pred_dur"] = pred_dur aln, _ = self.alignment(pred_dur) en = d.t() @ aln pr = self.prosody(en, s_pro) t_en = self.text_encoder(ids) asr = t_en @ aln xg = self.decoder(asr, pr["F0"], pr["N"], s_dec) nsamp = HOP_FRAME * int(pred_dur.sum()) noise = noise_fn(nsamp) if noise_fn is not None else Noise(z1=torch.zeros(nsamp)) har_source = self.source(pr["F0"], noise) mag, ph = stft(har_source) har = torch.cat([mag, ph], 0) audio = self.generator(xg, s_dec, har, cap) cap.update(en=en, shared=pr["shared"], F0_pred=pr["F0"], N_pred=pr["N"], t_en=t_en, asr=asr, dec_blk3=xg, har_source=har_source, har=har, audio=audio) return audio, pred_dur