Evaluation scripts for the Open TTS Leaderboard: https://huggingface.co/spaces/hf-audio/open_tts_leaderboard
Python
Add paradee scripts. (#5)
Eric Bezzam2b2cd31257d2
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdindex f73b88d..0d3bba0 100644--- a/.github/pull_request_template.md+++ b/.github/pull_request_template.md@@ -1,19 +1,15 @@## New model / backend**Model(s):** <!-- e.g. org/model-name, with a link to the model card -->-**Backend folder:** <!-- e.g. my-backend/ -->**Docker Space (public):** <!-- e.g. https://huggingface.co/spaces/YOUR_USERNAME/evals-my-backend -->-### Model info (for `model_info.csv`)+### Model info- License:-- Voice cloning: yes / no-- Batch inference: yes / no+- Voice cloning: yes OR no+- Batch inference: yes OR no- Number of supported languages:- Model size (B params):-- Runs with `transformers`: yes / no--### Evaluated splits-<!-- e.g. Seed-TTS tts/en, tts/zh, CV3-Eval zero_shot/{en,zh,...}; with or without voice cloning -->+- Runs with [transformers](https://github.com/huggingface/transformers): yes OR no### Results<!-- Paste the "Results per dataset" / "Composite Results" block printed at the end of submit_jobs.sh -->@@ -22,9 +18,9 @@```### Checklist-- [ ] `run_eval.py` and `submit_jobs.sh` follow the structure of the existing backends (see README, "Adding a new model")+- [ ] `run_eval.py` and `submit_jobs.sh` follow the structure of the existing backends (see README, ["Adding a new model"](https://github.com/huggingface/open-tts-leaderboard#adding-a-new-model))- [ ] Stage 1 runs on the default `h200` flavor (`FLAVOR` is not overridden)- [ ] Generation time excludes model loading / warm-up- [ ] Smoke test passed (`MAX_EVAL_SAMPLES=8 ONLY_LANGS="en" bash <backend>/submit_jobs.sh`)-- [ ] Full evaluation completed and results are in the bucket+- [ ] Full evaluation completed and results are in a bucket- [ ] (Optional) `--ttfa_probe` implemented and target added to `submit_ttfa_jobs.sh`diff --git a/paradee/run_eval.py b/paradee/run_eval.pynew file mode 100644index 0000000..c26f3f9--- /dev/null+++ b/paradee/run_eval.py@@ -0,0 +1,190 @@+"""+TTS synthesis for the Open TTS Leaderboard (Paradee backend, stage 1).++Paradee-8M (sahilmahendrakar/Paradee-8M-v1.0, https://github.com/sahilmahendrakar/paradee) is an+8M-parameter distillation of Kokoro-82M that speaks one voice (Kokoro's af_heart), English only.+The `paradee` package runs misaki G2P (Kokoro's own) and then one ONNX graph (phoneme ids -> 24 kHz+audio) in ONNX Runtime. This script loads it once, synthesizes each target text, times generation+for RTFx, saves wavs, and writes a manifest with `text`, `duration`, and generation `time` (empty+`pred_text`).++`Paradee.__call__` splits the text into sentences and runs the graph once per sentence, then+concatenates. The graph takes a single `[1, T]` sequence, so there is no batched API: rows are+processed serially, as in the Kokoro backend.+"""++import argparse+import os+import time++import numpy as np+import onnxruntime as ort+import soundfile as sf+from tqdm import tqdm++from paradee import SAMPLE_RATE, Paradee+from paradee.tts import REPO, REVISION++from run_eval_utils import (+ add_common_args, load_done_entries, load_tts_dataset, manifest_entry, open_manifest, output_paths,+ pending_batches, print_next_steps, set_seed, warm_up, wav_rel_path, write_entry,+)++ONNX_FILES = {True: "onnx/paradee_int8.onnx", False: "onnx/paradee.onnx"}+++def _onnx_path(quantized):+ from huggingface_hub import hf_hub_download++ return hf_hub_download(REPO, ONNX_FILES[quantized], revision=REVISION)+++def _use_cuda_session(tts, onnx_path, device, threads):+ """Replace the package's CPU session with a CUDA EP one on the same graph (same SessionOptions)."""+ device_id = int(device.split(":")[1]) if ":" in device else 0+ # Load pip-installed CUDA/cuDNN (nvidia-* wheels) when they are not on LD_LIBRARY_PATH.+ if hasattr(ort, "preload_dlls"):+ ort.preload_dlls()+ so = ort.SessionOptions()+ so.intra_op_num_threads = threads+ so.inter_op_num_threads = 1+ tts.session = ort.InferenceSession(+ onnx_path, so, providers=[("CUDAExecutionProvider", {"device_id": device_id}), "CPUExecutionProvider"]+ )+ # The CUDA EP silently falls back to CPU (e.g. missing cuDNN); refuse rather than mislabel.+ if "CUDAExecutionProvider" not in tts.session.get_providers():+ raise RuntimeError(f"--device={device} but the CUDA EP did not load: {tts.session.get_providers()}")+++def _print_model_size(onnx_path):+ """Sum the ONNX initializer element counts (int8 weights count once; scales/zero points are tiny)."""+ try:+ import onnx++ model = onnx.load(onnx_path, load_external_data=False)+ n_params = sum(int(np.prod(init.dims)) for init in model.graph.initializer)+ print(f"TTS model size: {n_params / 1e9:.3f}B parameters (sum of ONNX initializers)")+ except Exception as e:+ print(f"Could not compute ONNX parameter count ({e}); model card reports 8.07M parameters.")+++def main(args):+ set_seed(args.seed)++ onnx_path = _onnx_path(args.quantized)+ tts = Paradee(quantized=args.quantized, model_path=onnx_path, threads=args.threads)+ if args.device.startswith("cuda"):+ _use_cuda_session(tts, onnx_path, args.device, args.threads)+ print(+ f"Loaded Paradee ({args.model_id}@{REVISION}, {ONNX_FILES[args.quantized]}, "+ f"providers={tts.session.get_providers()}, threads={args.threads})"+ )+ _print_model_size(onnx_path)++ def synth_one(text):+ """Synthesize one text with the package's own sentence loop. Return (audio_1d_numpy, elapsed_s)."""+ start = time.perf_counter()+ audio = tts(text, speed=args.speed)+ elapsed = time.perf_counter() - start+ if audio.size == 0:+ audio = np.zeros(1, dtype=np.float32)+ return audio, elapsed++ def synth_one_streaming(text, early_stop=False):+ """TTFA probe only: the same sentence loop as Paradee.__call__, timestamping the first chunk.++ Returns (audio_1d_numpy, first_chunk_ts, n_chunks). A one-sentence prompt has nothing to+ stream (n_chunks == 1): first audio is last audio.+ """+ first, parts = None, []+ for ps in tts._chunks(text):+ parts.append(tts.generate_from_phonemes(ps, args.speed))+ if first is None:+ first = time.perf_counter()+ if early_stop:+ break+ if not parts:+ return np.zeros(1, dtype=np.float32), None, 0+ return np.concatenate(parts), first, len(parts)++ # Layout: results/<model_safe>/{MODEL_<safe>_DATASET_<dsid>.jsonl, <dsid>/output_<id>.wav}.+ # Manifest paths are relative to model_dir so later stages resolve them wherever it is copied.+ paths = output_paths(args)+ model_dir, dataset_dir_name, manifest_path = paths.model_dir, paths.dataset_dir_name, paths.manifest_path++ dataset = load_tts_dataset(args)++ # ── TTFA probe: latency only, writing nothing but a JSON sidecar ─────────+ # Timestamps the first sentence's audio (see synth_one_streaming).+ # 0 = off; N > 0 = N evenly spaced samples; N < 0 = the whole split (see scripts/ttfa_probe.py).+ if args.ttfa_probe != 0:+ # Imported here: ttfa_probe.py is injected only by submit_ttfa_jobs.sh.+ from ttfa_probe import run_probe, sample_indices+ chunk_counts = []++ def _ttfa_gen(job, early_stop):+ audio, first, n_chunks = synth_one_streaming(job["text"], early_stop)+ chunk_counts.append(n_chunks)+ return audio, SAMPLE_RATE, first++ run_probe(+ _ttfa_gen,+ [{"text": dataset[i][args.text_column]} for i in sample_indices(args.ttfa_probe, len(dataset))],+ model_id=args.model_id, dataset_path=args.dataset_path,+ dataset_config=args.dataset, split=args.split,+ out_dir=model_dir, n=args.ttfa_probe,+ # segments_per_utterance == 1 means one sentence in, nothing to stream.+ extra={"device": args.device, "providers": tts.session.get_providers(), "threads": args.threads,+ "quantized": args.quantized, "segments_per_utterance": chunk_counts},+ )+ return++ done_entries = load_done_entries(manifest_path, args.resume)+ manifest_file = open_manifest(manifest_path, done_entries)++ # Serial synthesis: one sample per "batch"; warm-up runs untimed on the first pending samples.+ starts = pending_batches(dataset, 1, done_entries, dataset_dir_name)+ warm_up(lambda batch: [synth_one(t) for t in batch[args.text_column]], dataset, starts, 1, args.warmup_steps)+ set_seed(args.seed)++ # ── Main loop: synthesize one sample at a time → write JSONL ─────────────+ for i in tqdm(starts, desc="Generating"):+ sample_id = dataset[i]["id"]+ text = dataset[i][args.text_column]++ # Store the path relative to model_dir (the manifest's dir); write to the full path.+ rel_path = wav_rel_path(dataset_dir_name, sample_id)+ path = os.path.join(model_dir, rel_path)++ audio, elapsed = synth_one(text)+ sf.write(path, audio, SAMPLE_RATE)++ write_entry(manifest_file, manifest_entry(rel_path, len(audio) / SAMPLE_RATE, elapsed, text))+ manifest_file.flush()++ manifest_file.close()+ print("Results saved at path:", os.path.abspath(manifest_path))+ print_next_steps(voice_clone=False)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()++ parser.add_argument("--model_id", type=str, default=REPO,+ help="HF model id (manifest/output naming; the package pins the repo + revision).")+ parser.add_argument("--quantized", action=argparse.BooleanOptionalAction, default=True,+ help="int8 graph (the package default, 'use this one' per the model card); "+ "--no-quantized for the fp32 graph.")+ parser.add_argument("--threads", type=int, default=1,+ help="ONNX Runtime intra-op threads. Default 1 = the package default, so the "+ "model is benchmarked as shipped.")+ parser.add_argument("--speed", type=float, default=1.0, help="Speech speed multiplier.")+ add_common_args(parser)++ args = parser.parse_args()++ print("*" * 100)+ print(f"Generating TTS with {args.model_id} on {args.dataset_path} / {args.dataset} / {args.split}")+ print("*" * 100)++ main(args)diff --git a/paradee/submit_jobs.sh b/paradee/submit_jobs.shnew file mode 100755index 0000000..58b717d--- /dev/null+++ b/paradee/submit_jobs.sh@@ -0,0 +1,52 @@+#!/bin/bash+# HF Jobs TTS eval — Paradee backend (fixed voice → 2 stages: generate → transcribe → score).+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["sahilmahendrakar/Paradee-8M-v1.0" ...]+# Shared orchestration (stages 2/3, injection, logging, scoring) lives in scripts/tts_jobs_common.sh.+source "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/scripts/tts_jobs_common.sh"++# ── Backend config ───────────────────────────────────────────────────────────+TTS_SPACE="${TTS_SPACE:-bezzam/evals-paradee}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-paradee/blob/main/Dockerfile)+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.+DEFAULT_STAGES="generate transcribe" # no SIM (fixed voice)+RUN_EVAL_INJECT="$(inject_run_eval)"++# ── Device / threads ─────────────────────────────────────────────────────────+# The package ships a 1-thread CPU session; run_eval.py swaps in the CUDA EP, which is ~3x faster+# (see paradee/run_eval.py). PARADEE_DEVICE=cpu benchmarks the package's own CPU session instead.+PARADEE_DEVICE="${PARADEE_DEVICE:-cuda:0}"+PARADEE_THREADS="${PARADEE_THREADS:-1}"++# English only (one voice, misaki American English G2P).+supports_language() { [[ "$1" == "en" ]]; }++# ── Stage 1: TTS generation (no batched API — one sample at a time) ──+generate_stage() {+ hf jobs run \+ --flavor "${FLAVOR}" --timeout 8h --secrets HF_TOKEN ${NAMESPACE_ARG} \+ --volume "hf://buckets/${RESULTS_BUCKET}:/results" "${TTS_IMAGE}" \+ bash -c "+ ${RUN_EVAL_INJECT}+ cd /app/paradee && python run_eval.py \+ --model_id=${MODEL_ID} \+ --dataset_path=${DATASET_PATH} \+ --dataset=${DATASET} \+ --split=${SPLIT} \+ --device=${PARADEE_DEVICE} \+ --threads=${PARADEE_THREADS} \+ --max_eval_samples=${MAX_EVAL_SAMPLES} &&+ mkdir -p /results &&+ cp -r results/${MODEL_SAFE} /results/+ "+}++# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment) ──+DATASET_CONFIGS=(+ "tts en en"+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"+)++# ── Models: "model_id" (CLI args override) ───────────────────────────────────+MODEL_CONFIGS=("sahilmahendrakar/Paradee-8M-v1.0")+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")++run_pipelinediff --git a/submit_ttfa_jobs.sh b/submit_ttfa_jobs.shindex 4696c46..e212fe6 100755--- a/submit_ttfa_jobs.sh+++ b/submit_ttfa_jobs.sh@@ -128,6 +128,8 @@ TTFA_TARGETS=(# is whole-utterance and is what the leaderboard's WER/RTFx are measured on."neutts-nano-gguf|neutts-nano|bezzam/evals-neutts|neuphonic/neutts-nano-q8-gguf|""omnivoice|omnivoice|bezzam/evals-omnivoice|k2-fsa/OmniVoice|--language=${TTFA_LANG}"+ # ONNX Runtime: the CUDA EP on the GPU flavor; TTFA_DEVICE=cpu runs the package's own 1-thread CPU session.+ "paradee|paradee|bezzam/evals-paradee|sahilmahendrakar/Paradee-8M-v1.0|""pocket-tts|pocket-tts|bezzam/evals-pocket|kyutai/pocket-tts|--language=${TTFA_LANG}""qwen3tts|qwen3tts|bezzam/evals-qwentts|Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice|--speaker=Aiden --mode=custom_voice --language=${TTFA_LANG}"# The same checkpoint under andimarafioti/faster-qwen3-tts (CUDA graphs, incremental audio).@@ -185,7 +187,7 @@ TTFA_TARGETS=()# Backends whose run_eval.py has no --voice_clone flag at all; passing one would be an error.-NO_CLONE_FLAG="inflect-nano inflect-v2 kokoro lfm2-audio magpie-tts photon qwen3tts qwen3tts-fast supertonic vibevoice_realtime voxtral-tts"+NO_CLONE_FLAG="inflect-nano inflect-v2 kokoro lfm2-audio magpie-tts paradee photon qwen3tts qwen3tts-fast supertonic vibevoice_realtime voxtral-tts"submit_one() {local backend="$1" space="$2" model_id="$3" extra="$4" engine="$5"