An 8M-parameter English text-to-speech model distilled from Kokoro-82M. 9 MB, runs 18x real time on one CPU thread.
Paradee 1.1: frame-rate decoder head, v1.1 numbers, arXiv link
Sahil Mahendrakar606e16e12f53
diff --git a/README.md b/README.mdindex 3dd0432..5f50e9e 100644--- a/README.md+++ b/README.md@@ -1,18 +1,20 @@# Paradee-Paradee is a small English text-to-speech model. It has 8.07M parameters and is distilled from+Paradee is a small English text-to-speech model. It has 7.88M parameters and is distilled from[Kokoro-82M](https://huggingface.co/hexgrad/Kokoro-82M), and it speaks one voice, Kokoro's `af_heart`.-- **Small.** The int8 model is one 9 MB ONNX file, against 325 MB for Kokoro.-- **Fast.** It runs about 18x faster than real time on one CPU thread, with no GPU.-- **Close to its teacher.** It scores 4.41 on UTMOS (Kokoro: 4.52) and has the same word error rate (5.7%).+- **Small.** The int8 model is one 8.5 MB ONNX file, against 325 MB for Kokoro.+- **Fast.** It runs about 62x faster than real time on one CPU thread, with no GPU.+- **Close to its teacher.** It scores 4.39 on UTMOS (Kokoro: 4.52) and its word error rate is within a few tenths of a point of Kokoro's.++**New in 1.1:** a new decoder head that makes the model more than 3x faster and leaves less buzz in voiced sounds. See [What changed in 1.1](#what-changed-in-11).Paradee also runs inside the browser. It is the light voice in the[Chickadee](https://github.com/sahilmahendrakar/chickadee) Chrome extension, where it needs no WebGPU and no download.-**Paper:** [Paradee: Distilling Kokoro-82M into an 8M-Parameter Single-Voice Text-to-Speech Model](paper/Paradee-Mahendrakar-2026.pdf)+**Paper:** [Paradee: Distilling Kokoro-82M into an 8M-Parameter Single-Voice Text-to-Speech Model](paper/Paradee-Mahendrakar-2026.pdf) ([arXiv:2610.06817](https://arxiv.org/abs/2610.06817))-**Model files and audio samples:** [huggingface.co/sahilmahendrakar/Paradee-8M-v1.0](https://huggingface.co/sahilmahendrakar/Paradee-8M-v1.0)+**Model files and audio samples:** [huggingface.co/sahilmahendrakar/Paradee-8M-v1.1](https://huggingface.co/sahilmahendrakar/Paradee-8M-v1.1) (the earlier release is at [Paradee-8M-v1.0](https://huggingface.co/sahilmahendrakar/Paradee-8M-v1.0))## Quick start@@ -27,24 +29,50 @@ From Python:from paradee import Paradee, SAMPLE_RATEimport soundfile as sf-tts = Paradee() # downloads the 9 MB model from the Hugging Face Hub the first time+tts = Paradee() # downloads the 8.5 MB model from the Hugging Face Hub the first timeaudio = tts("Paradee is a small voice that runs anywhere.")sf.write("hello.wav", audio, SAMPLE_RATE)```Text is turned into phonemes with [misaki](https://github.com/hexgrad/misaki), Kokoro's owngrapheme-to-phoneme library, which is what the training data used. The first run also downloads-misaki's English dictionary data.+misaki's English dictionary data. `Paradee(version="1.0")` loads the earlier release.++## What changed in 1.1++Version 1.0 used Kokoro's own audio generator at a smaller width, followed by a filter that fixed+the phase of voiced sound. Version 1.1 replaces both with a new head. The rest of the model (the+text side and the first part of the decoder) is the same.++The new head works at 80 frames a second and never upsamples, which is where the speed comes from.+For voiced sound it builds clean sine waves at the pitch and its multiples, then predicts a smooth+gain and a small phase correction for them. For everything else it shapes real noise, including+noise that pulses in time with the pitch, which is what Kokoro's upper frequencies mostly are.+Because the sine waves are generated from the pitch, their timing is right by construction, and+the separate phase filter is no longer needed.++Both ONNX files, on the same 200 held-out sentences and one CPU thread of an Apple M4 Pro:++| Release | Params | int8 file | Speed | UTMOS | WER |+|---|---:|---:|---:|---:|---:|+| Paradee 1.0 | 8.07M | 9.0 MB | 18x | 4.41 | 5.9% |+| **Paradee 1.1** | **7.88M** | **8.5 MB** | **62x** | **4.39** | **5.9%** |++UTMOS does not measure the buzz. By ear, 1.1 is the cleaner of the two. One measure that does+track it is how much energy sits on the multiples of the pitch compared with halfway between them,+between 2 and 4 kHz. Kokoro measures 3.1 dB, version 1.0 measures 1.3 dB and version 1.1 measures 3.9 dB.++The paper describes version 1.0.## How it compares-All numbers are on the same 200 held-out sentences, from the paper. Speed is on one CPU thread of+All numbers are on the same 200 held-out sentences, from the paper, which describes version 1.0. Speed is on one CPU thread ofan Apple M4 Pro.| Model (voice) | Params | File size | Speed | UTMOS | WER ||---|---:|---:|---:|---:|---:|| Kokoro-82M, teacher (af_heart) | 81.8M | 325 MB | 7.6x | 4.52 | 5.7% |-| **Paradee (af_heart)** | **8.07M** | **8.45 MB** | **25.0x** | **4.41** | **5.7%** |+| **Paradee 1.0 (af_heart)** | **8.07M** | **8.45 MB** | **25.0x** | **4.41** | **5.7%** || Kokoro-7M-Distill (af_msa) | 7.48M | 30.1 MB | 35.5x | 4.18 | 7.4% || Piper, en_US-lessac-medium | 15.7M | 63.2 MB | 15.4x | 4.36 | 8.8% || KittenTTS nano 0.8 (Bella) | 14.0M | 56.8 MB | 10.7x | 4.01 | 5.5% |@@ -52,28 +80,29 @@ an Apple M4 Pro.UTMOS is a neural network trained on human ratings. It predicts how natural a clip sounds, on ascale from 1 to 5. WER is the share of words that Whisper (base) transcribes wrongly.-The paper's speed is for PyTorch. The released ONNX file (int8, with the phase filter included)-runs at about 18x real time in onnxruntime on one thread. Checked on the same 200 sentences, it-scores UTMOS 4.41 and WER 6.0% (this WER script normalizes text slightly differently from the paper's).+The paper's speed is for PyTorch. The numbers for the released ONNX files are in the table under+[What changed in 1.1](#what-changed-in-11).## How it worksKokoro has two halves. A text side reads phonemes and predicts how long each one lasts, the pitchand loudness over time, and a feature vector for each phoneme. A decoder turns those into audio.-Paradee is Kokoro's own code at smaller widths, trained half by half against the frozen teacher.+Paradee is mostly Kokoro's own code at smaller widths, trained half by half against the frozen teacher.1. **Corpus.** Kokoro reads 12,000 WikiText-103 sentences (23.9 hours of audio), and everyintermediate value is saved.2. **Text side (4.23M parameters).** It learns to predict the teacher's durations, pitch, loudnessand phoneme features directly.-3. **Decoder (3.85M parameters).** It learns to turn the teacher's saved values into the teacher's- audio, first with spectrogram losses and then with adversarial training.+3. **Decoder (3.65M parameters).** It learns to turn the teacher's saved values into the teacher's+ audio, first with spectrogram losses and then with adversarial training. In 1.1 its last part is+ the new head described above, trained the same way with two extra losses that match how tonal+ and how pulsing the teacher's upper frequencies are.4. **Assembly.** The two halves are joined with no further training, and the weights are storedin int8.-A filter with no parameters then corrects the phase of voiced sound between 2 and 8 kHz (phase is-the timing of each frequency's wave). This removes a slight buzz that the small decoder otherwise-leaves. The ONNX file includes this filter.+Version 1.0 also needed a filter with no parameters that corrected the phase of voiced sound+between 2 and 8 kHz (phase is the timing of each frequency's wave), to remove a slight buzz. In+1.1 the new head does not have that problem and the filter is gone.The code for every step is in [`training/`](training/). It runs on one laptop.diff --git a/paradee/__init__.py b/paradee/__init__.pyindex a12f404..676ccd7 100644--- a/paradee/__init__.py+++ b/paradee/__init__.py@@ -2,4 +2,4 @@from .tts import Paradee, SAMPLE_RATE__all__ = ["Paradee", "SAMPLE_RATE"]-__version__ = "1.0.0"+__version__ = "1.1.0"diff --git a/paradee/__main__.py b/paradee/__main__.pyindex b4942b6..fa0bb6c 100644--- a/paradee/__main__.py+++ b/paradee/__main__.py@@ -10,9 +10,10 @@ def main():ap.add_argument("-o", "--out", default="paradee.wav")ap.add_argument("--speed", type=float, default=1.0)ap.add_argument("--fp32", action="store_true", help="use the fp32 model instead of int8")+ ap.add_argument("--model-version", default="1.1", choices=["1.1", "1.0"])a = ap.parse_args()text = a.text if a.text is not None else sys.stdin.read()- audio = Paradee(quantized=not a.fp32)(text, speed=a.speed)+ audio = Paradee(version=a.model_version, quantized=not a.fp32)(text, speed=a.speed)pcm = (np.clip(audio, -1, 1) * 32767).astype("<i2")with wave.open(a.out, "wb") as w:w.setnchannels(1); w.setsampwidth(2); w.setframerate(SAMPLE_RATE); w.writeframes(pcm.tobytes())diff --git a/paradee/tts.py b/paradee/tts.pyindex dfb7d7d..64c6f4f 100644--- a/paradee/tts.py+++ b/paradee/tts.py@@ -4,8 +4,7 @@ import numpy as npimport onnxruntime as ortfrom huggingface_hub import hf_hub_download-REPO = "sahilmahendrakar/Paradee-8M-v1.0"-REVISION = "v1.0"+REPOS = {"1.1": "sahilmahendrakar/Paradee-8M-v1.1", "1.0": "sahilmahendrakar/Paradee-8M-v1.0"}SAMPLE_RATE = 24000MAX_PHONEMES = 510 # the text side has 512 positions, two of which are the pad tokens at each end@@ -13,15 +12,17 @@ MAX_PHONEMES = 510 # the text side has 512 positions, two of which are the padclass Paradee:"""Load once, then call with text to get a float32 waveform at 24 kHz.- quantized: use the 9 MB int8 file (default) instead of the 37 MB fp32 one. They sound the same.+ version: "1.1" (default) or "1.0", the earlier release with the slower decoder.+ quantized: use the 8.5 MB int8 file (default) instead of the 35 MB fp32 one. They sound the same.model_path / config_path: local files instead of downloading from the Hugging Face Hub.- threads: CPU threads for onnxruntime. One thread already runs about 20x faster than real time.+ threads: CPU threads for onnxruntime. One thread already runs about 60x faster than real time."""- def __init__(self, quantized=True, model_path=None, config_path=None, threads=1):+ def __init__(self, version="1.1", quantized=True, model_path=None, config_path=None, threads=1):+ repo, revision = REPOS[version], f"v{version}"name = "onnx/paradee_int8.onnx" if quantized else "onnx/paradee.onnx"- model_path = model_path or hf_hub_download(REPO, name, revision=REVISION)- config_path = config_path or hf_hub_download(REPO, "config.json", revision=REVISION)+ model_path = model_path or hf_hub_download(repo, name, revision=revision)+ config_path = config_path or hf_hub_download(repo, "config.json", revision=revision)self.vocab = json.load(open(config_path, encoding="utf-8"))["vocab"]so = ort.SessionOptions()so.intra_op_num_threads = threadsdiff --git a/pyproject.toml b/pyproject.tomlindex 7a49535..ebf8a92 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,6 +1,6 @@[project]name = "paradee"-version = "1.0.0"+version = "1.1.0"description = "An 8M-parameter English text-to-speech model distilled from Kokoro-82M"readme = "README.md"license = "Apache-2.0"@@ -22,7 +22,7 @@ dependencies = [paradee = "paradee.__main__:main"[project.urls]-"Model" = "https://huggingface.co/sahilmahendrakar/Paradee-8M-v1.0"+"Model" = "https://huggingface.co/sahilmahendrakar/Paradee-8M-v1.1"[build-system]requires = ["hatchling"]diff --git a/training/README.md b/training/README.mdindex 57981f1..74e20fd 100644--- a/training/README.md+++ b/training/README.md@@ -1,6 +1,7 @@# Training Paradee-This folder has the code that produced Paradee v1.0. Every run fits on one laptop: the original ran+This folder has the code that produced Paradee v1.0 and v1.1. Steps 1 to 4 are v1.0, and step 5+adds the v1.1 head on top of them. Every run fits on one laptop: the original ranon a MacBook Pro with an Apple M4 Pro and 24 GB of memory, using PyTorch's MPS backend. Run everycommand from this folder. The environment is managed with [uv](https://docs.astral.sh/uv/):@@ -64,6 +65,37 @@ Kokoro ships an ONNX-friendly STFT (`kokoro.custom_stft.CustomSTFT`). It does no`torch.stft`, which the decoder was trained with, and it costs about 0.5 UTMOS. The export usesits own exact version (`ConvSTFT`) instead.+## 5. The v1.1 head++Version 1.1 keeps the text side and the first part of decoder A, and replaces the audio generator+and the phase filter with a head that works at 80 frames a second (`scripts/vhead.py`, head `v2`).+The trainer starts from the stage-two decoder of step 3.++```bash+X=(--head v2 --fine-stft --harm-weight 2 --mod-weight 5 --shards 999 --utmos)+# stage one: spectrogram losses plus the two statistic losses, all 24 shards+uv run python scripts/train_vhead.py $X --steps 40000 --eval-every 10000 --tag 2_full+# stage two: adversarial training, spectrogram losses weighted 3x, batch size 8+uv run python scripts/train_vhead.py $X --gan --mel-weight 3 --bs 8 --init-from checkpoints/vh2_full/last.pt --steps 15000 --tag 2_fullgan+# one ONNX graph, fp32 and int8+uv run python scripts/export_paradee_v1_1.py checkpoints/vh2_fullgan/last.pt+```++`--harm-weight` matches how much of the teacher's energy sits on multiples of the pitch, per band.+`--mod-weight` matches how the loudness of the upper bands pulses with the pitch. Spectrogram+losses alone leave the upper harmonics too clean, which sounds buzzy.++The released head did not start stage one from scratch. It was first developed on 8 shards, and+those runs were carried over: 20,000 steps with spectrogram losses, about 13,000 more as the two+statistic losses were added, and 8,000 after the short-window noise path was added. The 40,000+steps on all the data and the 15,000 adversarial steps then followed as above. Starting stage one+from scratch with the commands above has not been tested end to end.++```bash+uv run python scripts/vh_ab.py checkpoints/vh2_fullgan/last.pt 200 --wer # v1.0 against the new head, PyTorch+uv run python scripts/onnx_eval.py 200 v1.1=models/paradee_v1.1/paradee_int8.onnx # a released-style ONNX file+```+## Evaluation```bash@@ -81,4 +113,5 @@ uv run python scripts/wer.py out/some_dir # Whisper (base) WER agai| `student.py` | The text-side student: Kokoro's text modules at smaller widths, with a learned constant voice || `student_decoder.py` | The decoder student: Kokoro's decoder at configurable widths (preset `A` is Paradee) || `discriminators.py` | The multi-period and multi-resolution discriminators used in stage two |+| `vhead.py` | The v1.1 head and the decoder that uses it || `quantize_student.py` | Weight-only int8 in PyTorch, with its effect on quality |diff --git a/training/scripts/export_paradee_v1_1.py b/training/scripts/export_paradee_v1_1.pynew file mode 100644index 0000000..8e52828--- /dev/null+++ b/training/scripts/export_paradee_v1_1.py@@ -0,0 +1,161 @@+"""Export the Paradee pipeline with the frame-rate head (vhead.py, head v2) as ONE ONNX graph for the browser:+input_ids [1,T] int64, speed [1] float -> waveform [1,S] float at 24 kHz. Same interface as export_paradee.py; no+phase filter. The head is rewritten without complex numbers (conv1d DFT bases), checked against the torch head on the+same noise, then written as fp32 and as the small copy (int8 weights, fp16 vectors, DFT bases generated at load time).+usage: export_paradee_v1_1.py DEC_CKPT [--text checkpoints/text_s+mlp/last.pt] [--out models/paradee_v1.1]"""+import sys, glob, os, time, argparse, warnings, torch, numpy as np, torch.nn as nn, torch.nn.functional as F+warnings.filterwarnings("ignore"); sys.path.insert(0, "scripts")+from student import TextStudent, alignment+from vhead import VDecoder, SR, FHOP+from torch.nn.utils import remove_weight_norm+from torch.nn.utils.parametrize import is_parametrized, remove_parametrizations+ap = argparse.ArgumentParser(); ap.add_argument("dec"); ap.add_argument("--text", default="checkpoints/text_s+mlp/last.pt"); ap.add_argument("--out", default="models/paradee_v1.1")+A = ap.parse_args(); os.makedirs(A.out, exist_ok=True)++def strip(m):+ for x in m.modules():+ try: remove_weight_norm(x)+ except Exception: pass+ if is_parametrized(x, "weight"):+ try: remove_parametrizations(x, "weight", leave_parametrized=True)+ except Exception: pass++class ConvSTFT(nn.Module):+ """torch.stft / torch.istft (hann, centre, reflect) as conv1d / conv_transpose1d with real and imaginary parts kept apart."""+ def __init__(self, n, hop):+ super().__init__(); self.n, self.hop, self.K = n, hop, n // 2 + 1; w = torch.hann_window(n, dtype=torch.float64); k = torch.arange(self.K, dtype=torch.float64)[:, None]+ ang = 2 * torch.pi * ((k * torch.arange(n, dtype=torch.float64)) % n) / n; c = torch.full((self.K, 1), 2.0, dtype=torch.float64); c[0] = c[-1] = 1+ self.register_buffer("fwd", (torch.cat([torch.cos(ang), -torch.sin(ang)]) * w).float()[:, None])+ self.register_buffer("inv", (torch.cat([torch.cos(ang) * c, -torch.sin(ang) * c]) / n * w).float()[:, None]); self.register_buffer("w2", (w ** 2).float()[None, None])+ def transform(self, x): # [B,S] -> re, im [B,K,frames]+ y = F.conv1d(F.pad(x[:, None], (self.n // 2, self.n // 2), mode="reflect"), self.fwd, stride=self.hop); return y[:, :self.K], y[:, self.K:]+ def inverse(self, re, im):+ y = F.conv_transpose1d(torch.cat([re, im], 1), self.inv, stride=self.hop)[:, 0]+ env = F.conv_transpose1d(torch.ones_like(re[:1, :1]), self.w2, stride=self.hop)[:, 0]+ return (y / env.clamp_min(1e-8))[:, self.n // 2: -(self.n // 2)]++class HeadX(nn.Module):+ """SourceFilterHead2.forward without complex ops, float64 on-device tricks or repeat_interleave."""+ def __init__(self, h):+ super().__init__(); self.h = h; self.st = ConvSTFT(h.n_fft, h.hop); self.sb = ConvSTFT(150, 75)+ self.register_buffer("k", torch.arange(1, h.K + 1).float()[None, :, None]); self.register_buffer("fr", torch.linspace(0, SR / 2, h.nb)[None, :, None])+ def forward(self, x, f0, noise=None):+ h = self.h; n = x.shape[2]; T = n * h.up; S = n * FHOP+ z = h.norm0(h.inp(x).transpose(1, 2)).transpose(1, 2)+ for b in h.blocks: z = b(z)+ hn = h.norm1(z.transpose(1, 2)); o = h.out(hn).view(1, T, h.C * h.G + 1); o = torch.cat([o, o[:, -1:]], 1)+ g = (o[..., :-1].reshape(1, T + 1, h.C, h.G) @ h.M.T).permute(0, 2, 3, 1)+ gh, gn = torch.exp(g[:, 0].clamp(max=6)), torch.exp(g[:, 3].clamp(max=6)); um = torch.sqrt(g[:, 1] ** 2 + g[:, 2] ** 2).clamp_min(1e-4); ur, ui = g[:, 1] / um, g[:, 2] / um+ # sine bank (vhead.sine_bank): running phase in float64 at frame rate, wrapped, then interpolated between frame centres+ r = f0.double() * FHOP / SR; c = torch.cumsum(r, 1); c = (c - torch.floor(c)).float(); d = torch.cat([r[:, 1:], torch.zeros_like(r[:, :1])], 1).float()+ t = torch.arange(S, device=x.device); p = (t.float() + 0.5) / FHOP - 0.5; i = torch.clamp(torch.floor(p), min=0).long(); i = torch.minimum(i, (n - 1) * torch.ones_like(i)); frac = torch.clamp(p - i.float(), 0, 1)+ cyc = c[:, i] + frac * d[:, i]; f0s = f0[:, t // FHOP]; uv = (f0s > 10).float()+ amp = ((f0s[:, None] * self.k < 11000).float() * uv[:, None])+ e = (torch.sin(2 * torch.pi * self.k * cyc[:, None]) * amp).sum(1) * 0.1+ nz = torch.randn_like(e) if noise is None else noise+ Er, Ei = self.st.transform(e); Nr, Ni = self.st.transform(nz); j = 0+ for m in range(1, h.mod + 1):+ for fn in (torch.cos, torch.sin):+ a = g[:, 4 + j]; mr, mi = self.st.transform(nz * uv * fn(2 * torch.pi * m * cyc)); Nr = Nr + a * mr; Ni = Ni + a * mi; j += 1+ f0f = torch.cat([f0[:, torch.arange(T, device=x.device) // h.up], f0[:, -1:]], 1).clamp_min(60); ang = 2 * torch.pi * (self.fr / f0f[:, None]) * (0.5 * torch.tanh(o[..., -1])[:, None])+ Hr = gh * (ur * torch.cos(ang) - ui * torch.sin(ang)); Hi = gh * (ur * torch.sin(ang) + ui * torch.cos(ang))+ y = self.st.inverse(Er * Hr - Ei * Hi + Nr * gn, Er * Hi + Ei * Hr + Ni * gn)+ if h.burst:+ gb = torch.exp((h.out_b(hn).view(1, n * 4, h.Gb) @ h.Mb.T).clamp(max=6)).transpose(1, 2); gb = torch.cat([gb, gb[..., -1:]], -1)+ br, bi = self.sb.transform(nz.flip(-1)); y = y + self.sb.inverse(br * gb, bi * gb)+ return y++class Paradee2(nn.Module):+ def __init__(self, ts, vd): super().__init__(); self.ts, self.vd, self.head = ts, vd, HeadX(vd.head)+ def text(self, ids):+ t = self.ts; p = t.predictor; s = t.style+ d_en = t.bert_encoder(t.bert(ids, attention_mask=torch.ones_like(ids))).transpose(-1, -2)+ x = d_en; T = ids.shape[1]; sx = s[:, :, None].expand(-1, -1, T); x = torch.cat([x, sx], 1)+ for b in p.text_encoder.lstms:+ if isinstance(b, nn.LSTM): x = b(x.transpose(-1, -2))[0].transpose(-1, -2)+ else: x = torch.cat([b(x.transpose(-1, -2), s).transpose(-1, -2), sx], 1)+ d = x.transpose(-1, -2); dur = torch.sigmoid(p.duration_proj(p.lstm(d)[0])).sum(-1)[0]+ e = t.text_encoder; h = e.embedding(ids).transpose(1, 2)+ for c in e.cnn: h = c(h)+ return d, dur, t.asr_proj(e.lstm(h.transpose(1, 2))[0]).transpose(-1, -2)+ def trunk(self, asr, F0_curve, N):+ v = self.vd; s = v.style; F0 = v.F0_conv(F0_curve.unsqueeze(1)); Nn = v.N_conv(N.unsqueeze(1))+ x = v.encode(torch.cat([asr, F0, Nn], 1), s); asr_res = v.asr_res(asr); res = True+ for block in v.decode:+ if res: x = torch.cat([x, asr_res, F0, Nn], 1)+ x = block(x, s)+ if block.upsample_type != "none": res = False+ return x+ def forward(self, input_ids, speed):+ d, dur, asr_tok = self.text(input_ids)+ n = torch.clamp(torch.round(dur / speed), min=1).long()+ end = torch.cumsum(n, 0); start = end - n; f = torch.arange(end[-1])[None]+ aln = ((f >= start[:, None]) & (f < end[:, None])).float()[None]+ F0, N = self.ts.predictor.F0Ntrain(d.transpose(-1, -2) @ aln, self.ts.style)+ return self.head(self.trunk(asr_tok @ aln, F0, N), F0)++ts = TextStudent("s+mlp").eval(); ts.load_state_dict(torch.load(A.text, map_location="cpu")["model"])+vd = VDecoder(head="v2").eval(); vd.load_ckpt(A.dec); strip(ts); strip(vd); m = Paradee2(ts, vd).eval()+held = torch.load(sorted(glob.glob("data/teacher/shard_*.pt"))[0])[:4]++# 1. the rewritten head matches the torch head on the same inputs and noise+with torch.no_grad():+ r = held[0]; aln = alignment(r["pred_dur"]); Fr = aln.shape[1]; asr = (r["t_en"].float() @ aln)[None]; F0 = r["F0"][None, :2 * Fr]; N = r["N"][None, :2 * Fr]+ nz = torch.randn(1, 2 * Fr * FHOP); ref = vd(asr, F0, N, noise=nz); mine = m.head(m.trunk(asr, F0, N), F0, noise=nz)+print(f"head check: max |export - torch| = {(mine - ref).abs().max():.2e} (signal peak {ref.abs().max():.2f})")++# 2. export+path = f"{A.out}/paradee.onnx"; ids = held[1]["ids"][None]+torch.onnx.export(m, (ids, torch.ones(1)), path, input_names=["input_ids", "speed"], output_names=["waveform"],+ dynamic_axes={"input_ids": {1: "tokens"}, "waveform": {1: "samples"}}, opset_version=17, dynamo=False)+print(f"exported {path}: {os.path.getsize(path)/1e6:.1f} MB")++# 3. small copy: weight matrices int8 per output channel, other float vectors fp16, DFT bases generated from a few ops+import onnx+from onnx import numpy_helper, helper, TensorProto+g = onnx.load(path); nq = nh = nb = 0; new_nodes = []+def basis(n, inverse):+ w = torch.hann_window(n, dtype=torch.float64); k = torch.arange(n // 2 + 1, dtype=torch.float64)[:, None]; ang = 2 * torch.pi * ((k * torch.arange(n, dtype=torch.float64)) % n) / n+ c = torch.full((n // 2 + 1, 1), 2.0, dtype=torch.float64); c[0] = c[-1] = 1+ return ((torch.cat([torch.cos(ang) * c, -torch.sin(ang) * c]) / n * w) if inverse else (torch.cat([torch.cos(ang), -torch.sin(ang)]) * w)).float()[:, None].numpy()+def basis_nodes(name, n, inverse):+ """[2K,1,n] = cat(cos, -sin)(2 pi k t / n) * per-row scale * hann(t), with k*t reduced mod n in int64 so fp32 cos stays exact"""+ p = name + "_gen_"; K = n // 2 + 1; row = np.ones((2 * K, 1), np.float32)+ if inverse: row[:] = 2 / n; row[[0, K - 1, K, 2 * K - 1]] = 1 / n+ g.graph.initializer.extend([numpy_helper.from_array(np.arange(K, dtype=np.int64)[:, None], p + "k"), numpy_helper.from_array(np.arange(n, dtype=np.int64)[None], p + "n"),+ numpy_helper.from_array(np.array(n, np.int64), p + "N"), numpy_helper.from_array(np.array(2 * np.pi / n, np.float32), p + "c"),+ numpy_helper.from_array(torch.hann_window(n).numpy()[None], p + "w"), numpy_helper.from_array(row, p + "row"), numpy_helper.from_array(np.array([1], np.int64), p + "ax")])+ return [helper.make_node("Mul", [p + "k", p + "n"], [p + "kn"]), helper.make_node("Mod", [p + "kn", p + "N"], [p + "m"]),+ helper.make_node("Cast", [p + "m"], [p + "mf"], to=TensorProto.FLOAT), helper.make_node("Mul", [p + "mf", p + "c"], [p + "a"]),+ helper.make_node("Cos", [p + "a"], [p + "cos"]), helper.make_node("Sin", [p + "a"], [p + "sin"]), helper.make_node("Neg", [p + "sin"], [p + "nsin"]),+ helper.make_node("Concat", [p + "cos", p + "nsin"], [p + "cs"], axis=0), helper.make_node("Mul", [p + "cs", p + "w"], [p + "b0"]), helper.make_node("Mul", [p + "b0", p + "row"], [p + "b"]),+ helper.make_node("Unsqueeze", [p + "b", p + "ax"], [name])]+for init in list(g.graph.initializer):+ w = numpy_helper.to_array(init); name = init.name+ if w.dtype != np.float32: continue+ hit = [(n, inv) for n in (600, 150) for inv in (False, True) if w.shape == (n + 2, 1, n) and np.abs(w - basis(n, inv)).max() < 1e-4 * np.abs(w).max()]+ if hit: g.graph.initializer.remove(init); new_nodes += basis_nodes(name, *hit[0]); nb += 1+ elif w.ndim >= 2 and w.size >= 1024:+ sc = np.abs(w).reshape(w.shape[0], -1).max(1) / 127; sc[sc == 0] = 1+ q = np.clip(np.round(w / sc.reshape((-1,) + (1,) * (w.ndim - 1))), -127, 127).astype(np.int8); g.graph.initializer.remove(init)+ g.graph.initializer.extend([numpy_helper.from_array(q, name + "_q"), numpy_helper.from_array(sc.astype(np.float16), name + "_s16"), numpy_helper.from_array(np.zeros(len(sc), np.int8), name + "_z")])+ new_nodes += [helper.make_node("Cast", [name + "_s16"], [name + "_s"], to=TensorProto.FLOAT), helper.make_node("DequantizeLinear", [name + "_q", name + "_s", name + "_z"], [name], axis=0)]; nq += 1+ elif w.size >= 64 and np.abs(w).max() < 6e4:+ g.graph.initializer.remove(init); g.graph.initializer.append(numpy_helper.from_array(w.astype(np.float16), name + "_16"))+ new_nodes.append(helper.make_node("Cast", [name + "_16"], [name], to=TensorProto.FLOAT)); nh += 1+for n_ in reversed(new_nodes): g.graph.node.insert(0, n_)+qpath = f"{A.out}/paradee_int8.onnx"; onnx.checker.check_model(g); onnx.save(g, qpath)+print(f"int8 weights for {nq} tensors, fp16 for {nh}, {nb} DFT bases generated -> {qpath}: {os.path.getsize(qpath)/1e6:.2f} MB")++# 4. ORT: length vs torch, speed on one thread, listening files+import onnxruntime as ort, soundfile as sf+so = ort.SessionOptions(); so.intra_op_num_threads = 1; so.inter_op_num_threads = 1+for p in (path, qpath):+ sess = ort.InferenceSession(p, so, providers=["CPUExecutionProvider"]); tot = secs = 0+ for rep in range(2):+ for i, r in enumerate(held):+ feed = {"input_ids": r["ids"][None].numpy(), "speed": np.ones(1, np.float32)}+ t = time.perf_counter(); y = sess.run(None, feed)[0]; dt = time.perf_counter() - t+ if rep: tot += dt; secs += y.shape[1] / SR; sf.write(f"{A.out}/held_{i + 1}_{os.path.basename(p)[:-5]}.wav", y[0], SR)+ with torch.no_grad(): yt = m(held[0]["ids"][None], torch.ones(1))+ print(f"{os.path.basename(p)}: length vs torch {sess.run(None, {'input_ids': held[0]['ids'][None].numpy(), 'speed': np.ones(1, np.float32)})[0].shape[1]} vs {yt.shape[1]}, {secs:.1f}s audio in {tot:.2f}s -> {secs / tot:.1f}x realtime on 1 thread")diff --git a/training/scripts/onnx_eval.py b/training/scripts/onnx_eval.pynew file mode 100644index 0000000..e2379d0--- /dev/null+++ b/training/scripts/onnx_eval.py@@ -0,0 +1,19 @@+"""Score released-style ONNX files (input_ids, speed -> waveform) on the held-out sentences: UTMOS, Whisper WER and+speed on one onnxruntime thread. usage: onnx_eval.py N_SENT NAME=PATH.onnx [NAME=PATH.onnx ...]"""+import sys, glob, os, re, time, warnings, torch, numpy as np, soundfile as sf, onnxruntime as ort; warnings.filterwarnings("ignore"); sys.path.insert(0, "scripts")+import whisper, jiwer, torchaudio+from utmos import score+N = int(sys.argv[1]); SR = 24000; held = torch.load(sorted(glob.glob("data/teacher/shard_*.pt"))[0])[:N]+wm = whisper.load_model("base"); norm = lambda s: " ".join(re.sub(r"[^a-z0-9 ]+", " ", s.lower()).split())+for arg in sys.argv[2:]:+ name, path = arg.split("=", 1); out = f"out/onnx_eval_{name}"; os.makedirs(out, exist_ok=True)+ so = ort.SessionOptions(); so.intra_op_num_threads = 1; so.inter_op_num_threads = 1+ sess = ort.InferenceSession(path, so, providers=["CPUExecutionProvider"]); tot = secs = 0.0; us, hyp, ref = [], [], []+ for i, r in enumerate(held):+ feed = {"input_ids": r["ids"][None].numpy(), "speed": np.ones(1, np.float32)}+ if i == 0: sess.run(None, feed)+ t = time.perf_counter(); y = sess.run(None, feed)[0][0]; tot += time.perf_counter() - t; secs += len(y) / SR+ f = f"{out}/held_{i + 1}.wav"; sf.write(f, y, SR); us.append(score(f))+ x = torchaudio.functional.resample(torch.tensor(y), SR, 16000).numpy()+ hyp.append(norm(wm.transcribe(x, language="en", fp16=False)["text"])); ref.append(norm(r["text"]))+ print(f"{name:10s} {os.path.getsize(path) / 1e6:5.2f} MB UTMOS {np.mean(us):.3f} +-{1.96 * np.std(us, ddof=1) / np.sqrt(N):.3f} WER {jiwer.wer(ref, hyp) * 100:.1f}% {secs / tot:.1f}x realtime (onnxruntime, 1 thread)", flush=True)diff --git a/training/scripts/train_vhead.py b/training/scripts/train_vhead.pynew file mode 100644index 0000000..7862034--- /dev/null+++ b/training/scripts/train_vhead.py@@ -0,0 +1,145 @@+"""Train decoder A's trunk + the frame-rate source-filter head (vhead.py) on teacher intermediates to+reproduce the teacher waveform. Same data, losses and critics as train_decoder.py.+usage: train_vhead.py [--steps N] [--gan --mel-weight 3 --init-from CKPT] [--tag T] resumable from checkpoints/vh{tag}/last.pt"""+import sys, os, glob, math, time, json, argparse, warnings, random+warnings.filterwarnings("ignore")+import torch, torch.nn.functional as F, soundfile as sf, torchaudio+sys.path.insert(0, "scripts")+from vhead import VDecoder+from student import alignment+ap = argparse.ArgumentParser(); ap.add_argument("--steps", type=int, default=5000)+ap.add_argument("--bs", type=int, default=16); ap.add_argument("--lr", type=float, default=2e-4); ap.add_argument("--seg", type=int, default=64)+ap.add_argument("--gan", action="store_true"); ap.add_argument("--gan-weight", type=float, default=1.0); ap.add_argument("--fm-weight", type=float, default=2.0); ap.add_argument("--mel-weight", type=float, default=45.0)+ap.add_argument("--init-from", default="", help="vhead checkpoint to start from (fresh optimiser)"); ap.add_argument("--trunk", default="checkpoints/dec_A_gan3/last.pt")+ap.add_argument("--phase-weight", type=float, default=0.0, help="wrapped loss between the head's phase offset and the teacher's phase relative to the sine bank, at harmonic bins")+ap.add_argument("--fine-stft", action="store_true", help="add STFT losses with 64- and 128-sample windows, shorter than a pitch period, so the loss sees how energy pulses within each period")+ap.add_argument("--flat-weight", type=float, default=0.0, help="match the teacher's spectral flatness (how tonal vs noise-like) per 750 Hz band and frame above 1.5 kHz; a statistic, so noise is not penalised for being random")+ap.add_argument("--harm-weight", type=float, default=0.0, help="match the teacher's harmonicity (energy at multiples of the pitch vs halfway between them, log ratio) per 1 kHz band and voiced frame, 1-9 kHz")+ap.add_argument("--mod-weight", type=float, default=0.0, help="match how each upper band's loudness pulses with the pitch (depth and timing, at 1x and 2x the pitch) in 50 ms windows; v2 head only")+ap.add_argument("--head", default="v1"); ap.add_argument("--dim", type=int, default=160); ap.add_argument("--blocks", type=int, default=4)+ap.add_argument("--utmos", action="store_true"); ap.add_argument("--eval-every", type=int, default=2500); ap.add_argument("--eval-only", action="store_true")+ap.add_argument("--device", default="mps"); ap.add_argument("--shards", type=int, default=8); ap.add_argument("--tag", default="")+A = ap.parse_args(); DEV = A.device; RUN = f"checkpoints/vh{A.tag}"; os.makedirs(RUN, exist_ok=True)++def load_rows():+ shards = sorted(glob.glob("data/teacher/shard_*.pt"))[:A.shards]+ def load(sh):+ rows = torch.load(sh)+ for r in rows:+ for k in ("audio_mps", "audio_cpu", "d", "dur", "ids"): r.pop(k, None)+ return rows+ rows0 = load(shards[0]); return rows0[:200], rows0[200:] + [r for sh in shards[1:] for r in load(sh)]+held, train = load_rows(); print(f"{len(train)} train / {len(held)} held-out", flush=True)+def full(r):+ aln = alignment(r["pred_dur"]); asr = r["t_en"].float() @ aln; Fr = aln.shape[1]+ return asr, r["F0"][:2 * Fr], r["N"][:2 * Fr], r["audio"][:600 * Fr].float() / 32767+def segment(r, seg):+ asr, F0, N, au = full(r); Fr = asr.shape[1]+ if Fr <= seg: pad = seg - Fr; asr = F.pad(asr, (0, pad)); F0 = F.pad(F0, (0, 2 * pad)); N = F.pad(N, (0, 2 * pad)); au = F.pad(au, (0, 600 * pad)); a = 0+ else: a = random.randint(0, Fr - seg)+ c0 = (F0[:2 * a].double() * 300 / 24000).sum() % 1 # bank phase accumulated before the crop+ return asr[:, a:a + seg], F0[2 * a:2 * (a + seg)], N[2 * a:2 * (a + seg)], au[600 * a:600 * (a + seg)], c0.float()+def collate(rows, seg):+ x = [segment(r, seg) for r in rows]; return [torch.stack([t[i] for t in x]).to(DEV) for i in range(5)]++mel = torchaudio.transforms.MelSpectrogram(24000, n_fft=1024, hop_length=256, n_mels=80).to(DEV)+def spec_losses(y, t):+ lm = F.l1_loss(torch.log(mel(y).clamp_min(1e-5)), torch.log(mel(t).clamp_min(1e-5))); ls = 0+ SZ = (64, 128, 512, 1024, 2048) if A.fine_stft else (512, 1024, 2048)+ for n in SZ:+ w = torch.hann_window(n, device=DEV)+ Y = torch.stft(y, n, n // 4, window=w, return_complex=True).abs(); T = torch.stft(t, n, n // 4, window=w, return_complex=True).abs()+ ls = ls + (T - Y).norm() / T.norm().clamp_min(1e-5) + F.l1_loss(torch.log(Y.clamp_min(1e-5)), torch.log(T.clamp_min(1e-5)))+ return lm, ls / len(SZ)++model = VDecoder(head=A.head, dim=A.dim, blocks=A.blocks).to(DEV); step = 0; last = f"{RUN}/last.pt"+opt = torch.optim.AdamW(model.parameters(), lr=A.lr, betas=(0.8, 0.99), weight_decay=0.01)+sched = lambda s: min(1, s / 500) * 0.5 * (1 + math.cos(math.pi * min(s, A.steps) / A.steps))+if A.gan:+ from discriminators import Discriminators, d_loss, g_loss+ D = Discriminators().to(DEV); optD = torch.optim.AdamW(D.parameters(), lr=A.lr, betas=(0.8, 0.99), weight_decay=0.01)+if os.path.exists(last):+ ck = torch.load(last, map_location=DEV); model.load_state_dict(ck["model"]); opt.load_state_dict(ck["opt"]); step = ck["step"]; print(f"resumed at {step}", flush=True)+ if A.gan and "D" in ck: D.load_state_dict(ck["D"]); optD.load_state_dict(ck["optD"])+elif A.init_from: model.load_ckpt(A.init_from, DEV); print(f"initialised from {A.init_from}", flush=True)+else: model.load_trunk(A.trunk); print(f"trunk from {A.trunk}, head from scratch", flush=True)++def flat_loss(y, t, n=2048, bw=64):+ w = torch.hann_window(n, device=DEV); out = []+ for x in (y, t):+ P = torch.stft(x, n, n // 4, window=w, return_complex=True).abs().pow(2).clamp_min(1e-10)[:, 128:128 + 13 * bw] # 1.5-11.25 kHz+ P = P.reshape(P.shape[0], 13, bw, -1); out.append(torch.log(P).mean(2) - torch.log(P.mean(2)))+ return F.l1_loss(out[0], out[1])+def harm_loss(y, t, f0, n=2048, hop=512):+ w = torch.hann_window(n, device=DEV); nfr = y.shape[-1] // hop + 1+ idx = (torch.arange(nfr, device=DEV) * hop // 300).clamp(max=f0.shape[1] - 1); lo = (idx - 2).clamp(min=0); hi = (idx + 2).clamp(max=f0.shape[1] - 1)+ f = f0[:, idx]; v = (torch.minimum(torch.minimum(f0[:, lo], f), f0[:, hi]) > 100).float() # steady voiced frames [B, T]+ fr = torch.arange(n // 2 + 1, device=DEV) * 24000 / n; ratio = fr[None, :, None] / f.clamp_min(60)[:, None]; frac = (ratio - ratio.round()).abs()+ mh, mi = (frac < 0.15).float(), ((frac - 0.5).abs() < 0.15).float(); bands = torch.stack([((fr >= 1000 * b) & (fr < 1000 * (b + 1))).float() for b in range(1, 9)]) # [8, bins]+ out = []+ for x in (y, t):+ P = torch.stft(x, n, hop, window=w, return_complex=True).abs().pow(2)+ out.append(torch.log((torch.einsum("bft,kf->bkt", P * mh, bands) + 1e-8) / (torch.einsum("bft,kf->bkt", P * mi, bands) + 1e-8)))+ return ((out[0] - out[1]).abs() * v[:, None]).sum() / (v.sum() * 8).clamp_min(1)+MODB = [(4, 8), (8, 12), (12, 16), (16, 21), (21, 29)] # 375 Hz bins: 1.5-3, 3-4.5, 4.5-6, 6-8, 8-11 kHz+def mod_loss(y, t, cyc, uv, n=64, hop=16, win=75):+ w = torch.hann_window(n, device=DEV); k = y.shape[-1] // hop + 1+ ph = 2 * torch.pi * F.pad(cyc, (0, hop))[:, ::hop][:, :k]; v = F.pad(uv, (0, hop))[:, ::hop][:, :k]+ carr = torch.stack([fn(m * ph) for m in (1, 2) for fn in (torch.cos, torch.sin)], 1) # [B, 4, T]+ D = []+ for x in (y, t):+ X = torch.stft(x, n, hop, window=w, return_complex=True).abs(); e = torch.stack([X[:, a:b].sum(1) for a, b in MODB], 1) # [B, 5, T]+ num = F.avg_pool1d((e[:, :, None] * carr[:, None]).flatten(1, 2), win, win // 2); den = F.avg_pool1d(e, win, win // 2).clamp_min(1e-5)+ D.append(2 * num.view(e.shape[0], 5, 4, -1) / den[:, :, None])+ vm = (F.avg_pool1d(v[:, None], win, win // 2) > 0.99).float()[:, :, None] # [B, 1, 1, W]+ return ((D[0] - D[1]).abs() * vm).sum() / (vm.sum() * 20).clamp_min(1)+def phase_terms(head, au, eq=True):+ """Wrapped losses (1 - cos) between the head's phase offset and the teacher's phase relative to the sine bank:+ absolute, group delay (difference across 1/2/3/5 bins) and frame-to-frame change. Weights = teacher x bank+ magnitude (only bins at voiced harmonics count), divided per bin by their average so every band counts."""+ L = head.last; T = head.stft(au); k = min(T.shape[-1], L["E"].shape[-1]); T, E, ph = T[..., :k], L["E"][..., :k], L["ph"][..., :k]+ w = T.abs() * E.abs(); tgt = (T * E.conj()).angle()+ if eq: w = w / w.mean((0, 2), keepdim=True).clamp_min(1e-5)+ err = ph - tgt; f = lambda e, ww: (ww * (1 - torch.cos(e))).sum() / ww.sum().clamp_min(1e-5)+ gd = sum(f(err[:, d:] - err[:, :-d], (w[:, d:] * w[:, :-d]).sqrt()) for d in (1, 2, 3, 5)) / 4+ return f(err, w), gd, f(err[..., 1:] - err[..., :-1], (w[..., 1:] * w[..., :-1]).sqrt())+def phase_loss(au): return sum(phase_terms(model.head, au))[email protected]_grad()+def evaluate(n_audio=8):+ model.eval(); from common import compare+ outs, refs, lp_acc = [], [], []; d = f"{RUN}/eval_{step}"; os.makedirs(d, exist_ok=True)+ for i, r in enumerate(held[:n_audio]):+ asr, F0, N, au = full(r); torch.manual_seed(i)+ y = model(asr[None].to(DEV), F0[None].to(DEV), N[None].to(DEV)).squeeze().cpu()+ if A.phase_weight > 0: lp_acc.append(phase_loss(au[None].to(DEV)).item())+ k = min(len(y), len(au)); outs.append(y[:k]); refs.append(au[:k]); sf.write(f"{d}/held_{i + 1}_student.wav", y.numpy(), 24000)+ raw, dtw, _ = compare(refs, outs); model.train(); ev = dict(step=step, dtw_l1=round(dtw, 4), raw_l1=round(raw, 4))+ if lp_acc: ev["held_phase"] = round(sum(lp_acc) / len(lp_acc), 4)+ if A.utmos:+ from utmos import score; ev["utmos"] = round(float(sum(score(f"{d}/held_{i + 1}_student.wav") for i in range(len(outs))) / len(outs)), 3)+ return ev+if A.eval_only: print(json.dumps(evaluate())); sys.exit()+print(f"{sum(p.numel() for p in model.parameters()) / 1e6:.2f}M params (head {sum(p.numel() for p in model.head.parameters()) / 1e6:.2f}M), device {DEV}", flush=True)+model.train(); t0 = time.time(); s0 = step; log = open(f"{RUN}/log.jsonl", "a")+while step < A.steps:+ asr, F0, N, au, c0 = collate(random.sample(train, A.bs), A.seg)+ for g in opt.param_groups: g["lr"] = A.lr * sched(step)+ y = model(asr, F0, N, c0=c0); lm, ls = spec_losses(y, au)+ if A.gan:+ ld = d_loss(D, au, y); optD.zero_grad(); ld.backward(); optD.step()+ adv, fm = g_loss(D, au, y); loss = A.mel_weight * (lm + ls) + A.gan_weight * adv + A.fm_weight * fm+ else: loss = lm + ls+ if A.phase_weight > 0: lp = phase_loss(au); loss = loss + A.phase_weight * lp+ if A.flat_weight > 0: lf = flat_loss(y, au); loss = loss + A.flat_weight * lf+ if A.harm_weight > 0: lh = harm_loss(y, au, F0); loss = loss + A.harm_weight * lh+ if A.mod_weight > 0: lmod = mod_loss(y, au, model.head.last["cyc"], model.head.last["uv"]); loss = loss + A.mod_weight * lmod+ opt.zero_grad(); loss.backward(); torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0); opt.step(); step += 1+ if step % 50 == 0: print(f"step {step} loss {loss.item():.4f} mel {lm.item():.4f} stft {ls.item():.4f}" + (f" adv {adv.item():.3f} fm {fm.item():.3f} d {ld.item():.3f}" if A.gan else "") + (f" phase {lp.item():.4f}" if A.phase_weight > 0 else "") + (f" flat {lf.item():.4f}" if A.flat_weight > 0 else "") + (f" harm {lh.item():.4f}" if A.harm_weight > 0 else "") + (f" mod {lmod.item():.4f}" if A.mod_weight > 0 else "") + f" {(time.time() - t0) / (step - s0):.2f}s/step", flush=True)+ if step % 500 == 0 or step == A.steps:+ ck = {"model": model.state_dict(), "opt": opt.state_dict(), "step": step}+ if A.gan: ck["D"] = D.state_dict(); ck["optD"] = optD.state_dict()+ torch.save(ck, last)+ if step % A.eval_every == 0 or step == A.steps:+ ev = evaluate(); print("EVAL", json.dumps(ev), flush=True); log.write(json.dumps(ev) + "\n"); log.flush()+ torch.save({"model": model.state_dict(), "step": step}, f"{RUN}/step{step}.pt")+print("done")diff --git a/training/scripts/vh_ab.py b/training/scripts/vh_ab.pynew file mode 100644index 0000000..41913bb--- /dev/null+++ b/training/scripts/vh_ab.py@@ -0,0 +1,56 @@+"""A/B for the frame-rate head: whole Paradee pipeline (student text side) through (a) the released decoder A ++locked33 filter and (b) a vhead checkpoint. Writes WAVs to out/vh_ab{tag}/ and prints UTMOS, harmonicity+(energy at harmonics vs between them, voiced frames, dB) and optionally Whisper WER.+usage: vh_ab.py VH_CKPT [N_SENT] [--tag T] [--wer] [--dim D --blocks B]"""+import sys, glob, os, re, argparse, time, warnings, torch, numpy as np, soundfile as sf; warnings.filterwarnings("ignore"); sys.path.insert(0, "scripts")+from student import TextStudent, alignment+from student_decoder import load_student_decoder+from vhead import VDecoder, HV+from phase_lock import lock+ap = argparse.ArgumentParser(); ap.add_argument("ckpt"); ap.add_argument("n", type=int, nargs="?", default=8); ap.add_argument("--tag", default=""); ap.add_argument("--wer", action="store_true")+ap.add_argument("--dim", type=int, default=160); ap.add_argument("--blocks", type=int, default=4); A = ap.parse_args()+torch.set_num_threads(1); out = f"out/vh_ab{A.tag}"; os.makedirs(out, exist_ok=True)+held = torch.load(sorted(glob.glob("data/teacher/shard_*.pt"))[0])[:A.n]+ts = TextStudent("s+mlp").eval(); ts.load_state_dict(torch.load("checkpoints/text_s+mlp/last.pt", map_location="cpu")["model"])+da = load_student_decoder("A", "checkpoints/dec_A_gan3/last.pt"); cap = {}+da.generator.m_source.register_forward_hook(lambda m, i, o: cap.__setitem__("src", o[0].squeeze()))+vh = VDecoder(head=HV(A.ckpt), dim=A.dim, blocks=A.blocks).eval(); vh.load_ckpt(A.ckpt)+NF, WIN, HOP, SR = 4096, 1024, 256, 24000; w = torch.hann_window(WIN); fr = np.arange(NF // 2 + 1) * SR / NF; BANDS = [(1000, 2000), (2000, 4000), (4000, 8000)]+def hnr(x, f0):+ X = torch.stft(x, NF, HOP, WIN, window=w, return_complex=True).abs().numpy() ** 2; res = {b: [] for b in BANDS}+ for j in range(X.shape[1]):+ a, f, c = [float(f0[min(int((j + d) * HOP / 300), len(f0) - 1)]) for d in (-2, 0, 2)]+ if min(a, f, c) < 80: continue+ for lo, hi in BANDS:+ ks = np.arange(int(np.ceil(lo / f)), int(hi / f)); P = X[:, j]+ h = sum(P[(fr > k * f - .15 * f) & (fr < k * f + .15 * f)].sum() for k in ks); ih = sum(P[(fr > (k + .5) * f - .15 * f) & (fr < (k + .5) * f + .15 * f)].sum() for k in ks)+ res[(lo, hi)].append(10 * np.log10((h + 1e-12) / (ih + 1e-12)))+ return {b: float(np.mean(v)) for b, v in res.items()}+names = ["teacher", "current", "newhead"]; H = {n: [] for n in names}; T = {"current": 0.0, "newhead": 0.0}; secs = 0+for i, r in enumerate(held):+ with torch.no_grad():+ ids = r["ids"][None]; Ln = torch.tensor([len(r["ids"])])+ pd, _, _, pasr = ts(ids, Ln); aln = alignment(torch.round(pd[0]).clamp(min=1).long())[None]+ _, F0, N, _ = ts(ids, Ln, aln); asr = pasr @ aln+ torch.manual_seed(i); t = time.perf_counter(); s = da(asr, F0, N).squeeze(); cur = lock(s, cap["src"], F0[0], 33); T["current"] += time.perf_counter() - t+ torch.manual_seed(i); t = time.perf_counter(); new = vh(asr, F0, N).squeeze(); T["newhead"] += time.perf_counter() - t+ secs += len(new) / SR; tea = r["audio"].float() / 32767+ for n, x in zip(names, (tea, cur, new)):+ sf.write(f"{out}/held_{i + 1}_{n}.wav", x.numpy(), SR)+ if n != "teacher": H[n].append(hnr(x, F0[0]))+ aln_t = alignment(r["pred_dur"]); H["teacher"].append(hnr(tea, r["F0"][:2 * aln_t.shape[1]]))+from utmos import score+print(f"{A.ckpt}, {A.n} held-out sentences, whole pipeline")+if A.wer:+ import whisper, jiwer, torchaudio; wm = whisper.load_model("base"); norm = lambda s: " ".join(re.sub(r"[^a-z0-9 ]+", " ", s.lower()).split())+for n in names:+ us = [score(f"{out}/held_{i + 1}_{n}.wav") for i in range(A.n)]; u = np.mean(us)+ line = f"{n:8s} UTMOS {u:.3f} +-{1.96 * np.std(us, ddof=1) / np.sqrt(A.n):.3f} harmonicity dB " + " ".join(f"{lo // 1000}-{hi // 1000}k {np.mean([h[(lo, hi)] for h in H[n]]):5.2f}" for lo, hi in BANDS)+ if n in T: line += f" decoder {secs / T[n]:4.0f}x realtime (torch fp32, 1 thread)"+ if A.wer:+ hyp, ref = [], []+ for i, r in enumerate(held):+ x, _ = sf.read(f"{out}/held_{i + 1}_{n}.wav", dtype="float32"); x = torchaudio.functional.resample(torch.tensor(x), SR, 16000).numpy()+ hyp.append(norm(wm.transcribe(x, language="en", fp16=False)["text"])); ref.append(norm(r["text"]))+ line += f" WER {jiwer.wer(ref, hyp) * 100:.1f}%"+ print(line, flush=True)diff --git a/training/scripts/vhead.py b/training/scripts/vhead.pynew file mode 100644index 0000000..2c4ee41--- /dev/null+++ b/training/scripts/vhead.py@@ -0,0 +1,150 @@+"""Frame-rate source-filter head (the Vocos idea with a harmonic source) in place of Kokoro's upsampling+iSTFTNet generator. Decoder A's AdaIN trunk is kept (80 frames a second). The head never upsamples: a few+ConvNeXt blocks at 80 fps predict, for every STFT bin of 2 frames per trunk frame (n_fft 600, hop 150),+a gain and a phase offset applied to the STFT of a clean sine bank built from the F0 curve (harmonic k has+phase k*phi), plus a gain for white noise. Harmonics therefore arrive phase-locked to the pitch by+construction, and the network only learns the spectral envelope and a slow phase correction.+usage: vhead.py prints params and FLOPs next to decoder A"""+import torch, torch.nn as nn, torch.nn.functional as F+from student_decoder import StudentDecoder+SR, FHOP = 24000, 300 # F0 frames are 300 samples++def sine_bank(f0, K=64, c0=None):+ """f0 [B, frames] (80 fps) -> [B, samples] sum of K harmonics with Kokoro's fundamental phase (frame-rate+ cumulative phase, linearly interpolated between frame centres), harmonics muted above 11 kHz and where+ unvoiced. The running phase is accumulated in float64 and wrapped per frame so harmonic 64 stays exact.+ c0 [B]: phase (cycles) accumulated before this crop, so a segment's bank matches the whole sentence's."""+ B, n = f0.shape; dev = f0.device+ r = (f0.cpu().double() * FHOP / SR) # cycles per frame+ c = ((torch.cumsum(r, 1) + (0 if c0 is None else c0.cpu().double()[:, None])) % 1).float().to(dev); d = F.pad(r[:, 1:], (0, 1)).float().to(dev) # wrapped start, advance to next centre+ p = (torch.arange(n * FHOP, device=dev) + 0.5) / FHOP - 0.5; i = p.floor().clamp(0, n - 1).long(); fr = (p - i).clamp(0, 1)+ cyc = c[:, i] + fr * d[:, i] # [B, samples] fundamental phase in cycles+ f0s = f0.repeat_interleave(FHOP, 1); k = torch.arange(1, K + 1, device=dev)[None, :, None]+ amp = ((f0s[:, None] * k < 11000) & (f0s[:, None] > 10)).float()+ return (torch.sin(2 * torch.pi * k * cyc[:, None]) * amp).sum(1) * 0.1, cyc, (f0s > 10).float()++class ConvNeXt(nn.Module):+ def __init__(self, dim, mult=3):+ super().__init__(); self.dw = nn.Conv1d(dim, dim, 7, padding=3, groups=dim); self.norm = nn.LayerNorm(dim)+ self.pw1 = nn.Linear(dim, dim * mult); self.pw2 = nn.Linear(dim * mult, dim); self.gamma = nn.Parameter(torch.full((dim,), 1e-2))+ def forward(self, x):+ h = self.norm(self.dw(x).transpose(1, 2)); return x + (self.gamma * self.pw2(F.gelu(self.pw1(h)))).transpose(1, 2)++class SourceFilterHead(nn.Module):+ def __init__(self, in_ch=128, dim=160, blocks=4, n_fft=600, hop=150, K=64, mod=2, mb=33):+ """mod: the noise part can also pulse with the pitch: extra sources noise*cos(m*phi), noise*sin(m*phi) for m = 1..mod,+ each with a signed gain relative to the plain noise gain, predicted at mb points across frequency (zero-init)."""+ super().__init__(); self.n_fft, self.hop, self.K, self.up, self.nb, self.mod, self.mb = n_fft, hop, K, FHOP // hop, n_fft // 2 + 1, mod, mb+ if mod: self.out_mod = nn.Linear(dim, self.up * 2 * mod * mb); nn.init.zeros_(self.out_mod.weight); nn.init.zeros_(self.out_mod.bias)+ self.inp = nn.Conv1d(in_ch, dim, 7, padding=3); self.norm0 = nn.LayerNorm(dim)+ self.blocks = nn.ModuleList([ConvNeXt(dim) for _ in range(blocks)]); self.norm1 = nn.LayerNorm(dim)+ self.out = nn.Linear(dim, self.up * self.nb * 3) # per bin: harmonic log-gain, harmonic phase offset, noise log-gain+ nn.init.trunc_normal_(self.out.weight, std=0.02)+ with torch.no_grad(): b = self.out.bias.view(self.up, 3, self.nb); b[:, 0] = -3.0; b[:, 1] = 0.0; b[:, 2] = -6.0+ self.register_buffer("window", torch.hann_window(n_fft), persistent=False)+ def stft(self, x): return torch.stft(x, self.n_fft, self.hop, window=self.window, return_complex=True)+ def forward(self, x, f0, noise=None, c0=None):+ B, _, n = x.shape+ h = self.norm0(self.inp(x).transpose(1, 2)).transpose(1, 2)+ for b in self.blocks: h = b(h)+ hn = self.norm1(h.transpose(1, 2)); o = self.out(hn).view(B, n, self.up, 3, self.nb).permute(0, 3, 4, 1, 2).reshape(B, 3, self.nb, n * self.up)+ o = torch.cat([o, o[..., -1:]], -1) # centred STFT has one more frame+ gh, ph, gn = torch.exp(o[:, 0].clamp(max=6)), o[:, 1], torch.exp(o[:, 2].clamp(max=6))+ with torch.no_grad():+ e, cyc, uv = sine_bank(f0, self.K, c0); E = self.stft(e)+ nz = torch.randn_like(e) if noise is None else noise; Nz = self.stft(nz)+ Nm = [self.stft(nz * uv * fn(2 * torch.pi * m * cyc)) for m in range(1, self.mod + 1) for fn in (torch.cos, torch.sin)]+ self.last = dict(E=E, gh=gh, ph=ph, gn=gn)+ if self.mod:+ a = self.out_mod(hn).view(B, n, self.up, 2 * self.mod, self.mb).permute(0, 3, 1, 2, 4).reshape(B * 2 * self.mod, n * self.up, self.mb)+ a = F.interpolate(a, size=self.nb, mode="linear", align_corners=True).view(B, 2 * self.mod, n * self.up, self.nb).transpose(2, 3)+ a = torch.cat([a, a[..., -1:]], -1); self.last["a"] = a+ Nz = Nz + sum(a[:, j] * Nm[j] for j in range(2 * self.mod))+ Y = E * torch.polar(gh, ph) + Nz * gn+ return torch.istft(Y, self.n_fft, self.hop, window=self.window, length=n * FHOP)++def warp_matrix(nb, G, sr=SR):+ """[nb, G] linear-interpolation weights from G points spaced evenly on a mel-like axis to nb linear STFT bins."""+ f = torch.linspace(0, sr / 2, nb); mel = lambda x: torch.log1p(x / 700); pos = mel(f) / mel(torch.tensor(sr / 2.0)) * (G - 1)+ i = pos.floor().clamp(0, G - 2).long(); w = pos - i; M = torch.zeros(nb, G); M[torch.arange(nb), i] = 1 - w; M[torch.arange(nb), i + 1] += w; return M++class SourceFilterHead2(SourceFilterHead):+ """Second design: every part has one job. The harmonic part is a smooth filter on the sine bank: gain and phase are+ predicted at G points across frequency (mel-spaced) and interpolated, plus one pulse shift per frame (a delay of the+ whole pulse, as a fraction of the pitch period), so it cannot scramble individual bins into fake noise. Anything+ noise-like has to come from the noise part (plain + pulsing with the pitch), whose gains are also on the G points."""+ def __init__(self, in_ch=128, dim=160, blocks=4, n_fft=600, hop=150, K=64, mod=2, G=80, burst=True, Gb=24):+ """burst: a second noise source shaped through a short STFT (150-sample window, 75 hop: 3 ms steps, 4 per trunk+ frame) with gains at Gb points, so consonant bursts and onsets are not smeared over the 25 ms main window."""+ nn.Module.__init__(self); self.burst, self.Gb = burst, Gb+ if burst:+ self.out_b = nn.Linear(dim, 4 * Gb); nn.init.trunc_normal_(self.out_b.weight, std=0.02); nn.init.constant_(self.out_b.bias, -7.0)+ self.register_buffer("wb", torch.hann_window(150), persistent=False); self.register_buffer("Mb", warp_matrix(76, Gb), persistent=False)+ self.n_fft, self.hop, self.K, self.up, self.nb, self.mod, self.G = n_fft, hop, K, FHOP // hop, n_fft // 2 + 1, mod, G+ self.inp = nn.Conv1d(in_ch, dim, 7, padding=3); self.norm0 = nn.LayerNorm(dim)+ self.blocks = nn.ModuleList([ConvNeXt(dim) for _ in range(blocks)]); self.norm1 = nn.LayerNorm(dim)+ self.C = 4 + 2 * mod # harmonic log-gain, phase cos, phase sin, noise log-gain, pulsing-noise gains+ self.out = nn.Linear(dim, self.up * (self.C * G + 1)); nn.init.trunc_normal_(self.out.weight, std=0.02)+ with torch.no_grad():+ b = self.out.bias.view(self.up, -1); b.zero_(); g = b[:, :self.C * G].view(self.up, self.C, G); g[:, 0] = -3.0; g[:, 1] = 1.0; g[:, 3] = -6.0+ self.register_buffer("window", torch.hann_window(n_fft), persistent=False); self.register_buffer("M", warp_matrix(self.nb, G), persistent=False)+ def forward(self, x, f0, noise=None, c0=None):+ B, _, n = x.shape; T = n * self.up+ h = self.norm0(self.inp(x).transpose(1, 2)).transpose(1, 2)+ for b in self.blocks: h = b(h)+ hn = self.norm1(h.transpose(1, 2)); o = self.out(hn).view(B, T, self.C * self.G + 1); o = torch.cat([o, o[:, -1:]], 1) # centred STFT has one more frame+ g = (o[..., :-1].reshape(B, T + 1, self.C, self.G) @ self.M.T).permute(0, 2, 3, 1) # [B, C, nb, T+1]+ gh, gn = torch.exp(g[:, 0].clamp(max=6)), torch.exp(g[:, 3].clamp(max=6)); u = torch.complex(g[:, 1], g[:, 2]); u = u / u.abs().clamp_min(1e-4)+ with torch.no_grad():+ e, cyc, uv = sine_bank(f0, self.K, c0); E = self.stft(e)+ nz = torch.randn_like(e) if noise is None else noise; Nz = self.stft(nz)+ Nm = [self.stft(nz * uv * fn(2 * torch.pi * m * cyc)) for m in range(1, self.mod + 1) for fn in (torch.cos, torch.sin)]+ f0f = torch.cat([f0.repeat_interleave(self.up, 1), f0[:, -1:]], 1).clamp_min(60) # per STFT frame+ ratio = torch.linspace(0, SR / 2, self.nb, device=x.device)[None, :, None] / f0f[:, None] # harmonic number of each bin+ shift = 0.5 * torch.tanh(o[..., -1])[:, None] # pulse shift, cycles+ Hh = gh * u * torch.polar(torch.ones_like(ratio), 2 * torch.pi * ratio * shift)+ self.last = dict(E=E, gh=gh, ph=Hh.angle(), gn=gn, a=g[:, 4:], shift=shift, cyc=cyc, uv=uv)+ Nz = Nz + sum(g[:, 4 + j] * Nm[j] for j in range(2 * self.mod))+ y = torch.istft(E * Hh + Nz * gn, self.n_fft, self.hop, window=self.window, length=n * FHOP)+ if self.burst:+ gb = torch.exp((self.out_b(hn).view(B, n * 4, self.Gb) @ self.Mb.T).clamp(max=6)).transpose(1, 2); gb = torch.cat([gb, gb[..., -1:]], -1)+ with torch.no_grad(): Nb = torch.stft(nz.flip(-1), 150, 75, window=self.wb, return_complex=True)+ self.last["gb"] = gb; y = y + torch.istft(Nb * gb, 150, 75, window=self.wb, length=n * FHOP)+ return y++class VDecoder(nn.Module):+ """Decoder A's AdaIN trunk + the frame-rate head."""+ def __init__(self, preset="A", head="v1", **kw):+ super().__init__(); t = StudentDecoder(preset); uic = t.generator.conv_post.in_channels * 4+ for k in ("encode", "decode", "F0_conv", "N_conv", "asr_res"): setattr(self, k, getattr(t, k))+ self.style = t.style; self.head = (SourceFilterHead2 if head == "v2" else SourceFilterHead)(in_ch=uic, **kw)+ def forward(self, asr, F0_curve, N, noise=None, c0=None):+ s = self.style.expand(asr.shape[0], -1)+ F0 = self.F0_conv(F0_curve.unsqueeze(1)); Nn = self.N_conv(N.unsqueeze(1))+ x = self.encode(torch.cat([asr, F0, Nn], 1), s); asr_res = self.asr_res(asr); res = True+ for block in self.decode:+ if res: x = torch.cat([x, asr_res, F0, Nn], 1)+ x = block(x, s)+ if block.upsample_type != "none": res = False+ return self.head(x, F0_curve, noise, c0)+ def load_trunk(self, path):+ sd = {k: v for k, v in torch.load(path, map_location="cpu")["model"].items() if not k.startswith(("generator.", "head."))}+ res = self.load_state_dict(sd, strict=False); assert all(k.startswith("head.") for k in res.missing_keys) and not res.unexpected_keys, res+ def load_ckpt(self, path, device="cpu"):+ """Load a vhead checkpoint; one from before the pulsing-noise sources gets them zero-initialised (same function)."""+ res = self.load_state_dict(torch.load(path, map_location=device)["model"], strict=False); assert all("out_mod" in k or "out_b" in k for k in res.missing_keys) and not res.unexpected_keys, res+ if any("out_b" in k for k in res.missing_keys): self.head.burst = False # checkpoint from before the short-window noise path++def HV(path):+ """Which head design a checkpoint holds (v2's output layer is the small one)."""+ return "v2" if torch.load(path, map_location="cpu")["model"]["head.out.weight"].shape[0] < 1500 else "v1"++if __name__ == "__main__":+ from torch.utils.flop_counter import FlopCounterMode+ T = 174; asr = torch.randn(1, 512, T); F0 = torch.rand(1, 2 * T) * 200 + 80; N = torch.randn(1, 2 * T)+ np_ = lambda m: sum(x.numel() for x in m.parameters()) / 1e6+ for name, m in [("decoder A", StudentDecoder("A")), ("A trunk + head", VDecoder()), ("A trunk + head2", VDecoder(head="v2"))]:+ m = m.eval().requires_grad_(False); fc = FlopCounterMode(display=False)+ with fc: out = m(asr, F0, N)+ hp = np_(m.head) if hasattr(m, "head") else np_(m.generator)+ print(f"{name:16s} {np_(m):5.2f}M params (head/generator {hp:.2f}M) {fc.get_total_flops() / (out.shape[-1] / SR) / 1e9:6.2f} GFLOP/s out {tuple(out.shape)}")