Skip to content

Evaluation scripts for the Open TTS Leaderboard: https://huggingface.co/spaces/hf-audio/open_tts_leaderboard

Python

Initial commit of eval scripts.

Eric B1645e63016f0
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 0000000..f73b88d
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,30 @@
+## 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`)
+- License:
+- Voice cloning: yes / no
+- Batch inference: yes / 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 -->
+
+### Results
+<!-- Paste the "Results per dataset" / "Composite Results" block printed at the end of submit_jobs.sh -->
+
+```
+```
+
+### Checklist
+- [ ] `run_eval.py` and `submit_jobs.sh` follow the structure of the existing backends (see README, "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
+- [ ] (Optional) `--ttfa_probe` implemented and target added to `submit_ttfa_jobs.sh`
diff --git a/.gitignore b/.gitignore
index 83972fa..badf68f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,6 @@
+*.jsonl
+*.json
+
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[codz]
@@ -216,3 +219,10 @@ __marimo__/
# Streamlit
.streamlit/secrets.toml
+
+# Backend Dockerfiles live in their HF Docker Spaces (bezzam/evals-*), not in this repo
+Dockerfile
+Dockerfile.*
+
+# Backend Dockerfiles live in their HF Spaces, not in this repo.
+Dockerfile
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..1694272
--- /dev/null
+++ b/README.md
@@ -0,0 +1,279 @@
+# Open TTS Leaderboard
+
+This repository contains the code for the Open TTS Leaderboard. The leaderboard is a Gradio Space that allows users to compare TTS models on a variety of datasets. The leaderboard is hosted at [hf-audio/open_tts_leaderboard](https://huggingface.co/spaces/hf-audio/open_tts_leaderboard).
+
+[Hugging Face Jobs](https://huggingface.co/docs/hub/en/jobs) are used to launch evaluations in a reproducible manner. Each model family contains its own model folder with the necessary scripts for launching the evaluation.
+
+The following datasets are used in the Open TTS Leaderboard:
+1. [Seed TTS Eval](https://github.com/BytedanceSpeech/seed-tts-eval) (`tts` config): `en` (English) and `zh` (Chinese).
+2. [CV3 Eval](https://github.com/QwenAudio/CV3-Eval): `en`, `zh`, `fr` (French), `es` (Spanish), `ja` (Japanese), `ko` (Korean), `it` (Italian), `de` (German), and `ru` (Russian) (`zero_shot` config, 500 samples per language).
+
+While human preference is the ultimate decider, **arenas cannot scale to keep up with the pace of TTS releases**. To this end, we use objective metrics to evaluate models on complementary aspects of performance:
+
+1. **Intelligibility**: word/character error rate (WER and CER) between the target text and the generated audio's transcript, using [Qwen3 ASR](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) (top ranking open-source model on the [Open ASR Leaderboard](https://huggingface.co/spaces/hf-audio/open_asr_leaderboard)).
+2. **Speed**: inverse real-time factor (RTFx) for batched offline inference on an H200 GPU, and time-to-first-audio (TTFA) for quantifying streaming batch size 1 latency on an A100 GPU and CPU.
+3. **Speaker similarity** by computing the cosine similarity (SIM) between [WavLM speaker embeddings](https://huggingface.co/bezzam/wavlm_large_finetune_seed_tts_eval) of the generated audio and the reference clip. Note that not all models support voice cloning, so those models are omitted from this evaluation.
+
+By relying on objective metrics **evaluating a model drops from a couple weeks (for collecting votes) to a couple hours** ⚡
+
+Our intention with this leaderboard is for it to be **shaped by the community**; we want to hear your feedback so the evaluations stay relevant and insightful.
+
+## Setup for running evaluations
+
+#### 1. Hugging Face account:
+- Create an account at https://huggingface.co/ and add credits for HF Jobs: https://huggingface.co/settings/billing
+- Create a [WRITE token](https://huggingface.co/settings/tokens/new?tokenType=write) and add it as an environment variable
+```bash
+echo 'export HF_TOKEN="your_token_here"' >> ~/.bashrc
+source ~/.bashrc
+# double-check it got added
+tail -n 3 ~/.bashrc
+```
+- Create a Storage Bucket to store results: https://huggingface.co/new-bucket
+
+#### 2. Create a virtual environment for launching HF Jobs:
+```
+# Clone the repository
+git clone [email protected]:ebezzam/open-tts-leaderboard.git
+cd open-tts-leaderboard
+
+# Create environment, e.g. with conda
+conda create -n tts_leaderboard python=3.12 -y
+conda activate tts_leaderboard
+(tts_leaderboard) pip install -r requirements.txt
+```
+
+#### 3. Prepare the (private) datasets
+
+Unfortunately the licenses of [Seed TTS](https://github.com/BytedanceSpeech/seed-tts-eval) and [CV3](https://github.com/QwenAudio/CV3-Eval) do not allow us to redistribute the datasets. However, the following scripts can be used to make personal (private) copies so that they are compatible with our evaluation scripts.
+```
+# seed tts eval
+# -- download
+(tts_leaderboard) pip install gdown
+(tts_leaderboard) gdown 1GlSjVfSHkW3-leKKBlfrjuuTGqQ_xaLP -O seedtts_testset.tar
+(tts_leaderboard) tar -xf seedtts_testset.tar
+# -- upload to your account on HF
+(tts_leaderboard) python scripts/prepare_seed_tts_eval.py YOUR_USERNAME/seed_tts_eval
+
+# cv3 eval
+# -- download
+(tts_leaderboard) git clone [email protected]:QwenAudio/CV3-Eval.git
+# -- upload to your account on HF
+(tts_leaderboard) python scripts/prepare_cv3_eval.py YOUR_USERNAME/cv3_eval
+```
+Keep the repo names (`seed_tts_eval`, `cv3_eval`) as above, so that `DATASET_NAMESPACE=YOUR_USERNAME` points every job at your copies.
+
+
+#### 4. Smoke test
+
+A quick smoke test (Transformers backend, single model, 8 samples of the English datasets) can verify that your setup is working:
+
+```bash
+DATASET_NAMESPACE="YOUR_USERNAME" \
+RESULTS_BUCKET="YOUR_USERNAME/your_bucket_name" \
+MAX_EVAL_SAMPLES=8 ONLY_LANGS="en" \
+bash transformers/submit_jobs.sh "facebook/seamless-m4t-v2-large 32 "
+
+### EXAMPLE OUTPUT
+********************************************************************************
+Results per dataset:
+********************************************************************************
+facebook/seamless-m4t-v2-large | bezzam-cv3_eval_zero_shot_en: WER = 4.55 %, RTFx = 23.01
+facebook/seamless-m4t-v2-large | bezzam-seed_tts_eval_tts_en: WER = 0.00 %, RTFx = 19.46
+
+********************************************************************************
+Composite Results:
+********************************************************************************
+facebook/seamless-m4t-v2-large: WER = 2.27 %
+facebook/seamless-m4t-v2-large: RTFx = 21.19
+********************************************************************************
+```
+
+
+## Batch evaluation (main tab)
+
+Each model family has its own folder (e.g. [kokoro/](kokoro/), [voxcpm2/](voxcpm2/), [transformers/](transformers/)) with a `submit_jobs.sh` that is run **locally** and submits HF Jobs to HF servers. The orchestration shared by all backends lives in [scripts/tts_jobs_common.sh](scripts/tts_jobs_common.sh).
+
+For each (model, dataset split) pair, the pipeline runs three sequential HF Jobs (two if the model is not voice cloning), followed by scoring on your machine. The splits of a model run in parallel; models run one after another.
+
+```mermaid
+flowchart LR
+ subgraph local["<big><b>Your machine</b></big>"]
+ submit["&lt;backend&gt;/submit_jobs.sh"]
+ score["<b>4. Score</b><br/>WER/CER · RTFx · SIM"]
+ end
+
+ subgraph jobs["<big><b>HF Jobs (per model × split)</b></big>"]
+ gen["<b>1. Generate</b><br/>&lt;backend&gt;/run_eval.py · H200"]
+ asr["<b>2. Transcribe</b><br/>Qwen3-ASR · L4"]
+ sim["<b>3. Speaker similarity</b><br/>WavLM-SV · L4"]
+ end
+
+ ds[("Private datasets<br/>seed_tts_eval / cv3_eval")]
+ bucket[("RESULTS_BUCKET<br/>wavs + JSONL manifests")]
+
+ submit --> gen --> asr -->|voice cloning only| sim
+ ds --> gen
+ gen -->|wavs + manifest| bucket
+ asr <-->|pred_text| bucket
+ sim <-->|sim| bucket
+ bucket -->|manifests only| score
+```
+
+1. **Generate** (`generate`): the backend's `run_eval.py` synthesizes every sample of the split and writes the wavs plus a JSONL manifest to `RESULTS_BUCKET`, in a folder per model.
+2. **Transcribe** (`transcribe`): [transformers/transcribe.py](transformers/transcribe.py) transcribes the wavs with [Qwen3-ASR-1.7B](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf), using the split's language as a hint.
+3. **Speaker similarity** (`sim`, voice cloning only): [transformers/score_similarity.py](transformers/score_similarity.py) compares each generated clip with its reference prompt, using the [Seed TTS Eval](https://github.com/BytedanceSpeech/seed-tts-eval#metrics) speaker-verification model (WavLM-large + ECAPA-TDNN, mirrored [here](https://huggingface.co/bezzam/wavlm_large_finetune_seed_tts_eval)).
+4. **Score** (on your machine): the model's manifests are synced to `./results/<model>` and scored per language:
+ - **WER** after text normalization (CER for `zh`, `ja`, `ko`)
+ - **RTFx**: total audio duration divided by total generation time, measured in stage 1
+ - **SIM**: mean speaker similarity, for voice cloning only
+
+The stages are separate jobs because the TTS, ASR and speaker-similarity models have conflicting dependencies: stage 1 uses the backend's own Docker Space image, and stages 2 and 3 share [bezzam/evals](https://huggingface.co/spaces/bezzam/evals).
+
+| Stage | Flavor | Hardware |
+|---|---|---|
+| 1. Generate | `h200` | 1x Nvidia H200 (141 GB) |
+| 2. Transcribe | `l4x1` | 1x Nvidia L4 (24 GB) |
+| 3. Speaker similarity | `l4x1` | 1x Nvidia L4 (24 GB) |
+
+RTFx is measured in stage 1, so every model is generated on the **same** flavor (`h200`); don't override `FLAVOR` in a backend. See the [HF Jobs documentation](https://huggingface.co/docs/huggingface_hub/main/en/guides/jobs#select-the-hardware) for pricing.
+
+All outputs are written to the bucket set by `RESULTS_BUCKET` (default: the official [hf-audio/tts_leaderboard_h200](https://huggingface.co/buckets/hf-audio/tts_leaderboard_h200)).
+
+Useful environment variables (see [scripts/tts_jobs_common.sh](scripts/tts_jobs_common.sh) for all of them):
+
+| Variable | Default | Purpose |
+|---|---|---|
+| `DATASET_NAMESPACE` | `bezzam` | Namespace holding your private `seed_tts_eval` / `cv3_eval` copies |
+| `RESULTS_BUCKET` | `hf-audio/tts_leaderboard_h200` | Bucket the jobs write to |
+| `MAX_EVAL_SAMPLES` | `-1` (all) | Cap samples per split, e.g. `8` for a smoke test |
+| `ONLY_LANGS` | (all) | Only run the configured splits for these languages, e.g. `"en zh"` |
+| `STAGES` | `generate transcribe sim` | Subset of stages, e.g. `"transcribe sim"` to re-score existing wavs |
+| `VOICE_CLONE` | `false` | Clone the prompt speaker (backends that support both modes) |
+| `ASR_OVERWRITE` / `SIM_OVERWRITE` | `false` | Recompute `pred_text` / `sim` instead of resuming. **Set `SIM_OVERWRITE=true` after regenerating audio**, otherwise old SIM scores are carried over |
+| `ORG_NAME` | (none) | Run the jobs under an organization's namespace |
+
+Examples:
+```bash
+# all configured models + splits of a backend
+bash kokoro/submit_jobs.sh
+
+# a specific model (overrides the backend's MODEL_CONFIGS; format is backend-specific)
+VOICE_CLONE=true bash transformers/submit_jobs.sh "vibevoice/VibeVoice-1.5B-hf 32 512"
+
+# re-score a local copy of the manifests, e.g. for one language
+python scripts/score_model.py --model_id hexgrad/Kokoro-82M --language en
+```
+
+Job logs are written to `<backend>/job_logs/`. Live status is at https://huggingface.co/settings/jobs.
+
+#### Publishing results
+
+The leaderboard reads its CSVs from [hf-audio/tts_leaderboard_results](https://huggingface.co/datasets/hf-audio/tts_leaderboard_results) (private dataset). [scripts/open_results_pr.py](scripts/open_results_pr.py) scores the bucket manifests the same way as above and opens a PR on that repo with the model's rows. Without `--open_pr` it is a dry run:
+```bash
+python scripts/open_results_pr.py --model_id openbmb/VoxCPM2 \
+ --license apache-2.0 --voice_cloning yes --batch_inference no \
+ --num_languages 9 --model_size_b 0.5 --transformers no --open_pr
+```
+
+
+## Adding a new model
+
+**PROTIP**: Ask your agent to make a new folder to evaluate the new model, and link a documentation page with usage. Ask it to use batch inference if possible and to implement the TTFA probe if the model supports streaming. If you give it permission to your HF account, ask it to make an HF space to run the model via HF jobs, taking inspiration from one of the existing configuration [here](https://huggingface.co/collections/bezzam/tts-eval).
+
+1. **Create the environment image.** Create a **public** [Docker Space](https://huggingface.co/new-space?sdk=docker) (HF Jobs can't pull private ones), e.g. `YOUR_USERNAME/evals-<backend>`, whose `Dockerfile` installs the model's dependencies. It only needs the Dockerfile; the eval scripts are injected at runtime. See the existing Spaces [here](https://huggingface.co/collections/bezzam/tts-eval). Models that run with `transformers` can instead be added to the [transformers/](transformers/) backend.
+2. **Write `<backend>/run_eval.py`**, which evaluates one dataset split. The shared helpers in [scripts/run_eval_utils.py](scripts/run_eval_utils.py) handle the parts common to every backend, so the script mostly contains the model-specific code. It should:
+ - synthesize the `text` column, cloning from `prompt_audio` / `prompt_text` when `--voice_clone` is set (off by default)
+ - time generation only, after `--warmup_steps` untimed warm-up batches (default 2), so RTFx is fair
+ - write the wavs and a manifest with the shared helpers
+ - optionally support `--ttfa_probe N` so the model can be included in the [TTFA evaluation](#time-to-first-audio-streaming-evaluation)
+
+ [kokoro/run_eval.py](kokoro/run_eval.py) is a short fixed-voice example, and [voxcpm2/run_eval.py](voxcpm2/run_eval.py) is a voice-cloning example.
+3. **Write `<backend>/submit_jobs.sh`**, which sources [scripts/tts_jobs_common.sh](scripts/tts_jobs_common.sh) and then:
+ - sets `TTS_SPACE` (your Docker Space) and `RUN_EVAL_INJECT="$(inject_run_eval)"`
+ - defines `generate_stage()`, the `hf jobs run` command for stage 1
+ - sets `SUPPORTS_VOICE_CLONE=true` if the model can clone, and optionally defines `supports_language()` to skip splits the model can't synthesize
+ - sets `DATASET_CONFIGS` and `MODEL_CONFIGS`, then calls `run_pipeline`
+4. **Smoke test** with `MAX_EVAL_SAMPLES=8 ONLY_LANGS="en" bash <backend>/submit_jobs.sh`, then run the full evaluation.
+5. **Open a PR** on this repository with the new backend folder, using the [pull request template](.github/pull_request_template.md). Include the scores printed at the end of the run. A maintainer will then publish the results to the leaderboard with `scripts/open_results_pr.py`.
+
+
+## Time-to-first audio (streaming) evaluation
+
+Time-to-first-audio (TTFA) measures how long a caller waits before it has audio it can start playing:
+- models that stream: time from the request to the first audio chunk
+- models that don't stream: time from the request until generation finishes, because playback can't start any earlier
+
+[submit_ttfa_jobs.sh](submit_ttfa_jobs.sh) launches one HF Job per entry in `TTFA_TARGETS`. Each job runs the backend's own `run_eval.py` with `--ttfa_probe`, so it measures the same code path as the main eval. Every model uses the same settings so the numbers are comparable:
+- **batch size 1**, because TTFA is a per-request latency
+- **the full split** of **CV3-Eval `zero_shot/en`** (500 samples). The first 3 are discarded as warm-up, and TTFA is reported as p50, p90 and p95.
+- **no voice cloning** (`VOICE_CLONE=false`): each model uses its own default voice
+- **`a100-large`** (1x Nvidia A100, 80 GB) for GPU, and **`cpu-upgrade`** (8 vCPU, 32 GB) with `TTFA_DEVICE=cpu`.
+
+```mermaid
+flowchart LR
+ subgraph local["<big><b>Your machine</b></big>"]
+ submit["<b>1. Submit</b><br/>submit_ttfa_jobs.sh"]
+ summary["<b>4. Summary</b><br/>printed from job logs"]
+ publish["<b>5. Publish</b><br/>scripts/open_results_pr.py"]
+ end
+
+ subgraph job["<big><b>HF Job (per target)</b></big>"]
+ server["<b>2. Start server</b><br/>vLLM / SGLang backends only"]
+ probe["<b>3. Probe</b><br/>&lt;backend&gt;/run_eval.py --ttfa_probe<br/>batch size 1 · A100 or CPU"]
+ end
+
+ ds[("cv3_eval<br/>zero_shot/en · 500 samples")]
+ bucket[("RESULTS_BUCKET<br/>JSON sidecar")]
+ lb[("hf-audio/tts_leaderboard_results<br/>streaming CSV")]
+
+ submit --> server -->|ready| probe
+ submit -.->|in-process backends| probe
+ ds --> probe
+ probe -->|JSON sidecar| bucket
+ probe -->|job log| summary
+ bucket --> publish -->|PR| lb
+```
+
+The probe only writes a small JSON file to the model's bucket folder (no wavs or manifests), so it is safe to run for models that already have results. GPU, CPU and alternative-engine results are kept side by side.
+
+```bash
+# all targets in TTFA_TARGETS
+bash submit_ttfa_jobs.sh
+# selected backends / labels / model ids
+bash submit_ttfa_jobs.sh kokoro breeze-tts
+# on CPU
+TTFA_DEVICE=cpu bash submit_ttfa_jobs.sh kokoro
+```
+
+To add a model, implement `--ttfa_probe` in its `run_eval.py` (see [scripts/ttfa_probe.py](scripts/ttfa_probe.py)) and add it to `TTFA_TARGETS` in [submit_ttfa_jobs.sh](submit_ttfa_jobs.sh).
+
+The leaderboard reports the p50 and p95 TTFA and the batch-1 RTFx (`python scripts/open_results_pr.py --model_id <model> --targets streaming`). **Batch-1 RTFx is not the leaderboard RTFx**, which is measured at each backend's real batch size.
+
+
+## Citation
+
+If you use the Open TTS Leaderboard, please cite it along with the benchmarks it evaluates on:
+
+```bibtex
+@misc{open_tts_leaderboard,
+ title={Open TTS Leaderboard},
+ author={Bezzam, Eric and others},
+ year={2026},
+ url={https://huggingface.co/spaces/hf-audio/open_tts_leaderboard},
+}
+
+@article{anastassiou2024seedtts,
+ title = {Seed-TTS: A Family of High-Quality Versatile Speech Generation Models},
+ author = {Anastassiou, Philip and others},
+ journal = {arXiv preprint arXiv:2406.02430},
+ year = {2024}
+}
+
+@article{du2025cosyvoice3,
+ title = {CosyVoice 3: Towards In-the-wild Speech Generation via Scaling-up and Post-training},
+ author = {Du, Zhihao and others},
+ journal = {arXiv preprint arXiv:2505.17589},
+ year = {2025}
+}
+```
diff --git a/audiocpp/run_eval.py b/audiocpp/run_eval.py
new file mode 100644
index 0000000..2c45989
--- /dev/null
+++ b/audiocpp/run_eval.py
@@ -0,0 +1,464 @@
+"""
+Time-to-first-audio probe for the Open TTS Leaderboard (audio.cpp backend).
+
+0xShug0/audio.cpp (https://github.com/0xShug0/audio.cpp) is a ggml C++ runtime whose
+`audiocpp_server` streams many TTS families over an OpenAI-style SSE endpoint. Some are a second
+ENGINE for models the leaderboard already evaluates (VoxCPM2, Supertonic, Pocket TTS, Breeze); the
+rest are only available here (see FAMILIES).
+
+ POST /v1/audio/speech {"model": ..., "input": ..., "stream_format": "sse", "response_format": "pcm"}
+ -> data: {"type": "speech.audio.delta", "audio": "<base64 PCM16 mono>"} (repeated)
+ -> data: {"type": "speech.audio.done", "timing": {"ttft_ms": ...}}
+ -> data: [DONE]
+
+The job runs the server itself: this script installs the model's GGUF package with
+`audiocpp_model_manager`, writes a one-model server config with `mode: "streaming"`, starts
+`audiocpp_server`, and is then a plain HTTP client of it. First audio = the first non-empty
+`speech.audio.delta` reaching the client, so the clock includes the (loopback) transport.
+
+Only families audio.cpp STREAMS are registered. Notably NOT Qwen3-TTS: audio.cpp's qwen3_tts is
+offline-only (model_specs/qwen3_tts.json lists `"modes": ["offline"]`). Some registered families
+(Supertonic, OmniVoice) "stream" one event per TEXT chunk, so a CV3 sentence arrives as one event;
+the probe reports those as not streaming, which is the honest label. Left out: segment-level,
+clone-only ports (ZipVoice, Sopro), MiraTTS (no published package), PersonaPlex (speech-to-speech).
+
+Packages are the full-precision GGUFs (bf16 / f16 / orig) where one is published, not the Q8
+defaults: a quantized model is a different model. Audio8 and VoxCPM1 publish only Q8_0; the
+package is recorded in the sidecar.
+
+Voice mode: --voice_clone sends each row's prompt_audio/prompt_text as the reference. Clone-only
+families (Confucius4) always clone; their sidecar then carries the `_voice_clone` suffix, so it
+is never mixed up with a fixed-voice number.
+
+TTFA only: audio.cpp's audio is not what the eval scores, so running without --ttfa_probe is
+refused. Sidecars are engine-tagged "audiocpp" by submit_ttfa_jobs.sh.
+"""
+
+import argparse
+import base64
+import io
+import json
+import os
+import subprocess
+import tempfile
+import time
+import wave
+
+import requests
+
+from run_eval_utils import add_common_args, load_tts_dataset, set_seed
+
+AUDIOCPP_DIR = os.environ.get("AUDIOCPP_DIR", "/app") # binaries of the ghcr.io/0xshug0/audio.cpp image
+
+# Leaderboard model id -> how audio.cpp serves it. Request fields mirror the reference backend's
+# defaults (its run_eval.py / the TTFA_TARGETS entry), so only the engine differs.
+FAMILIES = {
+ "openbmb/VoxCPM2": {
+ "family": "voxcpm2",
+ "package": "voxcpm2_bf16",
+ # voxcpm2/run_eval.py: cfg_value 2.0, inference_timesteps 10, no voice (plain TTS).
+ # retry_badcase must be off: retrying a finished bad case is offline-only.
+ "request": {"guidance_scale": 2.0, "num_inference_steps": 10},
+ "options": {"retry_badcase": "false"},
+ },
+ "Supertone/supertonic-3": {
+ "family": "supertonic",
+ "clone": False, # preset voices only
+ "package": "supertonic_3_orig",
+ # supertonic/run_eval.py: voice M1, total_steps 8, speed 1.05.
+ "request": {"voice": "M1", "num_inference_steps": 8, "speed": 1.05},
+ "language": True,
+ },
+ "kyutai/pocket-tts": {
+ "family": "pocket_tts",
+ # English only: other languages are separate packages (and models).
+ "package": "pocket_tts_english_bf16",
+ # pocket-tts/run_eval.py: English default voice `alba`; sampling left at the engine's defaults.
+ "request": {"voice": "alba"},
+ },
+ "BreezeBlue/Breeze-TTS-2": {
+ "family": "breeze_tts",
+ "package": "breeze_tts_2_bf16",
+ # breeze-tts/run_eval.py: reference-free voice design from a neutral per-language instruction
+ # (filled in main()), cfg 1.0. The streaming chunking is pinned to audio.cpp's defaults
+ # because it sets the TTFA floor; it is recorded in the sidecar.
+ "request": {"guidance_scale": 1.0},
+ "options": {"stream_frames_per_event": "16", "stream_lookahead_margin": "12"},
+ "instructions": {"en": "Speak clearly and naturally.", "zh": "请用清晰自然的语气朗读。"},
+ # Prompt-audio cloning is a separate task ("clon") for this family.
+ "clone_task": "clon",
+ },
+ "k2-fsa/OmniVoice": {
+ "family": "omnivoice",
+ "package": "omnivoice_bf16",
+ # omnivoice/run_eval.py: auto voice, num_step 32. One stream event per text chunk.
+ "request": {"num_inference_steps": 32},
+ "language": True,
+ },
+ # ── Not on the leaderboard: audio.cpp's streaming families, at their documented defaults ──
+ "kugelaudio/kugelaudio-0-open": {
+ "family": "kugelaudio",
+ "clone": False, # preset voices only
+ "package": "kugelaudio_0_open_bf16",
+ # `default`/`clear` are German voices; English text gets the British English preset.
+ "options": {"voice_id": "english_female"},
+ },
+ "neuphonic/neutts-2e": {
+ "family": "neutts",
+ "clone": False, # preset voices only
+ "package": "neutts_2e_orig",
+ "options": {"voice_id": "emily"},
+ },
+ "Edge0/Audio8-TTS-Preview-0.6b": {
+ "family": "audio8_tts",
+ "package": "audio8_tts_preview_0_6b_q8_0", # the only published package
+ },
+ "LiquidAI/LFM2.5-Audio-1.5B": {
+ "family": "lfm2_audio",
+ "clone": False, # preset voices only
+ "package": "lfm2_audio_1_5b_f16",
+ "request": {"voice": "us_female"},
+ # Two GGUFs (model + mmproj) with no embedded config: the server loads the package DIRECTORY.
+ "path": "dir",
+ },
+ "ekwek/Soprano-1.1-80M": {
+ "family": "soprano_tts",
+ "clone": False, # preset voices only
+ "package": "soprano_1_1_80m_bf16",
+ },
+ "openbmb/VoxCPM-0.5B": {
+ "family": "voxcpm1",
+ "package": "voxcpm1_0_5b_q8_0", # the only published package
+ "options": {"retry_badcase": "false"},
+ },
+ "dots-studio/dots.tts-soar": {
+ "family": "dots_tts",
+ "package": "dots_tts_soar_bf16",
+ },
+ "dots-studio/dots.tts-mf": {
+ "family": "dots_tts",
+ "package": "dots_tts_mf_bf16",
+ },
+ "netease-youdao/Confucius4-TTS": {
+ "family": "confucius4_tts",
+ "package": "confucius4_tts_orig",
+ "language": True,
+ "clone_only": True,
+ "clone_task": "clon",
+ "reference_text": False, # rejected as an unknown option: it clones from the audio alone
+ },
+}
+
+
+def _package_model_path(models_dir, family, package, as_dir=False):
+ """Install `package` (idempotent) and return the path of its .gguf (its directory if `as_dir`).
+
+ The file comes from the image's own model_specs/<family>.json (package `files` are relative to
+ the models root), so it always matches the binaries the job runs.
+ """
+ with open(os.path.join(AUDIOCPP_DIR, "model_specs", f"{family}.json"), encoding="utf-8") as f:
+ packages = {p["id"]: p for p in json.load(f)["packages"]}
+ if package not in packages:
+ raise SystemExit(f"No package {package!r} for family {family}; available: {sorted(packages)}")
+ gguf = [p for p in packages[package]["files"] if p.endswith(".gguf")]
+ if not gguf or (len(gguf) > 1 and not as_dir):
+ raise SystemExit(f"Expected one .gguf in package {package}, got {gguf}")
+
+ cmd = [os.path.join(AUDIOCPP_DIR, "audiocpp_model_manager"), "install", package, "--models-dir", models_dir]
+ print("$", " ".join(cmd), flush=True)
+ t0 = time.perf_counter()
+ # Retried: large downloads from the model host occasionally drop the connection.
+ for attempt in range(1, 4):
+ if subprocess.run(cmd, cwd=AUDIOCPP_DIR).returncode == 0:
+ break
+ if attempt == 3:
+ raise SystemExit(f"audiocpp_model_manager install {package} failed 3 times.")
+ print(f"install attempt {attempt} failed; retrying in {30 * attempt}s", flush=True)
+ time.sleep(30 * attempt)
+ print(f"installed {package} in {time.perf_counter() - t0:.1f}s", flush=True)
+
+ # Some packages install under a directory their spec does not name (e.g. Audio8's
+ # `Audio8-TTS-Preview-0.6B-GGUF/`), so fall back to finding the file by name.
+ path = os.path.join(models_dir, gguf[0])
+ if not os.path.exists(path):
+ found = [os.path.join(root, os.path.basename(gguf[0]))
+ for root, _, files in os.walk(models_dir) if os.path.basename(gguf[0]) in files]
+ if len(found) != 1:
+ raise SystemExit(f"Package {package} should provide {gguf[0]}; found {found} under {models_dir}.")
+ path = found[0]
+ return os.path.dirname(path) if as_dir else path
+
+
+def _start_server(args, cfg, model_path, workdir, task):
+ """Write a one-model streaming config, start audiocpp_server, wait for /health. Returns the Popen."""
+ backend = "cpu" if args.device == "cpu" else "cuda"
+ device = int(args.device.split(":", 1)[1]) if args.device.startswith("cuda:") else 0
+ # CPU: one worker per vCPU of the job's quota (submit_ttfa_jobs.sh exports OMP_NUM_THREADS from
+ # the cgroup). GPU: the CLI default; the compute is on the device.
+ threads = args.threads
+ if not threads:
+ threads = (int(os.environ.get("OMP_NUM_THREADS") or 0) or os.cpu_count()) if backend == "cpu" else 4
+ config = {
+ "host": "127.0.0.1",
+ "port": args.port,
+ "backend": backend,
+ "device": device,
+ "threads": threads,
+ # Load at startup, so /health means "ready" and the first timed row pays no load.
+ "lazy_load": False,
+ "models": [{
+ "id": "probe",
+ "family": cfg["family"],
+ "path": model_path,
+ "task": task,
+ "mode": "streaming",
+ }],
+ }
+ config_path = os.path.join(workdir, "server.json")
+ with open(config_path, "w", encoding="utf-8") as f:
+ json.dump(config, f, indent=1)
+ print("server config:", json.dumps(config), flush=True)
+
+ log_path = os.path.join(workdir, "server.log")
+ log = open(log_path, "w", encoding="utf-8")
+ proc = subprocess.Popen(
+ [os.path.join(AUDIOCPP_DIR, "audiocpp_server"), "--config", config_path, "--no-ui"],
+ cwd=AUDIOCPP_DIR, stdout=log, stderr=subprocess.STDOUT,
+ )
+ base_url = f"http://127.0.0.1:{args.port}"
+ deadline = time.time() + args.server_startup_timeout
+ while time.time() < deadline:
+ if proc.poll() is not None:
+ log.flush()
+ with open(log_path, encoding="utf-8", errors="replace") as f:
+ print("--- audiocpp_server log (full) ---\n" + f.read())
+ raise SystemExit(f"audiocpp_server exited with code {proc.returncode} before becoming healthy.")
+ try:
+ if requests.get(f"{base_url}/health", timeout=5).status_code == 200:
+ print(f"audiocpp_server healthy at {base_url} (backend={backend}, threads={threads})", flush=True)
+ return proc, base_url, log_path, threads
+ except requests.RequestException:
+ pass
+ time.sleep(2)
+ proc.kill()
+ raise SystemExit(f"audiocpp_server not healthy after {args.server_startup_timeout}s — see {log_path}")
+
+
+def main(args):
+ if args.ttfa_probe == 0:
+ raise SystemExit(
+ "This backend is TTFA-only: pass --ttfa_probe=N (or -1 for the whole split).\n"
+ "audio.cpp re-implements inference in ggml, so its audio is not the audio the\n"
+ "leaderboard's WER/RTFx are scored from. Use the model's own backend for those."
+ )
+ if args.model_id not in FAMILIES:
+ raise SystemExit(f"{args.model_id} is not registered for audio.cpp streaming. "
+ f"Registered: {sorted(FAMILIES)} (see the module docstring for what is not).")
+ cfg = FAMILIES[args.model_id]
+ package = args.package or cfg["package"]
+ set_seed(args.seed)
+
+ # Clone-only families always clone (their sidecar is suffixed `_voice_clone`, so it never
+ # passes for a fixed-voice number).
+ # Fixed-voice families ignore --voice_clone, like the other backends without a clone mode.
+ voice_clone = cfg.get("clone_only", False) or (args.voice_clone and cfg.get("clone", True))
+ if voice_clone != args.voice_clone:
+ print(f"NOTE: {cfg['family']} {'only clones' if voice_clone else 'has no clone mode'}; "
+ f"probing with voice_clone={voice_clone}.")
+ task = cfg.get("clone_task", "tts") if voice_clone else "tts"
+ mode_suffix = "_voice_clone" if voice_clone else ""
+
+ # Loaded BEFORE the server so a dataset problem fails fast. Audio is left undecoded (no
+ # torchcodec in this image): the reference is sent to the server as the original file bytes.
+ dataset = load_tts_dataset(
+ args, extra_columns=("prompt_audio", "prompt_text") if voice_clone else (), decode_audio=False)
+
+ # Imported HERE, not at module scope: the probe module is injected only by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+
+ def _reference(row):
+ """(base64 WAV, transcript) of a row's prompt, converted with ffmpeg if it is not a WAV."""
+ audio = row["prompt_audio"]
+ data = audio.get("bytes")
+ if data is None:
+ with open(audio["path"], "rb") as f:
+ data = f.read()
+ if data[:4] != b"RIFF":
+ data = subprocess.run(["ffmpeg", "-loglevel", "error", "-i", "pipe:0", "-f", "wav", "pipe:1"],
+ input=data, capture_output=True, check=True).stdout
+ return base64.b64encode(data).decode("ascii"), row["prompt_text"]
+
+ jobs = []
+ for i in sample_indices(args.ttfa_probe, len(dataset)):
+ row = dataset[i]
+ job = {"text": row[args.text_column]}
+ if voice_clone:
+ job["ref"] = _reference(row)
+ jobs.append(job)
+
+ workdir = tempfile.mkdtemp(prefix="audiocpp_")
+ model_path = _package_model_path(args.models_dir, cfg["family"], package, as_dir=cfg.get("path") == "dir")
+ proc, base_url, log_path, threads = _start_server(args, cfg, model_path, workdir, task)
+
+ try:
+ version = subprocess.run([os.path.join(AUDIOCPP_DIR, "audiocpp_server"), "--version"],
+ capture_output=True, text=True, timeout=30).stdout.strip() or None
+ except Exception: # noqa: BLE001 — diagnostics only
+ version = None
+ print(f"audio.cpp server version: {version}, image: {os.environ.get('AUDIOCPP_IMAGE')}")
+
+ def _body(text, stream, ref=None):
+ body = {"model": "probe", "input": text, "seed": args.seed, **cfg.get("request", {})}
+ options = dict(cfg.get("options", {}))
+ if "instructions" in cfg:
+ body["instructions"] = cfg["instructions"].get(args.language, cfg["instructions"]["en"])
+ if cfg.get("language"):
+ body["language"] = args.language
+ if ref is not None:
+ # The row's own prompt replaces any preset voice, as in the reference backends' clone mode.
+ body.pop("voice", None)
+ options.pop("voice_id", None)
+ body["voice_ref"] = {"type": "base64", "data": ref[0]}
+ if cfg.get("reference_text", True):
+ body["reference_text"] = ref[1]
+ if stream:
+ body.update(stream_format="sse", response_format="pcm")
+ if options:
+ body["options"] = options
+ return body
+
+ def _post(body, stream):
+ r = requests.post(f"{base_url}/v1/audio/speech", json=body, stream=stream, timeout=args.request_timeout)
+ if r.status_code != 200:
+ with open(log_path, encoding="utf-8", errors="replace") as f:
+ tail = f.read()[-4000:]
+ raise SystemExit(f"/v1/audio/speech returned {r.status_code}: {r.text[:2000]}\n"
+ f"--- server log (tail) ---\n{tail}")
+ return r
+
+ # Clone-mode warm-up uses a prompt from OUTSIDE the probe set: the server caches prepared
+ # references, so warming up on a probed row would make that row's TTFA artificially low.
+ warm_ref = None
+ if voice_clone:
+ probed = set(sample_indices(args.ttfa_probe, len(dataset)))
+ spare = next((i for i in range(len(dataset)) if i not in probed), None)
+ warm_ref = _reference(dataset[spare]) if spare is not None else jobs[0]["ref"]
+
+ # Untimed warm-up. The NON-streaming request returns a WAV, whose header is the only place the
+ # sample rate appears (SSE deltas are bare PCM16); the streaming ones prime the streaming path.
+ r = _post(_body("Hello there, this is a warm-up sentence for the engine.", stream=False, ref=warm_ref),
+ stream=False)
+ with wave.open(io.BytesIO(r.content)) as w:
+ sample_rate, channels = w.getframerate(), w.getnchannels()
+ print(f"output: {sample_rate} Hz, {channels} channel(s)")
+ if channels != 1:
+ raise SystemExit(f"Expected mono output, got {channels} channels.")
+
+ chunk_counts = [] # audio deltas per utterance: 1 means nothing was incremental
+ server_ttft_ms = [] # the server's own first-audio clock, for comparison with the client's
+
+ def _gen(job):
+ """One streaming request at batch size 1, timestamping the first audio delta.
+
+ Always a full generation (no early_stop parameter): the server runs one request at a time,
+ so abandoning a stream would leave it generating and inflate the NEXT row's TTFA.
+ Reference encoding (clone mode) happens server-side inside the timed request.
+ """
+ first, n_bytes, n_chunks, ttft = None, 0, 0, None
+ with _post(_body(job["text"], stream=True, ref=job.get("ref")), stream=True) as r:
+ for line in r.iter_lines():
+ if not line or not line.startswith(b"data:"):
+ continue
+ data = line[5:].strip()
+ if data == b"[DONE]":
+ break
+ event = json.loads(data)
+ kind = event.get("type")
+ if kind == "speech.audio.delta":
+ pcm = base64.b64decode(event["audio"])
+ if pcm and first is None:
+ first = time.perf_counter()
+ n_bytes += len(pcm)
+ n_chunks += 1
+ elif kind == "speech.audio.done":
+ ttft = (event.get("timing") or {}).get("ttft_ms")
+ elif kind == "error":
+ raise SystemExit(f"stream error event: {event}")
+ chunk_counts.append(n_chunks)
+ server_ttft_ms.append(ttft)
+ # PCM16 mono: 2 bytes per sample. Passed as seconds — only the duration is used.
+ return n_bytes / 2 / sample_rate, first
+
+ for i in range(args.warmup_steps):
+ t0 = time.perf_counter()
+ _gen({"text": "This is another warm-up sentence, streamed this time.", "ref": warm_ref})
+ print(f"streaming warm-up {i + 1}/{args.warmup_steps}: {time.perf_counter() - t0:.2f}s")
+ chunk_counts.clear()
+ server_ttft_ms.clear()
+
+ model_safe = args.model_id.replace("/", "-")
+ # Not created here: run_probe creates it on write, so a crash leaves no dir and the job fails.
+ out_dir = os.path.join("results", model_safe)
+
+ try:
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=out_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ extra={
+ "device": args.device,
+ "voice_clone": voice_clone,
+ "task": task,
+ "note": f"driven at batch size 1, audiocpp_server SSE streaming ({cfg['family']})",
+ "engine": "audio.cpp",
+ "engine_version": version,
+ "image": os.environ.get("AUDIOCPP_IMAGE"),
+ "family": cfg["family"],
+ "package": package,
+ "server_threads": threads,
+ "first_audio": "first non-empty speech.audio.delta received by the client (loopback HTTP)",
+ "request": {k: v for k, v in _body("<text>", stream=True, ref=("<prompt>", "<prompt_text>") if voice_clone else None).items()
+ if k not in ("model", "input")},
+ "sample_rate": sample_rate,
+ "chunks_per_utterance": chunk_counts,
+ # The server's own first-audio clock (excludes HTTP/SSE transport).
+ "server_ttft_ms": server_ttft_ms,
+ },
+ )
+ finally:
+ proc.terminate()
+ try:
+ proc.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ add_common_args(parser, voice_clone=False)
+ parser.set_defaults(dataset_path="bezzam/cv3_eval", dataset="zero_shot")
+
+ parser.add_argument("--model_id", type=str, default="openbmb/VoxCPM2",
+ help=f"Model id (names the sidecar); one of {sorted(FAMILIES)}.")
+ parser.add_argument("--package", type=str, default=None,
+ help="Override the audio.cpp package (e.g. a Q8_0 one). Recorded in the sidecar; "
+ "a different precision is a different model, so do not compare it naively.")
+ parser.add_argument("--language", type=str, default="en",
+ help="ISO language code; sent to families that take one, and picks Breeze's instruction.")
+ parser.add_argument("--models_dir", type=str, default="/tmp/audiocpp_models",
+ help="Where audiocpp_model_manager installs the package.")
+ parser.add_argument("--port", type=int, default=8080)
+ parser.add_argument("--threads", type=int, default=0,
+ help="Server worker threads; 0 = OMP_NUM_THREADS / nproc on CPU, 4 on GPU.")
+ parser.add_argument("--server_startup_timeout", type=int, default=1800,
+ help="Seconds to wait for /health (includes loading the model).")
+ parser.add_argument("--request_timeout", type=int, default=600)
+
+ args = parser.parse_args()
+
+ print("*" * 100)
+ print(f"TTFA probe: {args.model_id} via audio.cpp on {args.dataset_path} / {args.dataset} / {args.split}")
+ print("*" * 100)
+
+ main(args)
diff --git a/auk/run_eval.py b/auk/run_eval.py
new file mode 100644
index 0000000..485fcea
--- /dev/null
+++ b/auk/run_eval.py
@@ -0,0 +1,766 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (AuK backend, stage 1).
+"""
+
+import argparse
+import contextlib
+import glob
+import os
+import sys
+import time
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+from auk.infer.infer_auk import AukInfer
+
+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, wav_rel_path, warm_up, write_entry,
+)
+
+# Zero-shot TTS instruction; upstream uses this one template for both English and Chinese.
+ZERO_SHOT_TEMPLATE = 'Say the following with the same voice: "{text}"'
+
+# Instruct TTS (no reference audio), upstream template.
+INSTRUCT_TEMPLATE = (
+ 'Generate speech based on the following description: "{description}". '
+ 'The content to speak is: "{text}".'
+)
+# Neutral default description for --instruct. Deliberately plain: this measures intelligibility,
+# not prompt engineering.
+DEFAULT_VOICE_DESCRIPTION = (
+ "A clear, neutral adult voice reading at a natural pace in a quiet room, "
+ "with standard pronunciation and no strong emotion."
+)
+
+# AuK-Flash's distilled sampling recipe, copied from upstream `AukInfer.generate()`. The DMD
+# student bakes in its own guidance, so re-adding CFG blows up the amplitude (it clips hard).
+FLASH_T_GRID = [0.0, 0.07612049579620361, 0.2928932309150696, 0.6173166036605835, 1.0]
+FLASH_NFE = 4
+
+# Marker upstream appends to the text turn when there is no reference audio (Instruct TTS).
+NO_PROMPT_AUDIO_MARKER = "|<no_prompt_audio>|"
+
+
+def _resolve_model_dir(args):
+ """Locate the AuK release dir (config.yaml + *.safetensors + vae.safetensors).
+
+ The weights are not baked into the image, so the normal path is a Hub snapshot cached under
+ HF_HOME; `--checkpoint_dir` points at a local copy when there is one.
+ """
+ local = args.checkpoint_dir
+ if local:
+ if os.path.isfile(os.path.join(local, "config.yaml")):
+ return local
+ print(f"--checkpoint_dir {local!r} has no config.yaml; falling back to the Hub.")
+ from huggingface_hub import snapshot_download
+
+ print(f"Downloading {args.model_id} from the Hub (~6.8 GB, cached under HF_HOME) ...")
+ return snapshot_download(args.model_id)
+
+
+def _resolve_qwen_dir(args):
+ """Locate the Qwen2.5-Omni snapshot used as AuK's text/audio encoder.
+
+ The shipped config.yaml points at a repo-relative path that does not exist here, so this is
+ always passed explicitly to AukInfer(qwen_path=...).
+ """
+ local = args.qwen_dir
+ if local:
+ if os.path.isdir(local):
+ return local
+ print(f"--qwen_dir {local!r} not found; falling back to the Hub.")
+ from huggingface_hub import snapshot_download
+
+ print(f"Downloading {args.qwen_id} from the Hub (~12 GB, cached under HF_HOME) ...")
+ return snapshot_download(args.qwen_id)
+
+
+def _resolve_ckpt_file(model_dir):
+ """Pick the model checkpoint inside a release dir (`auk_base` / `auk_flash`, not the VAE)."""
+ candidates = [
+ p for p in sorted(glob.glob(os.path.join(model_dir, "*.safetensors")))
+ if os.path.basename(p) != "vae.safetensors"
+ ]
+ if not candidates:
+ raise FileNotFoundError(f"No model .safetensors (besides vae.safetensors) found in {model_dir}")
+ if len(candidates) > 1:
+ print(f"Multiple checkpoints in {model_dir}; using {candidates[0]}. Others: {candidates[1:]}")
+ return candidates[0]
+
+
+def _trim_trailing_silence(audio, sample_rate, top_db=40.0, keep_ms=200.0, frame_ms=20.0):
+ """Drop the silent tail of a fixed-length generation, keeping `keep_ms` of it.
+
+ AuK emits exactly the requested duration, so an over-estimate would otherwise count as
+ generated audio in RTFx. Only the tail is touched, to avoid clipping the first phoneme.
+ """
+ if audio.size == 0:
+ return audio
+ frame = max(1, int(sample_rate * frame_ms / 1000.0))
+ n_frames = len(audio) // frame
+ if n_frames < 2:
+ return audio
+ frames = audio[: n_frames * frame].reshape(n_frames, frame)
+ rms = np.sqrt(np.mean(np.square(frames.astype(np.float64)), axis=1))
+ peak = rms.max()
+ if peak <= 0:
+ return audio
+ threshold = peak * (10.0 ** (-top_db / 20.0))
+ voiced = np.nonzero(rms > threshold)[0]
+ if voiced.size == 0:
+ return audio
+ end = (voiced[-1] + 1) * frame + int(sample_rate * keep_ms / 1000.0)
+ return audio[: min(len(audio), end)]
+
+
+def _write_prompt_wav(path, prompt_audio, max_seconds=0.0):
+ """Write a dataset `prompt_audio` column value to a 16-bit PCM wav.
+
+ With `max_seconds > 0` the truncated clip is written, so the model's conditioning and stage 3's
+ SIM reference stay identical.
+ """
+ array = np.asarray(prompt_audio["array"], dtype=np.float32).reshape(-1)
+ sr = int(prompt_audio["sampling_rate"])
+ if max_seconds and len(array) > int(max_seconds * sr):
+ array = array[: int(max_seconds * sr)]
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ sf.write(path, array, sr, subtype="PCM_16")
+ return len(array) / sr
+
+
+def _build_messages(text, prompt_path, args):
+ """Compose the ChatML turn for one sample.
+
+ `prompt_path` is set in both leaderboard modes (per-sample or fixed reference); the
+ reference-free Instruct branch is reached only under `--instruct`.
+ """
+ if prompt_path is not None:
+ instruction = args.instruction_template.format(text=text)
+ return [{
+ "role": "user",
+ "content": [
+ {"type": "text", "text": instruction},
+ {"type": "audio", "audio": prompt_path},
+ ],
+ }]
+ # Instruct TTS: upstream's generate() appends this marker when there is no reference audio;
+ # this path bypasses generate(), so do it here. AuK often speaks the marker aloud.
+ instruction = INSTRUCT_TEMPLATE.format(description=args.voice_description, text=text)
+ return [{
+ "role": "user",
+ "content": [{"type": "text", "text": instruction + NO_PROMPT_AUDIO_MARKER}],
+ }]
+
+
+def _estimate_gen_seconds(text, prompt_text, ref_seconds, args):
+ """Target duration in seconds for one sample (AuK generates exactly this much audio).
+
+ `ratio` reproduces upstream `get_gen_duration()`: the reference duration scaled by the UTF-8
+ byte ratio of target text to reference transcript. Without a reference (`--instruct`) it falls
+ back to a flat bytes-per-second rate (upstream has no heuristic for that case).
+ """
+ if args.gen_seconds > 0:
+ return args.gen_seconds
+ n_bytes = max(1, len(text.encode("utf-8")))
+ use_ratio = args.duration_mode == "ratio" and prompt_text and ref_seconds
+ if use_ratio:
+ est = ref_seconds * n_bytes / max(1, len(prompt_text.encode("utf-8"))) / args.speed
+ else:
+ est = n_bytes / args.bytes_per_second / args.speed
+ est *= args.duration_scale
+ return float(min(max(est, args.min_gen_seconds), args.max_gen_seconds))
+
+
+def main(args):
+ # Set seed for reproducibility: the flow-matching sampler draws y0 noise and the VAE encoder
+ # samples from the posterior (mean + randn * exp(log_std)), so generation is stochastic.
+ set_seed(args.seed)
+
+ if not args.instruct:
+ # Fail fast, before the weight download: CFMEdit.build_cond_inputs imports qwen_omni_utils
+ # lazily on the reference-audio path, so a broken install would otherwise surface late.
+ import qwen_omni_utils # noqa: F401
+
+ model_dir = _resolve_model_dir(args)
+ ckpt_path = _resolve_ckpt_file(model_dir)
+ config_path = os.path.join(model_dir, "config.yaml")
+ qwen_path = _resolve_qwen_dir(args)
+
+ engine = AukInfer(
+ config_path,
+ ckpt_path,
+ device=args.device,
+ dtype=args.dtype,
+ qwen_path=qwen_path,
+ )
+ sampling_rate = int(engine.target_sample_rate) # 24000
+ latent_hz = sampling_rate / engine.downsample_rate # 50 Hz
+
+ # AuK-Flash only works under its fixed (t_grid, CFG-off) recipe; upstream's generate() enforces
+ # it and this path bypasses generate(), so apply the same lock here.
+ nfe, cfg_strength, sway, t_grid = args.nfe, args.cfg_strength, args.sway_sampling_coef, None
+ if args.t_grid:
+ t_grid = [float(x) for x in args.t_grid.split(",")]
+ if engine.is_flash:
+ nfe, cfg_strength, sway, t_grid = FLASH_NFE, 0.0, None, FLASH_T_GRID
+ print("AuK-Flash detected: sampling locked to the distilled 4-step / CFG-off recipe.")
+
+ n_params = sum(p.numel() for p in engine.model.transformer.parameters())
+ print(
+ f"Loaded AuK {args.model_id} from {model_dir} (sr={sampling_rate}, latent={latent_hz:.0f} Hz, "
+ f"nfe={nfe}, cfg={cfg_strength}, dtype={args.dtype}, device={engine.device})"
+ )
+ print(f"TTS model size: {n_params / 1e9:.2f}B parameters (DiT backbone; + Qwen2.5-Omni text encoder)")
+
+ is_cuda = torch.device(args.device).type == "cuda"
+
+ def _autocast():
+ """Fresh autocast context per call (matches upstream `_run`'s `torch.autocast("cuda", ...)`)."""
+ return torch.autocast("cuda", dtype=engine.dtype) if is_cuda else contextlib.nullcontext()
+
+ # ── Attention-memory budget, calibrated at runtime ───────────────────────
+ # Cost model: `n * max_total_latent_len**2`, a proxy for the [B, heads, T, T] attention mask.
+ # `None` = no budget yet: run the full batch, and on the first OOM derive the budget from the
+ # failed cost. --max_attn_cost skips that probe.
+ state = {"attn_budget": args.max_attn_cost or None}
+ # The failed attempt died partway through, so its true peak was higher; halving adds margin.
+ ATTN_BUDGET_SAFETY = 2
+
+ def _plan_chunks(indices, total_lens):
+ """Greedily chunk `indices` so each chunk's `len(chunk) * max_total_len**2` fits the budget.
+
+ Chunks stay contiguous to preserve manifest order; an over-budget sample forms a chunk of one.
+ """
+ if state["attn_budget"] is None:
+ return [list(indices)]
+ chunks, cur, cur_max = [], [], 0
+ for i in indices:
+ new_max = max(cur_max, total_lens[i])
+ if cur and (len(cur) + 1) * new_max**2 > state["attn_budget"]:
+ chunks.append(cur)
+ cur, cur_max = [i], total_lens[i]
+ else:
+ cur.append(i)
+ cur_max = new_max
+ if cur:
+ chunks.append(cur)
+ return chunks
+
+ @torch.inference_mode()
+ def _sample_chunk(refs, messages_batch, gen_latent_lens):
+ """One batched `CFMEdit.sample()` call; returns a list of [T] float32 numpy waveforms.
+
+ `refs` holds one [1, T] CPU waveform per sample (empty in Instruct mode). Mirrors upstream
+ `AukInfer._run()` with B > 1: encode and right-pad references, sample once, then slice and
+ decode each sample's generated span.
+ """
+ device = engine.device
+ batch = len(refs)
+ cloning = any(r.shape[-1] > 0 for r in refs)
+
+ ref_lens, ref_latents_list = [], []
+ if cloning:
+ for wav in refs:
+ # Per-sample VAE encode: exact, and cheap next to the sampler.
+ a = wav.to(device).unsqueeze(0) # [1, 1, T]
+ rl = a.shape[-1] // engine.downsample_rate
+ lat, enc_lens = engine.vae_model.encoding_and_normalization(
+ a,
+ sample_lengths=torch.tensor([rl * engine.downsample_rate], dtype=torch.long, device=device),
+ )
+ rl = min(rl, int(enc_lens[0].item()))
+ ref_lens.append(rl)
+ ref_latents_list.append(lat[0, :rl].float())
+ max_ref = max(ref_lens)
+ ref_latents = torch.zeros(batch, max_ref, engine.latent_dim, device=device, dtype=torch.float32)
+ for i, lat in enumerate(ref_latents_list):
+ ref_latents[i, : lat.shape[0]] = lat
+ else:
+ ref_lens = [0] * batch
+ ref_latents = torch.zeros(batch, 0, engine.latent_dim, device=device, dtype=torch.float32)
+
+ ref_lens_t = torch.tensor(ref_lens, dtype=torch.long, device=device)
+ total_lens_t = torch.tensor(
+ [r + g for r, g in zip(ref_lens, gen_latent_lens)], dtype=torch.long, device=device
+ )
+
+ with _autocast():
+ cond_inputs = engine.model.build_cond_inputs(messages_batch, engine.model.text_processor)
+ generated, _ = engine.model.sample(
+ cond=ref_latents,
+ text=cond_inputs,
+ duration=total_lens_t,
+ lens=ref_lens_t,
+ steps=nfe,
+ cfg_strength=cfg_strength,
+ sway_sampling_coef=sway,
+ t_grid=t_grid,
+ no_ref_audio=False,
+ seed=args.sample_seed if args.sample_seed >= 0 else None,
+ ) # [B, T_total_max, D]
+
+ audios = []
+ for i in range(batch):
+ rl, tl = ref_lens[i], int(total_lens_t[i].item())
+ gen_latent = generated[i, rl:tl, :].unsqueeze(0) # [1, T_new, D]
+ if gen_latent.shape[1] == 0 or not torch.isfinite(gen_latent).all():
+ audios.append(np.zeros(0, dtype=np.float32))
+ continue
+ gen_latent = engine.vae_model.denormalize(gen_latent).permute(0, 2, 1) # [1, D, T_new]
+ wav = engine.vae_model.inference_from_latents(gen_latent).cpu()
+ if wav.ndim == 3:
+ wav = wav.squeeze(0)
+ wav = wav.reshape(-1).to(torch.float32).numpy()
+ audios.append(wav if np.isfinite(wav).all() else np.zeros(0, dtype=np.float32))
+ return audios
+
+ def generate_tts(batch):
+ """Synthesize a minibatch; time the whole batch generation for RTFx."""
+ texts = list(batch[args.text_column])
+ minibatch_size = len(texts)
+ prompt_paths = batch.get("_prompt_path", [None] * minibatch_size)
+ ref_seconds = batch.get("_ref_seconds", [None] * minibatch_size)
+ prompt_texts = batch.get("prompt_text", [None] * minibatch_size)
+
+ gen_seconds = [
+ _estimate_gen_seconds(texts[i], prompt_texts[i], ref_seconds[i], args)
+ for i in range(minibatch_size)
+ ]
+ gen_latent_lens = [max(1, int(np.ceil(s * latent_hz))) for s in gen_seconds]
+
+ audios = [None] * minibatch_size
+ wasted_s = 0.0 # GPU time burned by sub-batches that OOM'd and were retried smaller
+
+ def _run_chunk(chunk):
+ refs = []
+ for i in chunk:
+ if prompt_paths[i] is None:
+ refs.append(torch.zeros(1, 0))
+ else:
+ # _load_audio downmixes to mono and resamples to the model's 24 kHz.
+ wav, _ = engine._load_audio(prompt_paths[i])
+ refs.append(wav)
+ messages_batch = [_build_messages(texts[i], prompt_paths[i], args) for i in chunk]
+ out = _sample_chunk(refs, messages_batch, [gen_latent_lens[i] for i in chunk])
+ for i, audio in zip(chunk, out):
+ audios[i] = audio
+
+ def _run_chunk_with_oom_retry(chunk):
+ """Run `chunk`; on OOM, tighten the budget and retry the two halves.
+
+ The OOM'd attempt's GPU time is subtracted from the timed region so RTFx reflects only
+ work that produced audio.
+ """
+ nonlocal wasted_s
+ attempt_start = torch.cuda.Event(enable_timing=True) if is_cuda else None
+ attempt_end = torch.cuda.Event(enable_timing=True) if is_cuda else None
+ if is_cuda:
+ attempt_start.record()
+ try:
+ _run_chunk(chunk)
+ return
+ except torch.OutOfMemoryError:
+ if len(chunk) == 1: # can't split further — a single sample OOMs on its own
+ raise
+ if is_cuda:
+ attempt_end.record()
+ torch.cuda.synchronize(device=args.device)
+ wasted_s += attempt_start.elapsed_time(attempt_end) / 1000.0
+ torch.cuda.empty_cache()
+
+ max_len = max(gen_latent_lens[i] + _ref_latent_len(i) for i in chunk)
+ failed_cost = len(chunk) * max_len**2
+ budget = max(1, failed_cost // ATTN_BUDGET_SAFETY)
+ if state["attn_budget"] is None or budget < state["attn_budget"]:
+ state["attn_budget"] = budget
+ print(
+ f"OOM on a sub-batch of {len(chunk)} (max {max_len} latent frames, cost {failed_cost}); "
+ f"attention budget now {state['attn_budget']} — pass "
+ f"--max_attn_cost={state['attn_budget']} to skip this probe on a rerun. "
+ "Halving and retrying.",
+ file=sys.stderr,
+ flush=True,
+ )
+ mid = len(chunk) // 2
+ _run_chunk_with_oom_retry(chunk[:mid])
+ _run_chunk_with_oom_retry(chunk[mid:])
+
+ def _ref_latent_len(i):
+ """Reference length in latent frames, for the cost model (0 without cloning)."""
+ if not ref_seconds[i]:
+ return 0
+ return int(ref_seconds[i] * latent_hz)
+
+ total_lens = {i: gen_latent_lens[i] + _ref_latent_len(i) for i in range(minibatch_size)}
+
+ # START TIMING (TTS batch generation)
+ if is_cuda:
+ torch.cuda.synchronize(device=args.device)
+ start_event = torch.cuda.Event(enable_timing=True)
+ end_event = torch.cuda.Event(enable_timing=True)
+ start_event.record()
+ else:
+ start_wall = time.perf_counter()
+
+ chunks = _plan_chunks(range(minibatch_size), total_lens)
+ if len(chunks) > 1:
+ print(
+ f"Split a minibatch of {minibatch_size} into sub-batches {[len(c) for c in chunks]} "
+ f"(max {max(total_lens.values())} latent frames, attention budget {state['attn_budget']})",
+ file=sys.stderr,
+ flush=True,
+ )
+ for chunk in chunks:
+ _run_chunk_with_oom_retry(chunk)
+
+ # END TIMING
+ if is_cuda:
+ end_event.record()
+ torch.cuda.synchronize(device=args.device)
+ runtime = start_event.elapsed_time(end_event) / 1000.0
+ else:
+ runtime = time.perf_counter() - start_wall
+ # Exclude time spent on OOM'd attempts that produced no audio.
+ runtime = max(runtime - wasted_s, 1e-6)
+ # per-sample generation time (RTFx is aggregated over the whole set at scoring time)
+ batch["generation_time_s"] = minibatch_size * [runtime / minibatch_size]
+
+ gen_paths, audio_length_s = [], []
+ for audio, sample_id in zip(audios, batch["id"]):
+ audio = np.asarray(audio, dtype=np.float32).reshape(-1)
+ if args.trim_trailing_silence:
+ audio = _trim_trailing_silence(
+ audio, sampling_rate, top_db=args.trim_top_db, keep_ms=args.trim_keep_ms
+ )
+ if audio.size == 0: # degenerate generation; write a stub so the pipeline continues
+ audio = np.zeros(int(0.1 * sampling_rate), dtype=np.float32)
+ # Store the path relative to model_dir_out (the manifest's dir); write to the full path.
+ rel_path = wav_rel_path(dataset_dir_name, sample_id)
+ sf.write(os.path.join(model_dir_out, rel_path), audio, sampling_rate)
+ gen_paths.append(rel_path)
+ audio_length_s.append(len(audio) / sampling_rate)
+
+ batch["gen_audio_filepath"] = gen_paths
+ batch["audio_length_s"] = audio_length_s
+ batch["references"] = list(batch[args.text_column]) # raw; normalized at scoring time
+ return batch
+
+ # ── Flat, bucket-friendly layout, per model ──────────────────────────────
+ # NOTE: must match resolve_mode() in submit_jobs.sh, which builds the same manifest names.
+ mode_suffix = "_voice_clone" if args.voice_clone else ("_instruct" if args.instruct else "")
+ paths = output_paths(args, mode_suffix)
+ model_dir_out, dataset_dir_name, output_dir = paths.model_dir, paths.dataset_dir_name, paths.output_dir
+ # Reference clips live under results/ so stage 3 SIM can read them; fixed-voice mode writes its
+ # single fixed_prompt.wav there too (the ChatML turn needs a path on disk).
+ if not args.instruct:
+ os.makedirs(os.path.join(output_dir, "prompts"), exist_ok=True)
+
+ # The reference columns are kept in every mode (fixed-voice mode may take its one reference
+ # from the split); they are dropped below when not cloning.
+ dataset = load_tts_dataset(args, ("prompt_text", "prompt_audio"))
+
+ # Dataset references are needed unless --instruct, or fixed-voice mode got an external clip.
+ needs_dataset_prompt = not args.instruct and not args.prompt_audio_path
+ missing = [c for c in ("prompt_text", "prompt_audio") if c not in dataset.column_names]
+ if missing and needs_dataset_prompt:
+ raise ValueError(
+ f"Dataset {args.dataset_path}/{args.dataset}/{args.split} is missing {missing}. "
+ "Pass --prompt_audio_path/--prompt_text to supply a fixed reference externally, or "
+ "--instruct to run upstream's reference-free Instruct TTS."
+ )
+
+ # ── Fixed-voice mode: resolve the ONE reference used for the whole split ──
+ # `fixed_prompt` stays None in the other two modes; _with_prompts and the TTFA probe branch on it.
+ fixed_prompt = None
+ if not args.voice_clone and not args.instruct:
+ fixed_rel = os.path.join(dataset_dir_name, "prompts", "fixed_prompt.wav")
+ fixed_full = os.path.join(model_dir_out, fixed_rel)
+ if args.prompt_audio_path:
+ if not args.prompt_text:
+ raise ValueError(
+ "--prompt_audio_path requires --prompt_text (the duration estimate scales the "
+ "reference's length by the target/reference UTF-8 byte ratio)."
+ )
+ audio, sr = sf.read(args.prompt_audio_path, dtype="float32", always_2d=True)
+ seconds = _write_prompt_wav(
+ fixed_full, {"array": audio.mean(axis=1), "sampling_rate": sr},
+ max_seconds=args.max_ref_seconds,
+ )
+ text = args.prompt_text
+ src = args.prompt_audio_path
+ else:
+ # Default: the split's own sample #--fixed_prompt_index, which keeps the reference
+ # language-matched.
+ if not 0 <= args.fixed_prompt_index < len(dataset):
+ raise ValueError(
+ f"--fixed_prompt_index={args.fixed_prompt_index} is out of range for a "
+ f"{len(dataset)}-sample split."
+ )
+ row = dataset[args.fixed_prompt_index]
+ seconds = _write_prompt_wav(
+ fixed_full, row["prompt_audio"], max_seconds=args.max_ref_seconds
+ )
+ text = row["prompt_text"]
+ src = f"{args.dataset}/{args.split} sample #{args.fixed_prompt_index} (id={row.get('id')})"
+ fixed_prompt = {"path": fixed_full, "text": text, "seconds": seconds}
+ print(
+ f"Fixed-voice mode: one {seconds:.2f}s reference for all {len(dataset)} samples, "
+ f"from {src}. SIM is skipped (no per-sample reference)."
+ )
+
+ # Not cloning: drop the reference columns so nothing triggers audio decoding.
+ if not args.voice_clone:
+ dataset = dataset.remove_columns([c for c in ("prompt_text", "prompt_audio") if c in dataset.column_names])
+
+ def _prepare_prompt(sample_id, prompt_audio):
+ """Materialize a sample's reference clip; return (rel_path, abs_path, seconds).
+
+ The wav is read both by AuK's Qwen encoder (via the ChatML `audio` path) and by stage 3 SIM.
+ """
+ rel = os.path.join(dataset_dir_name, "prompts", f"prompt_{sample_id}.wav")
+ path = os.path.join(model_dir_out, rel)
+ if os.path.exists(path) and args.resume:
+ info = sf.info(path)
+ return rel, path, info.frames / info.samplerate
+ seconds = _write_prompt_wav(path, prompt_audio, max_seconds=args.max_ref_seconds)
+ return rel, path, seconds
+
+ probe_out_dir = model_dir_out # real results dir, captured before the probe rebinds it
+
+ # ── TTFA probe: latency only (see scripts/ttfa_probe.py) ─────────────────
+ if args.ttfa_probe != 0:
+ # Imported HERE, not at module scope: the probe module is injected only by
+ # submit_ttfa_jobs.sh, so a top-level import would break every ordinary job.
+ from ttfa_probe import run_probe, sample_indices
+ import tempfile
+
+ model_dir_out = tempfile.mkdtemp(prefix="ttfa_out_")
+ dataset_dir_name = "ttfa"
+ os.makedirs(os.path.join(model_dir_out, dataset_dir_name, "prompts"), exist_ok=True)
+
+ columns = dataset.column_names
+ jobs = []
+ for i in sample_indices(args.ttfa_probe, len(dataset)):
+ job = {c: [dataset[i][c]] for c in columns}
+ if args.voice_clone:
+ _, path, seconds = _prepare_prompt(dataset[i]["id"], dataset[i]["prompt_audio"])
+ job["_prompt_path"] = [path]
+ job["_ref_seconds"] = [seconds]
+ elif fixed_prompt is not None:
+ job["_prompt_path"] = [fixed_prompt["path"]]
+ job["_ref_seconds"] = [fixed_prompt["seconds"]]
+ job["prompt_text"] = [fixed_prompt["text"]]
+ jobs.append(job)
+
+ def _gen(job):
+ result = generate_tts(job)
+ return float(result["audio_length_s"][0]), None, None
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=probe_out_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ extra={"device": args.device, "voice_clone": args.voice_clone,
+ "voice_mode": "clone" if args.voice_clone else ("instruct" if args.instruct else "fixed"),
+ "note": "driven at batch size 1; no streaming API (TTFA == full generation)"},
+ )
+ return
+
+ # ── Manifest (written incrementally; resume skips rows already in it) ───
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ def _with_prompts(batch):
+ """A dataset slice (dict of lists) with the reference clips materialized."""
+ n = len(batch["id"])
+ if args.voice_clone:
+ rels, prompt_paths, seconds = [], [], []
+ for j in range(n):
+ rel, path, sec = _prepare_prompt(batch["id"][j], batch["prompt_audio"][j])
+ rels.append(rel)
+ prompt_paths.append(path)
+ seconds.append(sec)
+ batch["_prompt_rel"] = rels
+ batch["_prompt_path"] = prompt_paths
+ batch["_ref_seconds"] = seconds
+ elif fixed_prompt is not None:
+ # One clip for the whole split. `prompt_text` is needed for the duration estimate.
+ batch["_prompt_path"] = [fixed_prompt["path"]] * n
+ batch["_ref_seconds"] = [fixed_prompt["seconds"]] * n
+ batch["prompt_text"] = [fixed_prompt["text"]] * n
+ return batch
+
+ # ── Main loop: TTS → write JSONL, one batch at a time ───────────────────
+ # Warm-up absorbs the first call's CUDA autotuning + lazy kernel loads, which would otherwise
+ # all land on batch 0's RTFx.
+ starts = pending_batches(dataset, args.batch_size, done_entries, dataset_dir_name)
+ warm_up(lambda b: generate_tts(_with_prompts(b)), dataset, starts, args.batch_size, args.warmup_steps)
+ for batch_start in tqdm(starts, desc="Generating"):
+ batch = generate_tts(_with_prompts(dataset[batch_start : batch_start + args.batch_size]))
+
+ # Append each sample to the JSONL immediately.
+ for j, (afp, alen, gtime, ref) in enumerate(zip(
+ batch["gen_audio_filepath"], batch["audio_length_s"],
+ batch["generation_time_s"], batch["references"],
+ )):
+ entry = manifest_entry(afp, alen, gtime, ref, batch["_prompt_rel"][j] if args.voice_clone else None)
+ write_entry(manifest_file, entry)
+ manifest_file.flush()
+
+ manifest_file.close()
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(args.voice_clone)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument(
+ "--model_id", type=str, default="tencent/AuK",
+ help="Model id (also used for manifest naming). 'tencent/AuK' or 'tencent/AuK-Flash'.",
+ )
+ parser.add_argument(
+ "--checkpoint_dir", type=str, default="",
+ help="OPTIONAL local release dir (config.yaml + auk_*.safetensors + vae.safetensors). "
+ "Empty (default) downloads --model_id from the Hub into the HF cache.",
+ )
+ parser.add_argument(
+ "--qwen_id", type=str, default="Qwen/Qwen2.5-Omni-3B",
+ help="Text/audio encoder repo. The shipped config.yaml points at a repo-relative path "
+ "that does not exist here, so this is always resolved and passed explicitly.",
+ )
+ parser.add_argument(
+ "--qwen_dir", type=str, default="",
+ help="OPTIONAL local Qwen2.5-Omni snapshot. Empty (default) downloads --qwen_id from the "
+ "Hub into the HF cache.",
+ )
+ # --batch_size is NOMINAL: sub-batched down to fit --max_attn_cost when sequences get long.
+ add_common_args(parser, batch_size=16, voice_clone=False)
+ parser.set_defaults(device="cuda:0")
+ parser.add_argument(
+ "--dtype", type=str, default="bf16", choices=["fp16", "bf16", "fp32"],
+ help="Autocast dtype for the sampler (AukInfer keeps the weights in fp32).",
+ )
+ parser.add_argument(
+ "--max_attn_cost", type=int, default=0,
+ help="Initial cap on `n * max_total_latent_frames^2` per sample() call; a minibatch "
+ "exceeding it is split. Default 0 = start unbounded and calibrate from the first OOM.",
+ )
+
+ # ── Sampling (ignored for AuK-Flash, which is locked to its distilled recipe) ──
+ parser.add_argument("--nfe", type=int, default=32, help="ODE steps (upstream default 32).")
+ parser.add_argument("--cfg_strength", type=float, default=2.0, help="CFG strength (upstream default 2.0).")
+ parser.add_argument(
+ "--sway_sampling_coef", type=float, default=-1.0,
+ help="Sway sampling coefficient (upstream default -1.0).",
+ )
+ parser.add_argument(
+ "--t_grid", type=str, default="",
+ help="Explicit comma-separated sampling times, overriding --nfe/--sway_sampling_coef.",
+ )
+
+ # ── Duration control (AuK generates EXACTLY the requested length) ──────────
+ parser.add_argument(
+ "--duration_mode", type=str, default="ratio", choices=["ratio", "rate"],
+ help="'ratio' (default) = upstream get_gen_duration(): reference duration scaled by the "
+ "UTF-8 byte ratio of target text to prompt_text. 'rate' = a flat "
+ "--bytes_per_second estimate. 'ratio' falls back to 'rate' when there is no "
+ "reference (--instruct).",
+ )
+ parser.add_argument(
+ "--gen_seconds", type=float, default=0.0,
+ help="Fixed target duration for EVERY sample, overriding the estimate. 0 = estimate.",
+ )
+ parser.add_argument(
+ "--bytes_per_second", type=float, default=13.0,
+ help="Speaking rate for --duration_mode rate, in UTF-8 bytes of target text per second. "
+ "~13 fits both English (~14 chars/s, 1 byte each) and Mandarin (~4.5 chars/s, 3 bytes).",
+ )
+ parser.add_argument("--speed", type=float, default=1.0, help="Divides the duration estimate (>1 = faster).")
+ parser.add_argument(
+ "--duration_scale", type=float, default=1.0,
+ help="Global multiplier on the duration estimate. >1 buys headroom against truncated "
+ "endings at the cost of more trailing silence (trimmed by default).",
+ )
+ parser.add_argument("--min_gen_seconds", type=float, default=0.5, help="Lower clamp on the estimate.")
+ parser.add_argument(
+ "--max_gen_seconds", type=float, default=30.0,
+ help="Upper clamp on the estimate. Upstream notes a ~30 s reference-plus-target budget.",
+ )
+ parser.add_argument(
+ "--max_ref_seconds", type=float, default=0.0,
+ help="Truncate each reference clip to at most N seconds before use. 0 (default) = off. "
+ "The truncated clip is what is written to prompts/, so the model's conditioning and "
+ "stage 3's SIM reference stay identical.",
+ )
+
+ # ── Output post-processing ────────────────────────────────────────────────
+ parser.add_argument(
+ "--trim_trailing_silence", action=argparse.BooleanOptionalAction, default=True,
+ help="Trim the silent tail of each fixed-length generation (default on), so an over-estimated "
+ "duration does not inflate RTFx.",
+ )
+ parser.add_argument("--trim_top_db", type=float, default=40.0, help="Silence threshold below the clip's peak frame RMS.")
+ parser.add_argument("--trim_keep_ms", type=float, default=200.0, help="Tail retained after the last voiced frame.")
+
+ # --voice_clone clones each sample's OWN prompt_audio (+ SIM); --no-voice_clone (default) uses
+ # ONE fixed reference for the whole split, comparable with the fixed-voice backends.
+ parser.add_argument(
+ "--fixed_prompt_index", type=int, default=0,
+ help="--no-voice_clone only: which sample of the split supplies the single reference. "
+ "Taking it from the split itself keeps the voice language-matched.",
+ )
+ parser.add_argument(
+ "--prompt_audio_path", type=str, default=None,
+ help="--no-voice_clone only: use this wav as the fixed reference instead of a dataset "
+ "sample (requires --prompt_text). Lets one voice be held constant across languages.",
+ )
+ parser.add_argument(
+ "--prompt_text", type=str, default=None,
+ help="Transcript of --prompt_audio_path. Required with it: the duration estimate scales "
+ "the reference's length by the target/reference byte ratio.",
+ )
+ parser.add_argument(
+ "--instruct", action="store_true",
+ help="DIAGNOSTIC, not the leaderboard path: upstream's reference-free Instruct TTS "
+ "(--voice_description, no reference audio). Requires --no-voice_clone and writes "
+ "'_instruct'-suffixed manifests. AuK often speaks the |<no_prompt_audio>| marker aloud.",
+ )
+ parser.add_argument(
+ "--voice_description", type=str, default=DEFAULT_VOICE_DESCRIPTION,
+ help="Natural-language voice description for --instruct.",
+ )
+ parser.add_argument(
+ "--instruction_template", type=str, default=ZERO_SHOT_TEMPLATE,
+ help="Zero-shot TTS instruction; must contain a {text} placeholder.",
+ )
+
+ parser.add_argument(
+ "--sample_seed", type=int, default=-1,
+ help="Seed re-applied inside CFMEdit.sample() for the y0 noise draw. -1 (default) = None, "
+ "i.e. let the global seed drive it; note upstream re-seeds per sample, which makes "
+ "every sample in a batch start from the SAME noise when this is set.",
+ )
+
+ args = parser.parse_args()
+
+ # --instruct is a third mode layered under --no-voice_clone.
+ if args.instruct and args.voice_clone:
+ parser.error("--instruct requires --no-voice_clone (it is the reference-free mode).")
+ for flag, value in (("--fixed_prompt_index", args.fixed_prompt_index != 0),
+ ("--prompt_audio_path", args.prompt_audio_path),
+ ("--prompt_text", args.prompt_text)):
+ if value and (args.voice_clone or args.instruct):
+ parser.error(f"{flag} only applies to fixed-voice mode (--no-voice_clone without --instruct).")
+
+ 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/auk/submit_jobs.sh b/auk/submit_jobs.sh
new file mode 100755
index 0000000..2b9a52e
--- /dev/null
+++ b/auk/submit_jobs.sh
@@ -0,0 +1,81 @@
+#!/bin/bash
+# HF Jobs TTS eval — AuK backend (generate → transcribe → SIM* → score; *voice-clone only).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["tencent/AuK 16" ...]
+# 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-auk}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-auk/blob/main/Dockerfile)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# ── Voice mode ───────────────────────────────────────────────────────────────
+# A reference audio is used either way; what the toggle changes is WHICH reference:
+# VOICE_CLONE=true each sample clones its own prompt_audio -> SIM stage runs.
+# VOICE_CLONE=false (default) ONE fixed reference for the whole split (the split's sample 0,
+# language-matched); SIM is skipped.
+# INSTRUCT=true (with VOICE_CLONE=false) diagnostic reference-free Instruct TTS; SIM is skipped.
+INSTRUCT="${INSTRUCT:-false}"
+VOICE_DESCRIPTION="${VOICE_DESCRIPTION:-}" # INSTRUCT only; "" = run_eval.py's neutral default
+FIXED_PROMPT_INDEX="${FIXED_PROMPT_INDEX:-}" # fixed-voice only; "" = run_eval.py's default (0)
+resolve_mode() {
+ voice_clone_mode
+ if [[ "${CLONE}" != "true" && "${INSTRUCT}" == "true" ]]; then
+ MODE_SUFFIX="_instruct"; VOICE_CLONE_FLAG="--no-voice_clone --instruct"
+ fi
+}
+
+# ── Languages AuK is documented for ─────────────────────────────────────────
+AUK_LANGUAGES="${AUK_LANGUAGES:-en zh}"
+supports_language() { [[ " ${AUK_LANGUAGES} " == *" $1 "* ]]; }
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id [batch_size] [duration_scale]". ──
+MAX_ATTN_COST="${MAX_ATTN_COST:-0}"
+generate_stage() {
+ local _ BATCH_SIZE DURATION_SCALE DESC_ARG="" FIXED_ARG=""
+ read -r _ BATCH_SIZE DURATION_SCALE <<< "${MODEL_CFG}"
+ BATCH_SIZE="${BATCH_SIZE:-16}" # tolerate a bare "model_id" with no extra fields
+ DURATION_SCALE="${DURATION_SCALE:-1.0}"
+ # Each flag is rejected outright by run_eval.py in the wrong mode, so only pass it in its own.
+ [[ "${INSTRUCT}" == "true" && -n "${VOICE_DESCRIPTION}" ]] && DESC_ARG=" --voice_description='${VOICE_DESCRIPTION}'"
+ [[ "${VOICE_CLONE}" != "true" && "${INSTRUCT}" != "true" && -n "${FIXED_PROMPT_INDEX}" ]] \
+ && FIXED_ARG=" --fixed_prompt_index=${FIXED_PROMPT_INDEX}"
+ hf jobs run \
+ --flavor "${FLAVOR}" --timeout 8h --secrets HF_TOKEN \
+ --env PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True" ${NAMESPACE_ARG} \
+ --volume "hf://buckets/${RESULTS_BUCKET}:/results" "${TTS_IMAGE}" \
+ bash -c "
+ ${RUN_EVAL_INJECT}
+ cd /app/auk && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --device=cuda:0 \
+ --batch_size=${BATCH_SIZE} \
+ --max_attn_cost=${MAX_ATTN_COST} \
+ --duration_scale=${DURATION_SCALE} \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} \
+ ${VOICE_CLONE_FLAG}${DESC_ARG}${FIXED_ARG} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment) ──
+# Seed-TTS zero-shot TTS splits: en (1088), zh (2020), zh_hard (400).
+DATASET_CONFIGS=(
+ "tts en en"
+ "tts zh zh"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot zh zh ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id [batch_size] [duration_scale]" (CLI args override) ─────
+MODEL_CONFIGS=(
+ "tencent/AuK 16 1.0"
+ "tencent/AuK-Flash 16 1.0"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/breeze-tts/run_eval.py b/breeze-tts/run_eval.py
new file mode 100644
index 0000000..cb88013
--- /dev/null
+++ b/breeze-tts/run_eval.py
@@ -0,0 +1,323 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (Breeze TTS 2 backend, stage 1).
+
+Breeze TTS 2 (BreezeBlue/Breeze-TTS-2) is a ~3.5B model — a Qwen3 "llama-1B"-flavor backbone,
+a T5Gemma2 text encoder, a 16-codebook depth decoder and a Mimi codec — run in-process from
+the cloned `breeze-tts` inference repo (its `models` + `breeze_infer` packages register the
+`breeze` architecture, which stock transformers does not know). This script loads the model,
+tokenizer and audio tokenizer once, synthesizes each target text, times generation for RTFx,
+saves wavs, and writes a manifest with `text`, `duration` and generation `time` (empty
+`pred_text`).
+
+Breeze has no built-in default voice, so the two tracks use its two templates:
+ --no-voice_clone (default) `tts_instruction` — reference-free "Voice Design" from a fixed instruction
+ (no SIM; the speaker is NOT stable across utterances).
+ --voice_clone `ref_edit_tata` — conditioned on the sample's reference clip + transcript.
+
+Both run through `FastBreezeStreamingRuntime` (the runtime `infer.py` uses), one sample at a time;
+--fast_all enables its CUDA-graph fast path. Output is 24 kHz mono.
+"""
+
+import argparse
+import os
+import sys
+import time
+from dataclasses import replace
+from pathlib import Path
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+from run_eval_utils import (
+ add_common_args,
+ count_parameters,
+ load_done_entries,
+ load_tts_dataset,
+ manifest_entry,
+ open_manifest,
+ output_paths,
+ pending_batches,
+ print_next_steps,
+ warm_up,
+ wav_rel_path,
+ write_entry,
+)
+
+# The breeze-tts inference repo is cloned (not pip-installed) at image build: its `models` and
+# `breeze_infer` packages are imported by path, and `configs/fast.json` is read from the same tree.
+BREEZE_REPO = Path(os.environ.get("BREEZE_REPO", "/opt/breeze-tts"))
+sys.path.insert(0, str(BREEZE_REPO))
+
+from breeze_infer.runtime import ( # noqa: E402
+ load_runtime,
+ set_all_seeds,
+ update_generation_config_for_breeze,
+)
+from breeze_infer.templates import get_template, prepare_inputs # noqa: E402
+from models.fast_streaming import FastBreezeStreamingRuntime, FastStreamingConfig # noqa: E402
+from models.warmup_profile import load_warmup_profile # noqa: E402
+
+# infer.py's own ceilings, which override the checkpoint's generation_config (max_new_tokens=750).
+MAX_NEW_TOKENS = 1500
+MAX_SEQ_LEN = 2048
+REPETITION_PENALTY = 1.1
+
+# Neutral instruction per language for the --no-voice_clone track; the model card says the
+# instruction language should match the target text. `en` is infer.py's default, `zh` its translation.
+DEFAULT_INSTRUCTIONS = {
+ "en": "Speak clearly and naturally.",
+ "zh": "请用清晰自然的语气朗读。",
+}
+
+
+def _default_instruction(language: str) -> str:
+ return DEFAULT_INSTRUCTIONS.get((language or "en").split("_")[0], DEFAULT_INSTRUCTIONS["en"])
+
+
+def main(args):
+ device = args.device
+ is_cuda = str(device).startswith("cuda")
+ instruction = args.instruction or _default_instruction(args.language)
+
+ # The weights are not baked into the image (licence), so they are downloaded here.
+ # `load_runtime` resolves `<ckpt>/audio_tokenizer` as a Path, so it must not be given a str.
+ if args.checkpoint_path:
+ ckpt_dir = Path(args.checkpoint_path)
+ else:
+ from huggingface_hub import snapshot_download
+
+ ckpt_dir = Path(snapshot_download(args.model_id))
+ print(f"Checkpoint: {ckpt_dir}")
+ tokenizer, model, audio_tokenizer = load_runtime(
+ ckpt_dir, device=device, attn_implementation=args.attn_implementation
+ )
+ update_generation_config_for_breeze(model)
+
+ streaming_config = FastStreamingConfig(
+ max_new_tokens=args.max_new_tokens,
+ max_seq_len=MAX_SEQ_LEN,
+ fast_all=args.fast_all,
+ repetition_penalty=REPETITION_PENALTY,
+ )
+ runtime = FastBreezeStreamingRuntime(model, audio_tokenizer, streaming_config, tokenizer=tokenizer)
+
+ # Build the fast path's CUDA graphs up front so that one-time cost stays out of the timings.
+ if runtime.fast_enabled:
+ profile = load_warmup_profile(BREEZE_REPO / "configs" / "fast.json")
+ profile = replace(profile, codec_chunk_frames=runtime.codec_chunk_frames)
+ manifest = runtime.warmup_from_profile(profile)
+ print(f"Fast-path warmup: {manifest['total_elapsed_ms']:.2f} ms")
+
+ sampling_rate = runtime.sample_rate # 24000
+ template_name = "ref_edit_tata" if args.voice_clone else "tts_instruction"
+ print(
+ f"Loaded Breeze TTS 2 ({args.model_id}, sr={sampling_rate}, template={template_name}, "
+ f"fast={runtime.fast_enabled})"
+ )
+ n_params = count_parameters(model)
+ print(f"TTS model size: {n_params / 1e9:.2f}B parameters (backbone + text encoder + depth decoder + codec)")
+
+ def synth_one(text, ref_path=None, ref_text=None, request_id="eval", early_stop=False):
+ """Synthesize one text; return (audio_1d_numpy, elapsed_s, ttfa).
+
+ With ref_path + ref_text the voice is cloned from that clip; otherwise it comes from
+ `instruction`. `prepare_inputs` is timed because it encodes the reference clip (the model's
+ own reference processing). `ttfa` holds two clocks, in ms:
+ ttfa_model_ms runtime's `ttfa_internal_ms`: prefill -> first decoded chunk.
+ ttfa_ms end to end, including prepare_inputs.
+ """
+ # Re-seed per sample for reproducibility (does NOT pin the voice-design speaker).
+ set_all_seeds(args.seed)
+
+ request = {"id": request_id, "text": text, "instruction": instruction, "speaker": args.speaker}
+ if ref_path is not None:
+ request["ref_audio_path"] = str(ref_path)
+ request["ref_text"] = ref_text
+
+ if is_cuda:
+ torch.cuda.synchronize(device=device)
+ start = time.perf_counter()
+
+ inputs = prepare_inputs(
+ tokenizer,
+ audio_tokenizer,
+ model,
+ [request],
+ get_template(template_name),
+ guidance_scale=args.cfg_scale,
+ guidance_scale_ref=None,
+ guidance_scale_ins=None,
+ )
+ chunks, ttfa = [], {"ttfa_ms": None, "ttfa_model_ms": None, "first_ts": None}
+ for chunk in runtime.iter_audio_chunks(inputs, request_id=request_id):
+ if not chunks:
+ # `.audio` is already a host numpy array, so no extra synchronize is needed.
+ first_ts = time.perf_counter()
+ ttfa["ttfa_ms"] = (first_ts - start) * 1000.0
+ ttfa["ttfa_model_ms"] = (chunk.timing or {}).get("ttfa_internal_ms")
+ # Absolute timestamp for the TTFA probe; stripped before the manifest is written.
+ ttfa["first_ts"] = first_ts
+ chunks.append(chunk.audio)
+ if early_stop:
+ break
+
+ if is_cuda:
+ torch.cuda.synchronize(device=device)
+ elapsed = time.perf_counter() - start
+
+ if chunks:
+ audio = np.concatenate([np.asarray(c, dtype=np.float32).reshape(-1) for c in chunks])
+ else:
+ audio = np.zeros(int(0.1 * sampling_rate), dtype=np.float32)
+ return audio, elapsed, ttfa
+
+ # 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.
+ mode_suffix = "_voice_clone" if args.voice_clone else ""
+ paths = output_paths(args, mode_suffix)
+ model_dir, dataset_dir_name, output_dir = paths.model_dir, paths.dataset_dir_name, paths.output_dir
+ # Reference clips are saved for stage 3 (SIM), and because the cloning template takes a path.
+ prompt_dir = os.path.join(output_dir, "prompts")
+ if args.voice_clone:
+ os.makedirs(prompt_dir, exist_ok=True)
+
+ dataset = load_tts_dataset(args, extra_columns=("prompt_text", "prompt_audio") if args.voice_clone else ())
+
+ # ── TTFA probe: writes ONLY a JSON sidecar (no wavs, no manifest) ─────────
+ # 0 = off; N > 0 = N evenly spaced samples; N < 0 = the whole split (see scripts/ttfa_probe.py).
+ if args.ttfa_probe != 0:
+ # Imported lazily: ttfa_probe.py is only injected by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+ import tempfile
+
+ # Reference clips go to a temp dir so existing results are never touched.
+ tmp_dir = tempfile.mkdtemp(prefix="ttfa_refs_")
+
+ def _gen(job, early_stop):
+ audio, _, ttfa = synth_one(
+ job["text"], ref_path=job.get("ref_path"), ref_text=job.get("ref_text"),
+ request_id=f"ttfa-{job['id']}", early_stop=early_stop,
+ )
+ return audio, sampling_rate, ttfa["first_ts"]
+
+ jobs = []
+ for i in sample_indices(args.ttfa_probe, len(dataset)):
+ sample_id = dataset[i]["id"]
+ job = {"id": sample_id, "text": dataset[i][args.text_column]}
+ if args.voice_clone:
+ pa = dataset[i]["prompt_audio"]
+ ref = os.path.join(tmp_dir, f"prompt_{sample_id}.wav")
+ sf.write(ref, np.asarray(pa["array"], dtype=np.float32), pa["sampling_rate"])
+ job["ref_path"], job["ref_text"] = ref, dataset[i]["prompt_text"]
+ jobs.append(job)
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=model_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ extra={"device": args.device, "fast_all": args.fast_all, "cfg_scale": args.cfg_scale},
+ )
+ return
+
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ def synth_row(row):
+ """Synthesize one dataset row; return (audio, elapsed, ttfa, prompt_rel_path)."""
+ sample_id = row["id"]
+ prompt_rel_path = prompt_path = prompt_text = None
+ if args.voice_clone:
+ # Save the reference clip before the timer — file I/O is not generation.
+ pa = row["prompt_audio"]
+ prompt_rel_path = os.path.join(dataset_dir_name, "prompts", f"prompt_{sample_id}.wav")
+ prompt_path = os.path.join(model_dir, prompt_rel_path)
+ if not os.path.exists(prompt_path):
+ sf.write(prompt_path, np.asarray(pa["array"], dtype=np.float32), pa["sampling_rate"])
+ prompt_text = row["prompt_text"]
+ audio, elapsed, ttfa = synth_one(
+ row[args.text_column], ref_path=prompt_path, ref_text=prompt_text, request_id=f"eval-{sample_id}"
+ )
+ return audio, elapsed, ttfa, prompt_rel_path
+
+ # ── Main loop: synthesize one sample at a time → write JSONL ─────────────
+ starts = pending_batches(dataset, 1, done_entries, dataset_dir_name)
+ warm_up(lambda b: synth_row({k: v[0] for k, v in b.items()}), dataset, starts, 1, args.warmup_steps)
+ for i in tqdm(starts, desc="Generating"):
+ row = dataset[i]
+ # Store the path relative to model_dir (the manifest's dir); write to the full path.
+ rel_path = wav_rel_path(dataset_dir_name, row["id"])
+ audio, elapsed, ttfa, prompt_rel_path = synth_row(row)
+ sf.write(os.path.join(model_dir, rel_path), audio, sampling_rate)
+
+ entry = manifest_entry(rel_path, len(audio) / sampling_rate, elapsed, row[args.text_column])
+ entry.update({k: v for k, v in ttfa.items() if k != "first_ts"})
+ if args.voice_clone:
+ entry.update(prompt_audio_filepath=prompt_rel_path, sim="")
+ write_entry(manifest_file, entry)
+ manifest_file.flush()
+
+ manifest_file.close()
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(args.voice_clone)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ add_common_args(parser, voice_clone=False)
+
+ parser.add_argument("--model_id", type=str, default="BreezeBlue/Breeze-TTS-2", help="Hub repo id (downloaded unless --checkpoint_path is set; also names the outputs).")
+ parser.add_argument(
+ "--checkpoint_path",
+ type=str,
+ default=None,
+ help="Local dir with the weights + bundled audio_tokenizer/. Default: snapshot_download(--model_id).",
+ )
+ parser.add_argument(
+ "--language",
+ type=str,
+ default=None,
+ help="Language of the target text; picks the default voice-design instruction. Defaults to --split.",
+ )
+ parser.add_argument(
+ "--attn_implementation",
+ type=str,
+ default="eager",
+ help="Backbone attention. 'eager' is infer.py's default; the T5Gemma2 text encoder always "
+ "uses flash_attention_2 (the checkpoint pins it), so flash-attn is required either way.",
+ )
+ parser.add_argument("--max_new_tokens", type=int, default=MAX_NEW_TOKENS, help="Max audio frames to generate.")
+ parser.add_argument(
+ "--cfg_scale",
+ type=float,
+ default=1.0,
+ help="Classifier-free guidance. 1.0 (infer.py's default) runs a single branch; >1 adds a "
+ "negative branch. The card suggests 4 to strengthen instruction-following.",
+ )
+ parser.add_argument(
+ "--instruction",
+ type=str,
+ default=None,
+ help="Natural-language delivery instruction. Defaults to a neutral one for --language.",
+ )
+ parser.add_argument("--speaker", type=str, default="S0", help="Speaker tag prefixed to each segment.")
+ parser.add_argument(
+ "--fast_all",
+ action=argparse.BooleanOptionalAction,
+ default=False,
+ help="Enable the CUDA-graph fast path for every stage (warmup excluded from timings). "
+ "Needs ~14.4 GiB instead of ~7.7 GiB.",
+ )
+
+ args = parser.parse_args()
+ if args.language is None:
+ args.language = args.split
+
+ 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/breeze-tts/submit_jobs.sh b/breeze-tts/submit_jobs.sh
new file mode 100755
index 0000000..e9df6e9
--- /dev/null
+++ b/breeze-tts/submit_jobs.sh
@@ -0,0 +1,63 @@
+#!/bin/bash
+# HF Jobs TTS eval — Breeze TTS 2 backend (generate → transcribe → SIM* → score; *voice-clone only).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["BreezeBlue/Breeze-TTS-2" ...]
+# 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-breeze}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-breeze/blob/main/Dockerfile)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# CUDA-graph fast path (vendor-supported; warmup excluded from timings). FAST_ALL=false for eager.
+FAST_ALL="${FAST_ALL:-true}"
+
+# ── Languages this backend can select ────────────────────────────────────────
+# Breeze TTS 2 is English + Chinese only; other CV3-Eval languages are skipped.
+BREEZE_LANGUAGES="en zh"
+supports_language() { [[ " ${BREEZE_LANGUAGES} " == *" $1 "* ]]; }
+
+# ── Voice cloning ────────────────────────────────────────────────────────────
+# Breeze has no default voice: VOICE_CLONE=false uses reference-free voice design (no SIM).
+# Standard clone mode + the fast-path flag.
+resolve_mode() {
+ voice_clone_mode
+ if [[ "${FAST_ALL}" == "true" ]]; then FAST_FLAG="--fast_all"; else FAST_FLAG="--no-fast_all"; fi
+}
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id" (Breeze synthesizes one sample at a time). ──
+# The weights are not baked into the image (licence), so run_eval.py downloads them at job start.
+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/breeze-tts && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --language=${ASR_LANG} \
+ --device=cuda:0 \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} \
+ ${VOICE_CLONE_FLAG} \
+ ${FAST_FLAG} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment) ──
+DATASET_CONFIGS=(
+ "tts en en"
+ "tts zh zh"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot zh zh ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id" (CLI args override) ───────────────────────────────────
+MODEL_CONFIGS=("BreezeBlue/Breeze-TTS-2")
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/chatterbox/run_eval.py b/chatterbox/run_eval.py
new file mode 100644
index 0000000..15d0557
--- /dev/null
+++ b/chatterbox/run_eval.py
@@ -0,0 +1,373 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (Chatterbox backend, stage 1).
+
+Chatterbox (ResembleAI/chatterbox) is a ~0.5B zero-shot TTS loaded in-process via the
+`chatterbox-tts` package, synthesized one text at a time (no batched API). Two checkpoints,
+selected with `--multilingual`:
+
+ * `ChatterboxTTS` (default) — the English-only checkpoint; `generate()` takes no language, so
+ use it for `en` only.
+ * `ChatterboxMultilingualTTS` (`--multilingual`) — the 23-language checkpoint (needs
+ `language_id`); outputs get a `_multilingual` suffix since it shares the model id. This also
+ covers Resemble's single-language finetunes (see `_load_single_language_pack`).
+
+Voice cloning (`--voice_clone`) conditions each sample on the per-sample `prompt_audio` via
+`audio_prompt_path`; outputs get a `_voice_clone` suffix. The default (`--no-voice_clone`) uses the
+built-in default voice and skips SIM.
+"""
+
+import argparse
+import os
+from pathlib import Path
+import time
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+# The multilingual class is imported lazily in `_load_model`.
+from chatterbox.tts import ChatterboxTTS
+
+from run_eval_utils import (
+ add_common_args, load_done_entries, load_tts_dataset, manifest_entry, open_manifest, output_paths,
+ pending_batches, print_model_size, print_next_steps, set_seed, warm_up, wav_rel_path, write_entry,
+)
+
+# The repo whose weights upstream's ChatterboxMultilingualTTS.from_pretrained() hardcodes.
+CHATTERBOX_BASE_REPO = "ResembleAI/chatterbox"
+
+
+# T3 filenames the multilingual from_local() may hardcode, depending on the chatterbox-tts version
+# (0.1.7 loads v2; newer builds default to v3). A single-language pack's T3 is staged under both.
+_MULTILINGUAL_T3_NAMES = ("t3_mtl23ls_v2.safetensors", "t3_mtl23ls_v3.safetensors")
+
+
+def _accepts(func, name):
+ """Whether `func` takes a keyword argument `name` (chatterbox-tts's API varies by version)."""
+ import inspect
+
+ try:
+ return name in inspect.signature(func).parameters
+ except (TypeError, ValueError):
+ return False
+
+
+def _load_single_language_pack(model_id, device, t3_model_file=None, s3gen_source="pack"):
+ """Load a Resemble 'single language pack' finetune (e.g. Chatterbox-Multilingual-zh-cmn).
+
+ `from_pretrained()` hardcodes the base repo, so the pack is snapshotted and loaded with
+ `from_local()`, which expects fixed filenames. A staging dir of symlinks (never mutating the HF
+ cache) presents:
+ * the pack's T3 (e.g. `t3_zh_cmn.safetensors`) under the multilingual T3 names;
+ * a decoder as `s3gen.pt`: the pack's own, or the base repo's (the decoder is
+ language-agnostic; 0.1.7 cannot load the V3 packs' `s3gen_v3.pt`). `s3gen_source="auto"`
+ tries the pack's and falls back to the base repo's on a load error.
+ """
+ from huggingface_hub import hf_hub_download, snapshot_download
+
+ from chatterbox.mtl_tts import ChatterboxMultilingualTTS
+
+ ckpt_dir = Path(snapshot_download(model_id))
+
+ if t3_model_file is None:
+ # The pack contains exactly one T3 checkpoint, named after its language.
+ candidates = sorted(
+ p.name for p in ckpt_dir.glob("t3_*.safetensors") if p.name not in _MULTILINGUAL_T3_NAMES
+ )
+ if len(candidates) != 1:
+ raise RuntimeError(
+ f"Expected exactly one language-specific t3_*.safetensors in {model_id}, found "
+ f"{candidates}. Pass --t3_model_file explicitly."
+ )
+ t3_model_file = candidates[0]
+
+ staged = Path("/tmp") / f"chatterbox_pack_{model_id.replace('/', '-')}"
+ staged.mkdir(parents=True, exist_ok=True)
+
+ def link(src, name):
+ dst = staged / name
+ if dst.is_symlink() or dst.exists():
+ dst.unlink()
+ os.symlink(src, dst)
+
+ for src in ckpt_dir.iterdir():
+ if not src.is_dir():
+ link(src, src.name)
+ # Present the pack's T3 under every name the loader might hardcode.
+ for name in _MULTILINGUAL_T3_NAMES:
+ link(ckpt_dir / t3_model_file, name)
+
+ kwargs = {}
+ if _accepts(ChatterboxMultilingualTTS.from_local, "t3_model"):
+ kwargs["t3_model"] = t3_model_file # newer API: name it explicitly
+
+ def attempt(which):
+ """Point staged/s3gen.pt at `which` decoder, then load."""
+ if which == "pack":
+ src = next((ckpt_dir / n for n in ("s3gen.pt", "s3gen_v3.pt") if (ckpt_dir / n).exists()), None)
+ if src is None:
+ return None # pack ships no decoder; nothing to try
+ else:
+ src = Path(hf_hub_download(CHATTERBOX_BASE_REPO, "s3gen.pt"))
+ link(src, "s3gen.pt")
+ print(f"Loading single-language pack {model_id} via from_local "
+ f"(t3={t3_model_file}, s3gen={which}:{src.name}, kwargs={list(kwargs)})")
+ return ChatterboxMultilingualTTS.from_local(staged, device, **kwargs)
+
+ if s3gen_source in ("pack", "base"):
+ model = attempt(s3gen_source)
+ if model is None:
+ raise RuntimeError(f"{model_id} ships no s3gen checkpoint; use --pack_s3gen=base.")
+ return model
+
+ # auto: prefer the pack's own decoder, fall back to the base repo's.
+ try:
+ model = attempt("pack")
+ if model is not None:
+ return model
+ except RuntimeError as e:
+ print(f"WARNING: the pack's s3gen did not load ({e.__class__.__name__}: "
+ f"{str(e).splitlines()[0]}); retrying with {CHATTERBOX_BASE_REPO}'s s3gen.pt.")
+ return attempt("base")
+
+
+def _load_model(args):
+ """Load the checkpoint selected by --multilingual / --model_id."""
+ if not args.multilingual:
+ # English-only checkpoint; generate() has no language argument at all.
+ return ChatterboxTTS.from_pretrained(device=args.device)
+
+ from chatterbox.mtl_tts import ChatterboxMultilingualTTS
+
+ if args.model_id == CHATTERBOX_BASE_REPO:
+ if _accepts(ChatterboxMultilingualTTS.from_pretrained, "t3_model"):
+ return ChatterboxMultilingualTTS.from_pretrained(device=args.device, t3_model=args.t3_model)
+ # Released 0.1.7 has no t3_model argument and always fetches the v2 multilingual T3.
+ print(
+ f"WARNING: installed chatterbox-tts has no t3_model argument — ignoring "
+ f"--t3_model={args.t3_model} and loading the v2 multilingual checkpoint. Rebuild the "
+ f"image against a newer chatterbox-tts for v3."
+ )
+ return ChatterboxMultilingualTTS.from_pretrained(device=args.device)
+ return _load_single_language_pack(
+ args.model_id, args.device, t3_model_file=args.t3_model_file, s3gen_source=args.pack_s3gen
+ )
+
+
+# ── chatterbox-tts attention-hook leak workaround ────────────────────────────────────────────────
+# Each multilingual `generate()` builds a fresh `AlignmentStreamAnalyzer` that registers forward
+# hooks on three `self_attn` modules and never removes them, so per-step cost grows with every
+# sample generated (and RTFx would measure the leak). Dropping the stale hooks before each call
+# keeps throughput flat; a no-op for the English-only checkpoint.
+_ALIGNMENT_HOOK_NAME = "attention_forward_hook"
+
+
+def _prune_alignment_hooks(model):
+ """Remove AlignmentStreamAnalyzer hooks left behind by earlier generate() calls; return the count.
+
+ Matches hooks by function name so unrelated hooks on the same modules are left alone, and keeps
+ torch's parallel per-hook flag dicts in sync with `_forward_hooks`.
+ """
+ layers = getattr(getattr(getattr(model, "t3", None), "tfmr", None), "layers", None)
+ if layers is None:
+ return 0
+ removed = 0
+ for layer in layers:
+ attn = getattr(layer, "self_attn", None)
+ hooks = getattr(attn, "_forward_hooks", None)
+ if not hooks:
+ continue
+ stale = [k for k, fn in hooks.items() if getattr(fn, "__name__", "") == _ALIGNMENT_HOOK_NAME]
+ for k in stale:
+ del hooks[k]
+ for flags in ("_forward_hooks_with_kwargs", "_forward_hooks_always_called"):
+ getattr(attn, flags, {}).pop(k, None)
+ removed += len(stale)
+ return removed
+
+
+def main(args):
+ # Set seed for reproducibility (Chatterbox's T3 backbone samples autoregressively).
+ set_seed(args.seed)
+
+ model = _load_model(args)
+ sampling_rate = model.sr # 24000
+ variant = f"multilingual, language_id={args.language}" if args.multilingual else "english-only"
+ print(f"Loaded Chatterbox ({variant}, sr={sampling_rate})")
+ print_model_size(model)
+
+ is_cuda = torch.device(args.device).type == "cuda"
+ pruning_logged = [] # one-shot flag so the log states the workaround engaged, without spamming
+
+ def synth_one(text, prompt_path):
+ """Synthesize one text (optionally cloning prompt_path); return (audio_1d_numpy, elapsed_seconds)."""
+ # Drop the previous call's leaked alignment hooks before the timer starts.
+ pruned = _prune_alignment_hooks(model)
+ if pruned and not pruning_logged:
+ pruning_logged.append(pruned)
+ print(f"Dropping {pruned} leaked alignment hooks per sample (chatterbox-tts hook leak).")
+ if is_cuda:
+ torch.cuda.synchronize(device=args.device)
+ start = time.perf_counter()
+ gen_kwargs = dict(
+ audio_prompt_path=prompt_path, # None → built-in default voice; else clone this clip
+ temperature=args.temperature,
+ cfg_weight=args.cfg_weight,
+ exaggeration=args.exaggeration,
+ )
+ # Only the multilingual checkpoint takes a language; ChatterboxTTS.generate() would reject it.
+ if args.multilingual:
+ gen_kwargs["language_id"] = args.language
+ wav = model.generate(text, **gen_kwargs)
+ if is_cuda:
+ torch.cuda.synchronize(device=args.device)
+ elapsed = time.perf_counter() - start
+ # generate() returns a (1, N) float tensor.
+ return wav.squeeze().detach().to(torch.float32).cpu().numpy(), elapsed
+
+ # Layout: results/<model_safe>/ MODEL_<safe>_DATASET_<dsid>.jsonl + <dsid>/output_<id>.wav
+ # where <dsid> = <dataset_safe>_<dataset>_<split><mode_suffix>. Manifest paths are relative to
+ # model_dir so later stages resolve them wherever the folder is copied (local or HF bucket).
+ # `_multilingual` separates the multilingual checkpoint, which shares the English model id.
+ mode_suffix = ("_multilingual" if args.multilingual else "") + ("_voice_clone" if args.voice_clone else "")
+ paths = output_paths(args, mode_suffix)
+ model_dir, dataset_dir_name, output_dir = paths.model_dir, paths.dataset_dir_name, paths.output_dir
+ # Reference clips must live under results/ (not tempfiles) so stage 3 SIM can read them.
+ prompt_dir = os.path.join(output_dir, "prompts")
+ if args.voice_clone:
+ os.makedirs(prompt_dir, exist_ok=True)
+
+ # Keep `id`, target text, and (when cloning) the per-sample reference.
+ dataset = load_tts_dataset(args, ("prompt_text", "prompt_audio") if args.voice_clone else ())
+
+ # ── TTFA probe: latency only, writing nothing but a JSON sidecar ─────────
+ # Same voice handling as the main loop; references go to a temp dir. No streaming API, so
+ # `first` is None -> whole-utterance clock.
+ # 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 only injected by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+ import tempfile
+
+ tmp_dir = tempfile.mkdtemp(prefix="ttfa_refs_")
+
+ def _ttfa_ref(i):
+ if not args.voice_clone:
+ return None
+ path = os.path.join(tmp_dir, f"prompt_{dataset[i]['id']}.wav")
+ pa = dataset[i]["prompt_audio"]
+ sf.write(path, np.asarray(pa["array"], dtype=np.float32), pa["sampling_rate"])
+ return path
+
+ jobs = [{"text": dataset[i][args.text_column], "prompt_path": _ttfa_ref(i)}
+ for i in sample_indices(args.ttfa_probe, len(dataset))]
+
+ run_probe(
+ lambda job: (synth_one(job["text"], job["prompt_path"])[0], sampling_rate, None),
+ jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=model_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ extra={"device": args.device, "voice_clone": args.voice_clone},
+ )
+ return
+
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ def prompt_for(row):
+ """When cloning, persist a row's reference clip (stage 3 SIM reads it); (rel_path, path) or Nones."""
+ if not args.voice_clone:
+ return None, None
+ prompt_rel_path = os.path.join(dataset_dir_name, "prompts", f"prompt_{row['id']}.wav")
+ prompt_path = os.path.join(model_dir, prompt_rel_path)
+ if not os.path.exists(prompt_path):
+ pa = row["prompt_audio"]
+ sf.write(prompt_path, np.asarray(pa["array"], dtype=np.float32), pa["sampling_rate"])
+ return prompt_rel_path, prompt_path
+
+ # Serial generation: batches of one sample.
+ starts = pending_batches(dataset, 1, done_entries, dataset_dir_name)
+ warm_up(lambda b: synth_one(b[args.text_column][0], prompt_for({c: b[c][0] for c in b})[1]),
+ dataset, starts, 1, args.warmup_steps)
+
+ # ── Main loop: synthesize one sample at a time → write JSONL ─────────────
+ for i in tqdm(starts, desc="Generating"):
+ row = dataset[i]
+ text = row[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, row["id"])
+ path = os.path.join(model_dir, rel_path)
+
+ # When cloning, condition on the persisted reference clip.
+ prompt_rel_path, prompt_path = prompt_for(row)
+
+ audio, elapsed = synth_one(text, prompt_path)
+ sf.write(path, audio, sampling_rate)
+
+ write_entry(manifest_file, manifest_entry(rel_path, len(audio) / sampling_rate, elapsed, text, prompt_rel_path))
+ manifest_file.flush()
+
+ manifest_file.close()
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(args.voice_clone)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument("--model_id", type=str, default="ResembleAI/chatterbox", help="Model id (for manifest naming).")
+ add_common_args(parser, voice_clone=False)
+ parser.add_argument(
+ "--multilingual",
+ action=argparse.BooleanOptionalAction,
+ default=False,
+ help="Load ChatterboxMultilingualTTS (23 languages, needs --language) instead of the "
+ "English-only ChatterboxTTS. Required for any non-English split: the English-only "
+ "checkpoint has no language argument and renders other languages as gibberish.",
+ )
+ parser.add_argument(
+ "--language",
+ type=str,
+ default="en",
+ help="Language code passed as `language_id` to the multilingual checkpoint (e.g. 'en', "
+ "'zh'). Upstream validates it against its 23 SUPPORTED_LANGUAGES. Ignored when "
+ "--no-multilingual.",
+ )
+ parser.add_argument(
+ "--t3_model",
+ type=str,
+ default="v3",
+ help="Multilingual T3 checkpoint for the base repo: 'v3' (default) or 'v2'.",
+ )
+ parser.add_argument(
+ "--t3_model_file",
+ type=str,
+ default=None,
+ help="For single-language packs only: the t3_*.safetensors filename to load. Auto-detected "
+ "when the pack contains exactly one.",
+ )
+ parser.add_argument(
+ "--pack_s3gen",
+ type=str,
+ choices=["auto", "pack", "base"],
+ default="auto",
+ help="For single-language packs only: whose speech decoder to use. 'auto' (default) tries "
+ "the pack's own s3gen and falls back to ResembleAI/chatterbox's s3gen.pt if the "
+ "installed chatterbox-tts can't load it. 'pack' or 'base' force one and fail loudly.",
+ )
+ # Generation params (defaults match the model's generate() defaults).
+ parser.add_argument("--temperature", type=float, default=0.8, help="Sampling temperature.")
+ parser.add_argument("--cfg_weight", type=float, default=0.5, help="Classifier-free guidance weight.")
+ parser.add_argument("--exaggeration", type=float, default=0.5, help="Emotion exaggeration.")
+
+ 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/chatterbox/submit_jobs.sh b/chatterbox/submit_jobs.sh
new file mode 100644
index 0000000..7ecab07
--- /dev/null
+++ b/chatterbox/submit_jobs.sh
@@ -0,0 +1,82 @@
+#!/bin/bash
+# HF Jobs TTS eval — Chatterbox backend (generate → transcribe → SIM* → score; *voice-clone only, VOICE_CLONE=true).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["ResembleAI/chatterbox multilingual en,zh" ...]
+# 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-chatterbox}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-chatterbox/blob/main/Dockerfile)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# ── Voice cloning: VOICE_CLONE=true clones the per-sample prompt + scores SIM;
+# false uses the built-in default voice. ──
+resolve_mode() {
+ # The multilingual checkpoint shares the English-only one's model id, so it gets its own
+ # manifest suffix (matching run_eval.py).
+ local _ VARIANT
+ read -r _ VARIANT _ <<< "${MODEL_CFG}"
+ if [[ "${VARIANT}" == "multilingual" ]]; then
+ MULTILINGUAL_FLAG="--multilingual"; voice_clone_mode "_multilingual"
+ else
+ MULTILINGUAL_FLAG="--no-multilingual"; voice_clone_mode
+ fi
+}
+
+# Skip (model, dataset) combos the checkpoint can't synthesize — the third MODEL_CONFIGS field is a
+# comma-separated list of supported language codes.
+supports_language() {
+ local want="$1" _ _v LANGS
+ read -r _ _v LANGS <<< "${MODEL_CFG}"
+ [[ ",${LANGS}," == *",${want},"* ]]
+}
+
+# ── Stage 1: TTS generation. Chatterbox synthesizes one sample at a time — no batch size. ──
+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/chatterbox && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --language=${ASR_LANG} \
+ --device=cuda:0 \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} \
+ ${MULTILINGUAL_FLAG} \
+ ${VOICE_CLONE_FLAG} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment to pick) ────────
+DATASET_CONFIGS=(
+ "tts en en"
+ "tts zh zh"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot fr fr ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot zh zh ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ja ja ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ko ko ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot de de ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot it it ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ru ru ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id variant supported_langs" (CLI args override) ───────────
+# variant: `english` -> ChatterboxTTS (English-only checkpoint, no language argument)
+# `multilingual` -> ChatterboxMultilingualTTS (needs language_id; `_multilingual` suffix)
+# supported_langs: comma-separated codes; combos outside the list are skipped (supports_language).
+# The two rows are different checkpoints in the same repo, separated by the manifest suffix.
+MODEL_CONFIGS=(
+ "ResembleAI/chatterbox english en"
+ "ResembleAI/chatterbox multilingual ar,da,de,el,en,es,fi,fr,he,hi,it,ja,ko,ms,nl,no,pl,pt,ru,sv,sw,tr,zh"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/cosyvoice3/run_eval.py b/cosyvoice3/run_eval.py
new file mode 100644
index 0000000..7e596ca
--- /dev/null
+++ b/cosyvoice3/run_eval.py
@@ -0,0 +1,483 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (Fun-CosyVoice3 backend, stage 1).
+
+There is no reference-free mode: the HF weights ship no `spk2info.pt`, and every other entry point
+takes a `prompt_wav`. The two modes differ in WHICH reference is used:
+
+ --voice_clone: each sample clones its own `prompt_audio`/`prompt_text`, so SIM can be
+ scored. Outputs get a `_voice_clone` suffix.
+ --no-voice_clone (default): ONE fixed reference for the whole split (default: the split's sample
+ `--fixed_prompt_index`, so it is language-matched), for WER/CER comparison against the
+ fixed-voice backends. SIM is skipped.
+
+Upstream behaviours worked around here:
+
+1. `inference_zero_shot()` yields one waveform PER SENTENCE; `synth_one` concatenates them.
+2. The reference is passed as a file path, so prompts are written to wavs (under `results/` for
+ stage 3), clipped to <= 30 s and upsampled to >= 16 kHz to satisfy upstream asserts.
+3. CosyVoice3 expects an instruct prefix on the PROMPT text (see upstream `cosyvoice3_example()`).
+4. The text frontend routes all non-Chinese text through the English wetext normalizer, which can
+ crash on some inputs (e.g. "1970년", "#5", doubled spaces); `synth_one` retries those with
+ `text_frontend=False`. It also spells digits out in English for non-en/zh text, so prefer
+ `--no_text_frontend` there.
+
+No native batching: texts are synthesized one at a time and `--batch_size` only controls manifest
+chunking / resume; per-sample time is batch time / batch size. `--device` is used only for timing,
+since `CosyVoiceModel` hardcodes `torch.device('cuda')`.
+"""
+
+import argparse
+import logging
+import os
+import sys
+import time
+import warnings
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+from run_eval_utils import (
+ add_common_args, load_done_entries, load_tts_dataset, manifest_entry, open_manifest, output_paths,
+ pending_batches, print_model_size, print_next_steps, set_seed, wav_rel_path, warm_up, write_entry,
+)
+
+# `cosyvoice` is used from a clone of the upstream repo; third_party/Matcha-TTS must be importable
+# too (cosyvoice3.yaml instantiates a matcha module at load time).
+COSYVOICE_ROOT = os.environ.get("COSYVOICE_ROOT", "/opt/CosyVoice")
+sys.path.insert(0, COSYVOICE_ROOT)
+sys.path.insert(0, os.path.join(COSYVOICE_ROOT, "third_party/Matcha-TTS"))
+
+# Silence cosyvoice's per-chunk INFO logs and per-sample warnings.
+warnings.filterwarnings("ignore")
+logging.getLogger().setLevel(logging.ERROR)
+
+from cosyvoice.cli.cosyvoice import AutoModel # noqa: E402
+
+torch.set_float32_matmul_precision("high")
+
+# Instruct-style prefix prepended to the PROMPT text. Overridable with --instruct_prefix.
+INSTRUCT_PREFIX = "You are a helpful assistant.<|endofprompt|>"
+# frontend._extract_speech_token() asserts prompt duration <= 30 s.
+PROMPT_MAX_SECONDS = 30.0
+# file_utils.load_wav() asserts sample_rate >= 16000 whenever it has to resample.
+PROMPT_MIN_SR = 16000
+
+
+def _resolve_model_dir(args):
+ """Return the model dir to load, honouring --llm_checkpoint.
+
+ `CosyVoice3Model.load()` hardcodes `llm.pt`, so to select `llm.rl.pt` without mutating the
+ weights dir, build a shadow dir of symlinks whose `llm.pt` points at the requested checkpoint.
+ """
+ model_dir = args.checkpoint_path if os.path.isdir(args.checkpoint_path) else args.model_id
+ if args.llm_checkpoint == "llm.pt":
+ return model_dir
+ if not os.path.isdir(model_dir):
+ raise ValueError(
+ f"--llm_checkpoint={args.llm_checkpoint} needs the weights on disk to build a shadow "
+ f"dir, but {args.checkpoint_path} is not a directory. Bake or download the weights first."
+ )
+ # Symlink targets must be absolute (relative ones resolve against the shadow dir).
+ abs_model_dir = os.path.abspath(model_dir)
+ src = os.path.join(abs_model_dir, args.llm_checkpoint)
+ if not os.path.exists(src):
+ raise ValueError(f"LM checkpoint {src} not found.")
+ shadow = os.path.join(args.shadow_dir, os.path.basename(abs_model_dir) + "_" + args.llm_checkpoint)
+ os.makedirs(shadow, exist_ok=True)
+ for name in os.listdir(abs_model_dir):
+ # Everything is symlinked through as-is except the LM, which is aliased to `llm.pt`.
+ if name in ("llm.pt", args.llm_checkpoint):
+ continue
+ link = os.path.join(shadow, name)
+ if not os.path.lexists(link):
+ os.symlink(os.path.join(abs_model_dir, name), link)
+ # Re-link unconditionally so a stale alias is never reused.
+ link = os.path.join(shadow, "llm.pt")
+ if os.path.lexists(link):
+ os.remove(link)
+ os.symlink(src, link)
+ print(f"Using LM checkpoint '{args.llm_checkpoint}' via shadow dir {shadow}")
+ return shadow
+
+
+def main(args):
+ # Set seed for reproducibility (the LM uses RAS sampling and the flow head is a CFM sampler).
+ seed = args.seed
+ set_seed(seed)
+ torch.backends.cudnn.deterministic = True
+
+ model = AutoModel(model_dir=_resolve_model_dir(args), fp16=args.fp16)
+ sampling_rate = int(model.sample_rate) # Fun-CosyVoice3: 24 kHz
+ print(
+ f"Loaded {args.model_id} (llm={args.llm_checkpoint}, sr={sampling_rate}, fp16={args.fp16}, "
+ f"speed={args.speed}, text_frontend={not args.no_text_frontend})"
+ )
+
+ # Parameter count: nn.Modules hang off `model.model` (.llm/.flow/.hift), a plain class, so walk
+ # both levels.
+ try:
+ print_model_size(model, getattr(model, "model", None))
+ except Exception as e:
+ print(f"Could not determine model size: {e}")
+
+ # Flat, bucket-friendly layout, per model:
+ # results/<model_safe>/ MODEL_<safe>_DATASET_<dsid>.jsonl + <dsid>/output_<id>.wav
+ # Manifest paths are relative to model_dir, so downstream stages resolve them wherever it is copied.
+ # The base and RL LMs share one model id, so the RL run gets its own suffix (as do voice modes).
+ # Must match resolve_mode() in submit_jobs.sh.
+ variant_suffix = "" if args.llm_checkpoint == "llm.pt" else "_rl"
+ mode_suffix = f"{variant_suffix}{'_voice_clone' if args.voice_clone else ''}"
+ paths = output_paths(args, mode_suffix)
+ model_dir, dataset_dir_name, output_dir = paths.model_dir, paths.dataset_dir_name, paths.output_dir
+
+ # The frontend opens the reference as a file, so prompts are written here (under `results/`
+ # so stage 3 can read them back to score speaker similarity).
+ os.makedirs(os.path.join(output_dir, "prompts"), exist_ok=True)
+ n_clipped = 0 # prompts truncated to PROMPT_MAX_SECONDS (reported at the end)
+ n_frontend_fallback = 0 # samples re-synthesized without the text frontend (see synth_one)
+ # Fixed-voice mode: one reference for the whole split, filled in after the dataset is loaded.
+ fixed_prompt = {"full": None, "text": None}
+
+ def write_prompt(path, prompt_audio):
+ """Write one cloning reference, enforcing the frontend's duration/sample-rate asserts."""
+ nonlocal n_clipped
+ array = np.asarray(prompt_audio["array"], dtype=np.float32).reshape(-1)
+ sr = int(prompt_audio["sampling_rate"])
+ # load_wav() asserts sr >= 16 kHz whenever it resamples.
+ if sr < PROMPT_MIN_SR:
+ import librosa # a cosyvoice dependency; imported lazily since this is the rare path
+
+ array = librosa.resample(array, orig_sr=sr, target_sr=PROMPT_MIN_SR)
+ sr = PROMPT_MIN_SR
+ # _extract_speech_token() asserts <= 30 s; some in-the-wild references exceed it.
+ max_samples = int(PROMPT_MAX_SECONDS * sr)
+ if len(array) > max_samples:
+ array = array[:max_samples]
+ n_clipped += 1
+ sf.write(path, array, sr)
+
+ def synth_one(text, prompt_text, prompt_path):
+ """Synthesize one utterance, concatenating the per-sentence chunks the generator yields."""
+ nonlocal n_frontend_fallback
+ # Re-seed per sample so sampling is reproducible regardless of batch layout.
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+
+ def infer(text_frontend):
+ return [
+ out["tts_speech"]
+ for out in model.inference_zero_shot(
+ text,
+ prompt_text,
+ prompt_path,
+ stream=False,
+ speed=args.speed,
+ text_frontend=text_frontend,
+ )
+ ]
+
+ try:
+ chunks = infer(not args.no_text_frontend)
+ except Exception as e:
+ # The English wetext normalizer crashes on some non-English inputs (module docstring,
+ # item 4). It runs before the first yield, so retrying with the frontend off is clean.
+ n_frontend_fallback += 1
+ print(
+ f"Warning: text frontend raised {type(e).__name__}; retrying with "
+ f"text_frontend=False for text: {text[:80]}"
+ )
+ chunks = infer(False)
+ if not chunks:
+ print(f"Warning: no audio generated for text: {text[:60]}...")
+ return np.zeros(int(0.1 * sampling_rate), dtype=np.float32)
+ # One chunk per sentence.
+ audio = torch.cat(chunks, dim=1) if len(chunks) > 1 else chunks[0]
+ return np.asarray(audio.detach().to(torch.float32).cpu()).reshape(-1)
+
+ def generate_tts(batch):
+ """Synthesize a minibatch of target texts (per-sample loop); time the batch for RTFx."""
+ texts_to_generate = list(batch[args.text_column])
+ minibatch_size = len(texts_to_generate)
+
+ if args.voice_clone:
+ # Write the per-sample prompts before timing (I/O is not generation). The relative path
+ # goes into the manifest for stage 3 (SIM).
+ prompt_rel_paths, prompt_full_paths = [], []
+ for sample_id, prompt_audio in zip(batch["id"], batch["prompt_audio"]):
+ prel = os.path.join(dataset_dir_name, "prompts", f"prompt_{sample_id}.wav")
+ ppath = os.path.join(model_dir, prel)
+ if not os.path.exists(ppath):
+ write_prompt(ppath, prompt_audio)
+ prompt_rel_paths.append(prel)
+ prompt_full_paths.append(ppath)
+ raw_prompt_texts = list(batch["prompt_text"])
+ else:
+ # Fixed-voice mode: the same reference for every sample; no SIM.
+ prompt_rel_paths = [None] * minibatch_size
+ prompt_full_paths = [fixed_prompt["full"]] * minibatch_size
+ raw_prompt_texts = [fixed_prompt["text"]] * minibatch_size
+ # CosyVoice3 wants the instruct prefix on the PROMPT text.
+ prompt_texts = [f"{args.instruct_prefix}{t}" for t in raw_prompt_texts]
+
+ # START TIMING (TTS generation for the whole minibatch)
+ torch.cuda.synchronize(device=args.device)
+ start_event = torch.cuda.Event(enable_timing=True)
+ end_event = torch.cuda.Event(enable_timing=True)
+ start_event.record()
+
+ # No batched API (inference_zero_shot takes one string): loop per sample.
+ wavs = [
+ synth_one(text, prompt_text, prompt_path)
+ for text, prompt_text, prompt_path in zip(texts_to_generate, prompt_texts, prompt_full_paths)
+ ]
+
+ # END TIMING
+ end_event.record()
+ torch.cuda.synchronize(device=args.device)
+ runtime = start_event.elapsed_time(end_event) / 1000.0
+ # per-sample generation time (RTFx is aggregated over the whole set at scoring time)
+ batch["generation_time_s"] = minibatch_size * [runtime / minibatch_size]
+
+ gen_paths, audio_length_s = [], []
+ for audio, sample_id in zip(wavs, batch["id"]):
+ rel_path = wav_rel_path(dataset_dir_name, sample_id)
+ sf.write(os.path.join(model_dir, rel_path), audio, sampling_rate)
+ gen_paths.append(rel_path)
+ audio_length_s.append(len(audio) / sampling_rate)
+
+ batch["gen_audio_filepath"] = gen_paths
+ batch["prompt_audio_filepath"] = prompt_rel_paths
+ batch["audio_length_s"] = audio_length_s
+ batch["references"] = list(batch[args.text_column]) # raw; normalized at scoring time
+ return batch
+
+ # The reference columns are kept in both modes (fixed-voice mode may take its one reference
+ # from the split); they are dropped below when not cloning.
+ dataset = load_tts_dataset(args, ("prompt_text", "prompt_audio"))
+
+ # A reference is mandatory in both modes, so the dataset must carry one unless fixed-voice mode
+ # was given an external reference.
+ needs_dataset_prompt = args.voice_clone or not args.prompt_audio_path
+ missing = [c for c in ("prompt_text", "prompt_audio") if c not in dataset.column_names]
+ if missing and needs_dataset_prompt:
+ raise ValueError(
+ f"Dataset {args.dataset_path}/{args.dataset}/{args.split} is missing {missing}. "
+ "Fun-CosyVoice3 has no built-in speaker (no spk2info.pt ships with the weights), so a "
+ "reference audio is required in every mode. Pass --prompt_audio_path/--prompt_text to "
+ "supply one externally."
+ )
+
+ # ── Fixed-voice mode: resolve the ONE reference used for the whole split ──
+ if not args.voice_clone:
+ fixed_rel = os.path.join(dataset_dir_name, "prompts", "fixed_prompt.wav")
+ fixed_full = os.path.join(model_dir, fixed_rel)
+ if args.prompt_audio_path:
+ if not args.prompt_text:
+ raise ValueError("--prompt_audio_path requires --prompt_text (the reference's transcript).")
+ audio, sr = sf.read(args.prompt_audio_path, dtype="float32", always_2d=True)
+ write_prompt(fixed_full, {"array": audio.mean(axis=1), "sampling_rate": sr})
+ fixed_prompt["text"] = args.prompt_text
+ src = args.prompt_audio_path
+ else:
+ # Default: the split's own sample #--fixed_prompt_index, which keeps the reference
+ # language-matched.
+ if not 0 <= args.fixed_prompt_index < len(dataset):
+ raise ValueError(
+ f"--fixed_prompt_index={args.fixed_prompt_index} is out of range for a "
+ f"{len(dataset)}-sample split."
+ )
+ row = dataset[args.fixed_prompt_index]
+ write_prompt(fixed_full, row["prompt_audio"])
+ fixed_prompt["text"] = row["prompt_text"]
+ src = f"{args.dataset}/{args.split} sample #{args.fixed_prompt_index} (id={row.get('id')})"
+ fixed_prompt["full"] = fixed_full
+ print(
+ f"Fixed-voice mode: one reference for all {len(dataset)} samples, from {src}. "
+ f"SIM is skipped (no per-sample reference)."
+ )
+
+ # Fixed-voice mode: drop the reference columns so nothing else triggers audio decoding.
+ if not args.voice_clone:
+ dataset = dataset.remove_columns([c for c in ("prompt_text", "prompt_audio") if c in dataset.column_names])
+
+ probe_out_dir = model_dir # real results dir, captured before the probe rebinds model_dir
+ # ── TTFA probe: latency only, writing nothing but a JSON sidecar ─────────
+ # One request at a time with stream=True, so the first-chunk timestamp is real. Returns before
+ # the main loop, so it never affects WER/RTFx. See scripts/ttfa_probe.py.
+ if args.ttfa_probe != 0:
+ # Imported here: the probe module is injected only by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+ import tempfile
+
+ model_dir = tempfile.mkdtemp(prefix="ttfa_out_")
+ dataset_dir_name = "ttfa"
+ output_dir = os.path.join(model_dir, dataset_dir_name)
+ os.makedirs(os.path.join(output_dir, "prompts"), exist_ok=True)
+
+ chunk_counts = [] # chunks per utterance
+ # Pristine value, read before anything has generated (see the reset in _gen).
+ token_hop_len_init = getattr(model.model, "token_hop_len", None)
+
+ def _gen(job, early_stop):
+ """One request with stream=True, timestamping the first chunk."""
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+ # CosyVoice2Model.tts() grows self.token_hop_len on every yield and never restores it,
+ # so later requests would stream nothing. Reset it so each request starts fresh.
+ if token_hop_len_init is not None:
+ model.model.token_hop_len = token_hop_len_init
+ first, chunks = None, []
+ for out in model.inference_zero_shot(
+ job[args.text_column][0],
+ f"{args.instruct_prefix}{job['_prompt_text']}",
+ job["_prompt_path"],
+ stream=True,
+ speed=args.speed,
+ text_frontend=not args.no_text_frontend,
+ ):
+ chunk = out["tts_speech"].reshape(-1).detach().to(torch.float32).cpu()
+ if first is None:
+ first = time.perf_counter()
+ chunks.append(chunk)
+ if early_stop:
+ break
+ chunk_counts.append(len(chunks))
+ if not chunks:
+ return 0.0, sampling_rate, None
+ return torch.cat(chunks).numpy(), sampling_rate, first
+
+ columns = dataset.column_names
+ jobs = []
+ for i in sample_indices(args.ttfa_probe, len(dataset)):
+ job = {c: [dataset[i][c]] for c in columns}
+ if args.voice_clone:
+ ref = os.path.join(output_dir, "prompts", f"prompt_{dataset[i]['id']}.wav")
+ write_prompt(ref, dataset[i]["prompt_audio"])
+ job["_prompt_path"], job["_prompt_text"] = ref, dataset[i]["prompt_text"]
+ else:
+ # Fixed-voice mode: the one reference the eval uses for the whole split.
+ job["_prompt_path"], job["_prompt_text"] = fixed_prompt["full"], fixed_prompt["text"]
+ jobs.append(job)
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=probe_out_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ # token_hop_len sets the streaming granularity, i.e. the floor under TTFA.
+ extra={"device": args.device, "note": "driven at batch size 1, stream=True",
+ "chunks_per_utterance": chunk_counts,
+ "token_hop_len": token_hop_len_init},
+ )
+ return
+
+ # ── Manifest (written incrementally; resume skips rows already in it) ───
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ # ── Main loop: TTS → write JSONL, one batch at a time ───────────────────
+ starts = pending_batches(dataset, args.batch_size, done_entries, dataset_dir_name)
+ warm_up(generate_tts, dataset, starts, args.batch_size, args.warmup_steps)
+ for batch_start in tqdm(starts, desc="Generating"):
+ batch = generate_tts(dataset[batch_start : batch_start + args.batch_size])
+
+ # Append each sample to the JSONL immediately. Only cloning runs carry the prompt path (its
+ # absence tells the pipeline to skip SIM).
+ for afp, ppath, alen, gtime, ref in zip(
+ batch["gen_audio_filepath"], batch["prompt_audio_filepath"], batch["audio_length_s"],
+ batch["generation_time_s"], batch["references"],
+ ):
+ entry = manifest_entry(afp, alen, gtime, ref, ppath if args.voice_clone else None)
+ write_entry(manifest_file, entry)
+ manifest_file.flush()
+
+ manifest_file.close()
+ if n_clipped:
+ print(f"NOTE: {n_clipped} prompt(s) were longer than {PROMPT_MAX_SECONDS:.0f}s and were clipped "
+ "(the frontend hard-asserts this limit).")
+ if n_frontend_fallback:
+ print(f"NOTE: {n_frontend_fallback} sample(s) crashed the (English) text frontend and were "
+ "synthesized from raw text instead — see the warnings above.")
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(args.voice_clone)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument(
+ "--model_id",
+ type=str,
+ default="FunAudioLLM/Fun-CosyVoice3-0.5B-2512",
+ help="Model id, used for the results folder / manifest name (and as the download fallback).",
+ )
+ parser.add_argument(
+ "--checkpoint_path",
+ type=str,
+ default="/opt/models/Fun-CosyVoice3-0.5B-2512",
+ help="Local dir with the weights (baked at image build); falls back to --model_id on the Hub.",
+ )
+ parser.add_argument(
+ "--llm_checkpoint",
+ type=str,
+ default="llm.pt",
+ choices=["llm.pt", "llm.rl.pt"],
+ help="Which LM checkpoint to load: 'llm.pt' (base) or 'llm.rl.pt' (the RL model, a separate "
+ "row in the model card's results table). The RL run gets an '_rl' manifest suffix.",
+ )
+ parser.add_argument(
+ "--shadow_dir",
+ type=str,
+ default="/tmp",
+ help="Where to build the symlink shadow dir used to select a non-default --llm_checkpoint.",
+ )
+ # --device is for our timing calls only (CosyVoiceModel hardcodes 'cuda'), so it must name the
+ # first visible GPU. --batch_size is only the manifest chunk size (generation is per sample).
+ add_common_args(parser, batch_size=32, voice_clone=False)
+ parser.add_argument("--fp16", action="store_true", help="Run the flow/hift stack in fp16 (default: fp32).")
+ parser.add_argument("--speed", type=float, default=1.0, help="Speaking-rate multiplier (1.0 = unchanged).")
+ parser.add_argument(
+ "--no_text_frontend",
+ action="store_true",
+ help="Disable cosyvoice's text frontend (wetext normalization + sentence splitting). Left ON "
+ "by default to match the library default.",
+ )
+ parser.add_argument(
+ "--instruct_prefix",
+ type=str,
+ default=INSTRUCT_PREFIX,
+ help="Instruct-style prefix prepended to the PROMPT text, as CosyVoice3 expects.",
+ )
+ # --voice_clone / --no-voice_clone (default): see the module docstring. A reference is required
+ # either way: CosyVoice3 has no reference-free entry point.
+ parser.add_argument(
+ "--fixed_prompt_index",
+ type=int,
+ default=0,
+ help="--no-voice_clone only: which sample of the split supplies the single reference. Taking "
+ "it from the split itself keeps the voice language-matched.",
+ )
+ parser.add_argument(
+ "--prompt_audio_path",
+ type=str,
+ default=None,
+ help="--no-voice_clone only: use this wav as the fixed reference instead of a dataset sample "
+ "(requires --prompt_text). Lets one voice be held constant across languages.",
+ )
+ parser.add_argument(
+ "--prompt_text",
+ type=str,
+ default=None,
+ help="Transcript of --prompt_audio_path (CosyVoice3 conditions on the reference's text).",
+ )
+
+ 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/cosyvoice3/submit_jobs.sh b/cosyvoice3/submit_jobs.sh
new file mode 100755
index 0000000..fceb446
--- /dev/null
+++ b/cosyvoice3/submit_jobs.sh
@@ -0,0 +1,83 @@
+#!/bin/bash
+# HF Jobs TTS eval — Fun-CosyVoice3 backend (generate → transcribe → SIM* → score; *voice-clone only).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["FunAudioLLM/Fun-CosyVoice3-0.5B-2512 32" ...]
+# 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-cosy}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-cosy/blob/main/Dockerfile)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# ── Voice mode ───────────────────────────────────────────────────────────────
+# A reference audio is mandatory either way (no built-in speaker); the toggle picks WHICH one:
+# VOICE_CLONE=true each sample clones its own prompt_audio -> SIM stage runs.
+# VOICE_CLONE=false (default) ONE fixed reference for the whole split (the split's sample 0,
+# language-matched); SIM is skipped.
+
+# The base and RL LMs share one HF model id, so the RL run gets its own manifest suffix (matching
+# run_eval.py). MODEL_CFG's optional 3rd field selects the checkpoint.
+resolve_mode() {
+ local _ _bs LLM VARIANT
+ read -r _ _bs LLM <<< "${MODEL_CFG}"
+ LLM="${LLM:-llm.pt}"
+ VARIANT=""; [[ "${LLM}" != "llm.pt" ]] && VARIANT="_rl"
+ voice_clone_mode "${VARIANT}"
+}
+
+# ── Languages Fun-CosyVoice3 covers (model card: 9 languages) ────────────────
+# Matched against asr_language (so `zh_hard` / `hard_zh` match `zh`).
+COSYVOICE3_LANGUAGES=" zh en ja ko de es fr it ru "
+supports_language() { [[ "${COSYVOICE3_LANGUAGES}" == *" $1 "* ]]; }
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id batch_size [llm_checkpoint]". ──
+# No batched API (inference_zero_shot takes one string); --batch_size only chunks manifest
+# writing / resume.
+generate_stage() {
+ local _ BATCH_SIZE LLM
+ read -r _ BATCH_SIZE LLM <<< "${MODEL_CFG}"
+ LLM="${LLM:-llm.pt}"
+ 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/cosyvoice3 && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --llm_checkpoint=${LLM} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --device=cuda:0 \
+ --batch_size=${BATCH_SIZE} \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} \
+ ${VOICE_CLONE_FLAG} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment) ──
+DATASET_CONFIGS=(
+ "tts en en"
+ "tts zh zh"
+ "zero_shot de de ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ko ko ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ru ru ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ja ja ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot zh zh ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot fr fr ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot it it ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id batch_size [llm_checkpoint]" (CLI args override) ───────
+# The base (llm.pt) and RL (llm.rl.pt) checkpoints write separate manifests, so both can coexist.
+MODEL_CONFIGS=(
+ # "FunAudioLLM/Fun-CosyVoice3-0.5B-2512 32"
+ "FunAudioLLM/Fun-CosyVoice3-0.5B-2512 32 llm.rl.pt"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/fishaudio-s2-pro/run_eval.py b/fishaudio-s2-pro/run_eval.py
new file mode 100644
index 0000000..29e547e
--- /dev/null
+++ b/fishaudio-s2-pro/run_eval.py
@@ -0,0 +1,278 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (Fish Audio S2-Pro backend, stage 1).
+
+S2-Pro (fishaudio/s2-pro) is a ~5B dual-AR TTS run in-process from the cloned `fish-speech` repo,
+one sample at a time (no batched API). Output is 44.1 kHz mono.
+
+With --voice_clone each sample's reference clip is encoded to VQ tokens and passed with its
+transcript; the reference wav is saved for SIM and outputs get a `_voice_clone` suffix. By default
+(--no-voice_clone) the default (seed-dependent) voice is used.
+"""
+
+import argparse
+import os
+import sys
+import time
+from functools import partial
+
+import numpy as np
+import soundfile as sf
+import torch
+from loguru import logger
+from tqdm import tqdm
+
+from run_eval_utils import (
+ add_common_args,
+ count_parameters,
+ 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,
+)
+
+import fish_speech.models.text2semantic.inference as fs_inference # noqa: E402
+from fish_speech.conversation import Conversation # noqa: E402
+from fish_speech.models.text2semantic.inference import ( # noqa: E402
+ init_model,
+ generate_long,
+ load_codec_model,
+ decode_to_audio,
+ encode_audio,
+)
+
+# Silence fish-speech's per-sample loguru INFO logs, per-token tqdm bar and prompt dump.
+logger.remove()
+logger.add(sys.stderr, level="WARNING")
+fs_inference.tqdm = partial(tqdm, disable=True)
+Conversation.visualize = lambda self, *args, **kwargs: None
+
+
+def main(args):
+ seed = args.seed
+ set_seed(seed)
+
+ device = args.device
+ precision = getattr(torch, args.dtype)
+
+ # Load text2semantic model (returns model + its single-token decode fn) and set up caches.
+ model, decode_one_token = init_model(args.checkpoint_path, device, precision, compile=False)
+ with torch.device(device):
+ model.setup_caches(
+ max_batch_size=1,
+ max_seq_len=model.config.max_seq_len,
+ dtype=next(model.parameters()).dtype,
+ )
+ codec = load_codec_model(os.path.join(args.checkpoint_path, "codec.pth"), device, precision)
+ sampling_rate = int(codec.sample_rate) # 44100
+ print(f"Loaded S2-Pro ({args.model_id}, sr={sampling_rate})")
+ n_params = count_parameters(model, codec)
+ if n_params:
+ print(f"TTS model size: {n_params / 1e9:.2f}B parameters (text2semantic + codec)")
+
+ is_cuda = str(device).startswith("cuda")
+
+ def synth_one_streaming(text, prompt_tokens=None, prompt_text=None, early_stop=False):
+ """Like synth_one, but timestamps the first audio: (audio_1d_numpy, first_audio_ts).
+
+ TTFA probe only. The first generate_long() segment is decoded as soon as it arrives (that
+ decode counts toward TTFA). Segments split only on `<|speaker:N|>` tags, so eval texts are
+ a single segment and `first` lands at end of generation; chunk-level streaming TTFA is
+ measured via sglang-omni instead (the s2pro-sglang target in submit_ttfa_jobs.sh).
+ """
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+ first, codes, pieces = None, [], []
+ for resp in generate_long(
+ model=model, device=device, decode_one_token=decode_one_token, text=text,
+ num_samples=1, max_new_tokens=args.max_new_tokens, top_p=args.top_p,
+ top_k=args.top_k, temperature=args.temperature, compile=False,
+ prompt_text=prompt_text, prompt_tokens=prompt_tokens,
+ ):
+ if resp.action == "sample":
+ codes.append(resp.codes)
+ if first is None:
+ seg = decode_to_audio(resp.codes.to(device), codec)
+ pieces.append(np.asarray(seg.detach().to(torch.float32).cpu()).reshape(-1))
+ first = time.perf_counter()
+ if early_stop:
+ break
+ elif resp.action == "next":
+ break
+ if not codes:
+ return np.zeros(1, dtype=np.float32), None
+ if len(codes) > 1:
+ rest = decode_to_audio(torch.cat(codes[1:], dim=1).to(device), codec)
+ pieces.append(np.asarray(rest.detach().to(torch.float32).cpu()).reshape(-1))
+ return np.concatenate(pieces), first
+
+ def synth_one(text, prompt_tokens=None, prompt_text=None):
+ """Synthesize one text; return (audio_1d_numpy, elapsed_s).
+
+ When prompt_tokens + prompt_text are given the generation is conditioned on that
+ reference clip (voice cloning); otherwise the default (seed-dependent) voice is used.
+ """
+ # Re-seed per sample so the (seed-dependent) default voice is consistent + reproducible.
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+ if is_cuda:
+ torch.cuda.synchronize()
+ start = time.perf_counter()
+
+ gen = generate_long(
+ model=model,
+ device=device,
+ decode_one_token=decode_one_token,
+ text=text,
+ num_samples=1,
+ max_new_tokens=args.max_new_tokens,
+ top_p=args.top_p,
+ top_k=args.top_k,
+ temperature=args.temperature,
+ compile=False,
+ prompt_text=prompt_text,
+ prompt_tokens=prompt_tokens,
+ )
+ codes = []
+ for resp in gen:
+ if resp.action == "sample":
+ codes.append(resp.codes)
+ elif resp.action == "next":
+ break
+
+ if codes:
+ merged = torch.cat(codes, dim=1) # (num_codebooks, T)
+ audio = decode_to_audio(merged.to(device), codec)
+ audio = np.asarray(audio.detach().to(torch.float32).cpu()).reshape(-1)
+ else:
+ audio = np.zeros(int(0.1 * sampling_rate), dtype=np.float32)
+
+ if is_cuda:
+ torch.cuda.synchronize()
+ return audio, time.perf_counter() - start
+
+ # 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.
+ mode_suffix = "_voice_clone" if args.voice_clone else ""
+ paths = output_paths(args, mode_suffix)
+ model_dir, dataset_dir_name, output_dir = paths.model_dir, paths.dataset_dir_name, paths.output_dir
+ # Persist reference clips under results/ so stage 3 (SIM) can read them from disk.
+ prompt_dir = os.path.join(output_dir, "prompts")
+ if args.voice_clone:
+ os.makedirs(prompt_dir, exist_ok=True)
+
+ dataset = load_tts_dataset(args, extra_columns=("prompt_text", "prompt_audio") if args.voice_clone else ())
+
+ # ── TTFA probe: writes ONLY a JSON sidecar (no wavs, no manifest) ─────────
+ # Same voice handling as the eval; references go to a temp dir so results are untouched.
+ # 0 = off; N > 0 = N evenly spaced samples; N < 0 = the whole split (see scripts/ttfa_probe.py).
+ if args.ttfa_probe != 0:
+ # Imported lazily: ttfa_probe.py is only injected by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+ import tempfile
+
+ tmp_dir = tempfile.mkdtemp(prefix="ttfa_refs_")
+
+ def _ttfa_ref(i):
+ if not args.voice_clone:
+ return None, None
+ path = os.path.join(tmp_dir, f"prompt_{dataset[i]['id']}.wav")
+ pa = dataset[i]["prompt_audio"]
+ sf.write(path, np.asarray(pa["array"], dtype=np.float32), pa["sampling_rate"])
+ return [encode_audio(path, codec, device).cpu()], [dataset[i]["prompt_text"]]
+
+ jobs = []
+ for i in sample_indices(args.ttfa_probe, len(dataset)):
+ job = {"text": dataset[i][args.text_column]}
+ job["prompt_tokens"], job["prompt_text"] = _ttfa_ref(i)
+ jobs.append(job)
+
+ def _ttfa_gen(job, early_stop):
+ audio, first = synth_one_streaming(
+ job["text"], prompt_tokens=job["prompt_tokens"], prompt_text=job["prompt_text"],
+ early_stop=early_stop,
+ )
+ return audio, sampling_rate, first
+
+ run_probe(
+ _ttfa_gen,
+ jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=model_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ extra={"device": args.device, "voice_clone": args.voice_clone},
+ )
+ return
+
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ def synth_row(row):
+ """Synthesize one dataset row; return (audio, elapsed, prompt_rel_path)."""
+ prompt_rel_path = prompt_tokens = prompt_text = None
+ if args.voice_clone:
+ # Save the reference clip (for SIM), then encode it to VQ tokens.
+ pa = row["prompt_audio"]
+ prompt_rel_path = os.path.join(dataset_dir_name, "prompts", f"prompt_{row['id']}.wav")
+ prompt_path = os.path.join(model_dir, prompt_rel_path)
+ if not os.path.exists(prompt_path):
+ sf.write(prompt_path, np.asarray(pa["array"], dtype=np.float32), pa["sampling_rate"])
+ # generate_long expects lists (one entry per reference segment); a bare tensor fails
+ # its `bool(prompt_tokens)` check.
+ prompt_text = [row["prompt_text"]]
+ prompt_tokens = [encode_audio(prompt_path, codec, device).cpu()]
+ audio, elapsed = synth_one(row[args.text_column], prompt_tokens=prompt_tokens, prompt_text=prompt_text)
+ return audio, elapsed, prompt_rel_path
+
+ # ── Main loop: synthesize one sample at a time → write JSONL ─────────────
+ starts = pending_batches(dataset, 1, done_entries, dataset_dir_name)
+ warm_up(lambda b: synth_row({k: v[0] for k, v in b.items()}), dataset, starts, 1, args.warmup_steps)
+ for i in tqdm(starts, desc="Generating"):
+ row = dataset[i]
+ # Store the path relative to model_dir (the manifest's dir); write to the full path.
+ rel_path = wav_rel_path(dataset_dir_name, row["id"])
+ audio, elapsed, prompt_rel_path = synth_row(row)
+ sf.write(os.path.join(model_dir, rel_path), audio, sampling_rate)
+
+ # `pred_text` is filled by stage 2 (ASR).
+ write_entry(manifest_file, manifest_entry(
+ rel_path, len(audio) / sampling_rate, elapsed, row[args.text_column], prompt_rel_path
+ ))
+ manifest_file.flush()
+
+ manifest_file.close()
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(args.voice_clone)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ add_common_args(parser, voice_clone=False)
+
+ parser.add_argument("--model_id", type=str, default="fishaudio/s2-pro", help="Model id (for manifest naming).")
+ parser.add_argument(
+ "--checkpoint_path",
+ type=str,
+ default="/opt/fish-speech/checkpoints/s2-pro",
+ help="Local dir with the S2-Pro safetensors + codec.pth (downloaded at image build).",
+ )
+ parser.add_argument("--dtype", type=str, default="bfloat16", help="Model precision, e.g. 'bfloat16'.")
+ parser.add_argument("--max_new_tokens", type=int, default=0, help="Max semantic tokens (0 = unbounded to context).")
+ parser.add_argument("--top_p", type=float, default=0.9, help="Top-p sampling.")
+ parser.add_argument("--top_k", type=int, default=30, help="Top-k sampling.")
+ parser.add_argument("--temperature", type=float, default=1.0, help="Sampling temperature.")
+
+ 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/fishaudio-s2-pro/submit_jobs.sh b/fishaudio-s2-pro/submit_jobs.sh
new file mode 100644
index 0000000..52cad06
--- /dev/null
+++ b/fishaudio-s2-pro/submit_jobs.sh
@@ -0,0 +1,52 @@
+#!/bin/bash
+# HF Jobs TTS eval — Fish Audio S2-Pro backend (generate → transcribe → SIM* → score; *voice-clone only).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["fishaudio/s2-pro" ...]
+# 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-fish}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-fish/blob/main/Dockerfile)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+SUPPORTS_VOICE_CLONE=true # VOICE_CLONE=true clones each sample's reference speaker + scores SIM
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id" (S2-Pro synthesizes 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/fishaudio-s2-pro && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --device=cuda:0 \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} \
+ ${VOICE_CLONE_FLAG} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment to pick) ────────
+DATASET_CONFIGS=(
+ "tts en en"
+ "tts zh zh"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot zh zh ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot fr fr ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ja ja ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ko ko ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot de de ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot it it ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ru ru ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id" (CLI args override) ───────────────────────────────────
+MODEL_CONFIGS=("fishaudio/s2-pro")
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/higgs/run_eval.py b/higgs/run_eval.py
new file mode 100644
index 0000000..b2ac50a
--- /dev/null
+++ b/higgs/run_eval.py
@@ -0,0 +1,435 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (Higgs TTS 3 backend, stage 1).
+
+Higgs TTS 3 is served by an SGLang server (`sgl-omni serve`, launched by higgs/submit_jobs.sh)
+exposing an OpenAI-compatible `/v1/audio/speech` endpoint, so this script is an HTTP client: it
+waits for the server, sends the target texts as synthesis requests, times the batched generation
+for RTFx, saves the wavs, and writes a manifest with `text`, `duration`, `time` and an empty
+`pred_text` (filled by stage 2 ASR; stage 3 scores SIM for voice-clone runs).
+
+Nothing here is Higgs-specific (`/v1/audio/speech` is sgl-omni's model-agnostic route), so
+submit_ttfa_jobs.sh also drives it against `fishaudio/s2-pro` (target `s2pro-sglang`). Keep
+model-specific values in the CLI defaults / the target's flags, not in the request-building code.
+
+Voice cloning (`--voice_clone`) conditions each request on the per-sample
+`prompt_audio`/`prompt_text`; outputs get a `_voice_clone` suffix. The default (`--no-voice_clone`)
+uses the model's default voice and skips SIM.
+"""
+
+import argparse
+import base64
+import io
+import json
+import os
+import time
+from concurrent.futures import ThreadPoolExecutor
+
+import numpy as np
+import requests
+import soundfile as sf
+from tqdm import tqdm
+
+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, warm_up, wav_rel_path, write_entry,
+)
+
+
+def print_model_size(model_id):
+ """Best-effort parameter count from the safetensors headers in the local HF cache.
+
+ The SGLang server has already downloaded the model; only shard headers are read.
+ """
+ try:
+ import struct
+
+ from huggingface_hub import hf_hub_download
+
+ def header_numels(path):
+ with open(path, "rb") as f:
+ header_len = struct.unpack("<Q", f.read(8))[0]
+ header = json.loads(f.read(header_len))
+ total = 0
+ for name, meta in header.items():
+ if name == "__metadata__":
+ continue
+ numel = 1
+ for d in meta.get("shape", []):
+ numel *= d
+ total += numel
+ return total
+
+ try:
+ # Sharded checkpoint: read the index, then each referenced shard's header.
+ idx = hf_hub_download(model_id, "model.safetensors.index.json", local_files_only=True)
+ with open(idx) as f:
+ weight_map = json.load(f)["weight_map"]
+ total = sum(header_numels(hf_hub_download(model_id, shard, local_files_only=True))
+ for shard in sorted(set(weight_map.values())))
+ except Exception:
+ # Single-file checkpoint.
+ total = header_numels(hf_hub_download(model_id, "model.safetensors", local_files_only=True))
+
+ print(f"TTS model size: {total / 1e9:.2f}B parameters")
+ except Exception as e:
+ print(f"Could not determine model size from cache: {e}")
+
+
+def wait_for_server(base_url, timeout_s, heartbeat_s=60):
+ """Poll the SGLang server's /health endpoint until it is ready (or time out).
+
+ Prints a heartbeat while waiting: the server logs to its own file, so otherwise the job
+ prints nothing until ready (weight download can take minutes).
+ """
+ started = time.time()
+ deadline = started + timeout_s
+ last_err = None
+ next_beat = started + heartbeat_s
+ while time.time() < deadline:
+ try:
+ r = requests.get(f"{base_url}/health", timeout=5)
+ if r.status_code == 200:
+ print(f"SGLang server ready at {base_url} after {time.time() - started:.0f}s")
+ return
+ except requests.RequestException as e:
+ last_err = e
+ now = time.time()
+ if now >= next_beat:
+ print(f" waiting for {base_url} ... {now - started:.0f}s elapsed "
+ f"(timeout {timeout_s}s; server output goes to its own log, dumped on failure)",
+ flush=True)
+ next_beat = now + heartbeat_s
+ time.sleep(3)
+ raise RuntimeError(f"SGLang server at {base_url} not ready after {timeout_s}s (last error: {last_err})")
+
+
+def main(args):
+ base_url = f"http://{args.host}:{args.port}"
+ wait_for_server(base_url, args.server_timeout)
+ # Server is up => the model is in the HF cache; report its parameter count.
+ print_model_size(args.model_id)
+
+ def speech_payload(job):
+ """Request body for one synthesis, shared by the batched path and the TTFA probe.
+
+ `job` is a (text, reference) tuple, where reference is the per-sample voice-clone
+ payload (a one-element list of {audio_path, text}) or None for the default voice.
+
+ --top_p is omitted unless set, so the server keeps the served model's own default.
+ """
+ text, reference = job
+ payload = {
+ "input": text,
+ "max_new_tokens": args.max_new_tokens,
+ "temperature": args.temperature,
+ "top_k": args.top_k,
+ # Fixed seed for reproducibility (harmless if the endpoint ignores it).
+ "seed": args.seed,
+ }
+ if args.top_p is not None:
+ payload["top_p"] = args.top_p
+ if reference is not None:
+ payload["references"] = reference
+ return payload
+
+ def synthesize(job):
+ """Send one synthesis request; return the raw WAV bytes."""
+ resp = requests.post(f"{base_url}/v1/audio/speech", json=speech_payload(job),
+ timeout=args.request_timeout)
+ if resp.status_code != 200:
+ raise RuntimeError(f"Synthesis request failed ({resp.status_code}): {resp.text[:500]}")
+ return resp.content
+
+ # The streaming dialect is server-version dependent, so it is negotiated on the first probe
+ # request and then reused:
+ # {"stream": True, "response_format": "pcm"} pinned sgl-omni: raw `audio/pcm` body, format
+ # in X-Sample-Rate / X-Channels / X-Bit-Depth (stream without pcm is rejected with 400).
+ # {"stream": True} the model card's SSE example: base64 audio chunks in `data:` events.
+ # {} no streaming — buffered whole utterance, first_ts None (whole-utterance clock).
+ STREAM_MODES = ({"stream": True, "response_format": "pcm"}, {"stream": True}, {})
+ stream_mode = [None] # index into STREAM_MODES; pinned after the first request that works
+
+ # Bytes per sample per channel, by soundfile subtype. Needed to length an SSE chunk that
+ # carries no RIFF header of its own (see _read_sse).
+ SUBTYPE_BYTES = {"PCM_16": 2, "PCM_24": 3, "PCM_32": 4, "FLOAT": 4, "DOUBLE": 8}
+
+ def _read_pcm(resp, early_stop):
+ """Raw PCM stream -> (audio_seconds, first_ts, n_chunks).
+
+ The body is headerless samples, so the first byte received is a real first-audio time.
+ """
+ rate = int(resp.headers["X-Sample-Rate"])
+ frame_bytes = (int(resp.headers.get("X-Channels", 1))
+ * int(resp.headers.get("X-Bit-Depth", 16)) // 8)
+ first, total, n_chunks = None, 0, 0
+ for chunk in resp.iter_content(chunk_size=None):
+ if not chunk:
+ continue
+ n_chunks += 1
+ total += len(chunk)
+ if first is None:
+ first = time.perf_counter()
+ if early_stop:
+ # Closing the response stops the server sending; TTFA is already known.
+ break
+ return total / frame_bytes / rate, first, n_chunks
+
+ def _read_sse(resp, early_stop):
+ """Server-Sent Events stream -> (audio_seconds, first_ts, n_chunks).
+
+ Each `data: {...}` line carries base64 audio in `audio.data`; the terminal one has
+ `finish_reason: "stop"`. Duration is summed per chunk, which is correct whether chunks are
+ standalone WAVs or headerless PCM after a first WAV.
+ """
+ first, n_chunks, frames, rate, frame_bytes = None, 0, 0, None, None
+ # chunk_size=None so each line surfaces as soon as its bytes arrive; the default
+ # 512-byte read would add a buffer wait to the very measurement being taken.
+ for line in resp.iter_lines(chunk_size=None):
+ if not line or not line.startswith(b"data: ") or line == b"data: [DONE]":
+ continue
+ event = json.loads(line[6:])
+ if event.get("finish_reason") == "stop":
+ break
+ data = (event.get("audio") or {}).get("data")
+ if not data:
+ continue
+ chunk = base64.b64decode(data)
+ n_chunks += 1
+ if chunk[:4] == b"RIFF":
+ info = sf.info(io.BytesIO(chunk))
+ rate = info.samplerate
+ frame_bytes = info.channels * SUBTYPE_BYTES.get(info.subtype, 2)
+ frames += info.frames
+ elif frame_bytes:
+ frames += len(chunk) // frame_bytes
+ else:
+ raise RuntimeError(
+ "First streamed chunk carries no RIFF header, so its sample rate is unknown "
+ f"and the audio duration cannot be measured (first bytes: {chunk[:8]!r})"
+ )
+ # Timestamp the first chunk holding actual frames, not a bare WAV header.
+ if first is None and frames > 0:
+ first = time.perf_counter()
+ if early_stop:
+ break
+ if not rate:
+ raise RuntimeError("Event stream carried no audio chunks")
+ return frames / rate, first, n_chunks
+
+ def synthesize_streaming(job, early_stop=False):
+ """Like synthesize(), but incrementally: (audio_seconds, first_ts, n_chunks).
+
+ Used only by the TTFA probe; the batched (RTFx) path keeps the buffered request.
+ `first_ts` is None when the server did not stream, so the probe falls back to the
+ whole-utterance clock.
+ """
+ payload = speech_payload(job)
+ rejected = None
+ for index in range(stream_mode[0] or 0, len(STREAM_MODES)):
+ extra = STREAM_MODES[index]
+ with requests.post(f"{base_url}/v1/audio/speech", json={**payload, **extra},
+ timeout=args.request_timeout, stream=True) as resp:
+ # A 400 while the route is still unknown means this server does not accept this
+ # streaming dialect: try the next one instead of failing the job.
+ if resp.status_code == 400 and stream_mode[0] is None and index + 1 < len(STREAM_MODES):
+ rejected = resp.text[:300]
+ print(f" [ttfa] server rejected {extra}: {rejected}\n"
+ f" trying {STREAM_MODES[index + 1]}", flush=True)
+ continue
+ if resp.status_code != 200:
+ raise RuntimeError(f"Synthesis request failed ({resp.status_code}): {resp.text[:500]}")
+ if stream_mode[0] is None:
+ stream_mode[0] = index
+ print(f" [ttfa] streaming route: {extra or 'none (buffered)'} "
+ f"-> {resp.headers.get('content-type')}", flush=True)
+ content_type = resp.headers.get("content-type", "")
+ if "event-stream" in content_type:
+ return _read_sse(resp, early_stop)
+ if "pcm" in content_type or "X-Sample-Rate" in resp.headers:
+ return _read_pcm(resp, early_stop)
+ # Buffered mode, or the server ignored `stream`: no first-chunk time exists.
+ info = sf.info(io.BytesIO(resp.content))
+ return info.frames / info.samplerate, None, 1
+ raise RuntimeError(f"No usable /v1/audio/speech streaming route (last rejection: {rejected})")
+
+ # Layout: results/<model_safe>/ MODEL_<safe>_DATASET_<dsid>.jsonl + <dsid>/output_<id>.wav
+ # where <dsid> = <dataset_safe>_<dataset>_<split><mode_suffix>. Manifest paths are relative to
+ # model_dir so later stages resolve them wherever the folder is copied (local or HF bucket).
+ mode_suffix = "_voice_clone" if args.voice_clone else ""
+ paths = output_paths(args, mode_suffix)
+ model_dir, dataset_dir_name, output_dir = paths.model_dir, paths.dataset_dir_name, paths.output_dir
+ # Reference clips must live under results/ (not tempfiles) so stage 3 SIM can read them.
+ prompt_dir = os.path.join(output_dir, "prompts")
+ if args.voice_clone:
+ os.makedirs(prompt_dir, exist_ok=True)
+
+ # Reuse one thread pool across batches; concurrency = batch_size.
+ executor = ThreadPoolExecutor(max_workers=args.batch_size)
+
+ def generate_tts(texts, ids, references):
+ """Synthesize a batch of texts concurrently; time the wall-clock batch for RTFx."""
+ minibatch_size = len(texts)
+
+ # START TIMING (concurrent batch generation on the server)
+ start = time.perf_counter()
+ wav_bytes_list = list(executor.map(synthesize, zip(texts, references)))
+ runtime = time.perf_counter() - start
+ # per-sample generation time (RTFx is aggregated over the whole set at scoring time)
+ per_sample_time = runtime / minibatch_size
+
+ gen_paths, audio_length_s = [], []
+ for wav_bytes, sample_id in zip(wav_bytes_list, ids):
+ # 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)
+ # Write the returned WAV bytes verbatim, then read back for duration/sample rate.
+ with open(os.path.join(model_dir, rel_path), "wb") as f:
+ f.write(wav_bytes)
+ data, sr = sf.read(io.BytesIO(wav_bytes))
+ gen_paths.append(rel_path)
+ audio_length_s.append(len(data) / sr)
+
+ return gen_paths, audio_length_s, minibatch_size * [per_sample_time]
+
+ # Keep `id`, target text, and (when cloning) the per-sample reference.
+ dataset = load_tts_dataset(args, ("prompt_text", "prompt_audio") if args.voice_clone else ())
+
+ probe_out_dir = model_dir # real results dir, captured before the probe rebinds model_dir
+ # ── TTFA probe: latency only, writing nothing but a JSON sidecar ─────────
+ # TTFA is per-request, so the probe sends one streaming request at a time into a temp dir and
+ # returns before the batched path; WER/RTFx runs never reach this branch.
+ # 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 only injected by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+ import tempfile
+
+ model_dir = tempfile.mkdtemp(prefix="ttfa_out_")
+ dataset_dir_name = "ttfa"
+ output_dir = os.path.join(model_dir, dataset_dir_name)
+ os.makedirs(os.path.join(output_dir, "prompts"), exist_ok=True)
+
+ stream_chunks = [] # per-sample chunk counts, reported in the sidecar
+
+ def _gen(job, early_stop):
+ reference = None
+ if args.voice_clone:
+ ref_path = os.path.join(output_dir, "prompts", f"prompt_{job['id'][0]}.wav")
+ pa = job["prompt_audio"][0]
+ sf.write(ref_path, np.asarray(pa["array"], dtype=np.float32), pa["sampling_rate"])
+ reference = [{"audio_path": ref_path, "text": job["prompt_text"][0]}]
+ audio_s, first, n_chunks = synthesize_streaming(
+ (job[args.text_column][0], reference), early_stop)
+ stream_chunks.append(n_chunks)
+ return audio_s, None, first
+
+ columns = dataset.column_names
+ jobs = [{c: [dataset[i][c]] for c in columns}
+ for i in sample_indices(args.ttfa_probe, len(dataset))]
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=probe_out_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ # No "device": this backend is an HTTP client of sglang and has no --device argument.
+ extra={"note": "driven at batch size 1, one request in flight",
+ # Audio chunks per response; 1 everywhere means the server buffered.
+ "response_chunks": stream_chunks},
+ )
+ return
+
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ def prepare_references(batch):
+ """When cloning, persist each reference clip and build the per-request payload (the SGLang
+ server + stage-3 SIM both read `prompt_audio_filepath`); (prompt_paths, references)."""
+ ids = batch["id"]
+ prompt_paths = [None] * len(ids)
+ references = [None] * len(ids)
+ if args.voice_clone:
+ for j, sid in enumerate(ids):
+ # Store the path relative to model_dir (the manifest's dir); write to the full path.
+ prel = os.path.join(dataset_dir_name, "prompts", f"prompt_{sid}.wav")
+ pp = os.path.join(model_dir, prel)
+ if not os.path.exists(pp):
+ pa = batch["prompt_audio"][j]
+ sf.write(pp, np.asarray(pa["array"], dtype=np.float32), pa["sampling_rate"])
+ prompt_paths[j] = prel
+ # The SGLang server was launched from a different cwd than this client, so
+ # give it an absolute path (the manifest keeps the relative path for stage 3).
+ references[j] = [{"audio_path": os.path.abspath(pp), "text": batch["prompt_text"][j] or ""}]
+ return prompt_paths, references
+
+ def run_batch(batch):
+ prompt_paths, references = prepare_references(batch)
+ return prompt_paths, generate_tts(list(batch[args.text_column]), batch["id"], references)
+
+ starts = pending_batches(dataset, args.batch_size, done_entries, dataset_dir_name)
+ warm_up(run_batch, dataset, starts, args.batch_size, args.warmup_steps)
+
+ # ── Main loop: TTS → write JSONL, one batch at a time ───────────────────
+ for batch_start in tqdm(starts, desc="Generating"):
+ batch = dataset[batch_start : batch_start + args.batch_size]
+ texts = list(batch[args.text_column])
+ prompt_paths, (gen_paths, audio_length_s, gen_times) = run_batch(batch)
+
+ # Append each sample to the JSONL immediately.
+ for afp, ppath, alen, gtime, ref in zip(gen_paths, prompt_paths, audio_length_s, gen_times, texts):
+ write_entry(manifest_file, manifest_entry(afp, alen, gtime, ref, ppath if args.voice_clone else None))
+ manifest_file.flush()
+
+ manifest_file.close()
+ executor.shutdown()
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(args.voice_clone)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument(
+ "--model_id",
+ type=str,
+ default="bosonai/higgs-tts-3-4b",
+ help="Higgs TTS model id served by the SGLang server (for output-path naming).",
+ )
+ parser.add_argument("--host", type=str, default="127.0.0.1", help="SGLang server host.")
+ parser.add_argument("--port", type=int, default=8000, help="SGLang server port.")
+ parser.add_argument(
+ "--server_timeout", type=int, default=1200, help="Seconds to wait for the SGLang server to become ready."
+ )
+ parser.add_argument("--request_timeout", type=int, default=300, help="Per-request timeout (seconds).")
+ add_common_args(parser, batch_size=16, voice_clone=False)
+ # Generation params: the model card's /v1/audio/speech example values.
+ parser.add_argument(
+ "--max_new_tokens",
+ type=int,
+ default=1024,
+ help="Max audio tokens per synthesis request (model-card default 1024 = ~40 s at the 25 Hz "
+ "codec rate).",
+ )
+ parser.add_argument(
+ "--temperature",
+ type=float,
+ default=0.8,
+ help="Sampling temperature (model-card default 0.8). Do NOT set 0.0: greedy decoding makes "
+ "this model fail to emit EOS on a large fraction of prompts, which loops to "
+ "--max_new_tokens instead of producing a usable clip.",
+ )
+ parser.add_argument("--top_k", type=int, default=50,
+ help="Top-k sampling (Higgs model-card default 50). S2-Pro accepts only -1 "
+ "or 1..30, so that target passes --top_k=30.")
+ parser.add_argument("--top_p", type=float, default=None,
+ help="Top-p sampling. Unset = leave it to the server's default for the "
+ "served model (see speech_payload).")
+
+ args = parser.parse_args()
+
+ print("*" * 100)
+ print(f"Generating TTS with {args.model_id} (SGLang @ {args.host}:{args.port}) on "
+ f"{args.dataset_path} / {args.dataset} / {args.split}")
+ print("*" * 100)
+
+ main(args)
diff --git a/higgs/submit_jobs.sh b/higgs/submit_jobs.sh
new file mode 100644
index 0000000..b2ebe2a
--- /dev/null
+++ b/higgs/submit_jobs.sh
@@ -0,0 +1,75 @@
+#!/bin/bash
+# HF Jobs TTS eval — Higgs backend (generate → transcribe → SIM* → score; *voice-clone only, VOICE_CLONE=true).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["bosonai/higgs-tts-3-4b 16" ...]
+# 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-higgs}" # stage-1 image (SGLang-Omni, Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-higgs/blob/main/Dockerfile)
+SGLANG_PORT="${SGLANG_PORT:-8000}"
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+# run_eval.py imports no `normalizer`, so no NORMALIZER_INJECT / PYTHONPATH is needed here.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# Voice cloning (VOICE_CLONE=true): clone the per-sample reference + score SIM; else built-in voice.
+SUPPORTS_VOICE_CLONE=true
+
+# ── Stage 1: launch the SGLang server, then generate via the HTTP client. MODEL_CFG = "model_id concurrency". ──
+# Higgs TTS is served (not loaded in-process): sgl-omni serve exposes an OpenAI-compatible
+# /v1/audio/speech endpoint; run_eval.py polls /health, then sends synthesis requests. It is an
+# HTTP client, so it takes --host/--port (and NO --device). --allowed-local-media-path lets the
+# server read the voice-clone reference wavs that run_eval.py writes under results/.
+generate_stage() {
+ local _ BATCH_SIZE
+ read -r _ BATCH_SIZE <<< "${MODEL_CFG}"
+ 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}
+ set -e
+ mkdir -p /app/higgs/results
+ /opt/omni/bin/sgl-omni serve --model-path ${MODEL_ID} --host 127.0.0.1 --port ${SGLANG_PORT} \
+ --allowed-local-media-path /app/higgs/results \
+ > /app/higgs/results/sglang_server_${SPLIT}.log 2>&1 &
+ SERVER_PID=\$!
+ trap 'kill \$SERVER_PID 2>/dev/null || true' EXIT
+ cd /app/higgs && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --host=127.0.0.1 \
+ --port=${SGLANG_PORT} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --batch_size=${BATCH_SIZE} \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} \
+ ${VOICE_CLONE_FLAG}
+ mkdir -p /results
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment to pick) ────────
+# Higgs TTS 3 is multilingual and infers the language from the text (no --language flag, no
+# `supports_language` gate), so asr_language is only the stage-2 ASR hint.
+DATASET_CONFIGS=(
+ "tts en en"
+ "tts zh zh"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot fr fr ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot zh zh ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ja ja ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ko ko ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot de de ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot it it ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ru ru ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id concurrency" (CLI args override) ───────────────────────
+MODEL_CONFIGS=(
+ "bosonai/higgs-tts-3-4b 32"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/index-tts/run_eval.py b/index-tts/run_eval.py
new file mode 100644
index 0000000..9429305
--- /dev/null
+++ b/index-tts/run_eval.py
@@ -0,0 +1,453 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (IndexTTS-2.5 backend, stage 1).
+
+IndexTTS-2.5 is run from a source clone of https://github.com/index-tts/index-tts via
+`indextts.infer_v2_5.IndexTTS2` (22.05 kHz output). `infer()` takes the language as a REQUIRED
+`lang` argument, so `--language` is passed through from the dataset config; submit_jobs.sh skips
+the languages the model does not support.
+
+No native batching: upstream fixes the batch at one utterance (CFM caches allocated at
+max_batch_size=1, GPT `num_return_sequences=1`, `infer()` takes one string). `--batch_size` only
+controls manifest chunking / resume; per-sample time is batch time / batch size.
+
+There is no reference-free mode (`infer()` requires `spk_audio_prompt`). The two modes differ in
+WHICH reference is used:
+
+ --voice_clone: each sample clones its own `prompt_audio`, so SIM can be scored.
+ Outputs get a `_voice_clone` suffix.
+ --no-voice_clone (default): ONE fixed reference for the whole split (default: the split's sample
+ `--fixed_prompt_index`, so it is language-matched), for WER/CER comparison against the
+ fixed-voice backends. SIM is skipped.
+ NOTE fixed-voice RTFx is not strictly comparable with cloning RTFx: upstream caches the
+ speaker conditioning keyed on the prompt path, so it is encoded once for the whole split.
+"""
+
+import argparse
+import contextlib
+import logging
+import os
+import warnings
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+from run_eval_utils import (
+ add_common_args, load_done_entries, load_tts_dataset, manifest_entry, open_manifest, output_paths,
+ pending_batches, print_model_size, print_next_steps, set_seed, wav_rel_path, warm_up, write_entry,
+)
+
+# index-tts pulls in chatty deps (modelscope, transformers, numba); keep warnings/info out of the
+# way so the outer "Generating" tqdm is the only progress output.
+warnings.filterwarnings("ignore")
+for _name in ("modelscope", "numba", "matplotlib"):
+ logging.getLogger(_name).setLevel(logging.WARNING)
+try:
+ from transformers.utils import logging as _hf_logging
+
+ _hf_logging.set_verbosity_error()
+except Exception:
+ pass
+
+# `indextts.infer_v2_5` sets HF_HUB_CACHE to a relative path at import time, which would redirect
+# `load_dataset`; restore the pre-import value. The model loads its weights from explicit paths.
+_HF_HUB_CACHE_BEFORE = os.environ.get("HF_HUB_CACHE")
+
+from indextts.infer_v2_5 import IndexTTS2 # noqa: E402
+
+if _HF_HUB_CACHE_BEFORE is None:
+ os.environ.pop("HF_HUB_CACHE", None)
+else:
+ os.environ["HF_HUB_CACHE"] = _HF_HUB_CACHE_BEFORE
+
+torch.set_float32_matmul_precision("high")
+
+# `infer()` returns int16-valued samples (upstream scales by 32767 for Gradio); soundfile wants
+# float32 in [-1, 1].
+INT16_SCALE = 32768.0
+
+
+def main(args):
+ # Set seed for reproducibility (the GPT samples mel codes and the s2mel head is a CFM sampler).
+ seed = args.seed
+ set_seed(seed)
+ torch.backends.cudnn.deterministic = True
+
+ checkpoint_path = _resolve_checkpoint(args)
+ cfg_path = os.path.join(checkpoint_path, "config.yaml")
+ model = IndexTTS2(
+ cfg_path=cfg_path,
+ model_dir=checkpoint_path,
+ device=args.device,
+ use_bf16=args.use_bf16,
+ # Off by default: the fused BigVGAN kernel needs nvcc, and plain torch keeps RTFx
+ # like-for-like with the other backends.
+ use_cuda_kernel=args.use_cuda_kernel,
+ use_deepspeed=False, # not installed (upstream ships it as an extra)
+ use_accel=False, # needs flash-attn (upstream `accel` extra), not installed
+ use_torch_compile=False,
+ # QwenEmotion is only needed for infer(use_emo_text=True), which this eval never uses.
+ use_qwen_emo=False,
+ )
+ # 22.05 kHz: the s2mel/BigVGAN output rate, read from the config rather than hardcoded.
+ sampling_rate = int(model.cfg.s2mel["preprocess_params"]["sr"])
+ print(
+ f"Loaded IndexTTS-2.5 ({args.model_id}, sr={sampling_rate}, bf16={args.use_bf16}, "
+ f"lang={args.language}, max_text_tokens_per_segment={args.max_text_tokens_per_segment})"
+ )
+
+ # Parameter count: IndexTTS2 is not an nn.Module, so sum unique params over its nn.Module attributes.
+ try:
+ print_model_size(model)
+ except Exception as e:
+ print(f"Could not determine model size: {e}")
+
+ # Flat, bucket-friendly layout, per model:
+ # results/<model_safe>/ MODEL_<safe>_DATASET_<dsid>.jsonl + <dsid>/output_<id>.wav
+ # Manifest paths are relative to model_dir, so downstream stages resolve them wherever it is copied.
+ # Keep the two modes' audio separate so voice-clone and fixed-voice runs don't overwrite.
+ mode_suffix = "_voice_clone" if args.voice_clone else ""
+ paths = output_paths(args, mode_suffix)
+ model_dir, dataset_dir_name, output_dir = paths.model_dir, paths.dataset_dir_name, paths.output_dir
+
+ # `infer()` takes the reference as a file path; prompts live under `results/` for stage 3 SIM.
+ os.makedirs(os.path.join(output_dir, "prompts"), exist_ok=True)
+ # Fixed-voice mode: one reference for the whole split, filled in after the dataset is loaded.
+ fixed_prompt = {"full": None}
+ n_empty = 0 # samples that produced no audio (reported at the end)
+ # infer_generator() prints several progress lines per call; redirect stdout only (tqdm and
+ # tracebacks go to stderr).
+ devnull = None if args.verbose_model else open(os.devnull, "w")
+
+ def quiet_model():
+ return contextlib.nullcontext() if devnull is None else contextlib.redirect_stdout(devnull)
+
+ def write_prompt(path, prompt_audio):
+ """Write one reference clip to `path` as a wav (upstream truncates it to 15 s itself)."""
+ array = np.asarray(prompt_audio["array"], dtype=np.float32).reshape(-1)
+ sf.write(path, array, int(prompt_audio["sampling_rate"]))
+
+ def synth_one(text, prompt_path):
+ """Synthesize one utterance and return it as a float32 waveform.
+
+ `output_path=None` makes `infer()` return the samples, keeping file I/O out of the timed region.
+ """
+ nonlocal n_empty
+ # Re-seed per sample so generation is reproducible regardless of batch layout.
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+ out = model.infer(
+ spk_audio_prompt=prompt_path,
+ text=text,
+ output_path=None,
+ lang=args.language,
+ # emo_audio_prompt=None: the speaker reference doubles as the emotion reference
+ # (upstream's plain zero-shot cloning path).
+ emo_audio_prompt=None,
+ interval_silence=args.interval_silence,
+ max_text_tokens_per_segment=args.max_text_tokens_per_segment,
+ duration_factor=args.duration_factor,
+ text_normalization=not args.no_text_normalization,
+ verbose=False,
+ )
+ # infer() returns None when its generator yielded nothing (it swallows the IndexError).
+ if out is None:
+ n_empty += 1
+ print(f"Warning: no audio generated for text: {text[:60]}...")
+ return np.zeros(int(0.1 * sampling_rate), dtype=np.float32)
+ _, wav_int16 = out
+ return np.asarray(wav_int16, dtype=np.float32).reshape(-1) / INT16_SCALE
+
+ def generate_tts(batch):
+ """Synthesize a minibatch of target texts (per-sample loop); time the batch for RTFx."""
+ texts_to_generate = list(batch[args.text_column])
+ minibatch_size = len(texts_to_generate)
+
+ # Write the prompts before timing (I/O is not generation). The relative path goes into the
+ # manifest for stage 3 (SIM).
+ if args.voice_clone:
+ prompt_rel_paths, prompt_full_paths = [], []
+ for sample_id, prompt_audio in zip(batch["id"], batch["prompt_audio"]):
+ prel = os.path.join(dataset_dir_name, "prompts", f"prompt_{sample_id}.wav")
+ ppath = os.path.join(model_dir, prel)
+ if not os.path.exists(ppath):
+ write_prompt(ppath, prompt_audio)
+ prompt_rel_paths.append(prel)
+ prompt_full_paths.append(ppath)
+ else:
+ # Fixed-voice mode: the same reference for every sample; no SIM.
+ prompt_rel_paths = [None] * minibatch_size
+ prompt_full_paths = [fixed_prompt["full"]] * minibatch_size
+
+ # START TIMING (TTS generation for the whole minibatch)
+ torch.cuda.synchronize(device=args.device)
+ start_event = torch.cuda.Event(enable_timing=True)
+ end_event = torch.cuda.Event(enable_timing=True)
+ start_event.record()
+
+ # No batched API (see the module docstring): loop per sample.
+ with quiet_model():
+ wavs = [
+ synth_one(text, prompt_path)
+ for text, prompt_path in zip(texts_to_generate, prompt_full_paths)
+ ]
+
+ # END TIMING
+ end_event.record()
+ torch.cuda.synchronize(device=args.device)
+ runtime = start_event.elapsed_time(end_event) / 1000.0
+ # per-sample generation time (RTFx is aggregated over the whole set at scoring time)
+ batch["generation_time_s"] = minibatch_size * [runtime / minibatch_size]
+
+ gen_paths, audio_length_s = [], []
+ for audio, sample_id in zip(wavs, batch["id"]):
+ # 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)
+ sf.write(os.path.join(model_dir, rel_path), audio, sampling_rate)
+ gen_paths.append(rel_path)
+ audio_length_s.append(len(audio) / sampling_rate)
+
+ batch["gen_audio_filepath"] = gen_paths
+ batch["prompt_audio_filepath"] = prompt_rel_paths
+ batch["audio_length_s"] = audio_length_s
+ batch["references"] = list(batch[args.text_column]) # raw; normalized at scoring time
+ return batch
+
+ # `prompt_audio` is kept in both modes (fixed-voice mode may take its one reference from the
+ # split); it is dropped below when not cloning. `prompt_text` is unused: infer() takes no transcript.
+ dataset = load_tts_dataset(args, ("prompt_audio",))
+
+ # A reference is mandatory in both modes, so the dataset must carry one unless fixed-voice mode
+ # was given an external reference.
+ needs_dataset_prompt = args.voice_clone or not args.prompt_audio_path
+ if "prompt_audio" not in dataset.column_names and needs_dataset_prompt:
+ raise ValueError(
+ f"Dataset {args.dataset_path}/{args.dataset}/{args.split} has no `prompt_audio` column. "
+ "IndexTTS-2.5 has no built-in speaker, so a reference audio is required in every mode. "
+ "Pass --prompt_audio_path to supply one externally."
+ )
+
+ # ── Fixed-voice mode: resolve the ONE reference used for the whole split ──
+ if not args.voice_clone:
+ fixed_rel = os.path.join(dataset_dir_name, "prompts", "fixed_prompt.wav")
+ fixed_full = os.path.join(model_dir, fixed_rel)
+ if args.prompt_audio_path:
+ audio, sr = sf.read(args.prompt_audio_path, dtype="float32", always_2d=True)
+ write_prompt(fixed_full, {"array": audio.mean(axis=1), "sampling_rate": sr})
+ src = args.prompt_audio_path
+ else:
+ # Default: the split's own sample #--fixed_prompt_index, which keeps the reference
+ # language-matched.
+ if not 0 <= args.fixed_prompt_index < len(dataset):
+ raise ValueError(
+ f"--fixed_prompt_index={args.fixed_prompt_index} is out of range for a "
+ f"{len(dataset)}-sample split."
+ )
+ row = dataset[args.fixed_prompt_index]
+ write_prompt(fixed_full, row["prompt_audio"])
+ src = f"{args.dataset}/{args.split} sample #{args.fixed_prompt_index} (id={row.get('id')})"
+ fixed_prompt["full"] = fixed_full
+ print(
+ f"Fixed-voice mode: one reference for all {len(dataset)} samples, from {src}. "
+ f"SIM is skipped (no per-sample reference)."
+ )
+
+ # Fixed-voice mode: drop the reference column so nothing else triggers audio decoding.
+ if not args.voice_clone and "prompt_audio" in dataset.column_names:
+ dataset = dataset.remove_columns(["prompt_audio"])
+
+ probe_out_dir = model_dir # real results dir, captured before the probe rebinds model_dir
+ # ── TTFA probe: latency only, writing nothing but a JSON sidecar ─────────
+ # Drives generate_tts() with one-row batches; `model_dir`/`dataset_dir_name` are rebound to a
+ # temp dir (generate_tts closes over them) so nothing lands in the results tree. TTFA is the
+ # whole-utterance time: infer(stream_return=True) yields per 120-token text segment, so it would
+ # emit a single chunk for eval-length utterances anyway. See scripts/ttfa_probe.py.
+ if args.ttfa_probe != 0:
+ # Imported here: the probe module is injected only by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+ import tempfile
+
+ model_dir = tempfile.mkdtemp(prefix="ttfa_out_")
+ dataset_dir_name = "ttfa"
+ output_dir = os.path.join(model_dir, dataset_dir_name)
+ os.makedirs(os.path.join(output_dir, "prompts"), exist_ok=True)
+
+ def _gen(job):
+ out = generate_tts(dict(job))
+ return float(out["audio_length_s"][0]), None, None
+
+ columns = dataset.column_names
+ jobs = [{c: [dataset[i][c]] for c in columns}
+ for i in sample_indices(args.ttfa_probe, len(dataset))]
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=probe_out_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ extra={"device": args.device,
+ "note": "driven at batch size 1, blocking infer() (see the probe note in run_eval.py)"},
+ )
+ return
+
+ # ── Manifest (written incrementally; resume skips rows already in it) ───
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ # ── Main loop: TTS → write JSONL, one batch at a time ───────────────────
+ starts = pending_batches(dataset, args.batch_size, done_entries, dataset_dir_name)
+ warm_up(generate_tts, dataset, starts, args.batch_size, args.warmup_steps)
+ for batch_start in tqdm(starts, desc="Generating"):
+ batch = generate_tts(dataset[batch_start : batch_start + args.batch_size])
+
+ # Append each sample to the JSONL immediately. Only cloning runs carry the prompt path (its
+ # absence tells the pipeline to skip SIM).
+ for afp, ppath, alen, gtime, ref in zip(
+ batch["gen_audio_filepath"], batch["prompt_audio_filepath"], batch["audio_length_s"],
+ batch["generation_time_s"], batch["references"],
+ ):
+ entry = manifest_entry(afp, alen, gtime, ref, ppath if args.voice_clone else None)
+ write_entry(manifest_file, entry)
+ manifest_file.flush()
+
+ manifest_file.close()
+ if devnull is not None:
+ devnull.close()
+ if n_empty:
+ print(f"NOTE: {n_empty} sample(s) generated no audio and were written as 0.1 s of silence.")
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(args.voice_clone)
+
+
+def _resolve_checkpoint(args):
+ """Return a writable dir holding the IndexTTS-2.5 weights + its auxiliary models.
+
+ Unless --checkpoint_path points at a pre-populated dir, the weights are downloaded to a
+ writable `local_dir` (IndexTTS2 stores auxiliary models under `<model_dir>/hf_cache/`).
+ `qwen0.6bemo4-merge/` is skipped since main() passes use_qwen_emo=False.
+ """
+ from huggingface_hub import snapshot_download
+
+ if args.checkpoint_path:
+ checkpoint_path = args.checkpoint_path
+ if not os.path.isfile(os.path.join(checkpoint_path, "config.yaml")):
+ raise FileNotFoundError(
+ f"No config.yaml under --checkpoint_path={checkpoint_path}. Point it at a dir "
+ f"populated by `hf download {args.model_id} --local-dir <dir>`, or drop the flag "
+ "to let this script download the weights itself."
+ )
+ print(f"Using existing checkpoint dir {os.path.abspath(checkpoint_path)}")
+ else:
+ print(f"Downloading {args.model_id} to {os.path.abspath(args.download_dir)} ...")
+ checkpoint_path = snapshot_download(
+ args.model_id,
+ local_dir=args.download_dir,
+ ignore_patterns=["qwen0.6bemo4-merge/*"],
+ )
+
+ # Fetch the auxiliary models (w2v-BERT, CAMPPlus, BigVGAN, ...) up front with upstream's helper,
+ # so the download is a visible step instead of a stall inside __init__.
+ from indextts.utils.model_download import ensure_models_available
+
+ ensure_models_available(checkpoint_path)
+ return checkpoint_path
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument(
+ "--model_id",
+ type=str,
+ default="IndexTeam/IndexTTS-2.5",
+ help="Model id, used for the results folder / manifest name.",
+ )
+ parser.add_argument(
+ "--checkpoint_path",
+ type=str,
+ default=None,
+ help="Local dir already holding the weights + config.yaml. Default: download --model_id "
+ "into --download_dir.",
+ )
+ parser.add_argument(
+ "--download_dir",
+ type=str,
+ default="checkpoints",
+ help="Where to download the weights when --checkpoint_path is not given. Must be writable: "
+ "IndexTTS2 stores its auxiliary models under <dir>/hf_cache/.",
+ )
+ parser.add_argument(
+ "--language",
+ type=str,
+ default="en",
+ help="Language tag passed to infer(lang=...). IndexTTS-2.5 covers zh, en, ja, es, ar (plus "
+ "the mixed 'zhen'); it does NOT infer the language from the text. An unknown tag falls "
+ "back to upstream's 'common' token, which is why submit_jobs.sh gates the combos instead.",
+ )
+ # --batch_size is only the manifest chunk size (no batched API; generation is per sample).
+ add_common_args(parser, batch_size=32, voice_clone=False)
+ parser.add_argument(
+ "--use_bf16",
+ action=argparse.BooleanOptionalAction,
+ default=True,
+ help="Run the GPT backbone in bfloat16 (the model card's own example passes use_bf16=True).",
+ )
+ parser.add_argument(
+ "--use_cuda_kernel",
+ action="store_true",
+ help="Compile BigVGAN's fused anti-alias activation CUDA kernel. Needs nvcc (a -devel base "
+ "image); off by default so RTFx is measured on the same plain-torch vocoder path as "
+ "the other backends.",
+ )
+ parser.add_argument(
+ "--max_text_tokens_per_segment",
+ type=int,
+ default=120,
+ help="Upstream default. Longer texts are split into segments, synthesized separately and "
+ "concatenated with --interval_silence between them.",
+ )
+ parser.add_argument(
+ "--interval_silence",
+ type=int,
+ default=200,
+ help="Milliseconds of silence inserted between segments of one utterance (upstream default).",
+ )
+ parser.add_argument(
+ "--duration_factor", type=float, default=1.0, help="Speech-rate control (0.5-2.0; 1.0 = model default)."
+ )
+ parser.add_argument(
+ "--no_text_normalization",
+ action="store_true",
+ help="Disable IndexTTS's own text normalization (on by default, as upstream ships it).",
+ )
+ parser.add_argument(
+ "--verbose_model",
+ action="store_true",
+ help="Let infer()'s per-sample progress/timing prints through (suppressed by default).",
+ )
+ # --voice_clone / --no-voice_clone (default): see the module docstring. A reference is required
+ # either way: IndexTTS-2.5 has no built-in speaker.
+ parser.add_argument(
+ "--fixed_prompt_index",
+ type=int,
+ default=0,
+ help="--no-voice_clone only: which sample of the split supplies the fixed reference "
+ "(default 0), keeping the voice language-matched to the split.",
+ )
+ parser.add_argument(
+ "--prompt_audio_path",
+ type=str,
+ default=None,
+ help="--no-voice_clone only: use this wav as the fixed reference instead of a dataset sample "
+ "(e.g. one shared voice across languages).",
+ )
+
+ 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/index-tts/submit_jobs.sh b/index-tts/submit_jobs.sh
new file mode 100755
index 0000000..8366dbd
--- /dev/null
+++ b/index-tts/submit_jobs.sh
@@ -0,0 +1,67 @@
+#!/bin/bash
+# HF Jobs TTS eval — IndexTTS-2.5 backend (generate → transcribe → SIM* → score; *voice-clone only).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["IndexTeam/IndexTTS-2.5 32" ...]
+# 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-indextts}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-indextts/blob/main/Dockerfile)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# ── Voice mode ───────────────────────────────────────────────────────────────
+# A reference audio is mandatory either way (no built-in speaker); the toggle picks WHICH one:
+# VOICE_CLONE=true each sample clones its own prompt_audio -> SIM stage runs.
+# VOICE_CLONE=false (default) ONE fixed reference for the whole split (the split's sample 0,
+# language-matched); SIM is skipped.
+SUPPORTS_VOICE_CLONE=true
+
+# ── Languages IndexTTS-2.5 covers (model card: zh, en, ja, es, ar) ───────────
+# An unsupported `lang` does NOT raise upstream, it just produces wrong-language audio, so gate
+# the combos here. Matched against asr_language (so `zh_hard` / `hard_zh` match `zh`).
+INDEXTTS_LANGUAGES=" zh en ja es ar "
+supports_language() { [[ "${INDEXTTS_LANGUAGES}" == *" $1 "* ]]; }
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id batch_size". ──
+# No batched API; --batch_size only chunks manifest writing / resume. See run_eval.py.
+generate_stage() {
+ local _ BATCH_SIZE
+ read -r _ BATCH_SIZE <<< "${MODEL_CFG}"
+ 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/index-tts && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --language=${ASR_LANG} \
+ --device=cuda:0 \
+ --batch_size=${BATCH_SIZE} \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} \
+ ${VOICE_CLONE_FLAG} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment) ──
+# asr_language doubles as the TTS `lang` tag (--language above).
+DATASET_CONFIGS=(
+ "tts en en"
+ "tts zh zh"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot zh zh ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ja ja ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id batch_size" (CLI args override) ────────────────────────
+MODEL_CONFIGS=(
+ "IndexTeam/IndexTTS-2.5 32"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/inflect-nano/run_eval.py b/inflect-nano/run_eval.py
new file mode 100644
index 0000000..9523840
--- /dev/null
+++ b/inflect-nano/run_eval.py
@@ -0,0 +1,146 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (Inflect-Nano-v1 backend, stage 1).
+
+Inflect-Nano-v1 (owensong/Inflect-Nano-v1) is a tiny (~4.6M param) FastSpeech-style
+acoustic model + Snake-HiFiGAN vocoder that runs in-process from its own repo. This
+script imports the repo's `inference` module (which self-registers its vendored paths on
+import), loads the acoustic + vocoder checkpoints, synthesizes each target text with the
+single built-in voice, times generation for RTFx, saves wavs, and writes a manifest with
+`text`, `duration`, and generation `time` (with an empty `pred_text` placeholder).
+
+The model has no batched inference API, so texts are synthesized one at a time.
+
+Stage 2 (`transformers/transcribe.py`, run in the shared `bezzam/evals` image) transcribes the
+wavs with Qwen3-ASR to fill `pred_text`, and stage 4 (`normalizer.eval_utils.score_results`, run
+locally) computes WER + RTFx from the completed manifest. Fixed voice, so no stage 3 (SIM).
+"""
+
+import argparse
+import os
+import sys
+import time
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+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,
+)
+
+# Inflect-Nano outputs 24 kHz waveforms (fixed).
+SAMPLING_RATE = 24_000
+
+
+def main(args):
+ set_seed(args.seed)
+
+ # Make the model repo importable, then import its inference module. inference.py inserts
+ # its own repo root + vendored frontend onto sys.path at import time, so this is enough.
+ sys.path.insert(0, args.model_repo)
+ from inference import load_acoustic, load_vocoder, synthesize, DEFAULT_ACOUSTIC, DEFAULT_VOCODER
+
+ device = torch.device(args.device)
+ acoustic_path = args.acoustic_weights or DEFAULT_ACOUSTIC
+ vocoder_path = args.vocoder_weights or DEFAULT_VOCODER
+ acoustic, speakers, ac_params = load_acoustic(acoustic_path, device)
+ vocoder, vo_params = load_vocoder(vocoder_path, device)
+ print(f"Loaded Inflect-Nano ({(ac_params + vo_params) / 1e6:.2f}M params, voices={list(speakers)})")
+
+ is_cuda = device.type == "cuda"
+
+ def synth_one(text):
+ """Synthesize one text; return (audio, elapsed_seconds)."""
+ if is_cuda:
+ torch.cuda.synchronize(device=device)
+ start = time.perf_counter()
+ audio = synthesize(
+ text, acoustic, vocoder, speakers, device,
+ length_scale=args.length_scale, pitch_scale=args.pitch_scale, energy_scale=args.energy_scale,
+ )
+ if is_cuda:
+ torch.cuda.synchronize(device=device)
+ return np.asarray(audio).reshape(-1), time.perf_counter() - start
+
+ # 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 ─────────
+ # No streaming API, so `first` is None and the probe records the whole-utterance time.
+ # 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
+ run_probe(
+ lambda job: (synth_one(job["text"])[0], SAMPLING_RATE, None),
+ [{"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, extra={"device": args.device},
+ )
+ 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) # so warm-up does not shift the RNG stream of the timed run
+
+ # ── 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, SAMPLING_RATE, subtype="PCM_16")
+
+ write_entry(manifest_file, manifest_entry(rel_path, len(audio) / SAMPLING_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="owensong/Inflect-Nano-v1",
+ help="Model id (used only for output-path / manifest naming).",
+ )
+ parser.add_argument(
+ "--model_repo",
+ type=str,
+ default="/opt/Inflect-Nano-v1",
+ help="Path to the cloned Inflect-Nano-v1 repo (provides the `inference` module + weights).",
+ )
+ parser.add_argument("--acoustic_weights", type=str, default=None, help="Override acoustic checkpoint path.")
+ parser.add_argument("--vocoder_weights", type=str, default=None, help="Override vocoder checkpoint path.")
+ # Prosody controls (defaults = neutral, matching the model's inference.py defaults).
+ parser.add_argument("--length_scale", type=float, default=1.0, help="Duration scale (>1 = slower).")
+ parser.add_argument("--pitch_scale", type=float, default=1.0, help="Pitch scale.")
+ parser.add_argument("--energy_scale", type=float, default=1.0, help="Energy scale.")
+ 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/inflect-nano/submit_jobs.sh b/inflect-nano/submit_jobs.sh
new file mode 100644
index 0000000..41724d3
--- /dev/null
+++ b/inflect-nano/submit_jobs.sh
@@ -0,0 +1,48 @@
+#!/bin/bash
+# HF Jobs TTS eval — Inflect-Nano backend (fixed voice → 2 stages: generate → transcribe → score).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["owensong/Inflect-Nano-v1" ...]
+# 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-inflect}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-inflect/blob/main/Dockerfile)
+DEFAULT_STAGES="generate transcribe" # no SIM (fixed voice)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# ── Stage 1: TTS generation (Inflect-Nano synthesizes one sample at a time — no batch size) ──
+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/inflect-nano && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --device=cuda:0 \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Languages this backend can select ────────────────────────────────────────
+# English-only (model card: `language: [en]`); non-en splits are skipped rather than synthesized
+# with English phonemes, which would give a meaningless (>100%) CER.
+INFLECT_NANO_LANGUAGES="en"
+supports_language() { [[ " ${INFLECT_NANO_LANGUAGES} " == *" $1 "* ]]; }
+
+# ── 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=("owensong/Inflect-Nano-v1")
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/inflect-v2/run_eval.py b/inflect-v2/run_eval.py
new file mode 100644
index 0000000..c3c1c22
--- /dev/null
+++ b/inflect-v2/run_eval.py
@@ -0,0 +1,175 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (Inflect v2 backend, stage 1).
+
+Covers the Inflect **v2** family — `owensong/Inflect-Micro-v2` (9.4M parameters) and
+`owensong/Inflect-Nano-v2` (4.0M) — which share one codebase and one public API. Both are
+fixed-voice English VITS models at 24 kHz: no reference conditioning, so there is no voice-clone
+mode and no SIM stage.
+
+`owensong/Inflect-Nano-v1` is a different architecture with its own backend (`inflect-nano/`).
+
+The inference code lives *inside each model repo* (`inference.py` + `runtime/`), so this script
+snapshot_downloads the repo and loads `InflectTTS` from it by path. Generation is one sample at a
+time — `synthesize()` takes a single string, and the model has no batched API.
+
+Stage 2 (`transformers/transcribe.py`, run in the shared `bezzam/evals` image) transcribes the
+wavs with Qwen3-ASR to fill `pred_text`, and stage 4 (`normalizer.eval_utils.score_results`, run
+locally) computes WER + RTFx from the completed manifest.
+"""
+
+import argparse
+import importlib.util
+import logging
+import os
+import sys
+import time
+from pathlib import Path
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+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, warm_up, wav_rel_path, write_entry,
+)
+
+
+def _load_engine(ckpt_dir: Path, device: str):
+ """Import `InflectTTS` from the model repo's own inference.py and instantiate it.
+
+ Loaded by file path: inference.py puts its `runtime/` dir on sys.path and imports generic
+ module names (`commons`, `utils`, ...), so only one Inflect v2 model can be loaded per process.
+ """
+ entry = ckpt_dir / "inference.py"
+ if not entry.is_file():
+ raise FileNotFoundError(f"{entry} not found — is this an Inflect v2 model repo?")
+ spec = importlib.util.spec_from_file_location("inflect_v2_inference", entry)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+
+ # runtime/utils.py sets the ROOT logger to DEBUG at import (flooding output with httpx logs),
+ # so restore the previous level.
+ root_level = logging.getLogger().level
+ try:
+ spec.loader.exec_module(module)
+ engine = module.InflectTTS(ckpt_dir, device=device)
+ finally:
+ logging.getLogger().setLevel(root_level)
+ return engine
+
+
+def main(args):
+ from huggingface_hub import snapshot_download
+
+ # The repo carries the inference code as well as the weights. local_dir= is required:
+ # inference.py finds `runtime/` via `Path(__file__).resolve().parent`, which would follow the
+ # HF cache's symlinks into blobs/.
+ if args.checkpoint_path:
+ ckpt_dir = Path(args.checkpoint_path)
+ else:
+ ckpt_dir = Path(snapshot_download(args.model_id, local_dir=Path(args.local_dir) / args.model_id.replace("/", "-")))
+ print(f"Checkpoint: {ckpt_dir}")
+ if not (ckpt_dir / "runtime").is_dir():
+ raise RuntimeError(
+ f"{ckpt_dir}/runtime is missing — inference.py resolves its imports relative to its own "
+ "file, so the checkpoint must be a real directory tree, not a symlinked HF cache snapshot."
+ )
+
+ engine = _load_engine(ckpt_dir, args.device)
+ sampling_rate = engine.sample_rate # 24000
+ print(f"Loaded Inflect v2 ({args.model_id}, sr={sampling_rate}, device={args.device})")
+ print(
+ f"TTS model size: {engine.deployed_parameters / 1e9:.4f}B parameters deployed "
+ f"({engine.deployed_parameters:,}; {engine.checkpoint_parameters:,} in the checkpoint "
+ "before weight-norm collapsing)"
+ )
+
+ is_cuda = str(args.device).startswith("cuda")
+
+ def synth_one(text):
+ """Synthesize one text; return (audio_1d_numpy, elapsed_s). Deterministic given `seed`."""
+ if is_cuda:
+ torch.cuda.synchronize(device=args.device)
+ start = time.perf_counter()
+ _, audio = engine.synthesize(
+ text, speed=args.speed, variation=args.variation, seed=args.seed
+ )
+ if is_cuda:
+ torch.cuda.synchronize(device=args.device)
+ return np.asarray(audio, dtype=np.float32).reshape(-1), time.perf_counter() - start
+
+ # 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 ─────────
+ # No streaming API, so `first` is None and the probe records the whole-utterance time.
+ # 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
+ run_probe(
+ lambda job: (synth_one(job["text"])[0], sampling_rate, None),
+ [{"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,
+ extra={"device": args.device, "seed": args.seed},
+ )
+ 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)
+
+ # ── 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, sampling_rate)
+
+ write_entry(manifest_file, manifest_entry(rel_path, len(audio) / sampling_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="owensong/Inflect-Micro-v2",
+ help="Inflect v2 model repo (Micro-v2 or Nano-v2); also names the manifest.")
+ parser.add_argument("--checkpoint_path", type=str, default=None,
+ help="Local Inflect v2 repo dir. Default: download --model_id under --local_dir.")
+ parser.add_argument("--local_dir", type=str, default="/tmp/inflect_v2_models",
+ help="Where to materialise the model repo as real files (not cache symlinks).")
+ parser.add_argument("--speed", type=float, default=1.0, help="Speaking rate (0.5-2.0).")
+ parser.add_argument("--variation", type=float, default=0.667,
+ help="Sampling noise scale (0.0-1.0); upstream's default is 0.667.")
+ add_common_args(parser)
+ # Seed: upstream default 0. Generation is deterministic given it.
+ parser.set_defaults(seed=0)
+
+ 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/inflect-v2/submit_jobs.sh b/inflect-v2/submit_jobs.sh
new file mode 100755
index 0000000..de3d386
--- /dev/null
+++ b/inflect-v2/submit_jobs.sh
@@ -0,0 +1,59 @@
+#!/bin/bash
+# HF Jobs TTS eval — Inflect v2 backend (fixed voice → 2 stages: generate → transcribe → score).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["owensong/Inflect-Micro-v2" ...]
+# Shared orchestration (stages 2/3, injection, logging, scoring) lives in scripts/tts_jobs_common.sh.
+#
+# Serves the Inflect **v2** family (Micro-v2, Nano-v2), which share one codebase. Inflect-Nano-**v1**
+# is a different architecture and has its own backend under inflect-nano/.
+source "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/scripts/tts_jobs_common.sh"
+
+# ── Backend config ───────────────────────────────────────────────────────────
+TTS_SPACE="${TTS_SPACE:-bezzam/evals-inflect-v2}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-inflect-v2/blob/main/Dockerfile)
+DEFAULT_STAGES="generate transcribe" # no SIM (fixed voice, no reference to compare)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# ── Languages this backend can select ────────────────────────────────────────
+# English-only (model cards: `language: [en]`); non-en splits are skipped rather than synthesized
+# with English phonemes, which would give a meaningless (>100%) CER.
+INFLECT_V2_LANGUAGES="en"
+supports_language() { [[ " ${INFLECT_V2_LANGUAGES} " == *" $1 "* ]]; }
+
+# ── Stage 1: TTS generation (one sample at a time — no batched API) ──────────
+# The model repo carries the inference code as well as the ~40 MB checkpoint, so run_eval.py
+# snapshot_downloads it at job start; that is what lets one image serve both v2 sizes.
+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/inflect-v2 && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --device=cuda:0 \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Datasets: "config split asr_language [dataset_path]" ────────────────────
+# The optional 4th field points one line at a different dataset repo (default: Seed-TTS).
+# English-only model, so only the `en` splits.
+DATASET_CONFIGS=(
+ "tts en en"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id" (CLI args override) ───────────────────────────────────
+# Nano-v2 is the same code path and image — uncomment to evaluate both in one submission.
+MODEL_CONFIGS=(
+ "owensong/Inflect-Micro-v2"
+ # "owensong/Inflect-Nano-v2"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/kokoro/run_eval.py b/kokoro/run_eval.py
new file mode 100644
index 0000000..55dff4f
--- /dev/null
+++ b/kokoro/run_eval.py
@@ -0,0 +1,166 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (Kokoro-82M backend, stage 1).
+
+Kokoro-82M (hexgrad/Kokoro-82M) is an 82M StyleTTS2 + ISTFTNet model loaded in-process via
+the `kokoro` package (`KPipeline`). This script loads the pipeline once, synthesizes each
+target text with a fixed built-in voice, times generation for RTFx, saves wavs, and writes a
+manifest with `text`, `duration`, and generation `time` (empty `pred_text`).
+
+The pipeline chunks long inputs and yields one audio segment per chunk, so per row we
+concatenate all yielded segments. There is no GPU-batched API, so rows are processed serially.
+
+Stage 2 (`transformers/transcribe.py`, run in the shared `bezzam/evals` image) transcribes the
+wavs with Qwen3-ASR to fill `pred_text`, and stage 4 (`normalizer.eval_utils.score_results`, run
+locally) computes WER + RTFx from the completed manifest. Fixed voice, so no stage 3 (SIM).
+"""
+
+import argparse
+import os
+import time
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+from kokoro import KPipeline
+
+from run_eval_utils import (
+ add_common_args, load_done_entries, load_tts_dataset, manifest_entry, open_manifest, output_paths,
+ pending_batches, print_model_size, print_next_steps, set_seed, warm_up, wav_rel_path, write_entry,
+)
+
+# Kokoro outputs 24 kHz waveforms (fixed constant, not returned by the API).
+SAMPLING_RATE = 24_000
+
+
+def main(args):
+ set_seed(args.seed)
+
+ # Pass repo_id explicitly to silence the default-repo warning.
+ pipeline = KPipeline(lang_code=args.lang_code, repo_id=args.model_id, device=args.device)
+ print(f"Loaded Kokoro ({args.model_id}, voice={args.voice}, lang_code={args.lang_code})")
+ print_model_size(getattr(pipeline, "model", None))
+
+ is_cuda = (args.device or ("cuda" if torch.cuda.is_available() else "cpu")).startswith("cuda")
+
+ def synth_one(text):
+ """Synthesize one text; concatenate all chunk segments. Return (audio_1d_numpy, elapsed_s)."""
+ if is_cuda:
+ torch.cuda.synchronize()
+ start = time.perf_counter()
+ segments = [audio for _gs, _ps, audio in pipeline(text, voice=args.voice, speed=args.speed)]
+ if is_cuda:
+ torch.cuda.synchronize()
+ elapsed = time.perf_counter() - start
+
+ if not segments:
+ audio = np.zeros(1, dtype=np.float32)
+ else:
+ audio = torch.cat([s.reshape(-1) for s in segments]).detach().to(torch.float32).cpu().numpy()
+ return audio, elapsed
+
+ def synth_one_streaming(text, early_stop=False):
+ """TTFA probe only: return (audio_1d_numpy, first_segment_ts, n_segments).
+
+ KPipeline yields one segment per sentence, so a one-sentence prompt has nothing to stream
+ (n_segments == 1): first audio is last audio.
+ """
+ first, segments = None, []
+ n_chunks = 0
+ for _gs, _ps, audio in pipeline(text, voice=args.voice, speed=args.speed):
+ n_chunks += 1
+ if first is None:
+ # .cpu() forces the segment to be materialised, so the timestamp reflects audio
+ # actually in hand rather than a queued device op.
+ audio = audio.reshape(-1).detach().to(torch.float32).cpu()
+ first = time.perf_counter()
+ segments.append(audio)
+ if early_stop:
+ break
+ continue
+ segments.append(audio.reshape(-1).detach().to(torch.float32).cpu())
+ if not segments:
+ return np.zeros(1, dtype=np.float32), None, 0
+ return torch.cat(segments).numpy(), first, n_chunks
+
+ # 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 KPipeline segment (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
+ segment_counts = []
+
+ def _ttfa_gen(job, early_stop):
+ audio, first, n_chunks = synth_one_streaming(job["text"], early_stop)
+ segment_counts.append(n_chunks)
+ return audio, SAMPLING_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, "segments_per_utterance": segment_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) # so warm-up does not shift the RNG stream of the timed run
+
+ # ── 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, SAMPLING_RATE)
+
+ write_entry(manifest_file, manifest_entry(rel_path, len(audio) / SAMPLING_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="hexgrad/Kokoro-82M", help="Kokoro repo id.")
+ parser.add_argument(
+ "--voice",
+ type=str,
+ default="af_heart",
+ help="Kokoro voice pack (e.g. af_heart, af_bella, am_michael). Prefix must match --lang_code.",
+ )
+ parser.add_argument("--lang_code", type=str, default="a", help="Kokoro G2P language code; must match the voice prefix (e.g. 'a' = American English, 'z' = Mandarin).")
+ 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/kokoro/submit_jobs.sh b/kokoro/submit_jobs.sh
new file mode 100755
index 0000000..f355665
--- /dev/null
+++ b/kokoro/submit_jobs.sh
@@ -0,0 +1,67 @@
+#!/bin/bash
+# HF Jobs TTS eval — Kokoro backend (fixed voice → 2 stages: generate → transcribe → score).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["hexgrad/Kokoro-82M" ...]
+# 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-kokoro}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-kokoro/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)"
+
+# ── Language → (Kokoro lang_code, voice pack) ────────────────────────────────
+# Kokoro picks its G2P from a one-character lang_code, and a voice's first letter MUST equal it,
+# so each language needs a matching voice. Voices in hexgrad/Kokoro-82M:
+# a American English (20) b British English (8) e Spanish (3) f French (1) h Hindi (4)
+# i Italian (2) j Japanese (5) p Portuguese-BR (3) z Mandarin (8)
+# No German, Korean or Russian voice, so CV3-Eval's de/ko/ru splits cannot run here.
+declare -A KOKORO_LANG_CODE=( [en]=a [es]=e [fr]=f [it]=i [ja]=j [zh]=z [pt]=p [hi]=h )
+declare -A KOKORO_VOICES=( [en]=af_heart [es]=ef_dora [fr]=ff_siwis [it]=if_sara \
+ [ja]=jf_alpha [zh]=zf_xiaobei [pt]=pf_dora [hi]=hf_alpha )
+supports_language() { [[ -n "${KOKORO_LANG_CODE[$1]:-}" ]]; }
+# Setting KOKORO_VOICE forces one voice for every combo — only safe for a single-language run,
+# since a voice whose prefix does not match the lang_code is rejected by Kokoro.
+KOKORO_VOICE="${KOKORO_VOICE:-}"
+
+# ── Stage 1: TTS generation (Kokoro synthesizes one sample at a time — no batch size) ──
+generate_stage() {
+ local LANG_CODE VOICE
+ LANG_CODE="${KOKORO_LANG_CODE[${ASR_LANG}]}"
+ VOICE="${KOKORO_VOICE:-${KOKORO_VOICES[${ASR_LANG}]}}"
+ 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/kokoro && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --voice=${VOICE} \
+ --lang_code=${LANG_CODE} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --device=cuda:0 \
+ --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"
+ "tts zh zh"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot fr fr ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot it it ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ja ja ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot zh zh ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id" (CLI args override) ───────────────────────────────────
+MODEL_CONFIGS=("hexgrad/Kokoro-82M")
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/lfm2-audio/run_eval.py b/lfm2-audio/run_eval.py
new file mode 100644
index 0000000..508e2f2
--- /dev/null
+++ b/lfm2-audio/run_eval.py
@@ -0,0 +1,222 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (LFM2.5-Audio backend, stage 1).
+
+LFM2.5-Audio-1.5B (LiquidAI/LFM2.5-Audio-1.5B) is Liquid AI's end-to-end speech + text model: an
+LFM2.5 backbone whose RQ-transformer ("depthformer") emits 8 Mimi-compatible codebooks per 12.5 Hz
+frame, turned into 24 kHz audio by an LFM-based detokenizer (`processor.decode`). It is loaded
+in-process via the `liquid-audio` package. TTS uses the package's *sequential* generation with one
+of four fixed voices, picked by the system prompt (see VOICES); there is no voice cloning, and the
+model is English only.
+
+`generate_sequential` asserts a batch of one (`_prefill`: text.shape[0] == 1), so rows are
+processed serially. Per row we generate audio frames until the end-of-audio frame (all codes
+2048), detokenize them in one call, and time both together for RTFx.
+
+Upstream TTS example: https://github.com/Liquid4All/liquid-audio#tts
+
+Stage 2 (`transformers/transcribe.py`, run in the shared `bezzam/evals` image) transcribes the
+wavs with Qwen3-ASR to fill `pred_text`, and stage 4 (`normalizer.eval_utils.score_results`, run
+locally) computes WER + RTFx from the completed manifest. Fixed voice, so no stage 3 (SIM).
+"""
+
+import argparse
+import os
+import time
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+from liquid_audio import ChatState, LFM2AudioModel, LFM2AudioProcessor
+
+from run_eval_utils import (
+ add_common_args, load_done_entries, load_tts_dataset, manifest_entry, open_manifest, output_paths,
+ pending_batches, print_model_size, print_next_steps, set_seed, warm_up, wav_rel_path, write_entry,
+)
+
+# The detokenizer outputs 24 kHz mono (fixed constant, not returned by the API).
+SAMPLING_RATE = 24_000
+# Audio code that marks the end-of-audio frame (the depthformer's extra vocab entry).
+END_OF_AUDIO = 2048
+
+# The four built-in voices, selected by the system prompt (from the liquid-audio README).
+VOICES = {
+ "us_female": "Perform TTS. Use the US female voice.",
+ "us_male": "Perform TTS. Use the US male voice.",
+ "uk_female": "Perform TTS. Use the UK female voice.",
+ "uk_male": "Perform TTS. Use the UK male voice.",
+}
+
+
+def main(args):
+ set_seed(args.seed)
+
+ # The package's detokenizer is hard-coded to `.cuda()` (LFM2AudioProcessor.audio_detokenizer).
+ if not args.device.startswith("cuda"):
+ raise ValueError(f"liquid-audio's detokenizer only runs on CUDA; got --device={args.device}.")
+
+ processor = LFM2AudioProcessor.from_pretrained(args.model_id, device=args.device).eval()
+ model = LFM2AudioModel.from_pretrained(args.model_id, device=args.device).eval()
+ # The detokenizer is loaded lazily on first decode; load it now so it is counted and its load
+ # never lands in a timed generation.
+ detokenizer = processor.audio_detokenizer
+ print(f"Loaded LFM2.5-Audio ({args.model_id}, voice={args.voice})")
+ print_model_size(model, detokenizer)
+
+ system_prompt = VOICES[args.voice]
+ truncated = [] # rows that hit --max_new_tokens before the end-of-audio frame
+
+ def audio_frames(text):
+ """Yield the (8,) audio code frames for `text`, stopping at the end-of-audio frame."""
+ chat = ChatState(processor)
+ chat.new_turn("system")
+ chat.add_text(system_prompt)
+ chat.end_turn()
+ chat.new_turn("user")
+ chat.add_text(text)
+ chat.end_turn()
+ chat.new_turn("assistant")
+
+ for t in model.generate_sequential(
+ **chat,
+ max_new_tokens=args.max_new_tokens,
+ audio_temperature=args.audio_temperature,
+ audio_top_k=args.audio_top_k,
+ ):
+ if t.numel() == 1: # text token (<|audio_start|> etc.)
+ continue
+ # The audio is complete at end-of-audio; what follows is only the closing text tokens.
+ if t[0] == END_OF_AUDIO:
+ return
+ yield t
+ truncated.append(text)
+
+ def decode(frames):
+ """(8,) code frames → 1-D float32 numpy waveform."""
+ if not frames:
+ return np.zeros(1, dtype=np.float32)
+ waveform = processor.decode(torch.stack(frames, 1).unsqueeze(0))
+ return waveform[0].detach().to(torch.float32).cpu().numpy()
+
+ def synth_one(text):
+ """Synthesize one text. Return (audio_1d_numpy, elapsed_s)."""
+ torch.cuda.synchronize()
+ start = time.perf_counter()
+ # decode() ends with .cpu(), so the clock stops only once the audio is materialised.
+ audio = decode(list(audio_frames(text)))
+ elapsed = time.perf_counter() - start
+ return audio, elapsed
+
+ def synth_one_streaming(text, early_stop=False):
+ """TTFA probe only: return (audio_1d_numpy, first_audio_ts).
+
+ liquid-audio has no streaming decode API, but the detokenizer is causal (sliding-window
+ attention over the code frames), so decoding the first `--ttfa_chunk_frames` frames as soon
+ as they exist yields the audio a streaming client could start playing. The whole utterance
+ is still decoded in one call at the end, as in synth_one; the extra prefix decode is part of
+ the timed generation, so it slightly understates batch-1 RTFx, never TTFA.
+ """
+ frames, first = [], None
+ for frame in audio_frames(text):
+ frames.append(frame)
+ if first is None and len(frames) == args.ttfa_chunk_frames:
+ chunk = decode(frames) # ends with .cpu(): the audio is in hand
+ first = time.perf_counter()
+ if early_stop:
+ return chunk, first
+ audio = decode(frames)
+ if first is None: # shorter than one chunk: first audio is the whole utterance
+ first = time.perf_counter()
+ return audio, first
+
+ # 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 decoded chunk (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
+
+ def _ttfa_gen(job, early_stop):
+ audio, first = synth_one_streaming(job["text"], early_stop)
+ return audio, SAMPLING_RATE, first
+
+ # The probe discards its first rows as warm-up but does not run one: compile the kernels
+ # here so the first probed rows are not dominated by CUDA initialisation.
+ for i in range(min(args.warmup_steps, len(dataset))):
+ synth_one(dataset[i][args.text_column])
+ set_seed(args.seed)
+
+ 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,
+ # The chunk size is the floor under TTFA, so it is recorded with the numbers.
+ extra={"device": args.device, "voice": args.voice, "ttfa_chunk_frames": args.ttfa_chunk_frames},
+ )
+ 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) # so warm-up does not shift the RNG stream of the timed run
+ truncated.clear()
+
+ # ── 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, SAMPLING_RATE)
+
+ write_entry(manifest_file, manifest_entry(rel_path, len(audio) / SAMPLING_RATE, elapsed, text))
+ manifest_file.flush()
+
+ manifest_file.close()
+ if truncated:
+ print(f"WARNING: {len(truncated)} sample(s) hit --max_new_tokens={args.max_new_tokens} "
+ "before the end-of-audio frame (audio cut off).")
+ 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="LiquidAI/LFM2.5-Audio-1.5B", help="LFM2-Audio repo id.")
+ parser.add_argument("--voice", type=str, default="us_female", choices=sorted(VOICES),
+ help="Built-in voice (selected through the system prompt).")
+ # Sampling defaults from the liquid-audio README's TTS example.
+ parser.add_argument("--audio_temperature", type=float, default=0.8, help="Audio-code sampling temperature.")
+ parser.add_argument("--audio_top_k", type=int, default=64, help="Audio-code top-k.")
+ # 1 frame = 80 ms of audio, so 1024 frames is ~82 s: far beyond any eval utterance.
+ parser.add_argument("--max_new_tokens", type=int, default=1024,
+ help="Max generated tokens (text + audio frames) per sample.")
+ parser.add_argument("--ttfa_chunk_frames", type=int, default=1,
+ help="TTFA probe: frames (80 ms each) decoded for the first playable chunk.")
+ 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/lfm2-audio/submit_jobs.sh b/lfm2-audio/submit_jobs.sh
new file mode 100644
index 0000000..01b5212
--- /dev/null
+++ b/lfm2-audio/submit_jobs.sh
@@ -0,0 +1,47 @@
+#!/bin/bash
+# HF Jobs TTS eval — LFM2.5-Audio backend (fixed voice → 2 stages: generate → transcribe → score).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["LiquidAI/LFM2.5-Audio-1.5B" ...]
+# 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-lfm2-audio}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-lfm2-audio/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)"
+
+# English only (model card), with four built-in voices: us_female, us_male, uk_female, uk_male.
+supports_language() { [[ "$1" == "en" ]]; }
+LFM_VOICE="${LFM_VOICE:-us_female}"
+
+# ── Stage 1: TTS generation (generate_sequential is batch-1 only — no batch size) ──
+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/lfm2-audio && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --voice=${LFM_VOICE} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --device=cuda:0 \
+ --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=("LiquidAI/LFM2.5-Audio-1.5B")
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/magpie-tts/run_eval.py b/magpie-tts/run_eval.py
new file mode 100644
index 0000000..02c9374
--- /dev/null
+++ b/magpie-tts/run_eval.py
@@ -0,0 +1,469 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (NVIDIA Magpie TTS Multilingual backend, stage 1).
+
+Magpie TTS Multilingual is loaded via NeMo (`MagpieTTSModel`) with 5 baked speakers and no
+zero-shot cloning; output is 22.05 kHz. The HF repo is gated, so set HF_TOKEN.
+
+Batching: `do_tts()` is single-utterance, but its short-text path wraps `model.infer_batch()`,
+which takes a padded token batch. This script mirrors that wrapper for a whole minibatch; texts
+at/above the long-form threshold fall back to per-sample `do_tts()` inside the same timed block.
+
+Memory: NeMo's attention materializes the full (B, heads, T, T) matrix and CFG doubles the batch,
+so memory grows with the SQUARE of the padded length. `--batch_size` is therefore a nominal
+maximum: minibatches are split to fit a budget on `n * max_text_tokens^2` (see
+`_plan_chunk_size`), calibrated from the first OOM. Short texts keep the full batch, so their RTFx
+stays comparable with the other backends.
+"""
+
+import argparse
+import contextlib
+import logging as pylogging
+import os
+import sys
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+from nemo.collections.tts.models import MagpieTTSModel
+from nemo.utils import logging as nemo_logging
+
+from run_eval_utils import (
+ add_common_args, count_parameters, load_done_entries, load_tts_dataset, manifest_entry, open_manifest,
+ output_paths, pending_batches, print_next_steps, set_seed, wav_rel_path, warm_up, write_entry,
+)
+
+# NeMo is very chatty; errors only. infer_batch's raw prints are swallowed with redirect_stdout below.
+nemo_logging.setLevel(pylogging.ERROR)
+
+torch.set_float32_matmul_precision("high")
+
+# Baked speakers, from the model card.
+SPEAKER_MAP = {"John": 0, "Sofia": 1, "Aria": 2, "Jason": 3, "Leo": 4}
+
+# Language -> tokenizer-name candidates; copied from MagpieTTSModel.do_tts (NeMo v2.7.3).
+LANGUAGE_TOKENIZER_MAP = {
+ "en": ["english_phoneme", "english"],
+ "de": ["german_phoneme", "german"],
+ "es": ["spanish_phoneme", "spanish"],
+ "fr": ["french_chartokenizer", "french"],
+ "it": ["italian_phoneme", "italian"],
+ "vi": ["vietnamese_phoneme", "vietnamese"],
+ "zh": ["mandarin_phoneme", "mandarin", "chinese"],
+ # ja/hi are not in NeMo's do_tts map but the checkpoint ships these tokenizers. Keep them OUT of
+ # LONGFORM_WORD_THRESHOLDS: the long-form path uses do_tts, which would pick the wrong tokenizer.
+ "ja": ["japanese_phoneme", "japanese"],
+ "hi": ["hindi_chartokenizer", "hindi"],
+}
+
+# Word-count thresholds above which do_tts switches to long-form (sentence-chunked)
+# inference; copied from MagpieTTSModel._needs_longform_inference (NeMo v2.7.3).
+# Standard mode generates at most ~20 s of speech.
+LONGFORM_WORD_THRESHOLDS = {"en": 45, "es": 73, "fr": 69, "vi": 50, "it": 53, "de": 50}
+
+
+def _resolve_checkpoint(model_id, revision):
+ """Download the checkpoint's ``.nemo`` from the HF Hub at a pinned revision; return its path.
+
+ The revision is pinned because newer upstream configs are incompatible with this NeMo build.
+ A local ``.nemo`` path is returned unchanged.
+ """
+ if model_id.endswith(".nemo") and os.path.exists(model_id):
+ return model_id
+ from huggingface_hub import hf_hub_download, list_repo_files
+
+ token = os.environ.get("HF_TOKEN")
+ nemo_files = [f for f in list_repo_files(model_id, revision=revision, token=token) if f.endswith(".nemo")]
+ if len(nemo_files) != 1:
+ raise RuntimeError(f"Expected exactly one .nemo file in {model_id}@{revision}, found: {nemo_files}")
+ print(f"Downloading {model_id}/{nemo_files[0]} at revision {revision} ...")
+ return hf_hub_download(repo_id=model_id, filename=nemo_files[0], revision=revision, token=token)
+
+
+def _admit_checkpoint_locales(nemo_path):
+ """Whitelist any G2P locales the checkpoint declares but this NeMo build doesn't recognize.
+
+ The checkpoint ships tokenizers for locales (e.g. ``pt-BR``) that ``validate_locale`` rejects,
+ aborting model construction. That check is the only effect of ``locale`` here, so admitting
+ them leaves every tokenizer's vocab (and thus the embedding shape and bos/eos ids) unchanged.
+ ``SUPPORTED_LOCALES`` is mutated in place so every importer sees it.
+ """
+ from nemo.collections.common.tokenizers.text_to_speech import ipa_lexicon
+
+ wanted = set()
+ try:
+ from omegaconf import OmegaConf
+
+ cfg = MagpieTTSModel.restore_from(nemo_path, return_config=True)
+ stack = [OmegaConf.to_container(cfg, resolve=False)]
+ while stack:
+ node = stack.pop()
+ if isinstance(node, dict):
+ for key, val in node.items():
+ if key == "locale" and isinstance(val, str):
+ wanted.add(val)
+ else:
+ stack.append(val)
+ elif isinstance(node, list):
+ stack.extend(node)
+ except Exception as e:
+ print(f"Could not pre-read checkpoint config to detect locales ({e}); "
+ "falling back to a known-unsupported set.")
+ wanted = {"pt-BR"}
+
+ added = [loc for loc in sorted(wanted) if loc not in ipa_lexicon.SUPPORTED_LOCALES]
+ ipa_lexicon.SUPPORTED_LOCALES.extend(added)
+ if added:
+ print(f"Admitted checkpoint G2P locales not in this NeMo build: {added}")
+
+
+def main(args):
+ # Set seed for reproducibility (generation samples audio tokens).
+ set_seed(args.seed)
+ torch.backends.cudnn.deterministic = True
+
+ if args.speaker not in SPEAKER_MAP:
+ raise ValueError(f"Unknown speaker {args.speaker!r}; choose from {sorted(SPEAKER_MAP)}")
+ speaker_idx = SPEAKER_MAP[args.speaker]
+
+ nemo_path = _resolve_checkpoint(args.model_id, args.revision)
+ # Must run before the real load, otherwise __init__ aborts building the tokenizers.
+ _admit_checkpoint_locales(nemo_path)
+
+ # Also pulls the NanoCodec vocoder referenced by the checkpoint config.
+ model = MagpieTTSModel.restore_from(nemo_path)
+ model = model.to(args.device)
+ model.eval()
+ if args.cfg_scale is not None:
+ model.inference_parameters.cfg_scale = args.cfg_scale
+ sampling_rate = int(model.output_sample_rate) # 22050 (NanoCodec 22 kHz)
+ print(
+ f"Loaded Magpie TTS model {args.model_id} "
+ f"(speaker={args.speaker}[{speaker_idx}], language={args.language}, sr={sampling_rate}, "
+ f"use_cfg={args.use_cfg}, cfg_scale={model.inference_parameters.cfg_scale})"
+ )
+
+ # Report parameter count (deduped by id; MagpieTTSModel is a single nn.Module that
+ # also registers the NanoCodec decoder as a submodule).
+ try:
+ n_params = count_parameters(model)
+ if n_params:
+ print(f"TTS model size: {n_params / 1e9:.2f}B parameters (incl. codec)")
+ except Exception as e:
+ print(f"Could not determine model size: {e}")
+
+ # Resolve the tokenizer for the target language exactly like do_tts does.
+ available_tokenizers = list(model.tokenizer.tokenizers.keys())
+ tokenizer_name = None
+ for candidate in LANGUAGE_TOKENIZER_MAP.get(args.language, []):
+ if candidate in available_tokenizers:
+ tokenizer_name = candidate
+ break
+ if tokenizer_name is None:
+ tokenizer_name = available_tokenizers[0]
+ pad_id = model.tokenizer.pad
+ print(f"Using tokenizer '{tokenizer_name}' (available: {available_tokenizers})")
+
+ longform_threshold = LONGFORM_WORD_THRESHOLDS.get(args.language)
+
+ def _is_longform(text):
+ if longform_threshold is None:
+ return False
+ word_count = len(list(text)) if args.language == "zh" else len(text.split())
+ return word_count >= longform_threshold
+
+ # Flat, bucket-friendly layout, per model:
+ # results/<model_safe>/ MODEL_<safe>_DATASET_<dsid>.jsonl + <dsid>/output_<id>.wav
+ # Manifest paths are relative to model_dir, so downstream stages resolve them wherever it is copied.
+ paths = output_paths(args)
+ model_dir, dataset_dir_name = paths.model_dir, paths.dataset_dir_name
+
+ # ── Attention-memory budget, calibrated at runtime ───────────────────────
+ # Cost model: `n * max_text_tokens**2`, a proxy for the attention peak. `None` = no budget yet:
+ # run the full batch, and on the first OOM derive the budget from the failed cost.
+ # --max_attn_cost skips that probe.
+ attn_budget = args.max_attn_cost or None
+ # The failed attempt died partway through its decode, so its true peak was higher; halving adds margin.
+ ATTN_BUDGET_SAFETY = 2
+
+ def _plan_chunk_size(indices, token_lens):
+ """Greedily chunk `indices` so each chunk's ``len(chunk) * max_text_tokens**2`` fits the budget.
+
+ Chunks stay contiguous to preserve manifest order; an over-budget text forms a chunk of one.
+ """
+ if attn_budget is None:
+ return [list(indices)]
+ chunks, cur, cur_max = [], [], 0
+ for i in indices:
+ new_max = max(cur_max, token_lens[i])
+ if cur and (len(cur) + 1) * new_max**2 > attn_budget:
+ chunks.append(cur)
+ cur, cur_max = [i], token_lens[i]
+ else:
+ cur.append(i)
+ cur_max = new_max
+ if cur:
+ chunks.append(cur)
+ return chunks
+
+ def generate_tts(batch):
+ """Synthesize speech for a minibatch of target texts; time the batch generation for RTFx."""
+ texts = list(batch[args.text_column])
+ minibatch_size = len(texts)
+
+ # Short texts go through true batched infer_batch calls (the same call do_tts makes with
+ # batch size 1); rare long-form texts fall back to do_tts.
+ short_idx = [i for i, t in enumerate(texts) if not _is_longform(t)]
+ long_idx = [i for i in range(minibatch_size) if i not in short_idx]
+
+ audios = [None] * minibatch_size
+ token_lists = {} # index -> text token ids (populated inside the timed region below)
+ wasted_s = 0.0 # GPU time burned by sub-batches that OOM'd and were retried smaller
+
+ def _infer_chunk(chunk):
+ """One batched infer_batch call over `chunk` (indices into `texts`); fills `audios`."""
+ token_lens = [len(token_lists[i]) for i in chunk]
+ text_tensor = torch.full((len(chunk), max(token_lens)), pad_id, dtype=torch.long)
+ for row, i in enumerate(chunk):
+ text_tensor[row, : token_lens[row]] = torch.tensor(token_lists[i], dtype=torch.long)
+ nemo_batch = {
+ "text": text_tensor.to(model.device),
+ "text_lens": torch.tensor(token_lens, device=model.device, dtype=torch.long),
+ "speaker_indices": speaker_idx, # int broadcasts over the batch
+ }
+ out = model.infer_batch(
+ nemo_batch,
+ use_cfg=args.use_cfg,
+ use_local_transformer_for_inference=True,
+ )
+ for row, i in enumerate(chunk):
+ n = int(out.predicted_audio_lens[row].item())
+ audios[i] = out.predicted_audio[row, :n].detach().float().cpu().numpy()
+
+ def _infer_chunk_with_oom_retry(chunk):
+ """Run `chunk`; on OOM, tighten the budget and retry the two halves.
+
+ The aborted attempt's GPU time is excluded from the timed region so RTFx reflects only
+ work that produced audio. Messages go to stderr (stdout is swallowed here).
+ """
+ nonlocal wasted_s, attn_budget
+ attempt_start = torch.cuda.Event(enable_timing=True)
+ attempt_end = torch.cuda.Event(enable_timing=True)
+ attempt_start.record()
+ try:
+ _infer_chunk(chunk)
+ return
+ except torch.OutOfMemoryError:
+ if len(chunk) == 1: # can't split further — a single text OOMs on its own
+ raise
+ attempt_end.record()
+ torch.cuda.synchronize(device=args.device)
+ wasted_s += attempt_start.elapsed_time(attempt_end) / 1000.0
+ torch.cuda.empty_cache()
+
+ max_len = max(len(token_lists[i]) for i in chunk)
+ failed_cost = len(chunk) * max_len**2
+ tightened = failed_cost // ATTN_BUDGET_SAFETY
+ attn_budget = tightened if attn_budget is None else min(attn_budget, tightened)
+ print(
+ f"OOM on a sub-batch of {len(chunk)} (max {max_len} text tokens, cost {failed_cost}); "
+ f"attention budget now {attn_budget} — pass --max_attn_cost={attn_budget} to skip this "
+ f"probe on a rerun. Halving and retrying.",
+ file=sys.stderr,
+ flush=True,
+ )
+ mid = len(chunk) // 2
+ _infer_chunk_with_oom_retry(chunk[:mid])
+ _infer_chunk_with_oom_retry(chunk[mid:])
+
+ # START TIMING (TTS batch generation)
+ torch.cuda.synchronize(device=args.device)
+ start_event = torch.cuda.Event(enable_timing=True)
+ end_event = torch.cuda.Event(enable_timing=True)
+ start_event.record()
+
+ autocast_ctx = (
+ torch.autocast(device_type="cuda", dtype=getattr(torch, args.dtype))
+ if args.dtype != "float32"
+ else contextlib.nullcontext()
+ )
+ with torch.no_grad(), autocast_ctx, open(os.devnull, "w") as devnull, contextlib.redirect_stdout(devnull):
+ if short_idx:
+ # Tokenization stays inside the timed region: the phonemizer is part of the cost.
+ token_lists = {
+ i: model.tokenizer.encode(text=texts[i], tokenizer_name=tokenizer_name) + [model.eos_id]
+ for i in short_idx
+ }
+ token_lens = {i: len(t) for i, t in token_lists.items()}
+ chunks = _plan_chunk_size(short_idx, token_lens)
+ if len(chunks) > 1:
+ print(
+ f"Split a minibatch of {len(short_idx)} into sub-batches {[len(c) for c in chunks]} "
+ f"(max {max(token_lens.values())} text tokens, attention budget {attn_budget})",
+ file=sys.stderr,
+ flush=True,
+ )
+ for chunk in chunks:
+ _infer_chunk_with_oom_retry(chunk)
+
+ for i in long_idx:
+ wav, wav_len = model.do_tts(
+ texts[i],
+ language=args.language,
+ apply_TN=False,
+ use_cfg=args.use_cfg,
+ speaker_index=speaker_idx,
+ )
+ n = int(wav_len[0].item())
+ audios[i] = wav[0, :n].detach().float().cpu().numpy()
+
+ # END TIMING
+ end_event.record()
+ torch.cuda.synchronize(device=args.device)
+ # Exclude time spent on OOM'd attempts that produced no audio (see _infer_chunk_with_oom_retry).
+ runtime = max(start_event.elapsed_time(end_event) / 1000.0 - wasted_s, 1e-6)
+ # per-sample generation time (RTFx is aggregated over the whole set at scoring time)
+ batch["generation_time_s"] = minibatch_size * [runtime / minibatch_size]
+
+ gen_paths, audio_length_s = [], []
+ for audio, sample_id in zip(audios, batch["id"]):
+ # 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 = np.asarray(audio).reshape(-1)
+ if audio.size == 0: # degenerate generation; write a stub so the pipeline continues
+ audio = np.zeros(int(0.1 * sampling_rate), dtype=np.float32)
+ sf.write(path, audio, sampling_rate)
+ gen_paths.append(rel_path)
+ audio_length_s.append(len(audio) / sampling_rate)
+
+ batch["gen_audio_filepath"] = gen_paths
+ batch["audio_length_s"] = audio_length_s
+ batch["references"] = list(batch[args.text_column]) # raw; normalized at scoring time
+ return batch
+
+ # Fixed baked voice (no cloning): only `id` and the target text are kept.
+ dataset = load_tts_dataset(args)
+
+ probe_out_dir = model_dir # real results dir, captured before the probe rebinds model_dir
+ # ── TTFA probe: latency only, writing nothing but a JSON sidecar ─────────
+ # Drives generate_tts() with one-row batches; `model_dir`/`dataset_dir_name` are rebound to a
+ # temp dir (generate_tts closes over them) so nothing lands in the results tree. No streaming
+ # API, so TTFA is the whole-utterance time. See scripts/ttfa_probe.py.
+ if args.ttfa_probe != 0:
+ # Imported here: the probe module is injected only by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+ import tempfile
+
+ model_dir = tempfile.mkdtemp(prefix="ttfa_out_")
+ dataset_dir_name = "ttfa"
+ output_dir = os.path.join(model_dir, dataset_dir_name)
+ os.makedirs(output_dir, exist_ok=True)
+
+ def _gen(job):
+ result = generate_tts(job)
+ return float(result["audio_length_s"][0]), None, None
+
+ columns = dataset.column_names
+ jobs = [{c: [dataset[i][c]] for c in columns}
+ for i in sample_indices(args.ttfa_probe, len(dataset))]
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=probe_out_dir, mode_suffix="", n=args.ttfa_probe, # fixed voice: no clone mode
+ extra={"device": args.device, "note": "driven at batch size 1"},
+ )
+ return
+
+ # ── Manifest (written incrementally; resume skips rows already in it) ───
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ # ── Main loop: TTS → write JSONL, one batch at a time ───────────────────
+ starts = pending_batches(dataset, args.batch_size, done_entries, dataset_dir_name)
+ warm_up(generate_tts, dataset, starts, args.batch_size, args.warmup_steps)
+ for batch_start in tqdm(starts, desc="Generating"):
+ batch = generate_tts(dataset[batch_start : batch_start + args.batch_size])
+
+ # Append each sample to the JSONL immediately.
+ for afp, alen, gtime, ref in zip(
+ batch["gen_audio_filepath"], batch["audio_length_s"],
+ batch["generation_time_s"], batch["references"],
+ ):
+ write_entry(manifest_file, manifest_entry(afp, alen, gtime, ref))
+ manifest_file.flush()
+
+ manifest_file.close()
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(False)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument(
+ "--model_id",
+ type=str,
+ default="nvidia/magpie_tts_multilingual_357m",
+ help="Magpie TTS model id on the HF Hub (gated; needs HF_TOKEN), loaded with NeMo. "
+ "May also be a local .nemo path (then --revision is ignored).",
+ )
+ parser.add_argument(
+ "--revision",
+ type=str,
+ default="34d7e40da85cabc97f92198889b65cea27bc7fd1",
+ help="Pinned HF Hub revision (commit) of the checkpoint, known to load under NeMo 2.7.3. "
+ "Use 'main' for latest.",
+ )
+ parser.add_argument(
+ "--speaker",
+ type=str,
+ default="Sofia",
+ help="Baked speaker voice: John, Sofia, Aria, Jason, or Leo (no zero-shot cloning).",
+ )
+ parser.add_argument(
+ "--language",
+ type=str,
+ default="en",
+ help="Language code: en, de, es, fr, it, vi, zh, ja, hi (see LANGUAGE_TOKENIZER_MAP). An "
+ "unmapped language silently falls back to the first available tokenizer.",
+ )
+ parser.add_argument(
+ "--use_cfg",
+ action=argparse.BooleanOptionalAction,
+ default=True,
+ help="Classifier-free guidance (default on, matching do_tts). Disable with --no-use_cfg.",
+ )
+ parser.add_argument(
+ "--cfg_scale",
+ type=float,
+ default=None,
+ help="Override the checkpoint's CFG scale (model card batch example uses 2.5); default: checkpoint value.",
+ )
+ add_common_args(parser, batch_size=32)
+ parser.add_argument(
+ "--max_attn_cost",
+ type=int,
+ default=0,
+ help="Initial cap on `n * max_text_tokens^2` per infer_batch call; a minibatch exceeding it "
+ "is split into sub-batches. Default 0 = start unbounded and calibrate from the first OOM.",
+ )
+ parser.add_argument(
+ "--dtype",
+ type=str,
+ default="float32",
+ help="Generation precision. NeMo Magpie inference is float32 by default; other values "
+ "(e.g. 'bfloat16') run generation under torch.autocast.",
+ )
+
+ 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/magpie-tts/submit_jobs.sh b/magpie-tts/submit_jobs.sh
new file mode 100644
index 0000000..8d37a77
--- /dev/null
+++ b/magpie-tts/submit_jobs.sh
@@ -0,0 +1,70 @@
+#!/bin/bash
+# HF Jobs TTS eval — Magpie TTS backend (fixed voice → 2 stages: generate → transcribe → score).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["nvidia/magpie_tts_multilingual_357m 32 Sofia" ...]
+# 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-magpie}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-magpie/blob/main/Dockerfile)
+DEFAULT_STAGES="generate transcribe" # no SIM (fixed baked voice, no zero-shot cloning)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id batch_size speaker". ──
+# Generation memory is quadratic in text length, so:
+# * MAX_ATTN_COST — run_eval.py sub-batches when n*max_text_tokens^2 exceeds the budget.
+# 0 = calibrate from the first OOM; set it to the value the log printed to skip that probe.
+# * expandable_segments — allocation sizes change every batch, which otherwise fragments memory.
+MAX_ATTN_COST="${MAX_ATTN_COST:-0}"
+generate_stage() {
+ local _ BATCH_SIZE SPEAKER
+ read -r _ BATCH_SIZE SPEAKER <<< "${MODEL_CFG}"
+ hf jobs run \
+ --flavor "${FLAVOR}" --timeout 8h --secrets HF_TOKEN ${NAMESPACE_ARG} \
+ --env PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True" \
+ --volume "hf://buckets/${RESULTS_BUCKET}:/results" "${TTS_IMAGE}" \
+ bash -c "
+ ${RUN_EVAL_INJECT}
+ cd /app/magpie-tts && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --speaker=${SPEAKER} \
+ --language=${ASR_LANG} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --device=cuda:0 \
+ --batch_size=${BATCH_SIZE} \
+ --max_attn_cost=${MAX_ATTN_COST} \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Languages this backend can actually select ───────────────────────────────
+# An unmapped language silently falls back to the first tokenizer in run_eval.py, so gate the combos.
+# These are the 9 languages the checkpoint ships a tokenizer for (no Korean).
+MAGPIE_LANGUAGES="en de es fr it vi zh ja hi"
+supports_language() { [[ " ${MAGPIE_LANGUAGES} " == *" $1 "* ]]; }
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment) ──
+# asr_language is the language hint for both the TTS model and Qwen3-ASR, so it must be a real
+# language code (`zh_hard` pairs with `zh`).
+DATASET_CONFIGS=(
+ "tts en en"
+ "tts zh zh"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot zh zh ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ja ja ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot de de ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot fr fr ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot it it ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id batch_size speaker" (CLI args override) ────────────────
+# Baked speakers: John, Sofia, Aria, Jason, Leo (no zero-shot cloning).
+MODEL_CONFIGS=("nvidia/magpie_tts_multilingual_357m 32 Sofia")
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/moss-tts/run_eval.py b/moss-tts/run_eval.py
new file mode 100644
index 0000000..360e938
--- /dev/null
+++ b/moss-tts/run_eval.py
@@ -0,0 +1,241 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (MOSS-TTS backend, stage 1).
+
+MOSS-TTS (OpenMOSS-Team/MOSS-TTS) is an ~8B Qwen3-based delay-codebook TTS loaded in-process
+via transformers with `trust_remote_code=True`. Its API is custom: build conversation messages
+with the processor, run a custom `generate`, then `processor.decode` back to waveforms. It
+supports batched generation, so texts are synthesized in minibatches (the batch call is timed
+for RTFx).
+
+Voice cloning (`--voice_clone`): each message is built with the dataset's per-sample
+`prompt_audio` as the reference clip (written to `results/<model_safe>/<dsid>/prompts/prompt_{id}.wav`,
+which MOSS's `build_user_message(reference=[path])` and stage 3 both read). Outputs get a
+`_voice_clone` suffix so cloning and non-cloning runs coexist. By default (`--no-voice_clone`)
+the built-in default voice is used and speaker-similarity scoring is skipped.
+
+Wavs + a manifest with `text`, `duration`, and generation `time` (empty `pred_text`) are written
+for stage 2 (`transformers/transcribe.py`, Qwen3-ASR), stage 3 (`transformers/score_similarity.py`,
+speaker SIM — voice-clone only), and stage 4 (local `normalizer.eval_utils.score_results`, WER + RTFx + mean SIM).
+"""
+
+import argparse
+import os
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+from transformers import AutoModel, AutoProcessor
+
+from run_eval_utils import (
+ add_common_args,
+ load_done_entries,
+ load_tts_dataset,
+ manifest_entry,
+ open_manifest,
+ output_paths,
+ pending_batches,
+ print_model_size,
+ print_next_steps,
+ set_seed,
+ warm_up,
+ write_entry,
+)
+
+
+def main(args):
+ # Set seed for reproducibility (MOSS-TTS samples audio tokens).
+ set_seed(args.seed)
+
+ # SDPA backend hygiene (from the upstream CLI).
+ if torch.cuda.is_available():
+ torch.backends.cuda.enable_cudnn_sdp(False)
+ torch.backends.cuda.enable_flash_sdp(True)
+ torch.backends.cuda.enable_mem_efficient_sdp(True)
+
+ dtype = getattr(torch, args.dtype)
+ processor = AutoProcessor.from_pretrained(args.model_id, trust_remote_code=True)
+ # The audio (de)tokenizer runs the vocoder; move it to the compute device.
+ processor.audio_tokenizer = processor.audio_tokenizer.to(args.device)
+ model = AutoModel.from_pretrained(args.model_id, trust_remote_code=True, dtype=dtype).to(args.device)
+ model.eval()
+ sampling_rate = int(processor.model_config.sampling_rate) # 24000
+ print(f"Loaded MOSS-TTS ({args.model_id}, sr={sampling_rate})")
+ print_model_size(model)
+
+ # Layout: results/<model_safe>/{MODEL_<safe>_DATASET_<dsid>.jsonl, <dsid>/output_<id>.wav},
+ # <dsid> = <dataset_safe>_<dataset>_<split><mode_suffix>. Manifest paths are relative to
+ # model_dir so later stages resolve them wherever it is copied.
+ mode_suffix = "_voice_clone" if args.voice_clone else ""
+ paths = output_paths(args, mode_suffix)
+ model_dir, dataset_dir_name, output_dir = paths.model_dir, paths.dataset_dir_name, paths.output_dir
+ # Reference clips must live under results/ (not tempfiles) so stage 3 SIM can read them.
+ prompt_dir = os.path.join(output_dir, "prompts")
+ if args.voice_clone:
+ os.makedirs(prompt_dir, exist_ok=True)
+
+ def generate_tts(texts, ids, prompt_full_paths):
+ """Synthesize a batch of texts (optionally cloning prompt_full_paths); time the batch for RTFx.
+
+ `prompt_full_paths` must be on-disk paths (MOSS opens them); returned paths are relative.
+ """
+ minibatch_size = len(texts)
+ if args.voice_clone:
+ conversations = [
+ [processor.build_user_message(text=t, language=args.language, reference=[pp])]
+ for t, pp in zip(texts, prompt_full_paths)
+ ]
+ else:
+ conversations = [
+ [processor.build_user_message(text=t, language=args.language)] for t in texts
+ ]
+
+ # START TIMING (TTS batch generation)
+ torch.cuda.synchronize(device=args.device)
+ start_event = torch.cuda.Event(enable_timing=True)
+ end_event = torch.cuda.Event(enable_timing=True)
+ start_event.record()
+
+ batch = processor(conversations, mode="generation")
+ with torch.no_grad():
+ outputs = model.generate(
+ input_ids=batch["input_ids"].to(args.device),
+ attention_mask=batch["attention_mask"].to(args.device),
+ max_new_tokens=args.max_new_tokens,
+ audio_temperature=args.audio_temperature,
+ audio_top_p=args.audio_top_p,
+ audio_top_k=args.audio_top_k,
+ audio_repetition_penalty=args.audio_repetition_penalty,
+ )
+ messages = processor.decode(outputs)
+
+ # END TIMING
+ end_event.record()
+ torch.cuda.synchronize(device=args.device)
+ runtime = start_event.elapsed_time(end_event) / 1000.0
+ per_sample_time = runtime / minibatch_size
+
+ gen_paths, audio_length_s = [], []
+ for msg, sample_id in zip(messages, ids):
+ # Store the path relative to model_dir (the manifest's dir); write to the full path.
+ rel_path = os.path.join(dataset_dir_name, f"output_{sample_id}.wav")
+ path = os.path.join(model_dir, rel_path)
+ if msg is None or not getattr(msg, "audio_codes_list", None):
+ # Empty generation — write a short silence so the manifest stays aligned.
+ audio = np.zeros(int(0.1 * sampling_rate), dtype=np.float32)
+ else:
+ audio = msg.audio_codes_list[0]
+ audio = np.asarray(audio.detach().to(torch.float32).cpu()).reshape(-1)
+ sf.write(path, audio, sampling_rate)
+ gen_paths.append(rel_path)
+ audio_length_s.append(len(audio) / sampling_rate)
+
+ return gen_paths, audio_length_s, minibatch_size * [per_sample_time]
+
+ # Keep `id`, target text, and (when cloning) the per-sample reference.
+ dataset = load_tts_dataset(args, extra_columns=("prompt_text", "prompt_audio") if args.voice_clone else ())
+
+ probe_out_dir = model_dir # real results dir, captured before the probe rebinds model_dir
+ # ── TTFA probe: latency only, writing nothing but a JSON sidecar ─────────
+ # TTFA is per-request, so generate_tts() is driven with one-row batches. model_dir and
+ # dataset_dir_name are rebound to a temp dir (generate_tts reads them late-bound), so no
+ # results are touched. No streaming API: `first` is None -> whole-utterance fallback.
+ # 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
+ import tempfile
+
+ model_dir = tempfile.mkdtemp(prefix="ttfa_out_")
+ dataset_dir_name = "ttfa"
+ output_dir = os.path.join(model_dir, dataset_dir_name)
+ os.makedirs(os.path.join(output_dir, "prompts"), exist_ok=True)
+
+ def _gen(job):
+ ref = None
+ if args.voice_clone:
+ ref = os.path.join(output_dir, "prompts", f"prompt_{job['id'][0]}.wav")
+ pa = job["prompt_audio"][0]
+ sf.write(ref, np.asarray(pa["array"], dtype=np.float32), pa["sampling_rate"])
+ _, audio_length_s, _ = generate_tts(
+ [job[args.text_column][0]], [job["id"][0]], [ref]
+ )
+ return float(audio_length_s[0]), None, None
+
+ columns = dataset.column_names
+ jobs = [{c: [dataset[i][c]] for c in columns}
+ for i in sample_indices(args.ttfa_probe, len(dataset))]
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=probe_out_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ extra={"device": args.device, "note": "driven at batch size 1"},
+ )
+ return
+
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ def run_batch(batch):
+ """Persist the batch's reference clips (when cloning), then generate_tts; adds prompt paths."""
+ ids = batch["id"]
+ # MOSS + stage-3 SIM read the clips from disk. Store the path relative to model_dir (the
+ # manifest's dir); write to the full path.
+ prompt_rel_paths = [None] * len(ids)
+ prompt_full_paths = [None] * len(ids)
+ if args.voice_clone:
+ for j, sid in enumerate(ids):
+ prel = os.path.join(dataset_dir_name, "prompts", f"prompt_{sid}.wav")
+ pp = os.path.join(model_dir, prel)
+ if not os.path.exists(pp):
+ pa = batch["prompt_audio"][j]
+ sf.write(pp, np.asarray(pa["array"], dtype=np.float32), pa["sampling_rate"])
+ prompt_rel_paths[j] = prel
+ prompt_full_paths[j] = pp
+ return (*generate_tts(list(batch[args.text_column]), ids, prompt_full_paths), prompt_rel_paths)
+
+ starts = pending_batches(dataset, args.batch_size, done_entries, dataset_dir_name)
+ warm_up(run_batch, dataset, starts, args.batch_size, args.warmup_steps)
+
+ # ── Main loop: TTS → write JSONL, one batch at a time ───────────────────
+ for batch_start in tqdm(starts, desc="Generating"):
+ batch = dataset[batch_start : batch_start + args.batch_size]
+ gen_paths, audio_length_s, gen_times, prompt_rel_paths = run_batch(batch)
+
+ # `pred_text` is filled by stage 2 (ASR); `sim` by stage 3 (voice-clone only).
+ for afp, ppath, alen, gtime, ref in zip(
+ gen_paths, prompt_rel_paths, audio_length_s, gen_times, batch[args.text_column]
+ ):
+ write_entry(manifest_file, manifest_entry(afp, alen, gtime, ref, ppath))
+ manifest_file.flush()
+
+ manifest_file.close()
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(args.voice_clone)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ add_common_args(parser, batch_size=32, voice_clone=False)
+
+ parser.add_argument("--model_id", type=str, default="OpenMOSS-Team/MOSS-TTS", help="MOSS-TTS model id.")
+ parser.add_argument("--language", type=str, default=None, help="Language tag passed to build_user_message. Default: None, as in the model card, so the model infers it from the text.")
+ parser.add_argument("--dtype", type=str, default="bfloat16", help="Model dtype, e.g. 'bfloat16'.")
+ parser.add_argument("--max_new_tokens", type=int, default=4096, help="Max audio tokens per generation.")
+ # Audio-sampling params (MossTTSDelay recommended defaults).
+ parser.add_argument("--audio_temperature", type=float, default=1.7, help="Audio-token sampling temperature.")
+ parser.add_argument("--audio_top_p", type=float, default=0.8, help="Audio-token top-p.")
+ parser.add_argument("--audio_top_k", type=int, default=25, help="Audio-token top-k.")
+ parser.add_argument("--audio_repetition_penalty", type=float, default=1.0, help="Audio-token repetition penalty.")
+
+ 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/moss-tts/submit_jobs.sh b/moss-tts/submit_jobs.sh
new file mode 100644
index 0000000..cb5a3e8
--- /dev/null
+++ b/moss-tts/submit_jobs.sh
@@ -0,0 +1,57 @@
+#!/bin/bash
+# HF Jobs TTS eval — MOSS-TTS backend (generate → transcribe → SIM* → score; *voice-clone only).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["OpenMOSS-Team/MOSS-TTS 32" ...]
+# 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-moss}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-moss/blob/main/Dockerfile)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+SUPPORTS_VOICE_CLONE=true # VOICE_CLONE=true clones each sample's reference speaker + scores SIM
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id batch_size". ──
+generate_stage() {
+ local _ BATCH_SIZE
+ read -r _ BATCH_SIZE <<< "${MODEL_CFG}"
+ 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/moss-tts && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --device=cuda:0 \
+ --batch_size=${BATCH_SIZE} \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} \
+ ${VOICE_CLONE_FLAG} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment to pick) ────────
+DATASET_CONFIGS=(
+ "tts en en"
+ "tts zh zh"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot zh zh ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ja ja ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ko ko ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot de de ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot fr fr ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot it it ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ru ru ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id batch_size" (CLI args override) ────────────────────────
+MODEL_CONFIGS=(
+ "OpenMOSS-Team/MOSS-TTS 32"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/neutts-nano/run_eval.py b/neutts-nano/run_eval.py
new file mode 100644
index 0000000..f5e5249
--- /dev/null
+++ b/neutts-nano/run_eval.py
@@ -0,0 +1,383 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (NeuTTS Nano backend, stage 1).
+
+NeuTTS Nano (neuphonic/neutts-nano) is Neuphonic's compact zero-shot voice-cloning TTS: a small
+Qwen-style LM backbone emitting NeuCodec speech tokens, decoded to 24 kHz audio. Text is phonemized
+with espeak-ng and outputs are watermarked by default with resemble-perth. A `*-gguf` model id
+loads the backbone through llama_cpp instead (the only path that supports streaming).
+
+NeuTTS always synthesizes from a reference, so every sample uses the dataset's
+`prompt_audio`/`prompt_text`. `--voice_clone` adds the `_voice_clone` suffix and the SIM fields;
+the default (`--no-voice_clone`) only skips SIM.
+
+No native batching: `NeuTTS.infer()` takes one text, so `generate_tts(batch)` loops per sample and
+`--batch_size` only sets manifest-writing / resume granularity; the per-sample time is batch time /
+batch size. Reference encoding is inside the timed region (part of zero-shot inference); writing
+the prompt wavs to disk is not.
+"""
+
+import argparse
+import os
+import sys
+import time
+import warnings
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+# CPU-built llama_cpp, installed alongside the CUDA one (see the Dockerfile).
+LLAMA_CPP_CPU_PATH = os.environ.get("LLAMA_CPP_CPU_PATH", "/opt/llama-cpp-cpu")
+
+
+# Keep dependency chatter (transformers, phonemizer, perth) out of the way so the outer
+# "Generating" tqdm is the only progress output; warnings/errors still come through stderr.
+warnings.filterwarnings("ignore")
+try:
+ from transformers.utils import logging as _hf_logging
+
+ _hf_logging.set_verbosity_error()
+except Exception:
+ pass
+
+from neutts import NeuTTS # noqa: E402
+
+from run_eval_utils import ( # noqa: E402
+ add_common_args, count_parameters, 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,
+)
+
+torch.set_float32_matmul_precision("high")
+
+
+def main(args):
+ # Set seed for reproducibility (NeuTTS samples internally: do_sample=True, top_k=50).
+ seed = args.seed
+ set_seed(seed)
+ torch.backends.cudnn.deterministic = True
+
+ # llama_cpp ships as two mutually incompatible builds (see the Dockerfile): the CUDA one is
+ # the default, and its libllama.so links libcuda.so.1 — absent on a CPU-only machine, where
+ # importing it raises "Failed to load shared library". Put the CPU build first on sys.path
+ # for a CPU run, BEFORE NeuTTS() triggers the import.
+ if str(args.device).lower() == "cpu" and os.path.isdir(LLAMA_CPP_CPU_PATH):
+ sys.path.insert(0, LLAMA_CPP_CPU_PATH)
+ print(f"CPU run: using the CPU-built llama_cpp from {LLAMA_CPP_CPU_PATH}")
+
+ # Torch (non-GGUF) path: the backbone is loaded with AutoModelForCausalLM and moved to
+ # `backbone_device`; the NeuCodec codec goes to `codec_device`. `language` resolves to
+ # "en-us" automatically for neuphonic/neutts-nano (BACKBONE_LANGUAGE_MAP).
+ model = NeuTTS(
+ backbone_repo=args.model_id,
+ backbone_device=args.device,
+ codec_repo=args.codec_repo,
+ codec_device=args.device,
+ language=args.language,
+ )
+ sampling_rate = int(getattr(model, "sample_rate", 24_000)) # NeuCodec: 24 kHz
+
+ # A *-gguf model_id makes the package load the backbone through llama_cpp instead of
+ # transformers, which is what enables infer_stream(). That backbone is not an nn.Module.
+ is_gguf = bool(getattr(model, "_is_quantized_model", False))
+
+ # The `neutts` package loads the backbone in float32 (no dtype knob); optionally cast
+ # the backbone LM (the codec stays in float32). A gguf backbone is already quantized.
+ if args.dtype != "float32":
+ if is_gguf:
+ print(f"Ignoring --dtype={args.dtype}: the gguf backbone carries its own quantization.")
+ else:
+ model.backbone.to(getattr(torch, args.dtype))
+
+ if args.no_watermark:
+ # infer() skips resemble-perth watermarking when the watermarker is None.
+ model.watermarker = None
+
+ print(
+ f"Loaded NeuTTS model {args.model_id} (codec={args.codec_repo}, sr={sampling_rate}, "
+ f"dtype={args.dtype}, watermark={not args.no_watermark})"
+ )
+
+ # Report parameter count. NeuTTS is a wrapper around nn.Module components (backbone LM
+ # + NeuCodec), so sum unique params over any nn.Module attributes (dedup by id).
+ try:
+ n_params = count_parameters(model)
+ if n_params:
+ print(f"TTS model size: {n_params / 1e9:.2f}B parameters (backbone + codec)")
+ except Exception as e:
+ print(f"Could not determine model size: {e}")
+
+ # Layout: results/<model_safe>/ MODEL_<safe>_DATASET_<dsid>.jsonl + <dsid>/output_<id>.wav
+ # where <dsid> = <dataset_safe>_<dataset>_<split><mode_suffix>. Manifest paths are relative to
+ # model_dir so later stages resolve them wherever the folder is copied (local or HF bucket).
+ # Keep the two modes' audio separate so voice-clone and non-cloning runs don't overwrite.
+ mode_suffix = "_voice_clone" if args.voice_clone else ""
+ paths = output_paths(args, mode_suffix)
+ model_dir, dataset_dir_name, output_dir = paths.model_dir, paths.dataset_dir_name, paths.output_dir
+
+ # `encode_reference` takes a file path; prompts are written under `results/` so stage 3 can
+ # read them. Created regardless of --voice_clone since NeuTTS always needs a reference.
+ prompt_dir = os.path.join(output_dir, "prompts")
+ os.makedirs(prompt_dir, exist_ok=True)
+
+ n_watermark_skipped = [0] # near-empty takes that skipped watermarking
+ n_failed = [0] # samples that produced nothing after every retry
+
+ # ── Degenerate generations ───────────────────────────────────────────────
+ # The gguf backbone intermittently yields near-empty audio (perth's watermarker then fails
+ # with "Padding size should be less ...") or no speech tokens at all (ValueError "No valid
+ # speech tokens"). Retry (the library draws a fresh seed per call) inside the timed region,
+ # and count failures so they stay visible in the numbers.
+ TTS_MAX_ATTEMPTS = 3
+
+ def _infer_resilient(text, ref_codes, prompt_text):
+ """model.infer with retries; returns short silence if every attempt fails."""
+ last = None
+ for attempt in range(TTS_MAX_ATTEMPTS):
+ try:
+ return model.infer(text, ref_codes, prompt_text)
+ except ValueError as e:
+ if "No valid speech tokens" not in str(e):
+ raise
+ last = e
+ except RuntimeError as e:
+ if "Padding size should be less" not in str(e):
+ raise
+ # Near-empty audio: keep the take but skip the watermark, which cannot run on it.
+ n_watermark_skipped[0] += 1
+ saved, model.watermarker = model.watermarker, None
+ try:
+ return model.infer(text, ref_codes, prompt_text)
+ except (ValueError, RuntimeError) as e2:
+ last = e2
+ finally:
+ model.watermarker = saved
+ if attempt + 1 < TTS_MAX_ATTEMPTS:
+ print(f" retry {attempt + 1}/{TTS_MAX_ATTEMPTS - 1} after {type(last).__name__}: "
+ f"'{text[:40]}...'")
+ # Every attempt failed: write a short silence so the sample is scored (~100% WER).
+ n_failed[0] += 1
+ print(f" FAILED after {TTS_MAX_ATTEMPTS} attempts ({last}); writing silence: '{text[:40]}...'")
+ return np.zeros(int(0.5 * sampling_rate), dtype=np.float32)
+
+ def generate_tts(batch):
+ """Synthesize speech for a minibatch of target texts; time the generation for RTFx.
+
+ Loops one utterance at a time (no batched API); the whole loop is timed and divided by
+ the batch size. Returned paths are relative to model_dir.
+ """
+ texts_to_generate = list(batch[args.text_column])
+ minibatch_size = len(texts_to_generate)
+
+ # `encode_reference` takes a file path, so write the prompt clips to wavs first —
+ # outside the timed region (disk I/O is not part of inference).
+ prompt_rel_paths, prompt_full_paths = [], []
+ prompt_texts = list(batch["prompt_text"])
+ for sample_id, prompt_audio in zip(batch["id"], batch["prompt_audio"]):
+ # Store the path relative to model_dir (the manifest's dir); write to the full path.
+ prel = os.path.join(dataset_dir_name, "prompts", f"prompt_{sample_id}.wav")
+ ppath = os.path.join(model_dir, prel)
+ if not os.path.exists(ppath):
+ sf.write(
+ ppath,
+ np.asarray(prompt_audio["array"], dtype=np.float32),
+ prompt_audio["sampling_rate"],
+ )
+ prompt_rel_paths.append(prel)
+ prompt_full_paths.append(ppath)
+
+ # START TIMING (TTS generation for the whole minibatch)
+ # CUDA events time the torch stream; the gguf backbone runs in llama.cpp, so use a wall
+ # clock there instead.
+ if is_gguf:
+ t_start = time.perf_counter()
+ else:
+ torch.cuda.synchronize(device=args.device)
+ start_event = torch.cuda.Event(enable_timing=True)
+ end_event = torch.cuda.Event(enable_timing=True)
+ start_event.record()
+
+ wavs = []
+ for text, prompt_text, prompt_path in zip(texts_to_generate, prompt_texts, prompt_full_paths):
+ # Re-seed per sample so generation is reproducible regardless of batch layout.
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+ # Reference encoding is timed: it is part of zero-shot cloning inference.
+ ref_codes = model.encode_reference(prompt_path)
+ wav = _infer_resilient(text, ref_codes, prompt_text)
+ wavs.append(np.asarray(wav, dtype=np.float32).reshape(-1))
+
+ # END TIMING
+ if is_gguf:
+ runtime = time.perf_counter() - t_start
+ else:
+ end_event.record()
+ torch.cuda.synchronize(device=args.device)
+ runtime = start_event.elapsed_time(end_event) / 1000.0
+ # per-sample generation time (RTFx is aggregated over the whole set at scoring time)
+ batch["generation_time_s"] = minibatch_size * [runtime / minibatch_size]
+
+ gen_paths, audio_length_s = [], []
+ for audio, sample_id in zip(wavs, batch["id"]):
+ # 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)
+ sf.write(os.path.join(model_dir, rel_path), audio, sampling_rate)
+ gen_paths.append(rel_path)
+ audio_length_s.append(len(audio) / sampling_rate)
+
+ batch["gen_audio_filepath"] = gen_paths
+ batch["prompt_audio_filepath"] = prompt_rel_paths
+ batch["audio_length_s"] = audio_length_s
+ batch["references"] = list(batch[args.text_column]) # raw; normalized at scoring time
+ return batch
+
+ # Keep the reference clip/transcript regardless of --voice_clone (NeuTTS always needs one).
+ dataset = load_tts_dataset(args, ("prompt_text", "prompt_audio"))
+
+ probe_out_dir = model_dir # real results dir, captured before the probe rebinds model_dir
+ # ── TTFA probe: latency only, writing nothing but a JSON sidecar ─────────
+ # TTFA is per-request, so the probe drives one-row batches and returns before the batched
+ # path. `model_dir`/`dataset_dir_name` are rebound to a temp dir first; generate_tts closes
+ # over them (late binding), so its writes land there instead of the results tree.
+ # 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 only injected by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+ import tempfile
+
+ model_dir = tempfile.mkdtemp(prefix="ttfa_out_")
+ dataset_dir_name = "ttfa"
+ output_dir = os.path.join(model_dir, dataset_dir_name)
+ os.makedirs(os.path.join(output_dir, "prompts"), exist_ok=True)
+
+ chunk_counts = []
+ enc_s = [] # NeuCodec reference encode, per sample (torch)
+ first_chunk_s = [] # llama.cpp prefill + first chunk, per sample
+
+ def _gen(job, early_stop):
+ """One utterance, streaming when the backbone supports it.
+
+ NeuTTS.infer_stream() only exists for the gguf backbone; the torch path falls back
+ to the whole-utterance clock.
+ """
+ ref_path = os.path.join(output_dir, "prompts", f"prompt_{job['id'][0]}.wav")
+ pa = job["prompt_audio"][0]
+ sf.write(ref_path, np.asarray(pa["array"], dtype=np.float32), pa["sampling_rate"])
+
+ if not is_gguf:
+ result = generate_tts(job)
+ chunk_counts.append(1)
+ return float(result["audio_length_s"][0]), None, None
+
+ # Reference encoding stays inside the measurement, matching generate_tts. It is also
+ # timed separately (torch/NeuCodec vs llama.cpp) to attribute a slow first chunk.
+ first, chunks = None, []
+ _t_enc = time.perf_counter()
+ ref_codes = model.encode_reference(ref_path)
+ enc_s.append(time.perf_counter() - _t_enc)
+ _t_llm = time.perf_counter()
+ for chunk in model.infer_stream(
+ job[args.text_column][0], ref_codes, job["prompt_text"][0]
+ ):
+ if first is None:
+ first = time.perf_counter()
+ first_chunk_s.append(first - _t_llm)
+ chunks.append(np.asarray(chunk, dtype=np.float32).reshape(-1))
+ if early_stop:
+ break
+ chunk_counts.append(len(chunks))
+ if not chunks:
+ return np.zeros(1, dtype=np.float32), sampling_rate, None
+ return np.concatenate(chunks), sampling_rate, first
+
+ columns = dataset.column_names
+ jobs = [{c: [dataset[i][c]] for c in columns}
+ for i in sample_indices(args.ttfa_probe, len(dataset))]
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=probe_out_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ # Only a gguf backbone streams (~0.5 s chunks); torch rows are whole-utterance.
+ extra={"device": args.device, "note": "driven at batch size 1",
+ "quantized_backbone": is_gguf,
+ "chunks_per_utterance": chunk_counts,
+ "ref_encode_s": enc_s,
+ "prefill_to_first_chunk_s": first_chunk_s},
+ )
+ return
+
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ starts = pending_batches(dataset, args.batch_size, done_entries, dataset_dir_name)
+ warm_up(generate_tts, dataset, starts, 1, args.warmup_steps) # serial model: warm up on single samples
+ n_watermark_skipped[0] = n_failed[0] = 0 # count timed samples only
+
+ # ── Main loop: TTS → write JSONL, one batch at a time ───────────────────
+ for batch_start in tqdm(starts, desc="Generating"):
+ batch = generate_tts(dataset[batch_start : batch_start + args.batch_size])
+
+ # Append each sample to the JSONL immediately.
+ for afp, ppath, alen, gtime, ref in zip(
+ batch["gen_audio_filepath"], batch["prompt_audio_filepath"], batch["audio_length_s"],
+ batch["generation_time_s"], batch["references"],
+ ):
+ write_entry(manifest_file, manifest_entry(afp, alen, gtime, ref, ppath if args.voice_clone else None))
+ manifest_file.flush()
+
+ manifest_file.close()
+ if n_watermark_skipped[0] or n_failed[0]:
+ print(f"WARNING: {n_watermark_skipped[0]} near-empty generation(s) skipped watermarking; "
+ f"{n_failed[0]} sample(s) produced NO speech tokens after {TTS_MAX_ATTEMPTS} attempts "
+ "and were written as silence (they will score ~100% WER).")
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(args.voice_clone)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument(
+ "--model_id",
+ type=str,
+ default="neuphonic/neutts-nano",
+ help="NeuTTS backbone repo id, loadable with the `neutts` package (a *-gguf repo uses llama_cpp).",
+ )
+ parser.add_argument(
+ "--codec_repo",
+ type=str,
+ default="neuphonic/neucodec",
+ help="Audio codec repo id ('neuphonic/neucodec' or 'neuphonic/distill-neucodec').",
+ )
+ parser.add_argument(
+ "--language",
+ type=str,
+ default=None,
+ help="eSpeak language code for the phonemizer; None auto-resolves ('en-us' for neutts-nano).",
+ )
+ # --batch_size is the manifest-writing chunk size (NeuTTS has no batched API; generation is per sample).
+ add_common_args(parser, batch_size=32, voice_clone=False)
+ parser.add_argument(
+ "--dtype",
+ type=str,
+ default="float32",
+ help="Backbone dtype. The `neutts` package loads float32 (its documented path); pass "
+ "'bfloat16' to cast the backbone LM after loading (codec stays float32).",
+ )
+ parser.add_argument(
+ "--no_watermark",
+ action="store_true",
+ help="Disable the resemble-perth output watermark (applied by default inside NeuTTS.infer()).",
+ )
+
+ 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/neutts-nano/submit_jobs.sh b/neutts-nano/submit_jobs.sh
new file mode 100644
index 0000000..ea0027b
--- /dev/null
+++ b/neutts-nano/submit_jobs.sh
@@ -0,0 +1,53 @@
+#!/bin/bash
+# HF Jobs TTS eval — NeuTTS Nano backend (generate → transcribe → SIM* → score; *voice-clone only, VOICE_CLONE=true).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["neuphonic/neutts-nano 32" ...]
+# 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-neutts}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-neutts/blob/main/Dockerfile)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# ── Voice cloning: VOICE_CLONE=true appends `_voice_clone` + enables SIM.
+# Either way run_eval.py synthesizes from the per-sample reference (NeuTTS always needs one). ──
+SUPPORTS_VOICE_CLONE=true
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id batch_size" (batch_size optional). ──
+generate_stage() {
+ local _ BATCH_SIZE BATCH_SIZE_ARG=""
+ read -r _ BATCH_SIZE <<< "${MODEL_CFG}"
+ [[ -n "${BATCH_SIZE}" ]] && BATCH_SIZE_ARG="--batch_size=${BATCH_SIZE}"
+ 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/neutts-nano && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --device=cuda:0 \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} \
+ ${VOICE_CLONE_FLAG} \
+ ${BATCH_SIZE_ARG} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment to pick) ──
+DATASET_CONFIGS=(
+ "tts en en"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id batch_size" (batch_size optional; CLI args override) ────
+MODEL_CONFIGS=(
+ "neuphonic/neutts-nano 32"
+ "neuphonic/neutts-nano-q8-gguf 32"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/normalizer/__init__.py b/normalizer/__init__.py
new file mode 100644
index 0000000..7ebcff3
--- /dev/null
+++ b/normalizer/__init__.py
@@ -0,0 +1,2 @@
+from .normalizer import EnglishTextNormalizer, BasicMultilingualTextNormalizer
+__all__ = ["EnglishTextNormalizer", "BasicMultilingualTextNormalizer"]
diff --git a/normalizer/data_utils.py b/normalizer/data_utils.py
new file mode 100644
index 0000000..0d1a326
--- /dev/null
+++ b/normalizer/data_utils.py
@@ -0,0 +1,34 @@
+import re
+
+import num2words
+from normalizer import EnglishTextNormalizer, BasicMultilingualTextNormalizer
+
+
+class MultilingualNormalizer(BasicMultilingualTextNormalizer):
+ """BasicMultilingualTextNormalizer with optional number normalization.
+
+ Pass lang= to also convert digits to words via num2words.
+ """
+
+ def _normalize_numbers(self, text, lang):
+ # Join space-separated thousand groups (e.g. "10 000" -> "10000")
+ text = re.sub(r"(\d)\s+(\d{3})\b", r"\1\2", text)
+ # Convert remaining digit sequences to words
+ def _replace(m):
+ try:
+ return num2words.num2words(int(m.group()), lang=lang)
+ except Exception:
+ return m.group()
+ return re.sub(r"\d+", _replace, text)
+
+ def __call__(self, s, lang=None):
+ s = super().__call__(s)
+ if lang is not None:
+ s = self._normalize_numbers(s, lang)
+ return s
+
+
+normalizer = EnglishTextNormalizer()
+
+ml_normalizer = MultilingualNormalizer(remove_diacritics=False)
+
diff --git a/normalizer/english_abbreviations.py b/normalizer/english_abbreviations.py
new file mode 100644
index 0000000..970dc64
--- /dev/null
+++ b/normalizer/english_abbreviations.py
@@ -0,0 +1,1932 @@
+english_spelling_normalizer = {
+ "ok": "okay",
+ "kay": "okay",
+ "etcetera": "etc",
+ "accessorise": "accessorize",
+ "accessorised": "accessorized",
+ "accessorises": "accessorizes",
+ "accessorising": "accessorizing",
+ "acclimatisation": "acclimatization",
+ "acclimatise": "acclimatize",
+ "acclimatised": "acclimatized",
+ "acclimatises": "acclimatizes",
+ "acclimatising": "acclimatizing",
+ "accoutrements": "accouterments",
+ "aeon": "eon",
+ "aeons": "eons",
+ "aerogramme": "aerogram",
+ "aerogrammes": "aerograms",
+ "aeroplane": "airplane",
+ "aeroplanes": "airplanes",
+ "aesthete": "esthete",
+ "aesthetes": "esthetes",
+ "aesthetic": "esthetic",
+ "aesthetically": "esthetically",
+ "aesthetics": "esthetics",
+ "aetiology": "etiology",
+ "ageing": "aging",
+ "aggrandisement": "aggrandizement",
+ "agonise": "agonize",
+ "agonised": "agonized",
+ "agonises": "agonizes",
+ "agonising": "agonizing",
+ "agonisingly": "agonizingly",
+ "almanack": "almanac",
+ "almanacks": "almanacs",
+ "aluminium": "aluminum",
+ "amortisable": "amortizable",
+ "amortisation": "amortization",
+ "amortisations": "amortizations",
+ "amortise": "amortize",
+ "amortised": "amortized",
+ "amortises": "amortizes",
+ "amortising": "amortizing",
+ "amphitheatre": "amphitheater",
+ "amphitheatres": "amphitheaters",
+ "anaemia": "anemia",
+ "anaemic": "anemic",
+ "anaesthesia": "anesthesia",
+ "anaesthetic": "anesthetic",
+ "anaesthetics": "anesthetics",
+ "anaesthetise": "anesthetize",
+ "anaesthetised": "anesthetized",
+ "anaesthetises": "anesthetizes",
+ "anaesthetising": "anesthetizing",
+ "anaesthetist": "anesthetist",
+ "anaesthetists": "anesthetists",
+ "anaesthetize": "anesthetize",
+ "anaesthetized": "anesthetized",
+ "anaesthetizes": "anesthetizes",
+ "anaesthetizing": "anesthetizing",
+ "analogue": "analog",
+ "analogues": "analogs",
+ "analyse": "analyze",
+ "analysed": "analyzed",
+ "analyses": "analyzes",
+ "analysing": "analyzing",
+ "anglicise": "anglicize",
+ "anglicised": "anglicized",
+ "anglicises": "anglicizes",
+ "anglicising": "anglicizing",
+ "annualised": "annualized",
+ "antagonise": "antagonize",
+ "antagonised": "antagonized",
+ "antagonises": "antagonizes",
+ "antagonising": "antagonizing",
+ "apologise": "apologize",
+ "apologised": "apologized",
+ "apologises": "apologizes",
+ "apologising": "apologizing",
+ "appal": "appall",
+ "appals": "appalls",
+ "appetiser": "appetizer",
+ "appetisers": "appetizers",
+ "appetising": "appetizing",
+ "appetisingly": "appetizingly",
+ "arbour": "arbor",
+ "arbours": "arbors",
+ "archaeologically": "archeologically",
+ "archaeologist": "archeologist",
+ "archaeologists": "archeologists",
+ "archaeology": "archeology",
+ "archaeological": "archeological",
+ "ardour": "ardor",
+ "armour": "armor",
+ "armoured": "armored",
+ "armourer": "armorer",
+ "armourers": "armorers",
+ "armouries": "armories",
+ "armoury": "armory",
+ "artefact": "artifact",
+ "artefacts": "artifacts",
+ "authorise": "authorize",
+ "authorised": "authorized",
+ "authorises": "authorizes",
+ "authorising": "authorizing",
+ "axe": "ax",
+ "backpedalled": "backpedaled",
+ "backpedalling": "backpedaling",
+ "bannister": "banister",
+ "bannisters": "banisters",
+ "baptise": "baptize",
+ "baptised": "baptized",
+ "baptises": "baptizes",
+ "baptising": "baptizing",
+ "bastardise": "bastardize",
+ "bastardised": "bastardized",
+ "bastardises": "bastardizes",
+ "bastardising": "bastardizing",
+ "battleax": "battleaxe",
+ "baulk": "balk",
+ "baulked": "balked",
+ "baulking": "balking",
+ "baulks": "balks",
+ "bedevilled": "bedeviled",
+ "bedevilling": "bedeviling",
+ "behaviour": "behavior",
+ "behavioural": "behavioral",
+ "behaviourism": "behaviorism",
+ "behaviourist": "behaviorist",
+ "behaviourists": "behaviorists",
+ "behaviours": "behaviors",
+ "behove": "behoove",
+ "behoved": "behooved",
+ "behoves": "behooves",
+ "bejewelled": "bejeweled",
+ "belabour": "belabor",
+ "belaboured": "belabored",
+ "belabouring": "belaboring",
+ "belabours": "belabors",
+ "bevelled": "beveled",
+ "bevvies": "bevies",
+ "bevvy": "bevy",
+ "biassed": "biased",
+ "biassing": "biasing",
+ "bingeing": "binging",
+ "bougainvillaea": "bougainvillea",
+ "bougainvillaeas": "bougainvilleas",
+ "bowdlerise": "bowdlerize",
+ "bowdlerised": "bowdlerized",
+ "bowdlerises": "bowdlerizes",
+ "bowdlerising": "bowdlerizing",
+ "breathalyse": "breathalyze",
+ "breathalysed": "breathalyzed",
+ "breathalyser": "breathalyzer",
+ "breathalysers": "breathalyzers",
+ "breathalyses": "breathalyzes",
+ "breathalysing": "breathalyzing",
+ "brutalise": "brutalize",
+ "brutalised": "brutalized",
+ "brutalises": "brutalizes",
+ "brutalising": "brutalizing",
+ "busses": "buses",
+ "bussing": "busing",
+ "caesarean": "cesarean",
+ "caesareans": "cesareans",
+ "calibre": "caliber",
+ "calibres": "calibers",
+ "calliper": "caliper",
+ "callipers": "calipers",
+ "callisthenics": "calisthenics",
+ "canalise": "canalize",
+ "canalised": "canalized",
+ "canalises": "canalizes",
+ "canalising": "canalizing",
+ "cancellation": "cancelation",
+ "cancellations": "cancelations",
+ "cancelled": "canceled",
+ "cancelling": "canceling",
+ "candour": "candor",
+ "cannibalise": "cannibalize",
+ "cannibalised": "cannibalized",
+ "cannibalises": "cannibalizes",
+ "cannibalising": "cannibalizing",
+ "canonise": "canonize",
+ "canonised": "canonized",
+ "canonises": "canonizes",
+ "canonising": "canonizing",
+ "capitalise": "capitalize",
+ "capitalised": "capitalized",
+ "capitalises": "capitalizes",
+ "capitalising": "capitalizing",
+ "caramelise": "caramelize",
+ "caramelised": "caramelized",
+ "caramelises": "caramelizes",
+ "caramelising": "caramelizing",
+ "carbonise": "carbonize",
+ "carbonised": "carbonized",
+ "carbonises": "carbonizes",
+ "carbonising": "carbonizing",
+ "carolled": "caroled",
+ "carolling": "caroling",
+ "catalogue": "catalog",
+ "catalogued": "cataloged",
+ "catalogues": "catalogs",
+ "cataloguing": "cataloging",
+ "catalyse": "catalyze",
+ "catalysed": "catalyzed",
+ "catalyses": "catalyzes",
+ "catalysing": "catalyzing",
+ "categorise": "categorize",
+ "categorised": "categorized",
+ "categorises": "categorizes",
+ "categorising": "categorizing",
+ "cauterise": "cauterize",
+ "cauterised": "cauterized",
+ "cauterises": "cauterizes",
+ "cauterising": "cauterizing",
+ "cavilled": "caviled",
+ "cavilling": "caviling",
+ "centigramme": "centigram",
+ "centigrammes": "centigrams",
+ "centilitre": "centiliter",
+ "centilitres": "centiliters",
+ "centimetre": "centimeter",
+ "centimetres": "centimeters",
+ "centralise": "centralize",
+ "centralised": "centralized",
+ "centralises": "centralizes",
+ "centralising": "centralizing",
+ "centre": "center",
+ "centred": "centered",
+ "centrefold": "centerfold",
+ "centrefolds": "centerfolds",
+ "centrepiece": "centerpiece",
+ "centrepieces": "centerpieces",
+ "centres": "centers",
+ "channelled": "channeled",
+ "channelling": "channeling",
+ "characterise": "characterize",
+ "characterised": "characterized",
+ "characterises": "characterizes",
+ "characterising": "characterizing",
+ "cheque": "check",
+ "chequebook": "checkbook",
+ "chequebooks": "checkbooks",
+ "chequered": "checkered",
+ "cheques": "checks",
+ "chilli": "chili",
+ "chimaera": "chimera",
+ "chimaeras": "chimeras",
+ "chiselled": "chiseled",
+ "chiselling": "chiseling",
+ "circularise": "circularize",
+ "circularised": "circularized",
+ "circularises": "circularizes",
+ "circularising": "circularizing",
+ "civilise": "civilize",
+ "civilised": "civilized",
+ "civilises": "civilizes",
+ "civilising": "civilizing",
+ "clamour": "clamor",
+ "clamoured": "clamored",
+ "clamouring": "clamoring",
+ "clamours": "clamors",
+ "clangour": "clangor",
+ "clarinettist": "clarinetist",
+ "clarinettists": "clarinetists",
+ "collectivise": "collectivize",
+ "collectivised": "collectivized",
+ "collectivises": "collectivizes",
+ "collectivising": "collectivizing",
+ "colonisation": "colonization",
+ "colonise": "colonize",
+ "colonised": "colonized",
+ "coloniser": "colonizer",
+ "colonisers": "colonizers",
+ "colonises": "colonizes",
+ "colonising": "colonizing",
+ "colour": "color",
+ "colourant": "colorant",
+ "colourants": "colorants",
+ "coloured": "colored",
+ "coloureds": "coloreds",
+ "colourful": "colorful",
+ "colourfully": "colorfully",
+ "colouring": "coloring",
+ "colourize": "colorize",
+ "colourized": "colorized",
+ "colourizes": "colorizes",
+ "colourizing": "colorizing",
+ "colourless": "colorless",
+ "colours": "colors",
+ "commercialise": "commercialize",
+ "commercialised": "commercialized",
+ "commercialises": "commercializes",
+ "commercialising": "commercializing",
+ "compartmentalise": "compartmentalize",
+ "compartmentalised": "compartmentalized",
+ "compartmentalises": "compartmentalizes",
+ "compartmentalising": "compartmentalizing",
+ "computerise": "computerize",
+ "computerised": "computerized",
+ "computerises": "computerizes",
+ "computerising": "computerizing",
+ "conceptualise": "conceptualize",
+ "conceptualised": "conceptualized",
+ "conceptualises": "conceptualizes",
+ "conceptualising": "conceptualizing",
+ "connexion": "connection",
+ "connexions": "connections",
+ "contextualise": "contextualize",
+ "contextualised": "contextualized",
+ "contextualises": "contextualizes",
+ "contextualising": "contextualizing",
+ "cosier": "cozier",
+ "cosies": "cozies",
+ "cosiest": "coziest",
+ "cosily": "cozily",
+ "cosiness": "coziness",
+ "cosy": "cozy",
+ "councillor": "councilor",
+ "councillors": "councilors",
+ "counselled": "counseled",
+ "counselling": "counseling",
+ "counsellor": "counselor",
+ "counsellors": "counselors",
+ "crenelated": "crenellated",
+ "criminalise": "criminalize",
+ "criminalised": "criminalized",
+ "criminalises": "criminalizes",
+ "criminalising": "criminalizing",
+ "criticise": "criticize",
+ "criticised": "criticized",
+ "criticises": "criticizes",
+ "criticising": "criticizing",
+ "crueller": "crueler",
+ "cruellest": "cruelest",
+ "crystallisation": "crystallization",
+ "crystallise": "crystallize",
+ "crystallised": "crystallized",
+ "crystallises": "crystallizes",
+ "crystallising": "crystallizing",
+ "cudgelled": "cudgeled",
+ "cudgelling": "cudgeling",
+ "customise": "customize",
+ "customised": "customized",
+ "customises": "customizes",
+ "customising": "customizing",
+ "cypher": "cipher",
+ "cyphers": "ciphers",
+ "decentralisation": "decentralization",
+ "decentralise": "decentralize",
+ "decentralised": "decentralized",
+ "decentralises": "decentralizes",
+ "decentralising": "decentralizing",
+ "decriminalisation": "decriminalization",
+ "decriminalise": "decriminalize",
+ "decriminalised": "decriminalized",
+ "decriminalises": "decriminalizes",
+ "decriminalising": "decriminalizing",
+ "defence": "defense",
+ "defenceless": "defenseless",
+ "defences": "defenses",
+ "dehumanisation": "dehumanization",
+ "dehumanise": "dehumanize",
+ "dehumanised": "dehumanized",
+ "dehumanises": "dehumanizes",
+ "dehumanising": "dehumanizing",
+ "demeanour": "demeanor",
+ "demilitarisation": "demilitarization",
+ "demilitarise": "demilitarize",
+ "demilitarised": "demilitarized",
+ "demilitarises": "demilitarizes",
+ "demilitarising": "demilitarizing",
+ "demobilisation": "demobilization",
+ "demobilise": "demobilize",
+ "demobilised": "demobilized",
+ "demobilises": "demobilizes",
+ "demobilising": "demobilizing",
+ "democratisation": "democratization",
+ "democratise": "democratize",
+ "democratised": "democratized",
+ "democratises": "democratizes",
+ "democratising": "democratizing",
+ "demonise": "demonize",
+ "demonised": "demonized",
+ "demonises": "demonizes",
+ "demonising": "demonizing",
+ "demoralisation": "demoralization",
+ "demoralise": "demoralize",
+ "demoralised": "demoralized",
+ "demoralises": "demoralizes",
+ "demoralising": "demoralizing",
+ "denationalisation": "denationalization",
+ "denationalise": "denationalize",
+ "denationalised": "denationalized",
+ "denationalises": "denationalizes",
+ "denationalising": "denationalizing",
+ "deodorise": "deodorize",
+ "deodorised": "deodorized",
+ "deodorises": "deodorizes",
+ "deodorising": "deodorizing",
+ "depersonalise": "depersonalize",
+ "depersonalised": "depersonalized",
+ "depersonalises": "depersonalizes",
+ "depersonalising": "depersonalizing",
+ "deputise": "deputize",
+ "deputised": "deputized",
+ "deputises": "deputizes",
+ "deputising": "deputizing",
+ "desensitisation": "desensitization",
+ "desensitise": "desensitize",
+ "desensitised": "desensitized",
+ "desensitises": "desensitizes",
+ "desensitising": "desensitizing",
+ "destabilisation": "destabilization",
+ "destabilise": "destabilize",
+ "destabilised": "destabilized",
+ "destabilises": "destabilizes",
+ "destabilising": "destabilizing",
+ "dialled": "dialed",
+ "dialling": "dialing",
+ "dialogue": "dialog",
+ "dialogues": "dialogs",
+ "diarrhoea": "diarrhea",
+ "digitise": "digitize",
+ "digitised": "digitized",
+ "digitises": "digitizes",
+ "digitising": "digitizing",
+ "disc": "disk",
+ "discolour": "discolor",
+ "discoloured": "discolored",
+ "discolouring": "discoloring",
+ "discolours": "discolors",
+ "discs": "disks",
+ "disembowelled": "disemboweled",
+ "disembowelling": "disemboweling",
+ "disfavour": "disfavor",
+ "dishevelled": "disheveled",
+ "dishonour": "dishonor",
+ "dishonourable": "dishonorable",
+ "dishonourably": "dishonorably",
+ "dishonoured": "dishonored",
+ "dishonouring": "dishonoring",
+ "dishonours": "dishonors",
+ "disorganisation": "disorganization",
+ "disorganised": "disorganized",
+ "distil": "distill",
+ "distils": "distills",
+ "dramatisation": "dramatization",
+ "dramatisations": "dramatizations",
+ "dramatise": "dramatize",
+ "dramatised": "dramatized",
+ "dramatises": "dramatizes",
+ "dramatising": "dramatizing",
+ "draught": "draft",
+ "draughtboard": "draftboard",
+ "draughtboards": "draftboards",
+ "draughtier": "draftier",
+ "draughtiest": "draftiest",
+ "draughts": "drafts",
+ "draughtsman": "draftsman",
+ "draughtsmanship": "draftsmanship",
+ "draughtsmen": "draftsmen",
+ "draughtswoman": "draftswoman",
+ "draughtswomen": "draftswomen",
+ "draughty": "drafty",
+ "drivelled": "driveled",
+ "drivelling": "driveling",
+ "duelled": "dueled",
+ "duelling": "dueling",
+ "economise": "economize",
+ "economised": "economized",
+ "economises": "economizes",
+ "economising": "economizing",
+ "editorialise": "editorialize",
+ "editorialised": "editorialized",
+ "editorialises": "editorializes",
+ "editorialising": "editorializing",
+ "edoema": "edema",
+ "empathise": "empathize",
+ "empathised": "empathized",
+ "empathises": "empathizes",
+ "empathising": "empathizing",
+ "emphasise": "emphasize",
+ "emphasised": "emphasized",
+ "emphasises": "emphasizes",
+ "emphasising": "emphasizing",
+ "enamelled": "enameled",
+ "enamelling": "enameling",
+ "enamoured": "enamored",
+ "encyclopaedia": "encyclopedia",
+ "encyclopaedias": "encyclopedias",
+ "encyclopaedic": "encyclopedic",
+ "endeavour": "endeavor",
+ "endeavoured": "endeavored",
+ "endeavouring": "endeavoring",
+ "endeavours": "endeavors",
+ "energise": "energize",
+ "energised": "energized",
+ "energises": "energizes",
+ "energising": "energizing",
+ "enrol": "enroll",
+ "enrols": "enrolls",
+ "enthral": "enthrall",
+ "enthrals": "enthralls",
+ "epaulette": "epaulet",
+ "epaulettes": "epaulets",
+ "epicentre": "epicenter",
+ "epicentres": "epicenters",
+ "epilogue": "epilog",
+ "epilogues": "epilogs",
+ "epitomise": "epitomize",
+ "epitomised": "epitomized",
+ "epitomises": "epitomizes",
+ "epitomising": "epitomizing",
+ "equalisation": "equalization",
+ "equalise": "equalize",
+ "equalised": "equalized",
+ "equaliser": "equalizer",
+ "equalisers": "equalizers",
+ "equalises": "equalizes",
+ "equalising": "equalizing",
+ "eulogise": "eulogize",
+ "eulogised": "eulogized",
+ "eulogises": "eulogizes",
+ "eulogising": "eulogizing",
+ "evangelise": "evangelize",
+ "evangelised": "evangelized",
+ "evangelises": "evangelizes",
+ "evangelising": "evangelizing",
+ "exorcise": "exorcize",
+ "exorcised": "exorcized",
+ "exorcises": "exorcizes",
+ "exorcising": "exorcizing",
+ "extemporisation": "extemporization",
+ "extemporise": "extemporize",
+ "extemporised": "extemporized",
+ "extemporises": "extemporizes",
+ "extemporising": "extemporizing",
+ "externalisation": "externalization",
+ "externalisations": "externalizations",
+ "externalise": "externalize",
+ "externalised": "externalized",
+ "externalises": "externalizes",
+ "externalising": "externalizing",
+ "factorise": "factorize",
+ "factorised": "factorized",
+ "factorises": "factorizes",
+ "factorising": "factorizing",
+ "faecal": "fecal",
+ "faeces": "feces",
+ "familiarisation": "familiarization",
+ "familiarise": "familiarize",
+ "familiarised": "familiarized",
+ "familiarises": "familiarizes",
+ "familiarising": "familiarizing",
+ "fantasise": "fantasize",
+ "fantasised": "fantasized",
+ "fantasises": "fantasizes",
+ "fantasising": "fantasizing",
+ "favour": "favor",
+ "favourable": "favorable",
+ "favourably": "favorably",
+ "favoured": "favored",
+ "favouring": "favoring",
+ "favourite": "favorite",
+ "favourites": "favorites",
+ "favouritism": "favoritism",
+ "favours": "favors",
+ "feminise": "feminize",
+ "feminised": "feminized",
+ "feminises": "feminizes",
+ "feminising": "feminizing",
+ "fertilisation": "fertilization",
+ "fertilise": "fertilize",
+ "fertilised": "fertilized",
+ "fertiliser": "fertilizer",
+ "fertilisers": "fertilizers",
+ "fertilises": "fertilizes",
+ "fertilising": "fertilizing",
+ "fervour": "fervor",
+ "fibre": "fiber",
+ "fibreglass": "fiberglass",
+ "fibres": "fibers",
+ "fictionalisation": "fictionalization",
+ "fictionalisations": "fictionalizations",
+ "fictionalise": "fictionalize",
+ "fictionalised": "fictionalized",
+ "fictionalises": "fictionalizes",
+ "fictionalising": "fictionalizing",
+ "fillet": "filet",
+ "filleted": "fileted",
+ "filleting": "fileting",
+ "fillets": "filets",
+ "finalisation": "finalization",
+ "finalise": "finalize",
+ "finalised": "finalized",
+ "finalises": "finalizes",
+ "finalising": "finalizing",
+ "flautist": "flutist",
+ "flautists": "flutists",
+ "flavour": "flavor",
+ "flavoured": "flavored",
+ "flavouring": "flavoring",
+ "flavourings": "flavorings",
+ "flavourless": "flavorless",
+ "flavours": "flavors",
+ "flavoursome": "flavorsome",
+ "flyer": "flier",
+ "foetal": "fetal",
+ "foetid": "fetid",
+ "foetus": "fetus",
+ "foetuses": "fetuses",
+ "formalisation": "formalization",
+ "formalise": "formalize",
+ "formalised": "formalized",
+ "formalises": "formalizes",
+ "formalising": "formalizing",
+ "fossilisation": "fossilization",
+ "fossilise": "fossilize",
+ "fossilised": "fossilized",
+ "fossilises": "fossilizes",
+ "fossilising": "fossilizing",
+ "fraternisation": "fraternization",
+ "fraternise": "fraternize",
+ "fraternised": "fraternized",
+ "fraternises": "fraternizes",
+ "fraternising": "fraternizing",
+ "fulfil": "fulfill",
+ "fulfilment": "fulfillment",
+ "fulfils": "fulfills",
+ "funnelled": "funneled",
+ "funnelling": "funneling",
+ "gage": "gauge",
+ "gaged": "gauged",
+ "gages": "gauges",
+ "gaging": "gauging",
+ "galvanise": "galvanize",
+ "galvanised": "galvanized",
+ "galvanises": "galvanizes",
+ "galvanising": "galvanizing",
+ "gambolled": "gamboled",
+ "gambolling": "gamboling",
+ "gaol": "jail",
+ "gaolbird": "jailbird",
+ "gaolbirds": "jailbirds",
+ "gaolbreak": "jailbreak",
+ "gaolbreaks": "jailbreaks",
+ "gaoled": "jailed",
+ "gaoler": "jailer",
+ "gaolers": "jailers",
+ "gaoling": "jailing",
+ "gaols": "jails",
+ "gasses": "gases",
+ "generalisation": "generalization",
+ "generalisations": "generalizations",
+ "generalise": "generalize",
+ "generalised": "generalized",
+ "generalises": "generalizes",
+ "generalising": "generalizing",
+ "ghettoise": "ghettoize",
+ "ghettoised": "ghettoized",
+ "ghettoises": "ghettoizes",
+ "ghettoising": "ghettoizing",
+ "gipsies": "gypsies",
+ "glamor": "glamour",
+ "glamorise": "glamorize",
+ "glamorised": "glamorized",
+ "glamorises": "glamorizes",
+ "glamorising": "glamorizing",
+ "globalisation": "globalization",
+ "globalise": "globalize",
+ "globalised": "globalized",
+ "globalises": "globalizes",
+ "globalising": "globalizing",
+ "glueing": "gluing",
+ "goitre": "goiter",
+ "goitres": "goiters",
+ "gonorrhoea": "gonorrhea",
+ "gramme": "gram",
+ "grammes": "grams",
+ "gravelled": "graveled",
+ "grey": "gray",
+ "greyed": "grayed",
+ "greying": "graying",
+ "greyish": "grayish",
+ "greyness": "grayness",
+ "greys": "grays",
+ "grovelled": "groveled",
+ "grovelling": "groveling",
+ "groyne": "groin",
+ "groynes": "groins",
+ "gruelling": "grueling",
+ "gruellingly": "gruelingly",
+ "gryphon": "griffin",
+ "gryphons": "griffins",
+ "gynaecological": "gynecological",
+ "gynaecologist": "gynecologist",
+ "gynaecologists": "gynecologists",
+ "gynaecology": "gynecology",
+ "haematological": "hematological",
+ "haematologist": "hematologist",
+ "haematologists": "hematologists",
+ "haematology": "hematology",
+ "haemoglobin": "hemoglobin",
+ "haemophilia": "hemophilia",
+ "haemophiliac": "hemophiliac",
+ "haemophiliacs": "hemophiliacs",
+ "haemorrhage": "hemorrhage",
+ "haemorrhaged": "hemorrhaged",
+ "haemorrhages": "hemorrhages",
+ "haemorrhaging": "hemorrhaging",
+ "haemorrhoids": "hemorrhoids",
+ "harbour": "harbor",
+ "harboured": "harbored",
+ "harbouring": "harboring",
+ "harbours": "harbors",
+ "harmonisation": "harmonization",
+ "harmonise": "harmonize",
+ "harmonised": "harmonized",
+ "harmonises": "harmonizes",
+ "harmonising": "harmonizing",
+ "homoeopath": "homeopath",
+ "homoeopathic": "homeopathic",
+ "homoeopaths": "homeopaths",
+ "homoeopathy": "homeopathy",
+ "homogenise": "homogenize",
+ "homogenised": "homogenized",
+ "homogenises": "homogenizes",
+ "homogenising": "homogenizing",
+ "honour": "honor",
+ "honourable": "honorable",
+ "honourably": "honorably",
+ "honoured": "honored",
+ "honouring": "honoring",
+ "honours": "honors",
+ "hospitalisation": "hospitalization",
+ "hospitalise": "hospitalize",
+ "hospitalised": "hospitalized",
+ "hospitalises": "hospitalizes",
+ "hospitalising": "hospitalizing",
+ "humanise": "humanize",
+ "humanised": "humanized",
+ "humanises": "humanizes",
+ "humanising": "humanizing",
+ "humour": "humor",
+ "humoured": "humored",
+ "humouring": "humoring",
+ "humourless": "humorless",
+ "humours": "humors",
+ "hybridise": "hybridize",
+ "hybridised": "hybridized",
+ "hybridises": "hybridizes",
+ "hybridising": "hybridizing",
+ "hypnotise": "hypnotize",
+ "hypnotised": "hypnotized",
+ "hypnotises": "hypnotizes",
+ "hypnotising": "hypnotizing",
+ "hypothesise": "hypothesize",
+ "hypothesised": "hypothesized",
+ "hypothesises": "hypothesizes",
+ "hypothesising": "hypothesizing",
+ "idealisation": "idealization",
+ "idealise": "idealize",
+ "idealised": "idealized",
+ "idealises": "idealizes",
+ "idealising": "idealizing",
+ "idolise": "idolize",
+ "idolised": "idolized",
+ "idolises": "idolizes",
+ "idolising": "idolizing",
+ "immobilisation": "immobilization",
+ "immobilise": "immobilize",
+ "immobilised": "immobilized",
+ "immobiliser": "immobilizer",
+ "immobilisers": "immobilizers",
+ "immobilises": "immobilizes",
+ "immobilising": "immobilizing",
+ "immortalise": "immortalize",
+ "immortalised": "immortalized",
+ "immortalises": "immortalizes",
+ "immortalising": "immortalizing",
+ "immunisation": "immunization",
+ "immunise": "immunize",
+ "immunised": "immunized",
+ "immunises": "immunizes",
+ "immunising": "immunizing",
+ "impanelled": "impaneled",
+ "impanelling": "impaneling",
+ "imperilled": "imperiled",
+ "imperilling": "imperiling",
+ "individualise": "individualize",
+ "individualised": "individualized",
+ "individualises": "individualizes",
+ "individualising": "individualizing",
+ "industrialise": "industrialize",
+ "industrialised": "industrialized",
+ "industrialises": "industrializes",
+ "industrialising": "industrializing",
+ "inflexion": "inflection",
+ "inflexions": "inflections",
+ "initialise": "initialize",
+ "initialised": "initialized",
+ "initialises": "initializes",
+ "initialising": "initializing",
+ "initialled": "initialed",
+ "initialling": "initialing",
+ "instal": "install",
+ "instalment": "installment",
+ "instalments": "installments",
+ "instals": "installs",
+ "instil": "instill",
+ "instils": "instills",
+ "institutionalisation": "institutionalization",
+ "institutionalise": "institutionalize",
+ "institutionalised": "institutionalized",
+ "institutionalises": "institutionalizes",
+ "institutionalising": "institutionalizing",
+ "intellectualise": "intellectualize",
+ "intellectualised": "intellectualized",
+ "intellectualises": "intellectualizes",
+ "intellectualising": "intellectualizing",
+ "internalisation": "internalization",
+ "internalise": "internalize",
+ "internalised": "internalized",
+ "internalises": "internalizes",
+ "internalising": "internalizing",
+ "internationalisation": "internationalization",
+ "internationalise": "internationalize",
+ "internationalised": "internationalized",
+ "internationalises": "internationalizes",
+ "internationalising": "internationalizing",
+ "ionisation": "ionization",
+ "ionise": "ionize",
+ "ionised": "ionized",
+ "ioniser": "ionizer",
+ "ionisers": "ionizers",
+ "ionises": "ionizes",
+ "ionising": "ionizing",
+ "italicise": "italicize",
+ "italicised": "italicized",
+ "italicises": "italicizes",
+ "italicising": "italicizing",
+ "itemise": "itemize",
+ "itemised": "itemized",
+ "itemises": "itemizes",
+ "itemising": "itemizing",
+ "jeopardise": "jeopardize",
+ "jeopardised": "jeopardized",
+ "jeopardises": "jeopardizes",
+ "jeopardising": "jeopardizing",
+ "jewelled": "jeweled",
+ "jeweller": "jeweler",
+ "jewellers": "jewelers",
+ "jewellery": "jewelry",
+ "judgement": "judgment",
+ "kilogramme": "kilogram",
+ "kilogrammes": "kilograms",
+ "kilometre": "kilometer",
+ "kilometres": "kilometers",
+ "labelled": "labeled",
+ "labelling": "labeling",
+ "labour": "labor",
+ "laboured": "labored",
+ "labourer": "laborer",
+ "labourers": "laborers",
+ "labouring": "laboring",
+ "labours": "labors",
+ "lacklustre": "lackluster",
+ "legalisation": "legalization",
+ "legalise": "legalize",
+ "legalised": "legalized",
+ "legalises": "legalizes",
+ "legalising": "legalizing",
+ "legitimise": "legitimize",
+ "legitimised": "legitimized",
+ "legitimises": "legitimizes",
+ "legitimising": "legitimizing",
+ "leukaemia": "leukemia",
+ "levelled": "leveled",
+ "leveller": "leveler",
+ "levellers": "levelers",
+ "levelling": "leveling",
+ "libelled": "libeled",
+ "libelling": "libeling",
+ "libellous": "libelous",
+ "liberalisation": "liberalization",
+ "liberalise": "liberalize",
+ "liberalised": "liberalized",
+ "liberalises": "liberalizes",
+ "liberalising": "liberalizing",
+ "licence": "license",
+ "licenced": "licensed",
+ "licences": "licenses",
+ "licencing": "licensing",
+ "likeable": "likable",
+ "lionisation": "lionization",
+ "lionise": "lionize",
+ "lionised": "lionized",
+ "lionises": "lionizes",
+ "lionising": "lionizing",
+ "liquidise": "liquidize",
+ "liquidised": "liquidized",
+ "liquidiser": "liquidizer",
+ "liquidisers": "liquidizers",
+ "liquidises": "liquidizes",
+ "liquidising": "liquidizing",
+ "litre": "liter",
+ "litres": "liters",
+ "localise": "localize",
+ "localised": "localized",
+ "localises": "localizes",
+ "localising": "localizing",
+ "louvre": "louver",
+ "louvred": "louvered",
+ "louvres": "louvers",
+ "lustre": "luster",
+ "magnetise": "magnetize",
+ "magnetised": "magnetized",
+ "magnetises": "magnetizes",
+ "magnetising": "magnetizing",
+ "manoeuvrability": "maneuverability",
+ "manoeuvrable": "maneuverable",
+ "manoeuvre": "maneuver",
+ "manoeuvred": "maneuvered",
+ "manoeuvres": "maneuvers",
+ "manoeuvring": "maneuvering",
+ "manoeuvrings": "maneuverings",
+ "marginalisation": "marginalization",
+ "marginalise": "marginalize",
+ "marginalised": "marginalized",
+ "marginalises": "marginalizes",
+ "marginalising": "marginalizing",
+ "marshalled": "marshaled",
+ "marshalling": "marshaling",
+ "marvelled": "marveled",
+ "marvelling": "marveling",
+ "marvellous": "marvelous",
+ "marvellously": "marvelously",
+ "materialisation": "materialization",
+ "materialise": "materialize",
+ "materialised": "materialized",
+ "materialises": "materializes",
+ "materialising": "materializing",
+ "maximisation": "maximization",
+ "maximise": "maximize",
+ "maximised": "maximized",
+ "maximises": "maximizes",
+ "maximising": "maximizing",
+ "meagre": "meager",
+ "mechanisation": "mechanization",
+ "mechanise": "mechanize",
+ "mechanised": "mechanized",
+ "mechanises": "mechanizes",
+ "mechanising": "mechanizing",
+ "mediaeval": "medieval",
+ "memorialise": "memorialize",
+ "memorialised": "memorialized",
+ "memorialises": "memorializes",
+ "memorialising": "memorializing",
+ "memorise": "memorize",
+ "memorised": "memorized",
+ "memorises": "memorizes",
+ "memorising": "memorizing",
+ "mesmerise": "mesmerize",
+ "mesmerised": "mesmerized",
+ "mesmerises": "mesmerizes",
+ "mesmerising": "mesmerizing",
+ "metabolise": "metabolize",
+ "metabolised": "metabolized",
+ "metabolises": "metabolizes",
+ "metabolising": "metabolizing",
+ "metre": "meter",
+ "metres": "meters",
+ "mhm": "hmm",
+ "micrometre": "micrometer",
+ "micrometres": "micrometers",
+ "militarise": "militarize",
+ "militarised": "militarized",
+ "militarises": "militarizes",
+ "militarising": "militarizing",
+ "milligramme": "milligram",
+ "milligrammes": "milligrams",
+ "millilitre": "milliliter",
+ "millilitres": "milliliters",
+ "millimetre": "millimeter",
+ "millimetres": "millimeters",
+ "miniaturisation": "miniaturization",
+ "miniaturise": "miniaturize",
+ "miniaturised": "miniaturized",
+ "miniaturises": "miniaturizes",
+ "miniaturising": "miniaturizing",
+ "minibusses": "minibuses",
+ "minimise": "minimize",
+ "minimised": "minimized",
+ "minimises": "minimizes",
+ "minimising": "minimizing",
+ "misbehaviour": "misbehavior",
+ "misdemeanour": "misdemeanor",
+ "misdemeanours": "misdemeanors",
+ "misspelt": "misspelled",
+ "mitre": "miter",
+ "mitres": "miters",
+ "mm": "hmm",
+ "mmm": "hmm",
+ "mobilisation": "mobilization",
+ "mobilise": "mobilize",
+ "mobilised": "mobilized",
+ "mobilises": "mobilizes",
+ "mobilising": "mobilizing",
+ "modelled": "modeled",
+ "modeller": "modeler",
+ "modellers": "modelers",
+ "modelling": "modeling",
+ "modernise": "modernize",
+ "modernised": "modernized",
+ "modernises": "modernizes",
+ "modernising": "modernizing",
+ "moisturise": "moisturize",
+ "moisturised": "moisturized",
+ "moisturiser": "moisturizer",
+ "moisturisers": "moisturizers",
+ "moisturises": "moisturizes",
+ "moisturising": "moisturizing",
+ "monologue": "monolog",
+ "monologues": "monologs",
+ "monopolisation": "monopolization",
+ "monopolise": "monopolize",
+ "monopolised": "monopolized",
+ "monopolises": "monopolizes",
+ "monopolising": "monopolizing",
+ "moralise": "moralize",
+ "moralised": "moralized",
+ "moralises": "moralizes",
+ "moralising": "moralizing",
+ "motorised": "motorized",
+ "mould": "mold",
+ "moulded": "molded",
+ "moulder": "molder",
+ "mouldered": "moldered",
+ "mouldering": "moldering",
+ "moulders": "molders",
+ "mouldier": "moldier",
+ "mouldiest": "moldiest",
+ "moulding": "molding",
+ "mouldings": "moldings",
+ "moulds": "molds",
+ "mouldy": "moldy",
+ "moult": "molt",
+ "moulted": "molted",
+ "moulting": "molting",
+ "moults": "molts",
+ "moustache": "mustache",
+ "moustached": "mustached",
+ "moustaches": "mustaches",
+ "moustachioed": "mustachioed",
+ "multicoloured": "multicolored",
+ "nationalisation": "nationalization",
+ "nationalisations": "nationalizations",
+ "nationalise": "nationalize",
+ "nationalised": "nationalized",
+ "nationalises": "nationalizes",
+ "nationalising": "nationalizing",
+ "naturalisation": "naturalization",
+ "naturalise": "naturalize",
+ "naturalised": "naturalized",
+ "naturalises": "naturalizes",
+ "naturalising": "naturalizing",
+ "neighbour": "neighbor",
+ "neighbourhood": "neighborhood",
+ "neighbourhoods": "neighborhoods",
+ "neighbouring": "neighboring",
+ "neighbourliness": "neighborliness",
+ "neighbourly": "neighborly",
+ "neighbours": "neighbors",
+ "neutralisation": "neutralization",
+ "neutralise": "neutralize",
+ "neutralised": "neutralized",
+ "neutralises": "neutralizes",
+ "neutralising": "neutralizing",
+ "normalisation": "normalization",
+ "normalise": "normalize",
+ "normalised": "normalized",
+ "normalises": "normalizes",
+ "normalising": "normalizing",
+ "odour": "odor",
+ "odourless": "odorless",
+ "odours": "odors",
+ "oesophagus": "esophagus",
+ "oesophaguses": "esophaguses",
+ "oestrogen": "estrogen",
+ "offence": "offense",
+ "offences": "offenses",
+ "omelette": "omelet",
+ "omelettes": "omelets",
+ "optimise": "optimize",
+ "optimised": "optimized",
+ "optimises": "optimizes",
+ "optimising": "optimizing",
+ "organisation": "organization",
+ "organisational": "organizational",
+ "organisations": "organizations",
+ "organise": "organize",
+ "organised": "organized",
+ "organiser": "organizer",
+ "organisers": "organizers",
+ "organises": "organizes",
+ "organising": "organizing",
+ "orthopaedic": "orthopedic",
+ "orthopaedics": "orthopedics",
+ "ostracise": "ostracize",
+ "ostracised": "ostracized",
+ "ostracises": "ostracizes",
+ "ostracising": "ostracizing",
+ "outmanoeuvre": "outmaneuver",
+ "outmanoeuvred": "outmaneuvered",
+ "outmanoeuvres": "outmaneuvers",
+ "outmanoeuvring": "outmaneuvering",
+ "overemphasise": "overemphasize",
+ "overemphasised": "overemphasized",
+ "overemphasises": "overemphasizes",
+ "overemphasising": "overemphasizing",
+ "oxidisation": "oxidization",
+ "oxidise": "oxidize",
+ "oxidised": "oxidized",
+ "oxidises": "oxidizes",
+ "oxidising": "oxidizing",
+ "paederast": "pederast",
+ "paederasts": "pederasts",
+ "paediatric": "pediatric",
+ "paediatrician": "pediatrician",
+ "paediatricians": "pediatricians",
+ "paediatrics": "pediatrics",
+ "paedophile": "pedophile",
+ "paedophiles": "pedophiles",
+ "paedophilia": "pedophilia",
+ "palaeolithic": "paleolithic",
+ "palaeontologist": "paleontologist",
+ "palaeontologists": "paleontologists",
+ "palaeontology": "paleontology",
+ "panelled": "paneled",
+ "panelling": "paneling",
+ "panellist": "panelist",
+ "panellists": "panelists",
+ "paralyse": "paralyze",
+ "paralysed": "paralyzed",
+ "paralyses": "paralyzes",
+ "paralysing": "paralyzing",
+ "parcelled": "parceled",
+ "parcelling": "parceling",
+ "parlour": "parlor",
+ "parlours": "parlors",
+ "particularise": "particularize",
+ "particularised": "particularized",
+ "particularises": "particularizes",
+ "particularising": "particularizing",
+ "passivisation": "passivization",
+ "passivise": "passivize",
+ "passivised": "passivized",
+ "passivises": "passivizes",
+ "passivising": "passivizing",
+ "pasteurisation": "pasteurization",
+ "pasteurise": "pasteurize",
+ "pasteurised": "pasteurized",
+ "pasteurises": "pasteurizes",
+ "pasteurising": "pasteurizing",
+ "patronise": "patronize",
+ "patronised": "patronized",
+ "patronises": "patronizes",
+ "patronising": "patronizing",
+ "patronisingly": "patronizingly",
+ "pedalled": "pedaled",
+ "pedalling": "pedaling",
+ "pedestrianisation": "pedestrianization",
+ "pedestrianise": "pedestrianize",
+ "pedestrianised": "pedestrianized",
+ "pedestrianises": "pedestrianizes",
+ "pedestrianising": "pedestrianizing",
+ "penalise": "penalize",
+ "penalised": "penalized",
+ "penalises": "penalizes",
+ "penalising": "penalizing",
+ "pencilled": "penciled",
+ "pencilling": "penciling",
+ "personalise": "personalize",
+ "personalised": "personalized",
+ "personalises": "personalizes",
+ "personalising": "personalizing",
+ "pharmacopoeia": "pharmacopeia",
+ "pharmacopoeias": "pharmacopeias",
+ "philosophise": "philosophize",
+ "philosophised": "philosophized",
+ "philosophises": "philosophizes",
+ "philosophising": "philosophizing",
+ "philtre": "filter",
+ "philtres": "filters",
+ "phoney": "phony",
+ "plagiarise": "plagiarize",
+ "plagiarised": "plagiarized",
+ "plagiarises": "plagiarizes",
+ "plagiarising": "plagiarizing",
+ "plough": "plow",
+ "ploughed": "plowed",
+ "ploughing": "plowing",
+ "ploughman": "plowman",
+ "ploughmen": "plowmen",
+ "ploughs": "plows",
+ "ploughshare": "plowshare",
+ "ploughshares": "plowshares",
+ "polarisation": "polarization",
+ "polarise": "polarize",
+ "polarised": "polarized",
+ "polarises": "polarizes",
+ "polarising": "polarizing",
+ "politicisation": "politicization",
+ "politicise": "politicize",
+ "politicised": "politicized",
+ "politicises": "politicizes",
+ "politicising": "politicizing",
+ "popularisation": "popularization",
+ "popularise": "popularize",
+ "popularised": "popularized",
+ "popularises": "popularizes",
+ "popularising": "popularizing",
+ "pouffe": "pouf",
+ "pouffes": "poufs",
+ "practise": "practice",
+ "practised": "practiced",
+ "practises": "practices",
+ "practising": "practicing",
+ "praesidium": "presidium",
+ "praesidiums": "presidiums",
+ "pressurisation": "pressurization",
+ "pressurise": "pressurize",
+ "pressurised": "pressurized",
+ "pressurises": "pressurizes",
+ "pressurising": "pressurizing",
+ "pretence": "pretense",
+ "pretences": "pretenses",
+ "primaeval": "primeval",
+ "prioritisation": "prioritization",
+ "prioritise": "prioritize",
+ "prioritised": "prioritized",
+ "prioritises": "prioritizes",
+ "prioritising": "prioritizing",
+ "privatisation": "privatization",
+ "privatisations": "privatizations",
+ "privatise": "privatize",
+ "privatised": "privatized",
+ "privatises": "privatizes",
+ "privatising": "privatizing",
+ "professionalisation": "professionalization",
+ "professionalise": "professionalize",
+ "professionalised": "professionalized",
+ "professionalises": "professionalizes",
+ "professionalising": "professionalizing",
+ "programme": "program",
+ "programmes": "programs",
+ "prologue": "prolog",
+ "prologues": "prologs",
+ "propagandise": "propagandize",
+ "propagandised": "propagandized",
+ "propagandises": "propagandizes",
+ "propagandising": "propagandizing",
+ "proselytise": "proselytize",
+ "proselytised": "proselytized",
+ "proselytiser": "proselytizer",
+ "proselytisers": "proselytizers",
+ "proselytises": "proselytizes",
+ "proselytising": "proselytizing",
+ "psychoanalyse": "psychoanalyze",
+ "psychoanalysed": "psychoanalyzed",
+ "psychoanalyses": "psychoanalyzes",
+ "psychoanalysing": "psychoanalyzing",
+ "publicise": "publicize",
+ "publicised": "publicized",
+ "publicises": "publicizes",
+ "publicising": "publicizing",
+ "pulverisation": "pulverization",
+ "pulverise": "pulverize",
+ "pulverised": "pulverized",
+ "pulverises": "pulverizes",
+ "pulverising": "pulverizing",
+ "pummelled": "pummeled",
+ "pummelling": "pummeling",
+ "pyjama": "pajama",
+ "pyjamas": "pajamas",
+ "pzazz": "pizzazz",
+ "quarrelled": "quarreled",
+ "quarrelling": "quarreling",
+ "radicalise": "radicalize",
+ "radicalised": "radicalized",
+ "radicalises": "radicalizes",
+ "radicalising": "radicalizing",
+ "rancour": "rancor",
+ "randomise": "randomize",
+ "randomised": "randomized",
+ "randomises": "randomizes",
+ "randomising": "randomizing",
+ "rationalisation": "rationalization",
+ "rationalisations": "rationalizations",
+ "rationalise": "rationalize",
+ "rationalised": "rationalized",
+ "rationalises": "rationalizes",
+ "rationalising": "rationalizing",
+ "ravelled": "raveled",
+ "ravelling": "raveling",
+ "realisable": "realizable",
+ "realisation": "realization",
+ "realisations": "realizations",
+ "realise": "realize",
+ "realised": "realized",
+ "realises": "realizes",
+ "realising": "realizing",
+ "recognisable": "recognizable",
+ "recognisably": "recognizably",
+ "recognisance": "recognizance",
+ "recognise": "recognize",
+ "recognised": "recognized",
+ "recognises": "recognizes",
+ "recognising": "recognizing",
+ "reconnoitre": "reconnoiter",
+ "reconnoitred": "reconnoitered",
+ "reconnoitres": "reconnoiters",
+ "reconnoitring": "reconnoitering",
+ "refuelled": "refueled",
+ "refuelling": "refueling",
+ "regularisation": "regularization",
+ "regularise": "regularize",
+ "regularised": "regularized",
+ "regularises": "regularizes",
+ "regularising": "regularizing",
+ "remodelled": "remodeled",
+ "remodelling": "remodeling",
+ "remould": "remold",
+ "remoulded": "remolded",
+ "remoulding": "remolding",
+ "remoulds": "remolds",
+ "reorganisation": "reorganization",
+ "reorganisations": "reorganizations",
+ "reorganise": "reorganize",
+ "reorganised": "reorganized",
+ "reorganises": "reorganizes",
+ "reorganising": "reorganizing",
+ "revelled": "reveled",
+ "reveller": "reveler",
+ "revellers": "revelers",
+ "revelling": "reveling",
+ "revitalise": "revitalize",
+ "revitalised": "revitalized",
+ "revitalises": "revitalizes",
+ "revitalising": "revitalizing",
+ "revolutionise": "revolutionize",
+ "revolutionised": "revolutionized",
+ "revolutionises": "revolutionizes",
+ "revolutionising": "revolutionizing",
+ "rhapsodise": "rhapsodize",
+ "rhapsodised": "rhapsodized",
+ "rhapsodises": "rhapsodizes",
+ "rhapsodising": "rhapsodizing",
+ "rigour": "rigor",
+ "rigours": "rigors",
+ "ritualised": "ritualized",
+ "rivalled": "rivaled",
+ "rivalling": "rivaling",
+ "romanticise": "romanticize",
+ "romanticised": "romanticized",
+ "romanticises": "romanticizes",
+ "romanticising": "romanticizing",
+ "rumour": "rumor",
+ "rumoured": "rumored",
+ "rumours": "rumors",
+ "sabre": "saber",
+ "sabres": "sabers",
+ "saltpetre": "saltpeter",
+ "sanitise": "sanitize",
+ "sanitised": "sanitized",
+ "sanitises": "sanitizes",
+ "sanitising": "sanitizing",
+ "satirise": "satirize",
+ "satirised": "satirized",
+ "satirises": "satirizes",
+ "satirising": "satirizing",
+ "saviour": "savior",
+ "saviours": "saviors",
+ "savour": "savor",
+ "savoured": "savored",
+ "savouries": "savories",
+ "savouring": "savoring",
+ "savours": "savors",
+ "savoury": "savory",
+ "scandalise": "scandalize",
+ "scandalised": "scandalized",
+ "scandalises": "scandalizes",
+ "scandalising": "scandalizing",
+ "sceptic": "skeptic",
+ "sceptical": "skeptical",
+ "sceptically": "skeptically",
+ "scepticism": "skepticism",
+ "sceptics": "skeptics",
+ "sceptre": "scepter",
+ "sceptres": "scepters",
+ "scrutinise": "scrutinize",
+ "scrutinised": "scrutinized",
+ "scrutinises": "scrutinizes",
+ "scrutinising": "scrutinizing",
+ "secularisation": "secularization",
+ "secularise": "secularize",
+ "secularised": "secularized",
+ "secularises": "secularizes",
+ "secularising": "secularizing",
+ "sensationalise": "sensationalize",
+ "sensationalised": "sensationalized",
+ "sensationalises": "sensationalizes",
+ "sensationalising": "sensationalizing",
+ "sensitise": "sensitize",
+ "sensitised": "sensitized",
+ "sensitises": "sensitizes",
+ "sensitising": "sensitizing",
+ "sentimentalise": "sentimentalize",
+ "sentimentalised": "sentimentalized",
+ "sentimentalises": "sentimentalizes",
+ "sentimentalising": "sentimentalizing",
+ "sepulchre": "sepulcher",
+ "sepulchres": "sepulchers",
+ "serialisation": "serialization",
+ "serialisations": "serializations",
+ "serialise": "serialize",
+ "serialised": "serialized",
+ "serialises": "serializes",
+ "serialising": "serializing",
+ "sermonise": "sermonize",
+ "sermonised": "sermonized",
+ "sermonises": "sermonizes",
+ "sermonising": "sermonizing",
+ "sheikh": "sheik",
+ "shovelled": "shoveled",
+ "shovelling": "shoveling",
+ "shrivelled": "shriveled",
+ "shrivelling": "shriveling",
+ "signalise": "signalize",
+ "signalised": "signalized",
+ "signalises": "signalizes",
+ "signalising": "signalizing",
+ "signalled": "signaled",
+ "signalling": "signaling",
+ "smoulder": "smolder",
+ "smouldered": "smoldered",
+ "smouldering": "smoldering",
+ "smoulders": "smolders",
+ "snivelled": "sniveled",
+ "snivelling": "sniveling",
+ "snorkelled": "snorkeled",
+ "snorkelling": "snorkeling",
+ "snowplough": "snowplow",
+ "snowploughs": "snowplows",
+ "socialisation": "socialization",
+ "socialise": "socialize",
+ "socialised": "socialized",
+ "socialises": "socializes",
+ "socialising": "socializing",
+ "sodomise": "sodomize",
+ "sodomised": "sodomized",
+ "sodomises": "sodomizes",
+ "sodomising": "sodomizing",
+ "solemnise": "solemnize",
+ "solemnised": "solemnized",
+ "solemnises": "solemnizes",
+ "solemnising": "solemnizing",
+ "sombre": "somber",
+ "specialisation": "specialization",
+ "specialisations": "specializations",
+ "specialise": "specialize",
+ "specialised": "specialized",
+ "specialises": "specializes",
+ "specialising": "specializing",
+ "spectre": "specter",
+ "spectres": "specters",
+ "spiralled": "spiraled",
+ "spiralling": "spiraling",
+ "splendour": "splendor",
+ "splendours": "splendors",
+ "squirrelled": "squirreled",
+ "squirrelling": "squirreling",
+ "stabilisation": "stabilization",
+ "stabilise": "stabilize",
+ "stabilised": "stabilized",
+ "stabiliser": "stabilizer",
+ "stabilisers": "stabilizers",
+ "stabilises": "stabilizes",
+ "stabilising": "stabilizing",
+ "standardisation": "standardization",
+ "standardise": "standardize",
+ "standardised": "standardized",
+ "standardises": "standardizes",
+ "standardising": "standardizing",
+ "stencilled": "stenciled",
+ "stencilling": "stenciling",
+ "sterilisation": "sterilization",
+ "sterilisations": "sterilizations",
+ "sterilise": "sterilize",
+ "sterilised": "sterilized",
+ "steriliser": "sterilizer",
+ "sterilisers": "sterilizers",
+ "sterilises": "sterilizes",
+ "sterilising": "sterilizing",
+ "stigmatisation": "stigmatization",
+ "stigmatise": "stigmatize",
+ "stigmatised": "stigmatized",
+ "stigmatises": "stigmatizes",
+ "stigmatising": "stigmatizing",
+ "storey": "story",
+ "storeys": "stories",
+ "subsidisation": "subsidization",
+ "subsidise": "subsidize",
+ "subsidised": "subsidized",
+ "subsidiser": "subsidizer",
+ "subsidisers": "subsidizers",
+ "subsidises": "subsidizes",
+ "subsidising": "subsidizing",
+ "succour": "succor",
+ "succoured": "succored",
+ "succouring": "succoring",
+ "succours": "succors",
+ "sulphate": "sulfate",
+ "sulphates": "sulfates",
+ "sulphide": "sulfide",
+ "sulphides": "sulfides",
+ "sulphur": "sulfur",
+ "sulphurous": "sulfurous",
+ "summarise": "summarize",
+ "summarised": "summarized",
+ "summarises": "summarizes",
+ "summarising": "summarizing",
+ "swivelled": "swiveled",
+ "swivelling": "swiveling",
+ "symbolise": "symbolize",
+ "symbolised": "symbolized",
+ "symbolises": "symbolizes",
+ "symbolising": "symbolizing",
+ "sympathise": "sympathize",
+ "sympathised": "sympathized",
+ "sympathiser": "sympathizer",
+ "sympathisers": "sympathizers",
+ "sympathises": "sympathizes",
+ "sympathising": "sympathizing",
+ "synchronisation": "synchronization",
+ "synchronise": "synchronize",
+ "synchronised": "synchronized",
+ "synchronises": "synchronizes",
+ "synchronising": "synchronizing",
+ "synthesise": "synthesize",
+ "synthesised": "synthesized",
+ "synthesiser": "synthesizer",
+ "synthesisers": "synthesizers",
+ "synthesises": "synthesizes",
+ "synthesising": "synthesizing",
+ "syphon": "siphon",
+ "syphoned": "siphoned",
+ "syphoning": "siphoning",
+ "syphons": "siphons",
+ "systematisation": "systematization",
+ "systematise": "systematize",
+ "systematised": "systematized",
+ "systematises": "systematizes",
+ "systematising": "systematizing",
+ "tantalise": "tantalize",
+ "tantalised": "tantalized",
+ "tantalises": "tantalizes",
+ "tantalising": "tantalizing",
+ "tantalisingly": "tantalizingly",
+ "tasselled": "tasseled",
+ "technicolour": "technicolor",
+ "temporise": "temporize",
+ "temporised": "temporized",
+ "temporises": "temporizes",
+ "temporising": "temporizing",
+ "tenderise": "tenderize",
+ "tenderised": "tenderized",
+ "tenderises": "tenderizes",
+ "tenderising": "tenderizing",
+ "terrorise": "terrorize",
+ "terrorised": "terrorized",
+ "terrorises": "terrorizes",
+ "terrorising": "terrorizing",
+ "theatre": "theater",
+ "theatregoer": "theatergoer",
+ "theatregoers": "theatergoers",
+ "theatres": "theaters",
+ "theorise": "theorize",
+ "theorised": "theorized",
+ "theorises": "theorizes",
+ "theorising": "theorizing",
+ "tonne": "ton",
+ "tonnes": "tons",
+ "towelled": "toweled",
+ "towelling": "toweling",
+ "toxaemia": "toxemia",
+ "tranquillise": "tranquilize",
+ "tranquillised": "tranquilized",
+ "tranquilliser": "tranquilizer",
+ "tranquillisers": "tranquilizers",
+ "tranquillises": "tranquilizes",
+ "tranquillising": "tranquilizing",
+ "tranquillity": "tranquility",
+ "tranquillize": "tranquilize",
+ "tranquillized": "tranquilized",
+ "tranquillizer": "tranquilizer",
+ "tranquillizers": "tranquilizers",
+ "tranquillizes": "tranquilizes",
+ "tranquillizing": "tranquilizing",
+ "tranquilly": "tranquility",
+ "transistorised": "transistorized",
+ "traumatise": "traumatize",
+ "traumatised": "traumatized",
+ "traumatises": "traumatizes",
+ "traumatising": "traumatizing",
+ "travelled": "traveled",
+ "traveller": "traveler",
+ "travellers": "travelers",
+ "travelling": "traveling",
+ "travelogue": "travelog",
+ "travelogues": "travelogs",
+ "trialled": "trialed",
+ "trialling": "trialing",
+ "tricolour": "tricolor",
+ "tricolours": "tricolors",
+ "trivialise": "trivialize",
+ "trivialised": "trivialized",
+ "trivialises": "trivializes",
+ "trivialising": "trivializing",
+ "tumour": "tumor",
+ "tumours": "tumors",
+ "tunnelled": "tunneled",
+ "tunnelling": "tunneling",
+ "tyrannise": "tyrannize",
+ "tyrannised": "tyrannized",
+ "tyrannises": "tyrannizes",
+ "tyrannising": "tyrannizing",
+ "tyre": "tire",
+ "tyres": "tires",
+ "unauthorised": "unauthorized",
+ "uncivilised": "uncivilized",
+ "underutilised": "underutilized",
+ "unequalled": "unequaled",
+ "unfavourable": "unfavorable",
+ "unfavourably": "unfavorably",
+ "unionisation": "unionization",
+ "unionise": "unionize",
+ "unionised": "unionized",
+ "unionises": "unionizes",
+ "unionising": "unionizing",
+ "unorganised": "unorganized",
+ "unravelled": "unraveled",
+ "unravelling": "unraveling",
+ "unrecognisable": "unrecognizable",
+ "unrecognised": "unrecognized",
+ "unrivalled": "unrivaled",
+ "unsavoury": "unsavory",
+ "untrammelled": "untrammeled",
+ "urbanisation": "urbanization",
+ "urbanise": "urbanize",
+ "urbanised": "urbanized",
+ "urbanises": "urbanizes",
+ "urbanising": "urbanizing",
+ "utilisable": "utilizable",
+ "utilisation": "utilization",
+ "utilise": "utilize",
+ "utilised": "utilized",
+ "utilises": "utilizes",
+ "utilising": "utilizing",
+ "valour": "valor",
+ "vandalise": "vandalize",
+ "vandalised": "vandalized",
+ "vandalises": "vandalizes",
+ "vandalising": "vandalizing",
+ "vaporisation": "vaporization",
+ "vaporise": "vaporize",
+ "vaporised": "vaporized",
+ "vaporises": "vaporizes",
+ "vaporising": "vaporizing",
+ "vapour": "vapor",
+ "vapours": "vapors",
+ "verbalise": "verbalize",
+ "verbalised": "verbalized",
+ "verbalises": "verbalizes",
+ "verbalising": "verbalizing",
+ "victimisation": "victimization",
+ "victimise": "victimize",
+ "victimised": "victimized",
+ "victimises": "victimizes",
+ "victimising": "victimizing",
+ "videodisc": "videodisk",
+ "videodiscs": "videodisks",
+ "vigour": "vigor",
+ "visualisation": "visualization",
+ "visualisations": "visualizations",
+ "visualise": "visualize",
+ "visualised": "visualized",
+ "visualises": "visualizes",
+ "visualising": "visualizing",
+ "vocalisation": "vocalization",
+ "vocalisations": "vocalizations",
+ "vocalise": "vocalize",
+ "vocalised": "vocalized",
+ "vocalises": "vocalizes",
+ "vocalising": "vocalizing",
+ "vulcanised": "vulcanized",
+ "vulgarisation": "vulgarization",
+ "vulgarise": "vulgarize",
+ "vulgarised": "vulgarized",
+ "vulgarises": "vulgarizes",
+ "vulgarising": "vulgarizing",
+ "waggon": "wagon",
+ "waggons": "wagons",
+ "watercolour": "watercolor",
+ "watercolours": "watercolors",
+ "weaselled": "weaseled",
+ "weaselling": "weaseling",
+ "westernisation": "westernization",
+ "westernise": "westernize",
+ "westernised": "westernized",
+ "westernises": "westernizes",
+ "westernising": "westernizing",
+ "womanise": "womanize",
+ "womanised": "womanized",
+ "womaniser": "womanizer",
+ "womanisers": "womanizers",
+ "womanises": "womanizes",
+ "womanising": "womanizing",
+ "woollen": "woolen",
+ "woollens": "woolens",
+ "woollies": "woolies",
+ "woolly": "wooly",
+ "worshipped": "worshiped",
+ "worshipper": "worshiper",
+ "worshipping": "worshiping",
+ "yodelled": "yodeled",
+ "yodelling": "yodeling",
+ "yoghourt": "yogurt",
+ "yoghourts": "yogurts",
+ "yoghurt": "yogurt",
+ "yoghurts": "yogurts"
+}
+
+
+english_name_normalizer = {
+ # ── Double-letter variants ──────────────────────────────────────────────
+ "alan": "allen",
+ "allan": "allen",
+ "bridgette": "bridget",
+ "charly": "charlie",
+ "charley": "charlie",
+ "garry": "gary",
+ "gregg": "greg",
+ "jacky": "jackie",
+ "joann": "joanne",
+ "joane": "joanne",
+ "kellye": "kelly",
+ "kelli": "kelly",
+ "kelley": "kelly",
+ "lilly": "lily",
+ "micheal": "michael",
+ "michele": "michelle",
+ "mollie": "molly",
+ "phillip": "philip",
+ "sallie": "sally",
+ "stacey": "stacy",
+ "stacie": "stacy",
+ "tracey": "tracy",
+ "tracie": "tracy",
+ "bret": "brett",
+ "carrol": "carol",
+ "carole": "carol",
+ "carroll": "carol",
+ "allison": "alison",
+ "alyson": "alison",
+ "russel": "russell",
+ "douglass": "douglas",
+ "dominick": "dominic",
+ "robb": "rob",
+ # ── Chr/Kr variants ─────────────────────────────────────────────────────
+ "kris": "chris",
+ "kristopher": "christopher",
+ "cristopher": "christopher",
+ "kristina": "christina",
+ "kristen": "kristin",
+ # ── C/K variants ────────────────────────────────────────────────────────
+ "karl": "carl",
+ "kathy": "cathy",
+ "katherine": "catherine",
+ "kathryn": "catherine",
+ "catharine": "catherine",
+ "erik": "eric",
+ "erick": "eric",
+ "caren": "karen",
+ "caryn": "karen",
+ "karin": "karen",
+ "katelyn": "caitlin",
+ "kaitlyn": "caitlin",
+ "kaitlin": "caitlin",
+ "nikole": "nicole",
+ "veronika": "veronica",
+ "viktor": "victor",
+ "viktoria": "victoria",
+ "kevan": "kevin",
+ "patrik": "patrick",
+ "frederik": "frederick",
+ "fredrick": "frederick",
+ "lukas": "lucas",
+ # ── Silent letters / alternate spellings ───────────────────────────────
+ "ann": "anne",
+ "jon": "john",
+ "johnathan": "jonathan",
+ "jonathon": "jonathan",
+ "sara": "sarah",
+ "mathew": "matthew",
+ "nicolas": "nicholas",
+ "rachael": "rachel",
+ "rebekah": "rebecca",
+ "devorah": "deborah",
+ "theresa": "teresa",
+ "suzanne": "susanne",
+ "antony": "anthony",
+ "martyn": "martin",
+ "denis": "dennis",
+ "laurence": "lawrence",
+ "tomas": "thomas",
+ "tobey": "toby",
+ # ── Mac/Mc extensions ───────────────────────────────────────────────────
+ "macarthur": "mcarthur",
+ "macartney": "mccartney",
+ "macarthy": "mccarthy",
+ "maccarthy": "mccarthy",
+ "macdonald": "mcdonald",
+ "mackay": "mckay",
+ "mackenzie": "mckenzie",
+ "macleod": "mcleod",
+ "maclean": "mclean",
+ "macmillan": "mcmillan",
+ "macintosh": "mcintosh",
+ "macintyre": "mcintyre",
+ "macnamara": "mcnamara",
+ "macgowan": "mcgowan",
+ # ── International ─────────────────────────────────
+ "mohamad": "mohammed",
+ "mohamed": "mohammed",
+ "mohammad": "mohammed",
+ "muhammad": "mohammed",
+ "muhamad": "mohammed",
+ "muhammed": "mohammed",
+ "mouhamed": "mohammed",
+ "mouhamad": "mohammed",
+ "mahomet": "mohammed",
+ "fatimah": "fatima",
+ "yusuf": "yousef",
+ "yusef": "yousef",
+ "myriam": "miriam",
+ "rajeev": "rajiv",
+ # ── Miscellaneous homophones ────────────────────────────────────────────
+ "alphonso": "alfonso",
+ "bryan": "brian",
+ "geoffrey": "jeffrey",
+ "jeffery": "jeffrey",
+ "geoff": "jeff",
+ "neal": "neil",
+ "shaun": "sean",
+ "shawn": "sean",
+ "shayne": "shane",
+ "stephen": "steven",
+ "toni": "tony",
+ "leigh": "lee",
+ "lewis": "louis",
+ "marc": "mark",
+ "meghan": "megan",
+ "nathalie": "natalie",
+ "robyn": "robin",
+ "rodger": "roger",
+ "linsey": "lindsay",
+ "lindsey": "lindsay",
+ "zackary": "zachary",
+ "zachery": "zachary",
+ "zak": "zach",
+ "sheri": "sherry",
+ "cheri": "sherry",
+ "sherrie": "sherry",
+ "terri": "terry",
+ "lori": "laurie",
+ "jaime": "jamie",
+ "jayson": "jason",
+ "lesley": "leslie",
+ "lynda": "linda",
+ "lynne": "lynn",
+ "gayle": "gail",
+ "rhonda": "ronda",
+ "yvonne": "ivonne",
+ "stewart": "stuart",
+ "walther": "walter",
+ "symon": "simon",
+ "collin": "colin",
+ "dillon": "dylan",
+ "aron": "aaron",
+ "artur": "arthur",
+ "henri": "henry",
+ "josef": "joseph",
+ "pieter": "peter",
+}
+
+
+# Regex-based multi-word → single-token mappings.
+# Applied after symbol removal, so hyphens/punctuation are already stripped.
+# Keys are used with re.sub; values are the replacement strings.
+english_compound_normalizer = {
+ r"\bet\s+cetera\b": "etc",
+ r"\bal\s+right\b": "alright",
+ r"\ball\s+right\b": "alright",
+ r"\bhow\s+ever\b": "however",
+ r"\bwi\s+fi\b": "wifi",
+ r"\bhi\s+fi\b": "hifi",
+ r"\blo\s+fi\b": "lofi",
+ r"\bsci\s+fi\b": "scifi",
+ r"\be\s+mail\b": "email",
+ r"\be\s+book\b": "ebook",
+ r"\be\s+commerce\b": "ecommerce",
+ r"\bx\s+ray\b": "xray",
+ r"\bt\s+shirt\b": "tshirt",
+ r"\ba\s+m\b": "am",
+ r"\bp\s+m\b": "pm",
+ r"\bo\s+k\b": "okay",
+}
+
diff --git a/normalizer/eval_utils.py b/normalizer/eval_utils.py
new file mode 100644
index 0000000..d387f82
--- /dev/null
+++ b/normalizer/eval_utils.py
@@ -0,0 +1,458 @@
+import os
+import glob
+import json
+import re
+import unicodedata
+from difflib import SequenceMatcher
+
+from collections import defaultdict
+from kaldialign import batch_error_rate
+
+
+# ── Chinese / CJK scoring (CER instead of WER) ────────────────────────────────
+# CJK text has no word delimiters, so WER is meaningless; score per character (CER), as
+# seed-tts-eval's run_wer.py does for zh (it still labels it "WER").
+
+# CJK Unified Ideographs (+ Ext A/B+ and compat), Hiragana/Katakana, Hangul syllables.
+_CJK_PATTERN = re.compile(
+ "["
+ "㐀-䶿" # CJK Unified Ideographs Extension A
+ "一-鿿" # CJK Unified Ideographs
+ "豈-﫿" # CJK Compatibility Ideographs
+ "\U00020000-\U0002ffff" # CJK Unified Ideographs Extension B and beyond
+ "぀-ヿ" # Hiragana + Katakana
+ "가-힯" # Hangul syllables
+ "]"
+)
+
+# Language codes that must be scored with CER. The single source of truth for the CJK list.
+CJK_LANGUAGES = {"zh", "yue", "cmn", "ja", "jpn", "ko", "kor"}
+
+
+def is_cjk_language(language: str) -> bool:
+ """Whether `language` is CJK, matched on the part before the first `_`/`-` (e.g. "zh-cn")."""
+ return re.split(r"[_-]", language)[0] in CJK_LANGUAGES
+
+
+def default_multilingual(language: str) -> bool:
+ """Compound-boundary pre-folding: off for English (own normalizer) and CJK (scored per char)."""
+ return language != "en" and not is_cjk_language(language)
+
+
+# Kana/Hangul mark a string as Japanese/Korean, gating the Chinese-only folds below.
+_KANA_HANGUL_PATTERN = re.compile("[぀-ヿ가-힯]")
+_JAPANESE_KOREAN_LANGUAGES = {"ja", "jpn", "ko", "kor"}
+
+
+def _is_chinese(text: str, language: str = None) -> bool:
+ """Whether to apply the Chinese-specific folds to `text`.
+
+ Not Chinese if `language` is ja/ko (kanji-only Japanese is indistinguishable by script) or if
+ the text contains kana/Hangul (`language` may be 'en' for auto-detected CJK manifests).
+ """
+ if language and re.split(r"[_-]", language)[0] in _JAPANESE_KOREAN_LANGUAGES:
+ return False
+ return not _KANA_HANGUL_PATTERN.search(text)
+
+
+def _to_simplified(text: str) -> str:
+ """Fold traditional Chinese to simplified (as seed-tts-eval's run_wer.py does via zhconv).
+
+ ASR sometimes emits traditional characters while references are simplified; applied to both sides.
+ """
+ try:
+ from zhconv import convert
+ except ImportError as e:
+ raise ImportError(
+ "Scoring Chinese requires `zhconv` to fold traditional characters to simplified "
+ "before alignment (matching seed-tts-eval's run_wer.py). Install it with "
+ "`pip install zhconv`."
+ ) from e
+ return convert(text, "zh-cn")
+
+
+# ── Chinese homophone folding (lenient metric only) ───────────────────────────
+# Closed-class groups whose written distinction is a convention on one identical spoken form, so
+# the ASR's spelling choice is not a TTS error (cf. `english_spelling_normalizer`). Open-class
+# homophones (在/再, 做/作, ...) are excluded: context resolves them. Groups are chosen from
+# phonology and references only, never fitted to model outputs.
+CJK_HOMOPHONE_GROUPS = [
+ # Structural particle `de`. 地 (dì) and 得 (dé) are polyphonic, so this over-reaches, but the fold
+ # is applied to both sides and can only lower CER.
+ ("的", "地得"),
+ # Invariantly `tā`; gender/animacy is absent from the audio.
+ ("他", "她它"),
+]
+# variant char -> canonical char
+_CJK_HOMOPHONE_MAP = str.maketrans(
+ {variant: canonical for canonical, variants in CJK_HOMOPHONE_GROUPS for variant in variants}
+)
+
+# ── Japanese script folding (lenient metric only) ─────────────────────────────
+# Katakana and hiragana spellings of a word sound identical. Katakana→hiragana is a 1:1,
+# length-preserving codepoint map (U+30A1-U+30F6 → U+3041-U+3096); ー and ヷヸヹヺ are left alone.
+# Kanji↔kana is NOT folded: it needs a reading dictionary, is ambiguous and not length-preserving.
+_KATAKANA_TO_HIRAGANA = str.maketrans({cp: cp - 0x60 for cp in range(0x30A1, 0x30F7)})
+
+# ── CJK numeral notation folding (lenient metric only) ────────────────────────
+# ASR may write "2006年" where the reference has "二零零六年". A per-digit map matches the
+# positional readings used by Seed-TTS references and is length-preserving (unlike num2words).
+_CJK_NUMERAL_MAP = str.maketrans({
+ "0": "零", "1": "一", "2": "二", "3": "三", "4": "四",
+ "5": "五", "6": "六", "7": "七", "8": "八", "9": "九",
+ # Ideographic zero and the circle sometimes used for it in years (二〇二〇).
+ "〇": "零", "○": "零",
+})
+
+
+def cjk_normalizer(text: str, fold_homophones: bool = False, fold_numerals: bool = False, language: str = None) -> str:
+ """Normalize a CJK string for character-level (CER) scoring.
+
+ Mirrors seed-tts-eval's `process_one`: strip punctuation, fold traditional→simplified (Chinese
+ only), lowercase embedded Latin, and drop whitespace. With both flags off this is the strict,
+ seed-tts-eval-comparable form. `fold_homophones` applies CJK_HOMOPHONE_GROUPS (Chinese) or
+ katakana→hiragana (Japanese); `fold_numerals` maps Arabic digits to CJK numerals. Every fold is
+ length-preserving and applied to both sides, so it can only lower the error rate.
+ """
+ text = unicodedata.normalize("NFKC", text)
+ # Chinese only: on Japanese, zhconv rewrites kanji (俳優 → 俳优); on Korean it folds hanja.
+ is_chinese = _is_chinese(text, language)
+ if is_chinese:
+ text = _to_simplified(text)
+ text = text.lower()
+ # Drop every mark/symbol/punctuation (CJK and ASCII); keep the apostrophe, as seed-tts-eval does.
+ text = "".join(c for c in text if c == "'" or unicodedata.category(c)[0] not in "MSP")
+ # The Chinese groups must not run on Japanese (的/地/得 are distinct morphemes there).
+ if fold_homophones:
+ text = text.translate(_CJK_HOMOPHONE_MAP if is_chinese else _KATAKANA_TO_HIRAGANA)
+ if fold_numerals:
+ text = text.translate(_CJK_NUMERAL_MAP)
+ return "".join(text.split())
+
+
+def _is_mostly_cjk(texts, threshold: float = 0.5) -> bool:
+ """True when most of `texts` contain CJK characters (so the manifest wants CER)."""
+ sample = [t for t in texts if t and t.strip()]
+ if not sample:
+ return False
+ return sum(1 for t in sample if _CJK_PATTERN.search(t)) / len(sample) >= threshold
+
+
+def normalize_compound_pairs(refs, preds):
+ """Align compound word boundaries between ref/pred pairs.
+
+ When a mismatch region has identical characters ignoring whitespace,
+ normalize both sides to the joined form.
+ """
+ new_refs, new_preds = [], []
+ for ref_text, pred_text in zip(refs, preds):
+ ref_words = ref_text.split()
+ pred_words = pred_text.split()
+
+ sm = SequenceMatcher(None, ref_words, pred_words)
+ new_rw, new_pw = [], []
+
+ for tag, i1, i2, j1, j2 in sm.get_opcodes():
+ if tag == "equal":
+ new_rw.extend(ref_words[i1:i2])
+ new_pw.extend(pred_words[j1:j2])
+ else:
+ rc = "".join(ref_words[i1:i2])
+ pc = "".join(pred_words[j1:j2])
+ if rc == pc:
+ new_rw.append(rc)
+ new_pw.append(pc)
+ else:
+ new_rw.extend(ref_words[i1:i2])
+ new_pw.extend(pred_words[j1:j2])
+
+ new_refs.append(" ".join(new_rw))
+ new_preds.append(" ".join(new_pw))
+ return new_refs, new_preds
+
+
+def read_manifest(manifest_path: str):
+ """
+ Reads a manifest file (jsonl format) and returns a list of dictionaries containing samples.
+ """
+ data = []
+ with open(manifest_path, "r", encoding="utf-8") as f:
+ for line in f:
+ if len(line) > 0:
+ datum = json.loads(line)
+ data.append(datum)
+ return data
+
+
+# SIM backends that score into their own manifest fork, <manifest>_<backend>.jsonl (keep in sync
+# with `sim_manifest_path` in transformers/score_similarity.py). `xvector` writes `sim` in place.
+SIM_BACKEND_SUFFIXES = ("wavlm_seed_tts",)
+
+
+def score_results(directory: str, model_id: str = None, multilingual: bool = None, csv_only: bool = False, language: str = "en", manifests: list = None, sim_backend: str = "wavlm_seed_tts"):
+ """
+ Scores all result files in a directory and returns a composite score over all evaluated datasets.
+
+ Args:
+ directory: Path to the result directory, containing one or more jsonl files.
+ model_id: Optional, model name to filter out result files based on model name.
+ multilingual: If True, apply compound word boundary normalization before
+ WER computation. Default (None): `default_multilingual(language)`.
+ csv_only: If True, suppress the per-dataset and composite printouts.
+ language: Language code used for normalization (e.g. 'en', 'de', 'fr'). Non-'en' uses
+ ml_normalizer. CJK is scored per character (CER); it is also auto-detected per
+ manifest from the reference text.
+ manifests: Optional list of manifest file names (basenames or paths) to restrict scoring
+ to. `language` applies to every manifest in a call and only CJK is auto-detected,
+ so multi-language folders must be scored one language per call.
+ sim_backend: Which SIM manifest family to score; only one per call, since the SIM scales
+ differ. 'wavlm_seed_tts' prefers each `_wavlm_seed_tts.jsonl` fork, falling back
+ to the plain manifest (WER/RTFx only, SIM suppressed). 'xvector' reads only the
+ plain manifests.
+
+ Returns:
+ Composite score over all evaluated datasets and a dictionary of all results. Each
+ result carries a `metric` field ('WER' or 'CER') saying which error rate `wer` holds.
+ """
+
+ if multilingual is None:
+ multilingual = default_multilingual(language)
+
+ # Strip trailing slash
+ if directory.endswith(os.sep):
+ directory = directory[:-1]
+
+ # Find all result files in the directory
+ result_files = list(glob.glob(f"{directory}/**/*.jsonl", recursive=True))
+ result_files = list(sorted(result_files))
+
+ # Keep exactly one SIM manifest family — see the `sim_backend` arg.
+ def _sim_suffix_of(fp: str):
+ stem = os.path.basename(fp).removesuffix(".jsonl")
+ return next((s for s in SIM_BACKEND_SUFFIXES if stem.endswith(f"_{s}")), None)
+
+ def _canonical(name):
+ """Path with any SIM-backend suffix removed — the identity of a (model, dataset) manifest."""
+ head, base = os.path.split(name)
+ stem = base.removesuffix(".jsonl")
+ suffix = _sim_suffix_of(name)
+ return os.path.join(head, (stem.removesuffix(f"_{suffix}") if suffix else stem) + ".jsonl")
+
+ # Reject unknown names rather than silently reporting the other SIM scale ($SIM_BACKEND is
+ # otherwise unvalidated).
+ if sim_backend not in ("xvector",) + SIM_BACKEND_SUFFIXES:
+ raise ValueError(
+ f"Unknown sim_backend {sim_backend!r}; expected 'xvector' or one of {list(SIM_BACKEND_SUFFIXES)}."
+ )
+
+ # Files kept for WER/RTFx whose `sim` is on a different backend's scale and must not be reported.
+ sim_unavailable = set()
+ if sim_backend in SIM_BACKEND_SUFFIXES:
+ # One file per (model, dataset): the requested fork if present, else the plain manifest
+ # (e.g. fixed-voice models, which have no SIM stage).
+ by_canonical = defaultdict(dict)
+ for fp in result_files:
+ by_canonical[_canonical(fp)][_sim_suffix_of(fp)] = fp
+ chosen = []
+ for variants in by_canonical.values():
+ if sim_backend in variants:
+ chosen.append(variants[sim_backend])
+ elif None in variants:
+ chosen.append(variants[None])
+ sim_unavailable.add(variants[None])
+ result_files = sorted(chosen)
+ else:
+ result_files = [fp for fp in result_files if _sim_suffix_of(fp) is None]
+
+ # Filter files belonging to a specific model id
+ if model_id is not None and model_id != "":
+ print("Filtering models by id:", model_id)
+ model_id = model_id.replace("/", "-")
+ result_files = [
+ fp for fp in result_files
+ if f"/{model_id}/" in fp or f"MODEL_{model_id}_DATASET_" in fp
+ ]
+
+ # Compared by basename with any SIM-backend suffix stripped from both sides, so callers can
+ # name the plain manifests whichever SIM family is scored.
+ if manifests:
+ wanted = {os.path.basename(_canonical(m)) for m in manifests}
+ result_files = [fp for fp in result_files if os.path.basename(_canonical(fp)) in wanted]
+
+ # Check if any result files were found
+ if len(result_files) == 0:
+ raise ValueError(f"No result files found in {directory}")
+
+ # Utility function to parse the file path and extract model id, dataset path, dataset name and split
+ def parse_filepath(fp: str):
+ model_index = fp.find("MODEL_")
+ fp = fp[model_index:]
+ ds_index = fp.find("DATASET_")
+ model_id = fp[:ds_index].replace("MODEL_", "").rstrip("_")
+ author_index = model_id.find("-")
+ model_id = model_id[:author_index] + "/" + model_id[author_index + 1 :]
+
+ ds_fp = fp[ds_index:]
+ dataset_id = ds_fp.replace("DATASET_", "").removesuffix(".jsonl")
+ # Drop the SIM-backend suffix so dataset ids are the same whichever family is scored.
+ for suffix in SIM_BACKEND_SUFFIXES:
+ dataset_id = dataset_id.removesuffix(f"_{suffix}")
+ return model_id, dataset_id
+
+ # Compute WER results per dataset, and RTFx over all datasets
+ from normalizer import data_utils
+ results = {}
+ stale_sim_files = [] # (basename, sim_model) for manifests whose SIM was on the other scale
+
+ for result_file in result_files:
+ manifest = read_manifest(result_file)
+ model_id_of_file, dataset_id = parse_filepath(result_file)
+
+ raw_references = [datum["text"] for datum in manifest]
+ raw_predictions = [datum["pred_text"] for datum in manifest]
+
+ # CJK is scored per character (CER); detected from `language` or the reference text.
+ use_cer = is_cjk_language(language) or _is_mostly_cjk(raw_references)
+
+ if use_cer:
+ # `language` also gates the Chinese-only folds.
+ normalize = lambda t: cjk_normalizer(t, language=language)
+ elif language == "en":
+ normalize = data_utils.normalizer
+ else:
+ normalize = lambda t: data_utils.ml_normalizer(t, lang=language)
+ references = [normalize(t) for t in raw_references]
+ predictions = [normalize(t) for t in raw_predictions]
+
+ time = [datum["time"] for datum in manifest]
+ duration = [datum["duration"] for datum in manifest]
+ compute_rtfx = all(time) and all(duration)
+
+ # SIM is optional (voice-cloning backends only); averaged over rows that have it. Files in
+ # `sim_unavailable` carry another backend's scale, so no SIM is reported for them.
+ if result_file in sim_unavailable:
+ sims = []
+ if any(isinstance(datum.get("sim"), (int, float)) for datum in manifest):
+ stale_sim_files.append((os.path.basename(result_file), manifest[0].get("sim_model")))
+ else:
+ sims = [datum["sim"] for datum in manifest if isinstance(datum.get("sim"), (int, float))]
+ sim = round(100 * sum(sims) / len(sims), 2) if sims else None
+
+ if use_cer:
+ # Per-character alignment (merge_compounds is moot). The headline CJK number is the
+ # lenient CER (homophone + numeral folds), always <= the unnormalized CER.
+ _lenient = lambda t: cjk_normalizer(t, fold_homophones=True, fold_numerals=True, language=language)
+ folded = batch_error_rate(
+ [tuple(_lenient(t)) for t in raw_references],
+ [tuple(_lenient(t)) for t in raw_predictions],
+ merge_compounds=False,
+ )
+ total_ins, total_del, total_sub = folded["ins"], folded["del"], folded["sub"]
+ wer = folded["err_rate"]
+
+ # Unnormalized CER, directly comparable with seed-tts-eval's run_wer.py.
+ r = batch_error_rate(
+ [tuple(ref) for ref in references],
+ [tuple(pred) for pred in predictions],
+ merge_compounds=False,
+ )
+ cer_unnormalized = round(100 * r["err_rate"], 2)
+ else:
+ cer_unnormalized = None
+ # Hyphens are inaudible: fold them to whitespace on both sides. ml_normalizer keeps
+ # them, and num2words hyphenates e.g. French numerals ("dix-sept").
+ references = [r.replace("-", " ") for r in references]
+ predictions = [p.replace("-", " ") for p in predictions]
+ if multilingual:
+ # Pre-fold compound boundaries (e.g. German compounds); complements merge_compounds
+ # below, which also catches split compounds adjacent to other errors.
+ references, predictions = normalize_compound_pairs(references, predictions)
+ # Use kaldialign batch_error_rate with merge_compounds=True so that
+ # split compounds (e.g. "white paper" vs "whitepaper") count as
+ # 0 errors in either direction.
+ refs_split = [tuple(r.split()) for r in references]
+ preds_split = [tuple(p.split()) for p in predictions]
+ r = batch_error_rate(refs_split, preds_split, merge_compounds=True)
+ total_ins, total_del, total_sub = r["ins"], r["del"], r["sub"]
+ wer = r["err_rate"]
+
+ wer = round(100 * wer, 2)
+
+ if compute_rtfx:
+ audio_length = sum(duration)
+ inference_time = sum(time)
+ rtfx = round(audio_length / inference_time, 4)
+ else:
+ audio_length = inference_time = rtfx = None
+
+ result_key = f"{model_id_of_file} | {dataset_id}"
+ extra = {"ins": total_ins, "del": total_del, "sub": total_sub}
+ # `wer` holds the headline error rate; `metric` says whether it is a WER or a CER. For CJK
+ # it is the lenient CER, with `cer_unnormalized` the seed-tts-eval-comparable number.
+ results[result_key] = {"wer": wer, "metric": "CER" if use_cer else "WER", "cer_unnormalized": cer_unnormalized, "audio_length": audio_length, "inference_time": inference_time, "rtfx": rtfx, "sim": sim, **extra}
+
+ # Name the manifests whose SIM was dropped, even under csv_only, so a blank SIM is explained.
+ if stale_sim_files:
+ print(
+ f"NOTE: {len(stale_sim_files)} manifest(s) have a SIM from a different backend, so no SIM "
+ f"is reported for them. Re-run the SIM stage with --sim_backend={sim_backend}:"
+ )
+ for name, was in sorted(stale_sim_files):
+ print(f" {name} (scored by: {was or 'unknown'})")
+
+ if not csv_only:
+ print("*" * 80)
+ print("Results per dataset:")
+ print("*" * 80)
+
+ for k, v in results.items():
+ metrics = f"{k}: {v['metric']} = {v['wer']:0.2f} %"
+ if v.get("cer_unnormalized") is not None:
+ metrics += f" (unnormalized {v['cer_unnormalized']:0.2f} %)"
+ if v["rtfx"] is not None:
+ metrics += f", RTFx = {v['rtfx']:0.2f}"
+ if v.get("sim") is not None:
+ metrics += f", SIM = {v['sim']:0.2f} %"
+ print(metrics)
+
+ # composite WER should be computed over all datasets and with the same key
+ composite_wer = defaultdict(float)
+ composite_audio_length = defaultdict(float)
+ composite_inference_time = defaultdict(float)
+ composite_sim = defaultdict(float)
+ count_sim_entries = defaultdict(int)
+ count_entries = defaultdict(int)
+ composite_metrics = defaultdict(set)
+ for k, v in results.items():
+ key = k.split("|")[0].strip()
+ composite_metrics[key].add(v["metric"])
+ composite_wer[key] += v["wer"]
+ # Composite RTFx pools only the datasets that have timings.
+ if v["rtfx"] is not None:
+ composite_audio_length[key] += v["audio_length"]
+ composite_inference_time[key] += v["inference_time"]
+ if v.get("sim") is not None:
+ composite_sim[key] += v["sim"]
+ count_sim_entries[key] += 1
+ count_entries[key] += 1
+
+ # normalize scores & print
+ if not csv_only:
+ print()
+ print("*" * 80)
+ print("Composite Results:")
+ print("*" * 80)
+ for k, v in composite_wer.items():
+ wer = v / count_entries[k]
+ # Label mixed WER/CER averages as such.
+ label = "/".join(sorted(composite_metrics[k]))
+ print(f"{k}: {label} = {wer:0.2f} %")
+ for k in composite_audio_length:
+ rtfx = composite_audio_length[k] / composite_inference_time[k]
+ print(f"{k}: RTFx = {rtfx:0.2f}")
+ for k in composite_sim:
+ sim = composite_sim[k] / count_sim_entries[k]
+ print(f"{k}: SIM = {sim:0.2f} %")
+ print("*" * 80)
+
+ return composite_wer, results
diff --git a/normalizer/normalizer.py b/normalizer/normalizer.py
new file mode 100644
index 0000000..ea0ce41
--- /dev/null
+++ b/normalizer/normalizer.py
@@ -0,0 +1,656 @@
+# Copyright 2026 The OpenAI team and The HuggingFace Team. All rights reserved.
+# Most of the code is copy pasted from the original whisper repository
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import re
+import unicodedata
+from fractions import Fraction
+from typing import Iterator, List, Match, Optional, Union
+from .english_abbreviations import english_name_normalizer, english_spelling_normalizer, english_compound_normalizer
+
+
+# non-ASCII letters that are not separated by "NFKD" normalization
+ADDITIONAL_DIACRITICS = {
+ "œ": "oe",
+ "Œ": "OE",
+ "ø": "o",
+ "Ø": "O",
+ "æ": "ae",
+ "Æ": "AE",
+ "ß": "ss",
+ "ẞ": "SS",
+ "đ": "d",
+ "Đ": "D",
+ "ð": "d",
+ "Ð": "D",
+ "þ": "th",
+ "Þ": "th",
+ "ł": "l",
+ "Ł": "L",
+}
+
+
+def remove_symbols_and_diacritics(s: str, keep=""):
+ """
+ Replace any other markers, symbols, and punctuations with a space, and drop any diacritics (category 'Mn' and some
+ manual mappings)
+ """
+
+ def replace_character(char):
+ if char in keep:
+ return char
+ elif char in ADDITIONAL_DIACRITICS:
+ return ADDITIONAL_DIACRITICS[char]
+
+ elif unicodedata.category(char) == "Mn":
+ return ""
+
+ elif unicodedata.category(char)[0] in "MSP":
+ return " "
+
+ return char
+
+ return "".join(replace_character(c) for c in unicodedata.normalize("NFKD", s))
+
+
+def remove_symbols(s: str):
+ """
+ Replace any other markers, symbols, punctuations with a space, keeping diacritics
+ """
+ return "".join(" " if unicodedata.category(c)[0] in "MSP" else c for c in unicodedata.normalize("NFKC", s))
+
+
+class BasicMultilingualTextNormalizer:
+ def __init__(self, remove_diacritics: bool = True):
+ self.clean = remove_symbols_and_diacritics if remove_diacritics else remove_symbols
+
+ def __call__(self, s: str):
+ s = s.lower()
+ s = re.sub(r"[<\[][^>\]]*[>\]]", "", s) # remove words between brackets
+ s = re.sub(r"\(([^)]+?)\)", "", s) # remove words between parenthesis
+ s = self.clean(s).lower()
+
+ # Remove punctuations and extra spaces
+ s = re.sub(r"[^\w\s]", "", s)
+ s = re.sub(r"\s+", " ", s).strip()
+
+ return s
+
+
+class EnglishNumberNormalizer:
+ """
+ Convert any spelled-out numbers into arabic numbers, while handling:
+
+ - remove any commas
+ - keep the suffixes such as: `1960s`, `274th`, `32nd`, etc.
+ - spell out currency symbols after the number. e.g. `$20 million` -> `20000000 dollars`
+ - spell out `one` and `ones`
+ - interpret successive single-digit numbers as nominal: `one oh one` -> `101`
+ """
+
+ def __init__(self):
+ super().__init__()
+
+ self.zeros = {"o", "oh", "zero"}
+ # fmt: off
+ self.ones = {
+ name: i
+ for i, name in enumerate(
+ ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"],
+ start=1,
+ )
+ }
+ # fmt: on
+ self.ones_plural = {
+ "sixes" if name == "six" else name + "s": (value, "s") for name, value in self.ones.items()
+ }
+ self.ones_ordinal = {
+ "zeroth": (0, "th"),
+ "first": (1, "st"),
+ "second": (2, "nd"),
+ "third": (3, "rd"),
+ "fifth": (5, "th"),
+ "twelfth": (12, "th"),
+ **{
+ name + ("h" if name.endswith("t") else "th"): (value, "th")
+ for name, value in self.ones.items()
+ if value > 3 and value != 5 and value != 12
+ },
+ }
+ self.ones_suffixed = {**self.ones_plural, **self.ones_ordinal}
+
+ self.tens = {
+ "twenty": 20,
+ "thirty": 30,
+ "forty": 40,
+ "fifty": 50,
+ "sixty": 60,
+ "seventy": 70,
+ "eighty": 80,
+ "ninety": 90,
+ }
+ self.tens_plural = {name.replace("y", "ies"): (value, "s") for name, value in self.tens.items()}
+ self.tens_ordinal = {name.replace("y", "ieth"): (value, "th") for name, value in self.tens.items()}
+ self.tens_suffixed = {**self.tens_plural, **self.tens_ordinal}
+
+ self.multipliers = {
+ "hundred": 100,
+ "thousand": 1_000,
+ "million": 1_000_000,
+ "billion": 1_000_000_000,
+ "trillion": 1_000_000_000_000,
+ "quadrillion": 1_000_000_000_000_000,
+ "quintillion": 1_000_000_000_000_000_000,
+ "sextillion": 1_000_000_000_000_000_000_000,
+ "septillion": 1_000_000_000_000_000_000_000_000,
+ "octillion": 1_000_000_000_000_000_000_000_000_000,
+ "nonillion": 1_000_000_000_000_000_000_000_000_000_000,
+ "decillion": 1_000_000_000_000_000_000_000_000_000_000_000,
+ }
+ self.multipliers_plural = {name + "s": (value, "s") for name, value in self.multipliers.items()}
+ self.multipliers_ordinal = {name + "th": (value, "th") for name, value in self.multipliers.items()}
+ self.multipliers_suffixed = {**self.multipliers_plural, **self.multipliers_ordinal}
+ self.decimals = {*self.ones, *self.tens, *self.zeros}
+
+ self.preceding_prefixers = {
+ "minus": "-",
+ "negative": "-",
+ "plus": "+",
+ "positive": "+",
+ }
+ self.following_prefixers = {
+ "pound": "£",
+ "pounds": "£",
+ "euro": "€",
+ "euros": "€",
+ "dollar": "$",
+ "dollars": "$",
+ "cent": "¢",
+ "cents": "¢",
+ }
+ self.prefixes = set(list(self.preceding_prefixers.values()) + list(self.following_prefixers.values()))
+ self.suffixers = {
+ "per": {"cent": "%"},
+ "percent": "%",
+ }
+ self.specials = {"and", "double", "triple", "point"}
+
+ self.words = {
+ key
+ for mapping in [
+ self.zeros,
+ self.ones,
+ self.ones_suffixed,
+ self.tens,
+ self.tens_suffixed,
+ self.multipliers,
+ self.multipliers_suffixed,
+ self.preceding_prefixers,
+ self.following_prefixers,
+ self.suffixers,
+ self.specials,
+ ]
+ for key in mapping
+ }
+ self.literal_words = {"one", "ones"}
+
+ def process_words(self, words: List[str]) -> Iterator[str]:
+ prefix: Optional[str] = None
+ value: Optional[Union[str, int]] = None
+ skip = False
+
+ def to_fraction(s: str):
+ try:
+ return Fraction(s)
+ except ValueError:
+ return None
+
+ def output(result: Union[str, int]):
+ nonlocal prefix, value
+ result = str(result)
+ if prefix is not None:
+ result = prefix + result
+ value = None
+ prefix = None
+ return result
+
+ if len(words) == 0:
+ return
+
+ for i, current in enumerate(words):
+ prev = words[i - 1] if i != 0 else None
+ next = words[i + 1] if i != len(words) - 1 else None
+ if skip:
+ skip = False
+ continue
+
+ next_is_numeric = next is not None and re.match(r"^\d+(\.\d+)?$", next)
+ has_prefix = current[0] in self.prefixes
+ current_without_prefix = current[1:] if has_prefix else current
+ if re.match(r"^\d+(\.\d+)?$", current_without_prefix):
+ # arabic numbers (potentially with signs and fractions)
+ f = to_fraction(current_without_prefix)
+ if f is None:
+ raise ValueError("Converting the fraction failed")
+
+ if value is not None:
+ if isinstance(value, str) and value.endswith("."):
+ # concatenate decimals / ip address components
+ value = str(value) + str(current)
+ continue
+ else:
+ yield output(value)
+
+ prefix = current[0] if has_prefix else prefix
+ if f.denominator == 1:
+ value = f.numerator # store integers as int
+ else:
+ value = current_without_prefix
+ elif current not in self.words:
+ # non-numeric words
+ if value is not None:
+ yield output(value)
+ yield output(current)
+ elif current in self.zeros:
+ value = str(value or "") + "0"
+ elif current in self.ones:
+ ones = self.ones[current]
+
+ if value is None:
+ value = ones
+ elif isinstance(value, str) or prev in self.ones:
+ if prev in self.tens and ones < 10: # replace the last zero with the digit
+ value = value[:-1] + str(ones)
+ else:
+ value = str(value) + str(ones)
+ elif ones < 10:
+ if value % 10 == 0:
+ value += ones
+ else:
+ value = str(value) + str(ones)
+ else: # eleven to nineteen
+ if value % 100 == 0:
+ value += ones
+ else:
+ value = str(value) + str(ones)
+ elif current in self.ones_suffixed:
+ # ordinal or cardinal; yield the number right away
+ ones, suffix = self.ones_suffixed[current]
+ if value is None:
+ yield output(str(ones) + suffix)
+ elif isinstance(value, str) or prev in self.ones:
+ if prev in self.tens and ones < 10:
+ yield output(value[:-1] + str(ones) + suffix)
+ else:
+ yield output(str(value) + str(ones) + suffix)
+ elif ones < 10:
+ if value % 10 == 0:
+ yield output(str(value + ones) + suffix)
+ else:
+ yield output(str(value) + str(ones) + suffix)
+ else: # eleven to nineteen
+ if value % 100 == 0:
+ yield output(str(value + ones) + suffix)
+ else:
+ yield output(str(value) + str(ones) + suffix)
+ value = None
+ elif current in self.tens:
+ tens = self.tens[current]
+ if value is None:
+ value = tens
+ elif isinstance(value, str):
+ value = str(value) + str(tens)
+ else:
+ if value % 100 == 0:
+ value += tens
+ else:
+ value = str(value) + str(tens)
+ elif current in self.tens_suffixed:
+ # ordinal or cardinal; yield the number right away
+ tens, suffix = self.tens_suffixed[current]
+ if value is None:
+ yield output(str(tens) + suffix)
+ elif isinstance(value, str):
+ yield output(str(value) + str(tens) + suffix)
+ else:
+ if value % 100 == 0:
+ yield output(str(value + tens) + suffix)
+ else:
+ yield output(str(value) + str(tens) + suffix)
+ elif current in self.multipliers:
+ multiplier = self.multipliers[current]
+ if value is None:
+ value = multiplier
+ elif isinstance(value, str) or value == 0:
+ f = to_fraction(value)
+ p = f * multiplier if f is not None else None
+ if f is not None and p.denominator == 1:
+ value = p.numerator
+ else:
+ yield output(value)
+ value = multiplier
+ else:
+ before = value // 1000 * 1000
+ residual = value % 1000
+ value = before + residual * multiplier
+ elif current in self.multipliers_suffixed:
+ multiplier, suffix = self.multipliers_suffixed[current]
+ if value is None:
+ yield output(str(multiplier) + suffix)
+ elif isinstance(value, str):
+ f = to_fraction(value)
+ p = f * multiplier if f is not None else None
+ if f is not None and p.denominator == 1:
+ yield output(str(p.numerator) + suffix)
+ else:
+ yield output(value)
+ yield output(str(multiplier) + suffix)
+ else: # int
+ before = value // 1000 * 1000
+ residual = value % 1000
+ value = before + residual * multiplier
+ yield output(str(value) + suffix)
+ value = None
+ elif current in self.preceding_prefixers:
+ # apply prefix (positive, minus, etc.) if it precedes a number
+ if value is not None:
+ yield output(value)
+
+ if next in self.words or next_is_numeric:
+ prefix = self.preceding_prefixers[current]
+ else:
+ yield output(current)
+ elif current in self.following_prefixers:
+ # apply prefix (dollars, cents, etc.) only after a number
+ if value is not None:
+ prefix = self.following_prefixers[current]
+ yield output(value)
+ else:
+ yield output(current)
+ elif current in self.suffixers:
+ # apply suffix symbols (percent -> '%')
+ if value is not None:
+ suffix = self.suffixers[current]
+ if isinstance(suffix, dict):
+ if next in suffix:
+ yield output(str(value) + suffix[next])
+ skip = True
+ else:
+ yield output(value)
+ yield output(current)
+ else:
+ yield output(str(value) + suffix)
+ else:
+ yield output(current)
+ elif current in self.specials:
+ if next not in self.words and not next_is_numeric:
+ # apply special handling only if the next word can be numeric
+ if value is not None:
+ yield output(value)
+ yield output(current)
+ elif current == "and":
+ # ignore "and" after hundreds, thousands, etc.
+ if prev not in self.multipliers:
+ if value is not None:
+ yield output(value)
+ yield output(current)
+ elif current == "double" or current == "triple":
+ if next in self.ones or next in self.zeros:
+ repeats = 2 if current == "double" else 3
+ ones = self.ones.get(next, 0)
+ value = str(value or "") + str(ones) * repeats
+ skip = True
+ else:
+ if value is not None:
+ yield output(value)
+ yield output(current)
+ elif current == "point":
+ if next in self.decimals or next_is_numeric:
+ value = str(value or "") + "."
+ else:
+ # should all have been covered at this point
+ raise ValueError(f"Unexpected token: {current}")
+ else:
+ # all should have been covered at this point
+ raise ValueError(f"Unexpected token: {current}")
+
+ if value is not None:
+ yield output(value)
+
+ def preprocess(self, s: str):
+ # replace "<number> and a half" with "<number> point five"
+ results = []
+
+ segments = re.split(r"\band\s+a\s+half\b", s)
+ for i, segment in enumerate(segments):
+ if len(segment.strip()) == 0:
+ continue
+ if i == len(segments) - 1:
+ results.append(segment)
+ else:
+ results.append(segment)
+ last_word = segment.rsplit(maxsplit=2)[-1]
+ if last_word in self.decimals or last_word in self.multipliers:
+ results.append("point five")
+ else:
+ results.append("and a half")
+
+ s = " ".join(results)
+
+ # put a space at number/letter boundary
+ s = re.sub(r"([a-z])([0-9])", r"\1 \2", s)
+ s = re.sub(r"([0-9])([a-z])", r"\1 \2", s)
+
+ # but remove spaces which could be a suffix
+ s = re.sub(r"([0-9])\s+(st|nd|rd|th|s)\b", r"\1\2", s)
+
+ return s
+
+ def postprocess(self, s: str):
+ def combine_cents(m: Match):
+ try:
+ currency = m.group(1)
+ integer = m.group(2)
+ cents = int(m.group(3))
+ return f"{currency}{integer}.{cents:02d}"
+ except ValueError:
+ return m.string
+
+ def extract_cents(m: Match):
+ try:
+ return f"¢{int(m.group(1))}"
+ except ValueError:
+ return m.string
+
+ # apply currency postprocessing; "$2 and ¢7" -> "$2.07"
+ s = re.sub(r"([€£$])([0-9]+) (?:and )?¢([0-9]{1,2})\b", combine_cents, s)
+ s = re.sub(r"[€£$]0.([0-9]{1,2})\b", extract_cents, s)
+
+ # write "one(s)" instead of "1(s)", just for the readability
+ s = re.sub(r"\b1(s?)\b", r"one\1", s)
+
+ return s
+
+ def __call__(self, s: str):
+ s = self.preprocess(s)
+ s = " ".join(word for word in self.process_words(s.split()) if word is not None)
+ s = self.postprocess(s)
+
+ return s
+
+
+class EnglishSpellingNormalizer:
+ """
+ Applies British-American spelling mappings as listed in [1].
+
+ [1] https://www.tysto.com/uk-us-spelling-list.html
+ """
+
+ def __init__(self, english_spelling_mapping):
+ self.mapping = english_spelling_mapping
+
+ def __call__(self, s: str):
+ return " ".join(self.mapping.get(word, word) for word in s.split())
+
+
+class EnglishAcronymNormalizer:
+ """
+ Collapse sequences of single-character tokens (letters or digits) into single words.
+
+ This normalizes acronym spacing so that both spaced-out and joined forms match:
+ - "b b c" -> "bbc"
+ - "5 g" -> "5g"
+
+ Lone single-character words surrounded by multi-character words are left untouched
+ (e.g. "a big cat" stays "a big cat").
+ """
+
+ def __call__(self, s: str) -> str:
+ words = s.split()
+ result = []
+ i = 0
+ while i < len(words):
+ if len(words[i]) == 1 and words[i].isalnum():
+ # Start of a potential acronym run
+ run = [words[i]]
+ j = i + 1
+ while j < len(words) and len(words[j]) == 1 and words[j].isalnum():
+ run.append(words[j])
+ j += 1
+ # Require 3+ tokens if the run contains common words "a" or "i",
+ # otherwise 2+ is enough (e.g. "5 g" -> "5g")
+ has_common_word = any(c in ("a", "i") for c in run)
+ min_run = 3 if has_common_word else 2
+ if len(run) >= min_run:
+ result.append("".join(run))
+ else:
+ result.extend(run)
+ i = j
+ else:
+ result.append(words[i])
+ i += 1
+ return " ".join(result)
+
+
+class EnglishNameNormalizer:
+ """
+ Collapse common name spelling variants to a single canonical form.
+
+ This is intentionally conservative and token-based so it can be extended
+ with project-specific aliases when needed.
+ """
+
+ def __init__(self, english_name_mapping=english_name_normalizer):
+ self.mapping = english_name_mapping
+
+ def __call__(self, s: str):
+ return " ".join(self.mapping.get(word, word) for word in s.split())
+
+
+class EnglishTextNormalizer:
+ def __init__(self, english_spelling_mapping=english_spelling_normalizer):
+ self.ignore_patterns = r"\b(hmm|mm|mhm|mmm|uh|um|ah|aha|ahh|ahm|eh|ehehe|em|hm|huh|hum|mhum|uhm|umm|uhuh)\b"
+ self.replacers = {
+ # common contractions
+ r"\bwon't\b": "will not",
+ r"\bcan't\b": "can not",
+ r"\blet's\b": "let us",
+ r"\bain't\b": "aint",
+ r"\by'all\b": "you all",
+ r"\bwanna\b": "want to",
+ r"\bgotta\b": "got to",
+ r"\bgonna\b": "going to",
+ r"\bi'ma\b": "i am going to",
+ r"\bimma\b": "i am going to",
+ r"\bwoulda\b": "would have",
+ r"\bcoulda\b": "could have",
+ r"\bshoulda\b": "should have",
+ r"\bma'am\b": "madam",
+ # contractions in titles/prefixes
+ r"\bmr\b": "mister ",
+ r"\bmrs\b": "missus ",
+ r"\bst\b": "saint ",
+ r"\bdr\b": "doctor ",
+ r"\bprof\b": "professor ",
+ r"\bcapt\b": "captain ",
+ r"\bgov\b": "governor ",
+ r"\bald\b": "alderman ",
+ r"\bgen\b": "general ",
+ r"\bsen\b": "senator ",
+ r"\brep\b": "representative ",
+ r"\bpres\b": "president ",
+ r"\brev\b": "reverend ",
+ r"\bhon\b": "honorable ",
+ r"\basst\b": "assistant ",
+ r"\bassoc\b": "associate ",
+ r"\blt\b": "lieutenant ",
+ r"\bcol\b": "colonel ",
+ r"\bjr\b": "junior ",
+ r"\bsr\b": "senior ",
+ r"\besq\b": "esquire ",
+ # prefect tenses, ideally it should be any past participles, but it's harder..
+ r"'d been\b": " had been",
+ r"'s been\b": " has been",
+ r"'d gone\b": " had gone",
+ r"'s gone\b": " has gone",
+ r"'d done\b": " had done", # "'s done" is ambiguous
+ r"'s got\b": " has got",
+ # general contractions
+ r"n't\b": " not",
+ r"'re\b": " are",
+ r"\b(it|he|she|what|that|who|here|there|how|when|where|why|this)'s\b": r"\1 is",
+ r"'d\b": " would",
+ r"'ll\b": " will",
+ r"'t\b": " not",
+ r"'ve\b": " have",
+ r"'m\b": " am",
+ }
+ self.standardize_numbers = EnglishNumberNormalizer()
+ self.standardize_spellings = EnglishSpellingNormalizer(english_spelling_mapping)
+ self.standardize_names = EnglishNameNormalizer()
+ self.standardize_acronyms = EnglishAcronymNormalizer()
+ # Multi-word compound mappings — defined in english_abbreviations.py
+ self.compound_words = english_compound_normalizer
+
+ def __call__(self, s: str):
+ s = s.lower()
+
+ s = re.sub(r"[<\[][^>\]]*[>\]]", "", s) # remove words between brackets
+ s = re.sub(r"\(([^)]+?)\)", "", s) # remove words between parenthesis
+ s = re.sub(self.ignore_patterns, "", s)
+ s = re.sub(r"\s+'", "'", s) # standardize when there's a space before an apostrophe
+
+ for pattern, replacement in self.replacers.items():
+ s = re.sub(pattern, replacement, s)
+
+ s = re.sub(r"(\d),(\d)", r"\1\2", s) # remove commas between digits
+ s = re.sub(r"\.([^0-9]|$)", r" \1", s) # remove periods not followed by numbers
+ s = remove_symbols_and_diacritics(s, keep=".%$¢€£") # keep some symbols for numerics
+
+ # Normalize hardcoded compound words (e.g. "wi fi" -> "wifi" after hyphen removal)
+ for pattern, replacement in self.compound_words.items():
+ s = re.sub(pattern, replacement, s)
+
+ s = self.standardize_numbers(s)
+ s = self.standardize_spellings(s)
+ s = self.standardize_names(s)
+ s = self.standardize_acronyms(s)
+
+ # now remove prefix/suffix symbols that are not preceded/followed by numbers
+ s = re.sub(r"[.$¢€£]([^0-9])", r" \1", s)
+ s = re.sub(r"([^0-9])%", r"\1 ", s)
+
+ s = re.sub(r"\s+", " ", s) # replace any successive whitespace characters with a space
+
+ return s
diff --git a/omnivoice/run_eval.py b/omnivoice/run_eval.py
new file mode 100644
index 0000000..d9c300a
--- /dev/null
+++ b/omnivoice/run_eval.py
@@ -0,0 +1,208 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (OmniVoice backend, stage 1).
+
+OmniVoice (k2-fsa/OmniVoice) is a ~0.6B diffusion-LM TTS loaded in-process via the
+`omnivoice` package. It supports native batched generation, so texts are synthesized in
+minibatches (the batch call is timed for RTFx).
+
+`--voice_clone` clones each sample's `prompt_audio`/`prompt_text` reference and adds a
+`_voice_clone` suffix to outputs; by default (`--no-voice_clone`) OmniVoice picks its own speaker (no SIM).
+
+Stage 2 (`transformers/transcribe.py`) fills `pred_text` with Qwen3-ASR; stage 3
+(`transformers/score_similarity.py`, voice-clone only) fills `sim`; stage 4
+(`normalizer.eval_utils.score_results`) computes WER + RTFx (+ mean SIM).
+"""
+
+import argparse
+import os
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+from omnivoice import OmniVoice
+
+from run_eval_utils import (
+ add_common_args, load_done_entries, load_tts_dataset, manifest_entry, open_manifest, output_paths,
+ pending_batches, print_model_size, print_next_steps, set_seed, wav_rel_path, warm_up, write_entry,
+)
+
+torch.set_float32_matmul_precision("high")
+
+
+def main(args):
+ # Set seed for reproducibility (diffusion sampling).
+ set_seed(args.seed)
+
+ torch_dtype = getattr(torch, args.dtype)
+ model = OmniVoice.from_pretrained(args.model_id, device_map=args.device, dtype=torch_dtype)
+ sampling_rate = int(model.sampling_rate) # 24000
+ print(f"Loaded OmniVoice ({args.model_id}, sr={sampling_rate})")
+ if isinstance(model, torch.nn.Module):
+ print_model_size(model)
+
+ # Layout: results/<model_safe>/{manifest.jsonl, <dsid>/output_<id>.wav}; manifest paths are
+ # relative to model_dir.
+ # Keep the two modes' audio separate so voice-clone and auto-voice runs don't overwrite.
+ mode_suffix = "_voice_clone" if args.voice_clone else ""
+ paths = output_paths(args, mode_suffix)
+ model_dir, dataset_dir_name, output_dir = paths.model_dir, paths.dataset_dir_name, paths.output_dir
+
+ # Zero-shot voice cloning references (prompt_audio) are written here as wavs so
+ # `generate()` can take them as file paths and so stage 3 can score similarity.
+ if args.voice_clone:
+ os.makedirs(os.path.join(output_dir, "prompts"), exist_ok=True)
+
+ def generate_tts(texts, ids, prompt_audios, prompt_texts):
+ """Synthesize a batch of texts (optionally from cloning refs); time it for RTFx.
+
+ Returns manifest-ready paths (relative to model_dir) for the generated wavs and the
+ cloning prompts; the full on-disk paths are only used for I/O and for OmniVoice's
+ `ref_audio`, which needs a real readable path.
+ """
+ minibatch_size = len(texts)
+
+ # Write the cloning prompts to wavs BEFORE timing (I/O is not generation).
+ prompt_rel_paths, prompt_full_paths = [], []
+ if args.voice_clone:
+ for sample_id, prompt_audio in zip(ids, prompt_audios):
+ prel = os.path.join(dataset_dir_name, "prompts", f"prompt_{sample_id}.wav")
+ ppath = os.path.join(model_dir, prel)
+ if not os.path.exists(ppath):
+ sf.write(ppath, np.asarray(prompt_audio["array"], dtype=np.float32), prompt_audio["sampling_rate"])
+ prompt_rel_paths.append(prel)
+ prompt_full_paths.append(ppath)
+ else:
+ prompt_rel_paths = [""] * minibatch_size
+ prompt_full_paths = [""] * minibatch_size
+
+ # START TIMING (TTS batch generation)
+ torch.cuda.synchronize(device=args.device)
+ start_event = torch.cuda.Event(enable_timing=True)
+ end_event = torch.cuda.Event(enable_timing=True)
+ start_event.record()
+
+ # Voice-cloning mode passes per-sample reference audio/text; auto-voice mode lets
+ # OmniVoice pick its own speaker. Returns list[np.ndarray] @ 24kHz.
+ gen_kwargs = dict(
+ text=list(texts),
+ language=[args.language] * minibatch_size,
+ num_step=args.num_step,
+ )
+ if args.voice_clone:
+ gen_kwargs["ref_audio"] = list(prompt_full_paths)
+ gen_kwargs["ref_text"] = list(prompt_texts)
+ audios = model.generate(**gen_kwargs)
+
+ # END TIMING
+ end_event.record()
+ torch.cuda.synchronize(device=args.device)
+ runtime = start_event.elapsed_time(end_event) / 1000.0
+ per_sample_time = runtime / minibatch_size
+
+ gen_paths, audio_length_s = [], []
+ for audio, sample_id in zip(audios, ids):
+ # 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)
+ audio = np.asarray(audio).reshape(-1)
+ sf.write(os.path.join(model_dir, rel_path), audio, sampling_rate)
+ gen_paths.append(rel_path)
+ audio_length_s.append(len(audio) / sampling_rate)
+
+ return gen_paths, prompt_rel_paths, audio_length_s, minibatch_size * [per_sample_time]
+
+ # Keep `id` + the target text; for voice cloning also keep the reference
+ # `prompt_audio`/`prompt_text`. Drop everything else.
+ dataset = load_tts_dataset(args, ("prompt_text", "prompt_audio") if args.voice_clone else ())
+
+ probe_out_dir = model_dir # real results dir, captured before the probe rebinds model_dir
+ # ── TTFA probe: latency only, writing nothing but a JSON sidecar ─────────
+ # TTFA is per-request, so generate_tts() is driven with one-row batches. model_dir and
+ # dataset_dir_name are rebound to a temp dir (generate_tts reads them late-bound), so no
+ # results are touched. No streaming API: `first` is None -> whole-utterance fallback.
+ # 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
+ import tempfile
+
+ model_dir = tempfile.mkdtemp(prefix="ttfa_out_")
+ dataset_dir_name = "ttfa"
+ output_dir = os.path.join(model_dir, dataset_dir_name)
+ os.makedirs(os.path.join(output_dir, "prompts"), exist_ok=True)
+
+ def _gen(job):
+ result = generate_tts(
+ [job[args.text_column][0]], [job["id"][0]],
+ [job["prompt_audio"][0] if args.voice_clone else None],
+ [job["prompt_text"][0] if args.voice_clone else None],
+ )
+ return float(result[-2][0]), None, None
+
+ columns = dataset.column_names
+ jobs = [{c: [dataset[i][c]] for c in columns}
+ for i in sample_indices(args.ttfa_probe, len(dataset))]
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=probe_out_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ extra={"device": args.device, "note": "driven at batch size 1"},
+ )
+ return
+
+ # ── Manifest (written incrementally; resume skips rows already in it) ───
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ def run_batch(batch):
+ n_batch = len(batch["id"])
+ prompt_audios = batch["prompt_audio"] if args.voice_clone else [None] * n_batch
+ prompt_texts = list(batch["prompt_text"]) if args.voice_clone else [None] * n_batch
+ return generate_tts(list(batch[args.text_column]), batch["id"], prompt_audios, prompt_texts)
+
+ # ── Main loop: TTS → write JSONL, one batch at a time ───────────────────
+ starts = pending_batches(dataset, args.batch_size, done_entries, dataset_dir_name)
+ warm_up(run_batch, dataset, starts, args.batch_size, args.warmup_steps)
+ for batch_start in tqdm(starts, desc="Generating"):
+ batch = dataset[batch_start : batch_start + args.batch_size]
+ texts = list(batch[args.text_column])
+ gen_paths, prompt_paths, audio_length_s, gen_times = run_batch(batch)
+
+ for afp, ppath, alen, gtime, ref in zip(gen_paths, prompt_paths, audio_length_s, gen_times, texts):
+ entry = manifest_entry(afp, alen, gtime, ref, ppath if args.voice_clone else None)
+ write_entry(manifest_file, entry)
+ manifest_file.flush()
+
+ manifest_file.close()
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(args.voice_clone)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument("--model_id", type=str, default="k2-fsa/OmniVoice", help="OmniVoice model id.")
+ parser.add_argument(
+ "--language",
+ type=str,
+ default="en",
+ help="Language hint: an ISO id ('en', 'zh') or an English language name ('English', "
+ "'Chinese'). NOTE: OmniVoice matches ids case-sensitively and silently falls back to "
+ "language-agnostic generation (slightly worse) on an unrecognized value — so use "
+ "lowercase ids ('zh', not 'ZH' or 'cn').",
+ )
+ parser.add_argument("--num_step", type=int, default=32, help="Diffusion steps (16 = faster, 32 = default).")
+ parser.add_argument("--dtype", type=str, default="bfloat16", help="Model dtype, e.g. 'bfloat16'.")
+ add_common_args(parser, batch_size=16, voice_clone=False)
+
+ 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/omnivoice/submit_jobs.sh b/omnivoice/submit_jobs.sh
new file mode 100644
index 0000000..9745140
--- /dev/null
+++ b/omnivoice/submit_jobs.sh
@@ -0,0 +1,61 @@
+#!/bin/bash
+# HF Jobs TTS eval — OmniVoice backend (generate → transcribe → SIM* → score; *voice-clone only).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["k2-fsa/OmniVoice 32" ...]
+# 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-omnivoice}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-omnivoice/blob/main/Dockerfile)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# VOICE_CLONE=true: zero-shot voice cloning + SIM; false (default) = auto-voice.
+SUPPORTS_VOICE_CLONE=true
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id batch_size". ──
+generate_stage() {
+ local _ BATCH_SIZE
+ read -r _ BATCH_SIZE <<< "${MODEL_CFG}"
+ 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/omnivoice && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --language=${ASR_LANG} \
+ --device=cuda:0 \
+ --batch_size=${BATCH_SIZE} \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} \
+ ${VOICE_CLONE_FLAG} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment) ──
+# Without a 4th field the line uses DEFAULT_DATASET_PATH (bezzam/seed_tts_eval).
+DATASET_CONFIGS=(
+ "tts en en"
+ "tts zh zh"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot fr fr ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot zh zh ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ja ja ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ko ko ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot de de ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot it it ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ru ru ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id batch_size" (CLI args override) ────────────────────────
+MODEL_CONFIGS=(
+ "k2-fsa/OmniVoice 32"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/photon/run_eval.py b/photon/run_eval.py
new file mode 100644
index 0000000..1dd3a61
--- /dev/null
+++ b/photon/run_eval.py
@@ -0,0 +1,243 @@
+"""
+Time-to-first-audio probe for the Open TTS Leaderboard (Moondream Photon backend).
+
+A third-party engine for models the leaderboard already evaluates: Moondream's Photon runtime
+(https://moondream.ai/blog/photon-can-now-speak) serves Qwen/Qwen3-TTS-12Hz-{0.6B,1.7B}-CustomVoice
+and hexgrad/Kokoro-82M from the same checkpoints through its Kestrel engine, streaming audio.
+
+API (moondream>=2.5.0, which pins kestrel==0.8.2):
+
+ with md.photon(model_id, device=...) as voice:
+ stream = voice.synthesize(text=..., voice=..., language=..., stream=True) # Qwen3-TTS
+ stream = voice.synthesize(phonemes=..., voice=..., stream=True) # Kokoro
+ for update in stream: update["audio"], update["sample_rate"] # 24 kHz f32
+
+First audio = first AUDIBLE audio: kestrel's SpeechOnsetTrimmer buffers output until three
+consecutive 10 ms blocks exceed -45 dBFS and drops the leading silence. This clock is stricter than
+other backends' first-chunk-of-anything, and audio_s is slightly shorter.
+
+Kokoro takes phonemes: Photon ships no G2P, so we use kokoro's KPipeline(model=False) (the same
+misaki G2P + chunking as kokoro/run_eval.py). G2P runs inside the timed call, as in kokoro's TTFA,
+and its cost is recorded separately (g2p_ms).
+
+TTFA only: Photon's audio is not what the eval scores, so running without --ttfa_probe is
+refused. Sidecars are engine-tagged "photon" by submit_ttfa_jobs.sh. No voice cloning: only the
+CustomVoice Qwen3-TTS checkpoints and Kokoro voice packs are supported.
+"""
+
+import argparse
+import os
+import time
+
+import numpy as np
+import torch
+
+import moondream as md
+
+from run_eval_utils import add_common_args, load_tts_dataset, set_seed
+
+SAMPLE_RATE = 24_000 # Photon's fixed TTS output rate, for both models
+
+# Kept identical to qwen3tts/run_eval.py: the submit scripts pass ISO codes, Qwen3-TTS wants the
+# English language NAME. Photon casefolds it, so "English" and "english" are the same key.
+LANGUAGE_CODE_TO_NAME = {
+ "zh": "Chinese",
+ "en": "English",
+ "ja": "Japanese",
+ "ko": "Korean",
+ "de": "German",
+ "fr": "French",
+ "ru": "Russian",
+ "pt": "Portuguese",
+ "es": "Spanish",
+ "it": "Italian",
+}
+
+
+def _family(model_id):
+ name = model_id.split("/")[-1].lower()
+ if "kokoro" in name:
+ return "kokoro"
+ if "qwen3-tts" in name:
+ if "customvoice" not in name:
+ raise SystemExit(
+ f"Photon serves only the Qwen3-TTS CustomVoice checkpoints, not {model_id}.\n"
+ "Base (voice-clone) and VoiceDesign variants are not registered in kestrel 0.8.2."
+ )
+ return "qwen3tts"
+ raise SystemExit(f"Unsupported model for the Photon backend: {model_id} "
+ f"(registered: {md.photon_models()})")
+
+
+def main(args):
+ if args.ttfa_probe == 0:
+ raise SystemExit(
+ "This backend is TTFA-only: pass --ttfa_probe=N (or -1 for the whole split).\n"
+ "Photon's kernels and speech-onset trimming mean its audio is not the audio the\n"
+ "leaderboard's WER/RTFx are scored from. Use qwen3tts/ or kokoro/ for those."
+ )
+
+ family = _family(args.model_id)
+ if family == "qwen3tts" and not args.device.startswith("cuda"):
+ # Photon itself raises at engine start, but deeper and less clearly.
+ raise SystemExit(f"Photon runs Qwen3-TTS on CUDA only (got --device={args.device}). "
+ "Kokoro is the Photon model that runs on CPU.")
+
+ seed = args.seed
+ set_seed(seed)
+
+ from importlib.metadata import version
+ versions = {p: version(p) for p in ("moondream", "kestrel", "kestrel-kernels")}
+
+ t0 = time.perf_counter()
+ voice = md.photon(args.model_id, device=args.device)
+ print(f"Loaded {args.model_id} via Photon on {args.device} in {time.perf_counter() - t0:.1f}s "
+ f"({versions})")
+
+ g2p = None
+ if family == "kokoro":
+ # G2P only: model=False builds the misaki pipeline without loading Kokoro's weights, so the
+ # reference model never shares the GPU with Photon's copy.
+ from kokoro import KPipeline
+ g2p = KPipeline(lang_code=args.lang_code, repo_id=args.model_id, model=False)
+
+ g2p_ms = [] # Kokoro only: phonemization time inside each timed call
+ chunk_counts = [] # streamed updates per utterance — see the sidecar note below
+
+ def _request(text):
+ """Build the synthesize() kwargs for one utterance (G2P included for Kokoro)."""
+ if family == "kokoro":
+ t = time.perf_counter()
+ # Same chunking kokoro/run_eval.py gets from KPipeline; Photon re-splits at its own
+ # 510-phoneme limit, so joining the chunks back loses nothing.
+ phonemes = " ".join(r.phonemes for r in g2p(text) if r.phonemes)
+ g2p_ms.append((time.perf_counter() - t) * 1000.0)
+ return dict(phonemes=phonemes, voice=args.voice, speed=args.speed)
+ return dict(
+ text=text, voice=args.voice, language=args.language,
+ settings={
+ "do_sample": args.do_sample, "temperature": args.temperature,
+ "top_k": args.top_k, "top_p": args.top_p,
+ "repetition_penalty": args.repetition_penalty,
+ "max_tokens": args.max_new_tokens,
+ },
+ )
+
+ # Kestrel captures graphs / selects kernels on first use; keep that out of the probe rows.
+ for i in range(args.warmup_steps):
+ t0 = time.perf_counter()
+ voice.synthesize(**_request("Hello there, this is a warm-up sentence for the engine."))
+ print(f"warm-up {i + 1}/{args.warmup_steps}: {time.perf_counter() - t0:.2f}s")
+ g2p_ms.clear()
+
+ model_safe = args.model_id.replace("/", "-")
+ # Not created here: run_probe creates it on write, so a crash leaves no dir and the job fails.
+ out_dir = os.path.join("results", model_safe)
+
+ # Keeps only `id` + the text, so no Audio() column is ever decoded (no torchcodec needed).
+ dataset = load_tts_dataset(args)
+
+ # Imported HERE, not at module scope: the probe module is injected only by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+
+ def _gen(job, early_stop):
+ """One streaming synthesis at batch size 1, timestamping the first yielded update."""
+ torch.manual_seed(seed)
+ first, chunks, sample_rate = None, [], None
+ # Leaving the block closes the stream, which cancels an early-stopped request inside the
+ # engine: TTFA is already known and the rest of the utterance is pure cost.
+ with voice.synthesize(stream=True, **_request(job["text"])) as stream:
+ for update in stream:
+ audio = np.asarray(update["audio"], dtype=np.float32).reshape(-1)
+ if first is None:
+ if not audio.size:
+ continue
+ first = time.perf_counter()
+ sample_rate = update["sample_rate"]
+ chunks.append(audio)
+ if early_stop:
+ break
+ chunk_counts.append(len(chunks))
+ audio = np.concatenate(chunks) if chunks else np.zeros(0, dtype=np.float32)
+ return audio, sample_rate or SAMPLE_RATE, first
+
+ jobs = [{"text": dataset[i][args.text_column]}
+ for i in sample_indices(args.ttfa_probe, len(dataset))]
+
+ extra = {
+ "device": args.device,
+ "note": f"driven at batch size 1, Moondream Photon streaming ({family})",
+ "engine": "photon",
+ "engine_versions": versions,
+ "first_audio": "first audible (onset-trimmed, -45 dBFS x 3x10ms)",
+ # 1 update means nothing was incremental (Kokoro streams per ~510-phoneme segment, so a
+ # short prompt is one segment); many updates arriving late means buffering.
+ "chunks_per_utterance": chunk_counts,
+ "voice": args.voice,
+ }
+ if family == "kokoro":
+ extra.update({
+ "lang_code": args.lang_code, "speed": args.speed,
+ "g2p": "kokoro.KPipeline(model=False) / misaki, timed inside ttfa_ms",
+ "g2p_ms": g2p_ms,
+ })
+ else:
+ extra.update({
+ "language": args.language,
+ "sampling": {"temperature": args.temperature, "top_k": args.top_k, "top_p": args.top_p,
+ "do_sample": args.do_sample, "repetition_penalty": args.repetition_penalty},
+ })
+
+ try:
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=out_dir, n=args.ttfa_probe, extra=extra,
+ )
+ finally:
+ voice.close()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument(
+ "--model_id", type=str, default="Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice",
+ help="Qwen/Qwen3-TTS-12Hz-{0.6B,1.7B}-CustomVoice or hexgrad/Kokoro-82M — the SAME weights "
+ "the qwen3tts/ and kokoro/ backends load.",
+ )
+ parser.add_argument(
+ "--voice", type=str, default=None,
+ help="Qwen3-TTS built-in speaker (default Ryan) or Kokoro voice pack (default af_heart; its "
+ "prefix must match --lang_code).",
+ )
+ parser.add_argument("--language", type=str, default="English",
+ help="Qwen3-TTS only. ISO codes are mapped to the language NAME.")
+ parser.add_argument("--lang_code", type=str, default="a",
+ help="Kokoro only: KPipeline G2P language ('a' = American English).")
+ parser.add_argument("--speed", type=float, default=1.0, help="Kokoro only: speech speed.")
+ # Qwen3-TTS sampling — defaults are kestrel's Qwen3TTSSampling, which match qwen-tts and
+ # faster-qwen3-tts, so the three Qwen3-TTS engines are driven identically.
+ parser.add_argument("--max_new_tokens", type=int, default=2048)
+ parser.add_argument("--temperature", type=float, default=0.9)
+ parser.add_argument("--top_k", type=int, default=50)
+ parser.add_argument("--top_p", type=float, default=1.0)
+ parser.add_argument("--do_sample", action=argparse.BooleanOptionalAction, default=True)
+ parser.add_argument("--repetition_penalty", type=float, default=1.05)
+ # --warmup_steps = untimed synthesize() calls before the probe (Kestrel graph capture / kernel
+ # selection). --ttfa_probe is REQUIRED: this backend does nothing else.
+ add_common_args(parser)
+ parser.set_defaults(dataset_path="bezzam/cv3_eval", dataset="zero_shot")
+
+ args = parser.parse_args()
+ args.language = LANGUAGE_CODE_TO_NAME.get(args.language.lower(), args.language)
+ if args.voice is None:
+ args.voice = "af_heart" if "kokoro" in args.model_id.lower() else "Ryan"
+
+ print("*" * 100)
+ print(f"TTFA probe: {args.model_id} via Moondream Photon on "
+ f"{args.dataset_path} / {args.dataset} / {args.split}")
+ print("*" * 100)
+
+ main(args)
diff --git a/pocket-tts/run_eval.py b/pocket-tts/run_eval.py
new file mode 100644
index 0000000..9ed4d20
--- /dev/null
+++ b/pocket-tts/run_eval.py
@@ -0,0 +1,395 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (Pocket TTS backend, stage 1).
+
+Pocket TTS (kyutai/pocket-tts) is Kyutai's ~110M-parameter CPU-first streaming TTS (flow-matching
+LM over Mimi latents, 24 kHz output), loaded in-process via the `pocket_tts` package.
+
+`pocket_tts` ships one checkpoint per language; LANGUAGE_MAP translates the dataset language code
+to the config name. `--variant` picks a non-default checkpoint by suffixing it (`24l` = 24-layer
+preview models, `2026-01` / `2026-04` = dated English checkpoints); a non-empty variant is also
+appended to the output suffix so variants never overwrite each other under the shared model id.
+
+Voice cloning (`--voice_clone`) conditions each sample on the per-sample `prompt_audio`; outputs
+get a `_voice_clone` suffix. The default (`--no-voice_clone`) uses a predefined voice (`--speaker`,
+default per language) and skips SIM.
+"""
+
+import argparse
+import os
+import time
+from pathlib import Path
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+from pocket_tts import TTSModel
+
+from run_eval_utils import (
+ add_common_args, count_parameters, 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,
+)
+
+LANGUAGE_MAP = {
+ "en": "english",
+ "de": "german",
+ "es": "spanish",
+ "it": "italian",
+ "pt": "portuguese",
+ "fr": "french_24l", # no plain `french` config upstream
+}
+
+# Languages whose single checkpoint name already carries the variant: --variant does not change
+# the config loaded, but still affects the output suffix (kept in lockstep with submit_jobs.sh).
+_VARIANT_EXEMPT = {"fr"}
+
+# (language, variant) pairs whose config is NOT `<base>_<variant>`. The 24-layer English model is
+# only shipped under a dated name; the manifest suffix still reads `_24l` (the requested variant).
+_VARIANT_ALIASES = {("en", "24l"): "english_2026-04_24l"}
+
+# Default predefined voice per language, copied from pocket_tts.default_parameters
+# (DEFAULT_VOICE_FOR_LANGUAGE + DEFAULT_VOICE_FALLBACK). Only used with --no-voice_clone.
+DEFAULT_VOICE_FOR_LANGUAGE = {
+ "it": "giovanni",
+ "es": "lola",
+ "de": "juergen",
+ "pt": "rafael",
+ "fr": "estelle",
+}
+DEFAULT_VOICE_FALLBACK = "alba"
+
+
+def _resolve_config_name(code, variant):
+ """Translate (dataset language code, variant) to a pocket_tts config name, validated against
+ the configs installed in the image so a bad name fails fast with the real list."""
+ base = LANGUAGE_MAP.get(code)
+ if base is None:
+ raise ValueError(
+ f"Pocket TTS has no checkpoint for language '{code}'. Supported: "
+ f"{sorted(LANGUAGE_MAP)}. Gate the combo out in submit_jobs.sh instead of running "
+ f"it — there is no multilingual model to fall back on, so the WER would be meaningless."
+ )
+ name = base
+ if variant and code not in _VARIANT_EXEMPT:
+ name = _VARIANT_ALIASES.get((code, variant), f"{base}_{variant}")
+
+ from pocket_tts.utils.config import CONFIGS_DIR
+
+ available = sorted(p.stem for p in CONFIGS_DIR.glob("*.yaml"))
+ if name not in available:
+ raise ValueError(
+ f"Config '{name}' (language '{code}', variant '{variant}') is not available in the "
+ f"installed pocket-tts. Available: {available}"
+ )
+ return name
+
+
+def _resolve_speaker(args):
+ """Predefined voice for --no-voice_clone: explicit --speaker, else the per-language default."""
+ if args.speaker:
+ return args.speaker
+ return DEFAULT_VOICE_FOR_LANGUAGE.get(args.language, DEFAULT_VOICE_FALLBACK)
+
+
+def main(args):
+ # Set seed for reproducibility (the flow LM samples with temperature).
+ seed = args.seed
+ set_seed(seed)
+
+ config_name = _resolve_config_name(args.language, args.variant)
+
+ # `temp` is omitted when --temperature is unset, leaving the library's per-config default
+ # (0.3 for the English models, 0.7 otherwise).
+ load_kwargs = {
+ "language": config_name,
+ "sampler_decode_steps": args.sampler_decode_steps,
+ "eos_threshold": args.eos_threshold,
+ "quantize": args.quantize,
+ }
+ if args.temperature is not None:
+ load_kwargs["temp"] = args.temperature
+ model = TTSModel.load_model(**load_kwargs)
+ # load_model() always returns a CPU model; there is no device argument.
+ model.to(args.device)
+
+ if args.num_threads:
+ # pocket_tts pins torch to 1 thread at import; only override if explicitly asked.
+ torch.set_num_threads(args.num_threads)
+
+ sampling_rate = model.sample_rate # 24000
+ n_params = count_parameters(model)
+ print(
+ f"Loaded Pocket TTS {args.model_id} (config={config_name}, sr={sampling_rate}, "
+ f"temp={model.temp}, device={model.device}, torch_threads={torch.get_num_threads()})"
+ )
+ print(f"TTS model size: {n_params / 1e6:.0f}M parameters")
+
+ # Fail fast if pocket_tts silently fell back to the no-voice-cloning weights (gated download
+ # failed); otherwise the run would only raise on the first sample.
+ if args.voice_clone and not model.has_voice_cloning:
+ raise RuntimeError(
+ "pocket_tts fell back to the weights WITHOUT voice cloning (the Mimi encoder is zeroed "
+ "out), so --voice_clone cannot work. The download of kyutai/pocket-tts failed: check "
+ "network access, or accept the terms at https://huggingface.co/kyutai/pocket-tts and "
+ "set HF_TOKEN. Use --no-voice_clone to run with a predefined voice instead."
+ )
+ print(f"Voice cloning available: {model.has_voice_cloning}")
+
+ is_cuda = torch.device(args.device).type == "cuda"
+
+ # In fixed-voice mode the state is fetched once. `generate_audio` mutates the state it is
+ # given, so it must be reused with copy_state=True.
+ fixed_state = None
+ if not args.voice_clone:
+ speaker = _resolve_speaker(args)
+ fixed_state = model.get_state_for_audio_prompt(speaker)
+ print(f"Using predefined voice {speaker!r} (no cloning, SIM stage skipped).")
+
+ def synth_one_streaming(text, prompt_path):
+ """Like synth_one, but timestamps the first chunk: (audio_1d_numpy, first_audio_ts).
+
+ Used only by the TTFA probe (via generate_audio_stream). Reference encoding stays inside
+ the measured region, matching synth_one.
+ """
+ state = (
+ fixed_state
+ if fixed_state is not None
+ else model.get_state_for_audio_prompt(Path(prompt_path))
+ )
+ first, chunks = None, []
+ for chunk in model.generate_audio_stream(
+ state,
+ text,
+ max_tokens=args.max_tokens,
+ frames_after_eos=args.frames_after_eos,
+ copy_state=True,
+ ):
+ arr = np.asarray(chunk.reshape(-1).detach().to(torch.float32).cpu()
+ if hasattr(chunk, "detach") else chunk, dtype=np.float32).reshape(-1)
+ if first is None:
+ first = time.perf_counter()
+ chunks.append(arr)
+ if not chunks:
+ return np.zeros(1, dtype=np.float32), None
+ return np.concatenate(chunks), first
+
+ def synth_one(text, prompt_path):
+ """Synthesize one text; return (audio_1d_numpy, elapsed_seconds).
+
+ Reference encoding (get_state_for_audio_prompt) is inside the timed region, as for the
+ other cloning backends: it is per-utterance work for a zero-shot cloning model.
+ """
+ if is_cuda:
+ torch.cuda.synchronize(device=args.device)
+ start = time.perf_counter()
+ state = (
+ fixed_state
+ if fixed_state is not None
+ # Pass a Path, not a str: get_state_for_audio_prompt treats a str as a possible URL /
+ # hf:// ref / predefined-voice name before falling through to a local file.
+ else model.get_state_for_audio_prompt(Path(prompt_path))
+ )
+ audio = model.generate_audio(
+ state,
+ text,
+ max_tokens=args.max_tokens,
+ frames_after_eos=args.frames_after_eos,
+ copy_state=True, # never let generation consume the state we may reuse
+ )
+ if is_cuda:
+ torch.cuda.synchronize(device=args.device)
+ elapsed = time.perf_counter() - start
+ # generate_audio returns a 1D float32 tensor of PCM samples.
+ return audio.reshape(-1).detach().to(torch.float32).cpu().numpy(), elapsed
+
+ # Flat, bucket-friendly layout, per model
+ variant_suffix = f"_{args.variant}" if args.variant else ""
+ mode_suffix = variant_suffix + ("_voice_clone" if args.voice_clone else "")
+ paths = output_paths(args, mode_suffix)
+ model_dir, dataset_dir_name, output_dir = paths.model_dir, paths.dataset_dir_name, paths.output_dir
+ # Reference clips must live under results/ so stage 3 SIM can read them.
+ prompt_dir = os.path.join(output_dir, "prompts")
+ if args.voice_clone:
+ os.makedirs(prompt_dir, exist_ok=True)
+
+ # Keep `id`, target text, and (when cloning) the per-sample reference.
+ dataset = load_tts_dataset(args, ("prompt_text", "prompt_audio") if args.voice_clone else ())
+
+ # ── TTFA probe: latency only, writing nothing but a JSON sidecar (see scripts/ttfa_probe.py).
+ if args.ttfa_probe != 0:
+ # Imported here: ttfa_probe.py is only injected by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+ import tempfile
+
+ tmp_dir = tempfile.mkdtemp(prefix="ttfa_refs_")
+
+ def _ttfa_ref(i):
+ if not args.voice_clone:
+ return None
+ path = os.path.join(tmp_dir, f"prompt_{dataset[i]['id']}.wav")
+ _write_prompt_wav(path, dataset[i]["prompt_audio"])
+ return path
+
+ jobs = [{"text": dataset[i][args.text_column], "prompt_path": _ttfa_ref(i)}
+ for i in sample_indices(args.ttfa_probe, len(dataset))]
+
+ # Always a full generation (no early_stop parameter): pocket_tts decodes in a daemon thread
+ # that leaving the generator does NOT stop, so an early-stopped row left it decoding the
+ # rest of the utterance into the next row's measurement (TTFA 10-18x too high).
+ def _ttfa_gen(job):
+ audio, first = synth_one_streaming(job["text"], job["prompt_path"])
+ return audio, sampling_rate, first
+
+ run_probe(
+ _ttfa_gen,
+ jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=model_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ extra={"device": args.device, "voice_clone": args.voice_clone},
+ )
+ return
+
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ def prompt_for(row):
+ """When cloning, persist a row's reference clip; (prompt_rel_path, prompt_path) or Nones."""
+ if not args.voice_clone:
+ return None, None
+ prompt_rel_path = os.path.join(dataset_dir_name, "prompts", f"prompt_{row['id']}.wav")
+ prompt_path = os.path.join(model_dir, prompt_rel_path)
+ if not os.path.exists(prompt_path):
+ _write_prompt_wav(prompt_path, row["prompt_audio"])
+ return prompt_rel_path, prompt_path
+
+ # Serial generation: batches of one sample. Warm-up first: the first call is several times
+ # slower (CUDA autotuning), which would otherwise all land on sample 0's RTFx.
+ starts = pending_batches(dataset, 1, done_entries, dataset_dir_name)
+ warm_up(lambda b: synth_one(b[args.text_column][0], prompt_for({c: b[c][0] for c in b})[1]),
+ dataset, starts, 1, args.warmup_steps)
+
+ # ── Main loop: synthesize one sample at a time → write JSONL ─────────────
+ n_written = 0
+ for i in tqdm(starts, desc="Generating"):
+ row = dataset[i]
+ sample_id = row["id"]
+ text = row[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)
+
+ # When cloning, persist the reference clip to disk
+ prompt_rel_path, prompt_path = prompt_for(row)
+
+ # Re-seed per sample so generation is reproducible regardless of where a resume picked up.
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+ audio, elapsed = synth_one(text, prompt_path)
+ sf.write(path, audio, sampling_rate)
+
+ write_entry(manifest_file, manifest_entry(rel_path, len(audio) / sampling_rate, elapsed, text, prompt_rel_path))
+ # --batch_size only sets the manifest-flush interval; generation is one sample at a time.
+ n_written += 1
+ if n_written % args.batch_size == 0:
+ manifest_file.flush()
+
+ manifest_file.close()
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(args.voice_clone)
+
+
+def _write_prompt_wav(path, prompt_audio):
+ """Write a dataset `prompt_audio` column value to a 16-bit PCM wav."""
+ sf.write(
+ path,
+ np.asarray(prompt_audio["array"], dtype=np.float32),
+ prompt_audio["sampling_rate"],
+ subtype="PCM_16",
+ )
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument(
+ "--model_id", type=str, default="kyutai/pocket-tts", help="Model id (also used for manifest naming)."
+ )
+ # --batch_size is the manifest-flush granularity ONLY: Pocket TTS has no batched generation API.
+ add_common_args(parser, batch_size=32, voice_clone=False)
+ parser.add_argument(
+ "--language",
+ type=str,
+ default="en",
+ help="Dataset language code, mapped to a pocket_tts config via LANGUAGE_MAP.",
+ )
+ parser.add_argument(
+ "--variant",
+ type=str,
+ default="",
+ help="Non-default checkpoint for the same language, suffixed onto the config name: "
+ "'24l' for the 24-layer preview models, or '2026-01'/'2026-04' for the dated English "
+ "checkpoints. Empty (default) = the distilled production model. Also appended to the "
+ "output/manifest suffix.",
+ )
+ parser.add_argument(
+ "--num_threads",
+ type=int,
+ default=0,
+ help="Override torch's thread count. pocket_tts pins it to 1 at import; 0 (default) leaves "
+ "that as-is so the model is benchmarked as shipped. Only meaningful with --device=cpu.",
+ )
+ # Generation params. Defaults match the library's own (see load_model / MAX_TOKEN_PER_CHUNK).
+ parser.add_argument(
+ "--temperature",
+ type=float,
+ default=None,
+ help="Sampling temperature. Unset (default) = the config's `default_temperature` (0.3 for "
+ "the English models, 0.7 otherwise).",
+ )
+ parser.add_argument(
+ "--sampler_decode_steps", type=int, default=1,
+ help="Lagrangian Self Distillation decode steps (library default 1)."
+ )
+ parser.add_argument(
+ "--eos_threshold", type=float, default=-4.0, help="End-of-sequence threshold (library default -4.0)."
+ )
+ parser.add_argument(
+ "--max_tokens",
+ type=int,
+ default=50,
+ help="Max text tokens per generated CHUNK (library default 50). generate_audio splits "
+ "longer text into sentence chunks and concatenates — it does NOT truncate.",
+ )
+ parser.add_argument(
+ "--frames_after_eos",
+ type=int,
+ default=None,
+ help="Extra frames generated after EOS. None (default) = the library's per-text estimate.",
+ )
+ parser.add_argument(
+ "--quantize",
+ action="store_true",
+ help="Apply dynamic int8 quantization to the transformer (upstream: ~48%% less memory, ~27%% "
+ "faster on x86, WER unchanged). Off by default — it is a CPU (FBGEMM) optimization.",
+ )
+ parser.add_argument(
+ "--speaker",
+ type=str,
+ default="",
+ help="Predefined voice for --no-voice_clone (26 available: alba, anna, ..., vera). Empty "
+ "(default) picks the language's default: giovanni/it, lola/es, juergen/de, rafael/pt, "
+ "estelle/fr, alba otherwise.",
+ )
+
+ 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/pocket-tts/submit_jobs.sh b/pocket-tts/submit_jobs.sh
new file mode 100755
index 0000000..3041769
--- /dev/null
+++ b/pocket-tts/submit_jobs.sh
@@ -0,0 +1,88 @@
+#!/bin/bash
+# HF Jobs TTS eval — Pocket TTS backend (generate → transcribe → SIM* → score; *voice-clone only, VOICE_CLONE=true).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["kyutai/pocket-tts" ...]
+# Shared orchestration (stages 2/3, injection, logging, scoring) lives in scripts/tts_jobs_common.sh.
+#
+# kyutai/pocket-tts is gated on the Hub; if its download fails, pocket_tts silently substitutes the
+# no-voice-cloning weights, which run_eval.py detects (has_voice_cloning) and fails fast on.
+source "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/scripts/tts_jobs_common.sh"
+
+# ── Backend config ───────────────────────────────────────────────────────────
+TTS_SPACE="${TTS_SPACE:-bezzam/evals-pocket}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-pocket/blob/main/Dockerfile)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+# (Pocket TTS is CPU-first with no reported GPU speedup, so its RTFx here is a same-hardware number.)
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# ── Checkpoint variant ───────────────────────────────────────────────────────
+# pocket_tts ships one checkpoint per language; VARIANT selects a non-default one for the same
+# language by suffixing the config name (run_eval.py validates it against the installed configs):
+# "" -> english / german / spanish / italian / portuguese (distilled production models)
+# 24l -> german_24l, italian_24l, ... bigger 24-layer preview models, not distilled
+# 2026-01 / 2026-04 -> the dated English checkpoints (english_2026-04 == the `english` default).
+# It is language-independent because resolve_mode() runs once per MODEL, before the dataset loop.
+VARIANT="${VARIANT:-}"
+
+# ── Voice cloning (off by default): VOICE_CLONE=true clones the per-sample prompt + scores SIM ──
+# VOICE_CLONE=false uses a predefined voice (SPEAKER, or the language default) and skips SIM;
+# that path also works without the gated weights.
+SPEAKER="${SPEAKER:-}" # predefined voice, used only when VOICE_CLONE=false ("" = language default)
+resolve_mode() {
+ # A non-empty VARIANT gets its own suffix (matching run_eval.py), since every checkpoint
+ # shares the `kyutai/pocket-tts` model id.
+ voice_clone_mode "${VARIANT:+_${VARIANT}}"
+}
+
+# ── Languages Pocket TTS has a checkpoint for ────────────────────────────────
+# One checkpoint per language and no multilingual fallback (run_eval.py hard-errors on anything
+# else), so unsupported combos are skipped here. Every language listed also has a 24l variant.
+POCKET_LANGUAGES="en de es it pt fr"
+supports_language() { [[ " ${POCKET_LANGUAGES} " == *" $1 "* ]]; }
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id batch_size". ──
+# NOTE: batch_size only sets the manifest-flush granularity — Pocket TTS has no batched API.
+generate_stage() {
+ local _ BATCH_SIZE
+ read -r _ BATCH_SIZE <<< "${MODEL_CFG}"
+ BATCH_SIZE="${BATCH_SIZE:-32}" # tolerate a bare "model_id" with no second field
+ 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/pocket-tts && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --language=${ASR_LANG} \
+ --variant='${VARIANT}' \
+ --speaker='${SPEAKER}' \
+ --device=cuda:0 \
+ --batch_size=${BATCH_SIZE} \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} \
+ ${VOICE_CLONE_FLAG} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment to pick) ──
+# Seed-TTS zh and CV3-Eval ja/ko/ru/zh are omitted: Pocket TTS has no checkpoint for them.
+DATASET_CONFIGS=(
+ "tts en en"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot de de ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot fr fr ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot it it ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id batch_size" (CLI args override) ────────────────────────
+# One Hub repo holds every language checkpoint; the language comes from the dataset combo and the
+# checkpoint choice from VARIANT.
+MODEL_CONFIGS=(
+ "kyutai/pocket-tts 32"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/qwen3tts-fast/run_eval.py b/qwen3tts-fast/run_eval.py
new file mode 100644
index 0000000..4da0c4f
--- /dev/null
+++ b/qwen3tts-fast/run_eval.py
@@ -0,0 +1,293 @@
+"""
+Time-to-first-audio probe for the Open TTS Leaderboard (faster-qwen3-tts backend).
+
+A second ENGINE for the Qwen3-TTS checkpoints that `qwen3tts/run_eval.py` evaluates. Qwen's
+`qwen-tts` has no streaming API, so its TTFA is a whole-utterance clock; andimarafioti/faster-qwen3-tts
+re-implements inference over the same weights and exposes streaming generators, making a real TTFA
+measurable. It needs a newer `transformers` than `qwen-tts`, hence its own directory and image.
+
+--backend:
+ * torch (default) — CUDA graphs, GPU only.
+ * ggml — the qwentts.cpp runtime (GGUF weights from `Serveurperso/Qwen3-TTS-GGUF`),
+ which also runs on CPU.
+Both expose the same streaming generators, so _gen drives either unchanged.
+
+TTFA ONLY: upstream notes its outputs can differ slightly from the reference implementation, so
+running without --ttfa_probe is refused. Sidecars are engine-tagged by submit_ttfa_jobs.sh.
+"""
+
+import argparse
+import os
+import time
+
+import numpy as np
+import torch
+
+from faster_qwen3_tts import FasterQwen3TTS
+
+from run_eval_utils import add_common_args, load_tts_dataset, set_seed
+
+torch.set_float32_matmul_precision("high")
+
+# Kept identical to qwen3tts/run_eval.py: ISO code -> the English language NAME Qwen3-TTS wants.
+LANGUAGE_CODE_TO_NAME = {
+ "zh": "Chinese",
+ "en": "English",
+ "ja": "Japanese",
+ "ko": "Korean",
+ "de": "German",
+ "fr": "French",
+ "ru": "Russian",
+ "pt": "Portuguese",
+ "es": "Spanish",
+ "it": "Italian",
+}
+
+
+def main(args):
+ if args.ttfa_probe == 0:
+ raise SystemExit(
+ "This backend is TTFA-only: pass --ttfa_probe=N (or -1 for the whole split).\n"
+ "It exists to measure streaming latency for an engine whose audio upstream does NOT\n"
+ "guarantee matches the reference implementation, so it must not generate the wavs the\n"
+ "leaderboard's WER/RTFx are scored from. Use qwen3tts/run_eval.py for those."
+ )
+
+ seed = args.seed
+ set_seed(seed)
+ torch.backends.cudnn.deterministic = True
+
+ # Same rule as qwen3tts/run_eval.py so the two engines resolve the same variant for a model id.
+ if args.mode == "auto":
+ mode = "voice_clone" if "base" in args.model_id.split("/")[-1].lower() else "custom_voice"
+ else:
+ mode = args.mode
+
+ # The ggml backend's device is decided by the installed qwentts-cpp-python wheel, recorded only
+ # in its local-version suffix ("0.3.1+cpu", "0.3.1+cu128").
+ wheel_version = wheel_variant = None
+ if args.backend == "ggml":
+ from importlib.metadata import version, PackageNotFoundError
+ try:
+ wheel_version = version("qwentts-cpp-python")
+ wheel_variant = wheel_version.split("+", 1)[1] if "+" in wheel_version else None
+ except PackageNotFoundError:
+ raise SystemExit(
+ "--backend=ggml needs qwentts-cpp-python, which is not installed.\n"
+ "See the Dockerfile of the bezzam/evals-ggml-qwentts Space — the +cpu wheel comes from the Hub index, "
+ "not PyPI (PyPI ships the CUDA 12.8 build)."
+ )
+
+ if args.backend == "torch":
+ if not args.device.startswith("cuda"):
+ raise SystemExit(
+ f"--backend=torch needs a CUDA device (got --device={args.device}). CUDA graph\n"
+ "capture IS this backend's acceleration, so there is nothing to measure without it.\n"
+ "For a CPU measurement use --backend=ggml, which runs the qwentts.cpp runtime."
+ )
+ model = FasterQwen3TTS.from_pretrained(
+ args.model_id,
+ device=args.device,
+ dtype=getattr(torch, args.dtype),
+ attn_implementation=args.attn_implementation,
+ )
+ else:
+ # `quant` picks the GGUF (BF16 is lossless; Q8_0/Q4_K_M are a different model, recorded in
+ # the sidecar). GGMLQwen3TTS ignores --device, so cross-check it against the installed wheel
+ # to avoid filing a CPU measurement under a GPU flavor (or vice versa).
+ if wheel_variant == "cpu" and args.device.startswith("cuda"):
+ raise SystemExit(
+ f"--backend=ggml with --device={args.device}, but the installed "
+ f"qwentts-cpp-python is the CPU wheel ({wheel_version}).\n"
+ "It would compute on the CPU and the sidecar would be filed under a GPU flavor.\n"
+ "Run this target with TTFA_DEVICE=cpu, or build the image with a +cuNNN wheel."
+ )
+ if wheel_variant and wheel_variant.startswith("cu") and args.device == "cpu":
+ raise SystemExit(
+ f"--backend=ggml with --device=cpu, but the installed qwentts-cpp-python is a "
+ f"CUDA wheel ({wheel_version}).\n"
+ "The measurement would not be the CPU number it is labelled as. Install the "
+ "+cpu wheel for a CPU probe."
+ )
+ model = FasterQwen3TTS.from_pretrained(
+ args.model_id,
+ backend="ggml",
+ quant=args.quant,
+ )
+ print(f"Loaded {args.model_id} via faster-qwen3-tts backend={args.backend}"
+ f"{'/' + args.quant if args.backend == 'ggml' else ''} "
+ f"(mode={mode}, speaker={args.speaker}, language={args.language}, chunk_size={args.chunk_size})")
+
+ # Keep one-time CUDA graph capture (torch) / buffer priming (ggml) out of the timed rows.
+ if args.warmup:
+ t0 = time.perf_counter()
+ model.warmup()
+ print(f"warm-up ({args.backend}): {time.perf_counter() - t0:.2f}s")
+
+ model_safe = args.model_id.replace("/", "-")
+ # NOT created here (run_probe does it before writing): if the probe crashes, the job's final
+ # `cp -r results/<model> /results/` then fails instead of exiting 0 with no sidecar.
+ out_dir = os.path.join("results", model_safe)
+
+ # Unneeded columns are dropped BEFORE indexing rows: datasets decodes `prompt_audio` on
+ # __getitem__, which needs torchcodec even in custom_voice mode.
+ dataset = load_tts_dataset(args, extra_columns=("prompt_audio", "prompt_text") if mode == "voice_clone" else ())
+
+ # Imported lazily: ttfa_probe.py is only injected by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+
+ chunk_counts = [] # chunks per utterance
+
+ def _gen(job, early_stop):
+ """One streaming generation (batch size 1), timestamping the first yielded chunk."""
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+
+ common = dict(
+ text=job["text"],
+ language=args.language,
+ max_new_tokens=args.max_new_tokens,
+ temperature=args.temperature,
+ top_k=args.top_k,
+ top_p=args.top_p,
+ do_sample=args.do_sample,
+ repetition_penalty=args.repetition_penalty,
+ chunk_size=args.chunk_size,
+ )
+ if mode == "voice_clone":
+ stream = model.generate_voice_clone_streaming(
+ ref_audio=job["prompt_path"], ref_text=job["prompt_text"], **common)
+ else:
+ stream = model.generate_custom_voice_streaming(speaker=args.speaker, **common)
+
+ first, chunks, sample_rate = None, [], None
+ for new_audio, sr, _timing in stream:
+ if first is None:
+ first = time.perf_counter()
+ sample_rate = sr
+ chunks.append(np.asarray(new_audio, dtype=np.float32).reshape(-1))
+ if early_stop:
+ stream.close()
+ break
+
+ chunk_counts.append(len(chunks))
+ audio = np.concatenate(chunks) if chunks else np.zeros(0, dtype=np.float32)
+ return audio, sample_rate or args.sample_rate, first
+
+ jobs, prompt_dir = [], None
+ for i in sample_indices(args.ttfa_probe, len(dataset)):
+ row = dataset[i]
+ job = {"text": row[args.text_column]}
+ if mode == "voice_clone":
+ import soundfile as sf
+ # The ggml images ship no torchcodec; fail clearly instead of deep inside datasets.
+ try:
+ import torchcodec # noqa: F401
+ except ImportError:
+ raise SystemExit(
+ "--mode=voice_clone needs torchcodec to decode the dataset's prompt_audio, "
+ "and it is not installed.\n"
+ "Add `pip install \"torchcodec==0.7.*\"` to this backend's Dockerfile, or run "
+ "with --mode=custom_voice (what every TTFA target uses)."
+ )
+ # generate_voice_clone_streaming takes a path, not an array. Written to a temp dir so the
+ # results tree only ever receives the sidecar (and out_dir is not created early).
+ if prompt_dir is None:
+ import tempfile
+ prompt_dir = tempfile.mkdtemp(prefix="ttfa_refs_")
+ path = os.path.join(prompt_dir, f"prompt_{row.get('id', i)}.wav")
+ sf.write(path, np.asarray(row["prompt_audio"]["array"], dtype=np.float32),
+ row["prompt_audio"]["sampling_rate"])
+ job["prompt_path"], job["prompt_text"] = path, row["prompt_text"]
+ jobs.append(job)
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=out_dir, mode_suffix="_voice_clone" if mode == "voice_clone" else "",
+ n=args.ttfa_probe,
+ extra={
+ "device": args.device,
+ "note": f"driven at batch size 1, faster-qwen3-tts streaming, mode={mode}",
+ # chunks_per_utterance distinguishes "no incremental output" (1 chunk) from late delivery.
+ "chunks_per_utterance": chunk_counts,
+ # chunk_size sets the TTFA floor; TTFAs at different chunk sizes are not comparable.
+ "chunk_size": args.chunk_size,
+ "engine": "faster-qwen3-tts",
+ "backend": args.backend,
+ # TTFA is only comparable within one quant.
+ "quant": args.quant if args.backend == "ggml" else None,
+ "gguf_repo": "Serveurperso/Qwen3-TTS-GGUF" if args.backend == "ggml" else None,
+ # The ggml runtime wheel ("+cpu" vs "+cuNNN") is what decides CPU vs GPU.
+ "qwentts_cpp": wheel_version,
+ "sampling": {"temperature": args.temperature, "top_k": args.top_k, "top_p": args.top_p,
+ "do_sample": args.do_sample, "repetition_penalty": args.repetition_penalty},
+ },
+ )
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ add_common_args(parser)
+ # CV3-Eval by default. --device must be cuda for --backend=torch (ggml picks its own device).
+ parser.set_defaults(dataset_path="bezzam/cv3_eval", dataset="zero_shot")
+
+ parser.add_argument(
+ "--model_id", type=str, default="Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice",
+ help="Qwen3-TTS checkpoint. faster-qwen3-tts supports the 0.6B/1.7B Base, CustomVoice and "
+ "VoiceDesign variants — the SAME weights the qwen3tts backend loads.",
+ )
+ parser.add_argument(
+ "--mode", type=str, default="auto", choices=["auto", "custom_voice", "voice_clone"],
+ help="Matches qwen3tts/run_eval.py: 'custom_voice' uses a built-in --speaker, 'voice_clone' "
+ "clones the dataset's prompt_audio/prompt_text, 'auto' picks voice_clone for Base ids.",
+ )
+ parser.add_argument("--speaker", type=str, default="Ryan",
+ help="Built-in speaker voice. Ignored in voice_clone mode.")
+ parser.add_argument(
+ "--language", type=str, default="English",
+ help="Target language. ISO codes ('en', 'zh', ...) are mapped to the English NAME the model "
+ "wants, so the submit scripts pass the same code they give every other backend.",
+ )
+ parser.add_argument(
+ "--backend", type=str, default="torch", choices=["torch", "ggml"],
+ help="Runtime. 'torch' = CUDA graphs (GPU only). 'ggml' = the qwentts.cpp runtime, which "
+ "runs on CPU and is the only way to get a CPU TTFA for this model.",
+ )
+ parser.add_argument(
+ "--quant", type=str, default="BF16", choices=["BF16", "F32", "Q8_0", "Q4_K_M"],
+ help="GGUF quantization for --backend=ggml (from Serveurperso/Qwen3-TTS-GGUF). BF16 is "
+ "lossless w.r.t. the reference weights; Q8_0/Q4_K_M are a different model and their "
+ "TTFA is not comparable with a BF16 one. Ignored for --backend=torch.",
+ )
+ parser.add_argument("--dtype", type=str, default="bfloat16", help="Model dtype, e.g. 'bfloat16'.")
+ parser.add_argument("--attn_implementation", type=str, default="sdpa",
+ help="Attention impl ('sdpa'/'flash_attention_2').")
+ parser.add_argument("--sample_rate", type=int, default=24000,
+ help="Fallback sample rate, used only if the generator yields none.")
+ parser.add_argument(
+ "--chunk_size", type=int, default=12,
+ help="Codec frames per streamed chunk — the library default. This SETS the TTFA floor, so "
+ "keep it fixed across runs and never compare TTFA across different values.",
+ )
+ # Sampling defaults copied from the library's streaming signatures.
+ parser.add_argument("--max_new_tokens", type=int, default=2048)
+ parser.add_argument("--temperature", type=float, default=0.9)
+ parser.add_argument("--top_k", type=int, default=50)
+ parser.add_argument("--top_p", type=float, default=1.0)
+ parser.add_argument("--do_sample", action=argparse.BooleanOptionalAction, default=True)
+ parser.add_argument("--repetition_penalty", type=float, default=1.05)
+ parser.add_argument("--warmup", action=argparse.BooleanOptionalAction, default=True,
+ help="Warm up (torch: CUDA-graph capture; ggml: buffer priming) before the timed rows (on by default).")
+
+ args = parser.parse_args()
+ args.language = LANGUAGE_CODE_TO_NAME.get(args.language.lower(), args.language)
+
+ print("*" * 100)
+ print(f"TTFA probe: {args.model_id} via faster-qwen3-tts on "
+ f"{args.dataset_path} / {args.dataset} / {args.split}")
+ print(f"Target language: {args.language}, chunk_size: {args.chunk_size}")
+ print("*" * 100)
+
+ main(args)
diff --git a/qwen3tts/run_eval.py b/qwen3tts/run_eval.py
new file mode 100644
index 0000000..b46630f
--- /dev/null
+++ b/qwen3tts/run_eval.py
@@ -0,0 +1,267 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (Qwen3-TTS backend, stage 1).
+
+Runs in its own image because `qwen-tts` pins an older `transformers` than the Qwen3-ASR scorer.
+Two variants (auto-detected from --model_id, overridable with --mode), both natively batched:
+ * CustomVoice: built-in speaker via `generate_custom_voice` (--speaker broadcast over the batch).
+ * Base: zero-shot cloning via `generate_voice_clone` from each sample's `prompt_audio`/`prompt_text`;
+ reference clips are saved for SIM and outputs get a `_voice_clone` suffix.
+"""
+
+import argparse
+import os
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+from qwen_tts import Qwen3TTSModel
+
+from run_eval_utils import (
+ add_common_args,
+ load_done_entries,
+ load_tts_dataset,
+ manifest_entry,
+ open_manifest,
+ output_paths,
+ pending_batches,
+ print_model_size,
+ print_next_steps,
+ set_seed,
+ warm_up,
+ write_entry,
+)
+
+torch.set_float32_matmul_precision("high")
+
+# Qwen3-TTS takes the English language NAME; map the ISO codes the eval scripts pass. Unknown
+# values pass through so 'English'/'Chinese'/'Auto' still work.
+LANGUAGE_CODE_TO_NAME = {
+ "zh": "Chinese",
+ "en": "English",
+ "ja": "Japanese",
+ "ko": "Korean",
+ "de": "German",
+ "fr": "French",
+ "ru": "Russian",
+ "pt": "Portuguese",
+ "es": "Spanish",
+ "it": "Italian",
+}
+
+
+def main(args):
+ # Set seed for reproducibility (some models sample internally).
+ set_seed(args.seed)
+ torch.backends.cudnn.deterministic = True
+
+ # Resolve variant: Base models do zero-shot voice cloning from the dataset's
+ # prompt_audio/prompt_text; CustomVoice models use a built-in speaker.
+ if args.mode == "auto":
+ mode = "voice_clone" if "base" in args.model_id.split("/")[-1].lower() else "custom_voice"
+ else:
+ mode = args.mode
+
+ torch_dtype = getattr(torch, args.dtype)
+ model = Qwen3TTSModel.from_pretrained(
+ args.model_id,
+ device_map=args.device,
+ dtype=torch_dtype,
+ attn_implementation=args.attn_implementation,
+ )
+ if mode == "voice_clone":
+ print(f"Loaded Qwen3-TTS model {args.model_id} (mode=voice_clone, language={args.language})")
+ else:
+ print(f"Loaded Qwen3-TTS model {args.model_id} (mode=custom_voice, speaker={args.speaker}, language={args.language})")
+
+ # Report parameter count (Qwen3TTSModel is a wrapper: also sum its nn.Module attributes).
+ try:
+ print_model_size(model)
+ except Exception as e:
+ print(f"Could not determine model size: {e}")
+
+ # 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.
+ mode_suffix = "_voice_clone" if mode == "voice_clone" else ""
+ paths = output_paths(args, mode_suffix)
+ model_dir, dataset_dir_name, output_dir = paths.model_dir, paths.dataset_dir_name, paths.output_dir
+
+ # Voice-clone reference clips are saved under results/ for stage 3 (SIM).
+ prompt_dir = os.path.join(output_dir, "prompts")
+ if mode == "voice_clone":
+ os.makedirs(prompt_dir, exist_ok=True)
+
+ def generate_tts(batch):
+ """Synthesize speech for a minibatch of target texts; time the batch generation for RTFx."""
+ texts_to_generate = list(batch[args.text_column])
+ minibatch_size = len(texts_to_generate)
+
+ # Voice cloning (Base): per-sample reference audio + transcript from the dataset.
+ # qwen-tts accepts ref_audio as a list of (numpy_array, sampling_rate) tuples.
+ prompt_paths = [None] * minibatch_size
+ if mode == "voice_clone":
+ ref_audio = [
+ (np.asarray(a["array"], dtype=np.float32), a["sampling_rate"])
+ for a in batch["prompt_audio"]
+ ]
+ ref_text = list(batch["prompt_text"])
+ prompt_paths = []
+ for sample_id, a in zip(batch["id"], batch["prompt_audio"]):
+ prompt_rel_path = os.path.join(dataset_dir_name, "prompts", f"prompt_{sample_id}.wav")
+ ppath = os.path.join(model_dir, prompt_rel_path)
+ if not os.path.exists(ppath):
+ sf.write(ppath, np.asarray(a["array"], dtype=np.float32), a["sampling_rate"])
+ prompt_paths.append(prompt_rel_path)
+
+ # START TIMING (TTS batch generation)
+ torch.cuda.synchronize(device=args.device)
+ start_event = torch.cuda.Event(enable_timing=True)
+ end_event = torch.cuda.Event(enable_timing=True)
+ start_event.record()
+
+ # qwen-tts accepts lists for all per-sample args; broadcast the single language.
+ if mode == "voice_clone":
+ wavs, sr = model.generate_voice_clone(
+ text=texts_to_generate,
+ language=[args.language] * minibatch_size,
+ ref_audio=ref_audio,
+ ref_text=ref_text,
+ )
+ else:
+ wavs, sr = model.generate_custom_voice(
+ text=texts_to_generate,
+ language=[args.language] * minibatch_size,
+ speaker=[args.speaker] * minibatch_size,
+ )
+
+ # END TIMING
+ end_event.record()
+ torch.cuda.synchronize(device=args.device)
+ runtime = start_event.elapsed_time(end_event) / 1000.0
+ # per-sample generation time (RTFx is aggregated over the whole set at scoring time)
+ batch["generation_time_s"] = minibatch_size * [runtime / minibatch_size]
+
+ gen_paths, audio_length_s = [], []
+ for audio, sample_id in zip(wavs, batch["id"]):
+ # Store the path relative to model_dir (the manifest's dir); write to the full path.
+ rel_path = os.path.join(dataset_dir_name, f"output_{sample_id}.wav")
+ audio = np.asarray(audio).reshape(-1)
+ sf.write(os.path.join(model_dir, rel_path), audio, sr)
+ gen_paths.append(rel_path)
+ audio_length_s.append(len(audio) / sr)
+
+ batch["gen_audio_filepath"] = gen_paths
+ batch["prompt_audio_filepath"] = prompt_paths
+ batch["audio_length_s"] = audio_length_s
+ batch["references"] = list(batch[args.text_column]) # raw; normalized at scoring time
+ return batch
+
+ dataset = load_tts_dataset(args, extra_columns=("prompt_text", "prompt_audio") if mode == "voice_clone" else ())
+
+ probe_out_dir = model_dir # real results dir, captured before the probe rebinds model_dir
+ # ── TTFA probe: writes ONLY a JSON sidecar (no wavs, no manifest) ─────────
+ # TTFA is per-request, so generate_tts() is driven with one-row batches. No streaming API, so
+ # TTFA = whole-utterance time. `model_dir`/`dataset_dir_name` are rebound to a temp dir:
+ # generate_tts closes over them (late binding), so its writes never touch the results tree.
+ # 0 = off; N > 0 = N evenly spaced samples; N < 0 = the whole split (see scripts/ttfa_probe.py).
+ if args.ttfa_probe != 0:
+ # Imported lazily: ttfa_probe.py is only injected by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+ import tempfile
+
+ model_dir = tempfile.mkdtemp(prefix="ttfa_out_")
+ dataset_dir_name = "ttfa"
+ output_dir = os.path.join(model_dir, dataset_dir_name)
+ os.makedirs(os.path.join(output_dir, "prompts"), exist_ok=True)
+
+ def _gen(job):
+ result = generate_tts(job)
+ duration = result["audio_length_s"][0]
+ return float(duration), None, None
+
+ columns = dataset.column_names
+ jobs = [{c: [dataset[i][c]] for c in columns}
+ for i in sample_indices(args.ttfa_probe, len(dataset))]
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=probe_out_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ extra={"device": args.device, "note": "driven at batch size 1"},
+ )
+ return
+
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ starts = pending_batches(dataset, args.batch_size, done_entries, dataset_dir_name)
+ warm_up(generate_tts, dataset, starts, args.batch_size, args.warmup_steps)
+
+ # ── Main loop: TTS → write JSONL, one batch at a time ───────────────────
+ for batch_start in tqdm(starts, desc="Generating"):
+ batch = generate_tts(dataset[batch_start : batch_start + args.batch_size])
+
+ # Append each sample to the JSONL immediately. `pred_text` is filled by stage 2 (ASR);
+ # `sim` by stage 3 (speaker similarity, voice-clone only).
+ for afp, ppath, alen, gtime, ref in zip(
+ batch["gen_audio_filepath"], batch["prompt_audio_filepath"], batch["audio_length_s"],
+ batch["generation_time_s"], batch["references"],
+ ):
+ write_entry(manifest_file, manifest_entry(afp, alen, gtime, ref, ppath if mode == "voice_clone" else None))
+ manifest_file.flush()
+
+ manifest_file.close()
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(mode == "voice_clone")
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ add_common_args(parser, batch_size=32)
+
+ parser.add_argument(
+ "--model_id",
+ type=str,
+ default="Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice",
+ help="Qwen3-TTS model id, loadable with the `qwen-tts` package (CustomVoice or Base variant).",
+ )
+ parser.add_argument(
+ "--mode",
+ type=str,
+ default="auto",
+ choices=["auto", "custom_voice", "voice_clone"],
+ help=(
+ "Generation mode. 'custom_voice' uses a built-in --speaker (CustomVoice models); "
+ "'voice_clone' clones the dataset's prompt_audio/prompt_text per sample (Base models); "
+ "'auto' picks voice_clone when the model id contains 'Base'."
+ ),
+ )
+ parser.add_argument(
+ "--speaker",
+ type=str,
+ default="Ryan",
+ help="Built-in speaker voice (e.g. Ryan, Eric, Aiden, Dylan, Vivian, Serena). Ignored in voice_clone mode.",
+ )
+ parser.add_argument(
+ "--language",
+ type=str,
+ default="English",
+ help="Target language: an English name ('English', 'Chinese', ...), an ISO code ('en', 'zh', "
+ "...; mapped to the name), or 'Auto'.",
+ )
+ parser.add_argument("--dtype", type=str, default="bfloat16", help="Model dtype, e.g. 'bfloat16'.")
+ parser.add_argument("--attn_implementation", type=str, default="sdpa", help="Attention impl ('flash_attention_2'/'sdpa').")
+
+ args = parser.parse_args()
+
+ args.language = LANGUAGE_CODE_TO_NAME.get(args.language.lower(), args.language)
+
+ print("*" * 100)
+ print(f"Generating TTS with {args.model_id} on {args.dataset_path} / {args.dataset} / {args.split}")
+ print(f"Target language: {args.language}")
+ print("*" * 100)
+
+ main(args)
diff --git a/qwen3tts/submit_jobs.sh b/qwen3tts/submit_jobs.sh
new file mode 100644
index 0000000..0ca2e03
--- /dev/null
+++ b/qwen3tts/submit_jobs.sh
@@ -0,0 +1,90 @@
+#!/bin/bash
+# HF Jobs TTS eval — Qwen3-TTS backend (generate → transcribe → SIM* → score; *voice-clone only).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["Qwen/...-Base 32 -" ...]
+# Base models always run in voice-clone mode (no built-in speaker); CustomVoice models never do.
+# 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-qwentts}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-qwentts/blob/main/Dockerfile)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# ── Voice cloning (Base variants): clone the reference speaker + score SIM ──
+# Base checkpoints only support cloning, CustomVoice only built-in speakers, so the mode follows
+# the model; VOICE_CLONE only triggers a note/warning when it disagrees.
+VOICE_CLONE_MODELS=("base") # Base checkpoints clone; CustomVoice ones don't
+model_supports_voice_clone() {
+ local id_lc="${1,,}" pat
+ for pat in "${VOICE_CLONE_MODELS[@]}"; do [[ "$id_lc" == *"$pat"* ]] && return 0; done
+ return 1
+}
+# Sets RESOLVED_MODE (passed as --mode so bash and python agree on the suffix), CLONE (gates
+# the SIM stage) and MODE_SUFFIX.
+resolve_mode() {
+ if model_supports_voice_clone "${MODEL_ID}"; then
+ [[ "${VOICE_CLONE}" != "true" ]] && echo "Note: ${MODEL_ID} is a Base model and only supports voice cloning; running with voice_clone mode regardless of VOICE_CLONE."
+ VOICE_CLONE=true voice_clone_mode; RESOLVED_MODE="voice_clone"
+ else
+ [[ "${VOICE_CLONE}" == "true" ]] && echo "Warning: VOICE_CLONE=true but ${MODEL_ID} does not support cloning; using a built-in speaker (skips SIM)."
+ VOICE_CLONE=false voice_clone_mode; RESOLVED_MODE="custom_voice"
+ fi
+}
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id batch_size speaker". ──
+generate_stage() {
+ local _ BATCH_SIZE SPEAKER SPEAKER_ARG=""
+ read -r _ BATCH_SIZE SPEAKER <<< "${MODEL_CFG}"
+ # Base configs carry speaker "-": don't pass --speaker for those.
+ [[ -n "${SPEAKER}" && "${SPEAKER}" != "-" ]] && SPEAKER_ARG="--speaker=${SPEAKER}"
+ 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/qwen3tts && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --mode=${RESOLVED_MODE} \
+ ${SPEAKER_ARG} \
+ --language=${ASR_LANG} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --device=cuda:0 \
+ --batch_size=${BATCH_SIZE} \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Languages this backend can select ────────────────────────────────────────
+# Must match run_eval.py's LANGUAGE_CODE_TO_NAME: unmapped codes would reach the model verbatim.
+QWEN_TTS_LANGUAGES="zh en ja ko de fr ru pt es it"
+supports_language() { [[ " ${QWEN_TTS_LANGUAGES} " == *" $1 "* ]]; }
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment to pick) ────────
+DATASET_CONFIGS=(
+ "tts en en"
+ "tts zh zh"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot zh zh ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ja ja ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ko ko ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot de de ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot fr fr ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot it it ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ru ru ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+
+# ── Models: "model_id batch_size speaker" (CLI args override) ─────────────────
+# speaker is the built-in voice for CustomVoice models; "-" for Base models (which clone).
+MODEL_CONFIGS=(
+ "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice 32 Aiden"
+ "Qwen/Qwen3-TTS-12Hz-1.7B-Base 32 -"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..5bd1a2d
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,9 @@
+huggingface_hub
+numpy
+datasets<4.0
+soundfile
+librosa
+requests
+num2words
+kaldialign
+zhconv
diff --git a/scripts/open_results_pr.py b/scripts/open_results_pr.py
new file mode 100644
index 0000000..c89d683
--- /dev/null
+++ b/scripts/open_results_pr.py
@@ -0,0 +1,829 @@
+#!/usr/bin/env python3
+"""Pull a model's results from the HF bucket and open a PR against the published TTS CSVs.
+
+Scores the bucket manifests exactly the way `scripts/score_model.py` does (same
+`score_results`, one call per language so each gets its own normalizer), turns the per-language
+numbers into one row per benchmark file, upserts those rows into
+`hf-audio/tts_leaderboard_results`, and opens a single pull request carrying every changed file.
+
+Files written (all in that dataset repo):
+ model_info.csv metadata -- scoring cannot derive it, so it comes from the CLI flags
+ seed_tts.csv Seed-TTS-Eval, model's own/default voice (WER, RTFx)
+ seed_tts_voice_clone.csv Seed-TTS-Eval, cloning each prompt (WER, RTFx, SIM x2)
+ cv3.csv CV3-Eval, model's own/default voice (WER, RTFx + averages)
+ cv3_voice_clone.csv CV3-Eval, cloning each prompt (WER, RTFx, SIM + averages)
+ streaming.csv time-to-first-audio, CPU and GPU (TTFA, RTFx at batch 1)
+
+Nothing is pushed unless --open_pr is passed: the default is a dry run that prints the rows.
+
+Usage:
+ # dry run (default): show the rows that would be written
+ python scripts/open_results_pr.py --model_id openbmb/VoxCPM2
+
+ # the same, with the model_info.csv metadata, and actually open the PR
+ python scripts/open_results_pr.py --model_id openbmb/VoxCPM2 \
+ --license apache-2.0 --voice_cloning yes --batch_inference no \
+ --num_languages 9 --model_size_b 0.5 --transformers no --open_pr
+
+ # one benchmark only
+ python scripts/open_results_pr.py --model_id tencent/AuK --targets cv3_voice_clone --open_pr
+
+ # a backend variant that is published as its own row
+ python scripts/open_results_pr.py --model_id ResembleAI/chatterbox --variant multilingual \
+ --row_name "ResembleAI/chatterbox (ChatterboxMultilingualTTS)" --open_pr
+
+ # TTFA only, for a model probed through a separate inference engine
+ python scripts/open_results_pr.py --model_id Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice --targets streaming \
+ --engine photon --row_name "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice (photon)" --open_pr \
+ --note "https://moondream.ai/blog/photon-can-now-speak" --model_size_b 1.92
+
+ # re-use results already synced locally (e.g. by submit_jobs.sh)
+ python scripts/open_results_pr.py --model_id openbmb/VoxCPM2 --skip_sync
+"""
+
+import argparse
+import contextlib
+import csv
+import io
+import json
+import os
+import subprocess
+import sys
+
+REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, REPO_ROOT) # so `from normalizer import ...` resolves regardless of cwd
+
+from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download # noqa: E402
+
+from normalizer.eval_utils import SIM_BACKEND_SUFFIXES, default_multilingual, score_results # noqa: E402
+
+# Where the results live, and where they are published.
+RESULTS_BUCKET = "hf-audio/tts_leaderboard_h200"
+RESULTS_REPO = "hf-audio/tts_leaderboard_results"
+
+MODEL_INFO_FILE = "model_info.csv"
+
+# model_info.csv columns, and the flag each one is supplied by. Scoring cannot know any of these.
+# A flag that is not passed leaves the published cell untouched; a flag passed as "" clears it.
+METADATA_ARGS = {
+ "license": "license",
+ "voice cloning": "voice_cloning",
+ "batch inference": "batch_inference",
+ "# languages": "num_languages",
+ "Transformers": "transformers",
+ "model size (B)": "model_size_b",
+}
+
+# Second SIM column on seed_tts_voice_clone.csv: the `xvector` scale (WavLMForXVector), published
+# alongside the seed-tts-eval scale; the two are NOT comparable (see --sim_backend in
+# scripts/tts_jobs_common.sh).
+XVECTOR_SIM_COLUMN = "{lang} SIM (microsoft/wavlm-base-plus-sv)"
+XVECTOR_BACKEND = "xvector"
+
+CLONE_SUFFIX = "_voice_clone"
+
+
+class Target:
+ """One published benchmark file and the manifests that feed it.
+
+ marker: the `<eval>_<config>` substring a manifest name carries for this benchmark (a
+ substring, since the dataset namespace in front of it differs per user; see
+ scripts/prepare_*_eval.py).
+ voice_clone: which side of the `_voice_clone` split this file publishes.
+ xvector_sim: this file also carries the xvector-scale SIM column, which needs a second scoring
+ pass (one `score_results` call reports one SIM scale).
+ """
+
+ def __init__(self, filename, marker, voice_clone, xvector_sim=False):
+ self.filename = filename
+ self.marker = marker
+ self.voice_clone = voice_clone
+ self.xvector_sim = xvector_sim
+
+
+# Keyed by --targets value; the order here is the order the files are reported and committed in.
+TARGETS = {
+ "seed_tts": Target("seed_tts.csv", "seed_tts_eval_tts_", voice_clone=False),
+ "seed_tts_voice_clone": Target(
+ "seed_tts_voice_clone.csv", "seed_tts_eval_tts_", voice_clone=True, xvector_sim=True
+ ),
+ "cv3": Target("cv3.csv", "cv3_eval_zero_shot_", voice_clone=False),
+ "cv3_voice_clone": Target("cv3_voice_clone.csv", "cv3_eval_zero_shot_", voice_clone=True),
+}
+
+# streaming.csv is filled from the TTFA sidecars rather than by scoring, so it is not a Target.
+STREAMING_KEY = "streaming"
+STREAMING_FILE = "streaming.csv"
+TTFA_PREFIX = "TTFA_"
+# Sidecar flavor suffix -> the prefix of the streaming.csv columns it fills
+TTFA_COLUMN_GROUPS = {"cpu-upgrade": "CPU", "h200": "H200", "a100-large": "A100"}
+# Which group's streaming verdict wins when they disagree: the GPU probes first, newest hardware first.
+TTFA_VERDICT_ORDER = ["A100", "H200", "CPU"]
+# Row-level columns of streaming.csv that are not per-device measurements.
+STREAMING_API_COLUMN = "Streaming API"
+STREAMING_NOTE_COLUMN = "Note"
+STREAMING_SIZE_COLUMN = "Size (B)"
+
+
+# ── Bucket ───────────────────────────────────────────────────────────────────
+def sync_bucket(bucket, model_folder, local_dir, hf_token=None, clean=False):
+ """Sync one model's folder out of the bucket, manifests only (scoring never reads the wavs).
+
+ Same call `_wait_and_score` in scripts/tts_jobs_common.sh makes, so either's folder is usable.
+ """
+ source = f"hf://buckets/{bucket}/{model_folder}"
+ dest = os.path.join(local_dir, model_folder)
+ if clean and os.path.isdir(dest):
+ # `hf buckets sync` never deletes, so stale local manifests would otherwise still be scored.
+ print(f"Removing {dest} (--clean) ...")
+ subprocess.run(["rm", "-rf", dest], check=True)
+ print(f"Syncing {source} → {dest} ...")
+ os.makedirs(dest, exist_ok=True)
+ env = os.environ.copy()
+ if hf_token:
+ env["HF_TOKEN"] = hf_token
+ subprocess.run(
+ ["hf", "buckets", "sync", source, dest, "--exclude", "*.wav"],
+ check=True,
+ env=env,
+ )
+ print("Sync complete.\n")
+
+
+# ── Manifest discovery ───────────────────────────────────────────────────────
+def canonical_stem(basename):
+ """Manifest name with the `.jsonl` and any SIM-backend suffix removed.
+
+ A non-xvector SIM backend scores into a fork `<manifest>_<backend>.jsonl`; `score_results`
+ picks the right fork itself given the plain name.
+ """
+ stem = basename.removesuffix(".jsonl")
+ for suffix in SIM_BACKEND_SUFFIXES:
+ stem = stem.removesuffix(f"_{suffix}")
+ return stem
+
+
+def select_manifests(model_dir, model_safe, target, variant):
+ """Manifests in `model_dir` belonging to `target` (and `variant`).
+
+ Returns ({canonical stem: language}, [stems of the right benchmark that did not match]); the
+ latter usually means a backend variant (`_multilingual`, `_rl`) needs naming with --variant.
+ """
+ selected, unmatched = {}, []
+ prefix = f"MODEL_{model_safe}_DATASET_"
+ for name in sorted(os.listdir(model_dir)):
+ if not name.endswith(".jsonl"):
+ continue
+ stem = canonical_stem(name)
+ if not stem.startswith(prefix):
+ continue
+ index = stem.find(target.marker)
+ if index < 0:
+ continue
+ rest = stem[index + len(target.marker):]
+ is_clone = rest.endswith(CLONE_SUFFIX)
+ if is_clone != target.voice_clone:
+ continue
+ if is_clone:
+ rest = rest[: -len(CLONE_SUFFIX)]
+ # What remains is `<lang><variant>`. The variant comes from the CLI rather than being
+ # guessed: Seed-TTS's `zh_hard` split would otherwise read as `zh` + variant `_hard`.
+ if variant:
+ if not rest.endswith(variant):
+ unmatched.append(stem)
+ continue
+ rest = rest[: -len(variant)]
+ selected[stem] = rest
+ return selected, unmatched
+
+
+def select_ttfa_sidecars(model_dir, model_safe, variant, engine):
+ """TTFA sidecars for this model/variant/engine, as {column group: (path, payload)}, the group
+ being a TTFA_COLUMN_GROUPS value ("CPU", "H200", "A100").
+
+ One sidecar per group is published; sidecars from a flavor with no group are listed and
+ skipped. When a group has several (different splits, or
+ both a default-voice and a voice-clone probe) the default-voice one wins -- TTFA does not depend on
+ the corpus (see scripts/ttfa_probe.py) -- then the most recent; the others are listed.
+ """
+ prefix = f"{TTFA_PREFIX}MODEL_{model_safe}_DATASET_"
+ candidates = {}
+ for name in sorted(os.listdir(model_dir)):
+ if not (name.startswith(prefix) and name.endswith(".json")):
+ continue
+ # `<dataset>_<config>_<split><mode>[__<engine>]__<flavor>`
+ parts = name[len(prefix):].removesuffix(".json").split("__")
+ if len(parts) < 2:
+ continue # untagged sidecar (a probe run outside submit_ttfa_jobs.sh): hardware unknown
+ rest, flavor = parts[0], parts[-1]
+ tag = "__".join(parts[1:-1])
+ if tag != engine:
+ continue
+ is_clone = rest.endswith(CLONE_SUFFIX)
+ rest = rest.removesuffix(CLONE_SUFFIX)
+ # Same rule as the manifests: a variant is only matched when named.
+ if variant and not rest.endswith(variant):
+ continue
+ path = os.path.join(model_dir, name)
+ with open(path, encoding="utf-8") as handle:
+ payload = json.load(handle)
+ if not variant and payload.get("mode_suffix", "").removesuffix(CLONE_SUFFIX):
+ continue # a variant run (e.g. `_rl`); its own row needs --variant
+ device = TTFA_COLUMN_GROUPS.get(flavor)
+ if device is None:
+ print(f" NOTE: skipping {name}: {STREAMING_FILE} has no columns for flavor {flavor} "
+ f"(published flavors: {', '.join(TTFA_COLUMN_GROUPS)})")
+ continue
+ candidates.setdefault(device, []).append((is_clone, -os.path.getmtime(path), path, payload))
+ chosen = {}
+ for device, found in candidates.items():
+ found.sort(key=lambda c: (c[0], c[1]))
+ chosen[device] = (found[0][2], found[0][3])
+ for other in found[1:]:
+ print(f" NOTE: {device} TTFA taken from {os.path.basename(found[0][2])}; "
+ f"ignoring {os.path.basename(other[2])}")
+ return chosen
+
+
+def streaming_column(header, device, metric, stat=None):
+ """The header's `<device> ... <metric> ... <stat>` column (the published names are not uniform:
+ `CPU RTFx` but `H200 (RTFx)`), or None. `stat` ("(p50)", "(p95)") tells apart the several TTFA
+ columns of one device."""
+ for column in header:
+ if column.startswith(device + " ") and metric in column and (stat is None or stat in column):
+ return column
+ return None
+
+
+def collect_streaming_values(header, sidecars):
+ """streaming.csv row body from the chosen sidecars. Returns (values, notes)."""
+ values, notes = {}, []
+ for device, (path, payload) in sorted(sidecars.items()):
+ ttfa = payload.get("ttfa_ms") or {}
+ # p95 is absent from sidecars written before the probe reported it: that column is then
+ # left as published (empty for those models) rather than guessed.
+ for metric, stat, value in (("TTFA", "(p50)", ttfa.get("p50")),
+ ("TTFA", "(p95)", ttfa.get("p95")),
+ ("RTFx", None, payload.get("rtfx_batch1"))):
+ column = streaming_column(header, device, metric, stat)
+ if column and value is not None:
+ values[column] = fmt(value)
+ notes.append(f"{device}: {os.path.basename(path)}")
+ if payload.get("first_reported_but_not_early"):
+ notes.append(f"NOTE: {device} probe reported first-chunk timestamps that were not early "
+ f"(ttfa/gen {payload.get('ttfa_frac_of_gen')}); published as not streaming.")
+ # A GPU probe decides when they disagree: it is the headline measurement.
+ ordered = [g for g in TTFA_VERDICT_ORDER if g in sidecars]
+ verdicts = [sidecars[g][1].get("streaming") for g in ordered]
+ if verdicts and verdicts[0] is not None:
+ values[STREAMING_API_COLUMN] = "yes" if verdicts[0] else "no"
+ if len(set(verdicts)) > 1:
+ notes.append(f"NOTE: the {', '.join(ordered)} probes disagree on streaming; "
+ f"the {ordered[0]} verdict is used.")
+ return values, notes
+
+
+# ── Scoring ──────────────────────────────────────────────────────────────────
+def run_scoring(model_dir, model_id, manifests_by_language, sim_backend):
+ """Score each language separately; return {dataset_id: result}.
+
+ One call per language because `score_results` applies its `language` to every manifest it
+ reads (same as `_wait_and_score` in scripts/tts_jobs_common.sh).
+ """
+ scored = {}
+ for language, manifests in sorted(manifests_by_language.items()):
+ multilingual = default_multilingual(language)
+ buffer = io.StringIO()
+ try:
+ with contextlib.redirect_stdout(buffer):
+ _, results = score_results(
+ model_dir,
+ model_id=model_id,
+ csv_only=True,
+ language=language,
+ multilingual=multilingual,
+ manifests=sorted(f"{stem}.jsonl" for stem in manifests),
+ sim_backend=sim_backend,
+ )
+ except ValueError as exc:
+ # No manifests for this language -- normal when a model was not run on it.
+ print(f" [{language}] skipped: {exc}")
+ continue
+ # Surface anything score_results had to say (notably the stale-SIM NOTE behind a blank SIM).
+ for line in buffer.getvalue().splitlines():
+ if line.strip() and not line.startswith("Filtering models by id:"):
+ print(f" {line}")
+ for key, value in results.items():
+ # Keyed "<model> | <dataset id>"; only the dataset half is used, since the model half
+ # is rebuilt from the file name and mangles hyphenated namespaces (k2-fsa/OmniVoice).
+ scored[key.split("|", 1)[1].strip()] = value
+ print(f" [{language}] scored {len(manifests)} manifest(s) (multilingual={multilingual})")
+ return scored
+
+
+def fmt(value, digits=2):
+ """Published-CSV spelling of a metric: 2 decimals, no trailing zeros, blank when absent."""
+ if value is None:
+ return ""
+ return f"{value:.{digits}f}".rstrip("0").rstrip(".")
+
+
+def collect_values(target, header_languages, records, scored, scored_xvector):
+ """Merge one target's per-language results into a {column: value} row body."""
+ values, unknown = {}, []
+ for stem, language in sorted(records.items()):
+ if language not in header_languages:
+ unknown.append((stem, language))
+ continue
+ # The dataset id is what `score_results` keys its results by: everything after `_DATASET_`.
+ dataset_id = stem.split("_DATASET_", 1)[1]
+ result = scored.get(dataset_id)
+ if result is None:
+ continue
+ values[f"{language} WER"] = fmt(result["wer"])
+ values[f"{language} RTFx"] = fmt(result["rtfx"])
+ if result.get("sim") is not None:
+ values[f"{language} SIM"] = fmt(result["sim"])
+ if target.xvector_sim:
+ legacy = scored_xvector.get(dataset_id)
+ if legacy is not None and legacy.get("sim") is not None:
+ values[XVECTOR_SIM_COLUMN.format(lang=language)] = fmt(legacy["sim"])
+ return values, unknown
+
+
+# ── Published CSVs ───────────────────────────────────────────────────────────
+class Published:
+ """A published CSV, kept as its own bytes alongside the parsed rows.
+
+ The raw text lets an update splice a single line in (see `splice_row`): a csv round-trip is not
+ byte-identical, so every PR would otherwise be a whole-file rewrite.
+ """
+
+ def __init__(self, text):
+ self.text = text
+ self.lines = text.splitlines(keepends=True)
+ reader = csv.reader(io.StringIO(text, newline=""))
+ self.header = next(reader)
+ # Each row's span of physical lines, so it can be found again in `self.lines`. A quoted
+ # field may hold a newline, so a row is not necessarily one line.
+ self.rows, self.spans = [], []
+ start = reader.line_num
+ for row in reader:
+ end = reader.line_num
+ if row:
+ self.rows.append(row)
+ self.spans.append((start, end))
+ start = end
+ self.eol = line_terminator(self.lines[0]) if self.lines else "\n"
+ self.trailing_newline = bool(self.lines) and bool(line_terminator(self.lines[-1]))
+
+ def index_of(self, row_name):
+ """Position of `row_name` in `self.rows`, or None if the model is not published yet."""
+ for i, row in enumerate(self.rows):
+ if row and row[0].strip() == row_name:
+ return i
+ return None
+
+
+def line_terminator(line):
+ """The line's own ending, or "" for a last line that has none."""
+ for ending in ("\r\n", "\n", "\r"):
+ if line.endswith(ending):
+ return ending
+ return ""
+
+
+def fetch_csv(filename, hf_token):
+ path = hf_hub_download(RESULTS_REPO, filename, repo_type="dataset", token=hf_token)
+ with open(path, newline="", encoding="utf-8") as handle:
+ return Published(handle.read())
+
+
+def serialize_row(row):
+ """One CSV record, with no line ending of its own."""
+ buffer = io.StringIO(newline="")
+ csv.writer(buffer, lineterminator="\n").writerow(row)
+ return buffer.getvalue()[:-1]
+
+
+def splice_row(published, index, new_row):
+ """The file's content with just this model's line replaced, or appended.
+
+ Every other byte is the published file's own, so the PR diff is one line and merges cleanly
+ with PRs for other models. The one exception: a missing final newline is added, so later
+ appends are clean single-line insertions too.
+ """
+ lines = list(published.lines)
+ serialized = serialize_row(new_row)
+ eol = published.eol or "\n"
+ if index is None:
+ if lines and not published.trailing_newline:
+ lines[-1] += eol
+ lines.append(serialized + eol)
+ else:
+ first, last = published.spans[index]
+ lines[first:last] = [serialized + (line_terminator(lines[last - 1]) or eol)]
+ return "".join(lines)
+
+
+def rewrite_sorted(published, index, new_row):
+ """Whole file, rows re-sorted by model. Only --sort takes this path, since it moves lines on
+ purpose; the file's own line ending is still kept."""
+ rows = list(published.rows)
+ if index is None:
+ rows.append(new_row)
+ else:
+ rows[index] = new_row
+ rows.sort(key=lambda row: (row[0] or "").lower())
+ buffer = io.StringIO(newline="")
+ writer = csv.writer(buffer, lineterminator=published.eol or "\n")
+ writer.writerow(published.header)
+ writer.writerows(rows)
+ return buffer.getvalue() # ends with a newline, like splice_row -- see its docstring
+
+
+def render(published, index, new_row, sort):
+ return rewrite_sorted(published, index, new_row) if sort else splice_row(published, index, new_row)
+
+
+def header_languages(header):
+ """Languages the file publishes, read off its own header (every one has a `<lang> WER`)."""
+ return [
+ column[: -len(" WER")]
+ for column in header
+ if column.endswith(" WER") and column != "avg WER"
+ ]
+
+
+def upsert(published, row_name, values, metadata):
+ """Build `row_name`'s row. Returns (action, index, new_row).
+
+ `index` is the model's position in `published.rows`, or None when the model is new; the
+ caller hands both to `render`, which splices only that one line.
+ """
+ header = published.header
+ new_row = [row_name if column == "model" else values.get(column, "") for column in header]
+
+ index = published.index_of(row_name)
+ action = "added" if index is None else "updated"
+ if index is not None:
+ # Keep anything already published in a column this run has no value for: a re-run of
+ # one language must not blank the other languages, and hand-curated metadata must
+ # survive a results-only submission.
+ published_row = published.rows[index]
+ padded = published_row + [""] * (len(header) - len(published_row))
+ new_row = [new if new != "" else old for new, old in zip(new_row, padded)]
+
+ # Metadata is applied after the merge, not through it, so that a flag passed as "" clears the
+ # published cell instead of reading as "this run has no opinion".
+ columns = {column: i for i, column in enumerate(header)}
+ for column, value in metadata.items():
+ if column in columns:
+ new_row[columns[column]] = value
+ return action, index, new_row
+
+
+def recompute_averages(header, row, languages):
+ """Fill the `avg <metric>` columns from the MERGED row's per-language columns, so
+ re-submitting one language keeps the average over everything published. Returns notes to print.
+ """
+ notes = []
+ index = {column: i for i, column in enumerate(header)}
+ for metric in ("WER", "RTFx", "SIM"):
+ avg_column = f"avg {metric}"
+ if avg_column not in index:
+ continue
+ present, missing = [], []
+ for language in languages:
+ column = f"{language} {metric}"
+ if column not in index:
+ continue
+ raw = row[index[column]].strip()
+ if raw:
+ present.append(float(raw))
+ else:
+ missing.append(language)
+ if not present:
+ continue
+ if missing:
+ notes.append(
+ f"NOTE: '{avg_column}' is averaged over the {len(present)} language(s) with a "
+ f"result; no {metric} for: {', '.join(missing)}."
+ )
+ # Published averages carry full precision; 6 decimals only drops binary-float noise.
+ mean = sum(present) / len(present)
+ row[index[avg_column]] = f"{mean:.6f}".rstrip("0").rstrip(".")
+ return notes
+
+
+def show_row(header, row, action, filename, notes=()):
+ print(f"\n{filename} ({action}):")
+ for column, value in zip(header, row):
+ if value != "":
+ print(f" {column:<40} {value}")
+ blanks = [column for column, value in zip(header, row) if value == ""]
+ if blanks:
+ print(f" (blank: {', '.join(blanks)})")
+ for note in notes:
+ print(f" {note}")
+
+
+# ── Main ─────────────────────────────────────────────────────────────────────
+def main():
+ parser = argparse.ArgumentParser(
+ description="Open a PR adding a model's results to the published TTS leaderboard CSVs.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog=__doc__.split("Usage:", 1)[1],
+ )
+ parser.add_argument(
+ "--model_id",
+ required=True,
+ help="Model id as evaluated, e.g. openbmb/VoxCPM2. Selects the bucket folder and the "
+ "manifests, and labels the row unless --row_name overrides it.",
+ )
+ parser.add_argument(
+ "--row_name",
+ default=None,
+ help="Value written into the 'model' column (default: --model_id). Needed when one "
+ "checkpoint is published as several rows, e.g. "
+ "'ResembleAI/chatterbox (ChatterboxMultilingualTTS)'.",
+ )
+ parser.add_argument(
+ "--variant",
+ default="",
+ help="Backend variant embedded in the manifest names between the language and the mode, "
+ "e.g. 'multilingual' (Chatterbox) or 'rl' (CosyVoice 3). Leading '_' optional. "
+ "Default: the plain run, i.e. manifests with no variant.",
+ )
+ parser.add_argument(
+ "--targets",
+ nargs="+",
+ default=None,
+ choices=[*TARGETS, STREAMING_KEY],
+ help="Benchmark files to update (default: every one the model has results for).",
+ )
+ parser.add_argument(
+ "--skip_model_info",
+ action="store_true",
+ help=f"Do not touch {MODEL_INFO_FILE}.",
+ )
+ parser.add_argument(
+ "--engine",
+ default="",
+ help=f"{STREAMING_FILE} only: the inference-engine tag in the TTFA sidecar name (the "
+ "`engine_tag` of a submit_ttfa_jobs.sh target, e.g. 'sglang' or 'ovgguf'). Default: "
+ "the sidecar with no engine tag.",
+ )
+ parser.add_argument(
+ "--note",
+ default=None,
+ help=f"{STREAMING_FILE} 'Note' column. Omitted leaves it as published; '' clears it.",
+ )
+ parser.add_argument("--bucket", default=RESULTS_BUCKET, help="Override the source bucket.")
+ parser.add_argument(
+ "--local_dir",
+ default=None,
+ help="Where to sync results (default: <repo>/results, same place submit_jobs.sh uses).",
+ )
+ parser.add_argument("--skip_sync", action="store_true", help="Score already-downloaded results.")
+ parser.add_argument(
+ "--clean",
+ action="store_true",
+ help="Delete the local copy of the model's folder before syncing, so the bucket is the "
+ "only source of truth (sync alone never deletes).",
+ )
+ parser.add_argument(
+ "--sim_backend",
+ default="wavlm_seed_tts",
+ choices=[XVECTOR_BACKEND, *SIM_BACKEND_SUFFIXES],
+ help="Which SIM scale fills the 'SIM' columns (default: wavlm_seed_tts, the published "
+ "one). The legacy 'xvector' scale has its own column and is always read as well.",
+ )
+ parser.add_argument("--hf_token", default=os.environ.get("HF_TOKEN"), help="Defaults to $HF_TOKEN.")
+ parser.add_argument("--open_pr", action="store_true", help="Actually open the PR (default: dry run).")
+ parser.add_argument("--commit_message", default=None, help="PR title.")
+ parser.add_argument(
+ "--out_dir",
+ default=None,
+ help="Dry run: also write the updated CSVs to this directory.",
+ )
+ parser.add_argument(
+ "--sort",
+ action="store_true",
+ help="Re-sort rows case-insensitively by model, which rewrites the whole file (default: "
+ "append new rows at the end, so the PR diff is the model's one line and merges "
+ f"cleanly with other open PRs). {MODEL_INFO_FILE}, seed_tts.csv, "
+ f"seed_tts_voice_clone.csv, cv3.csv and {STREAMING_FILE} are alphabetical today; cv3_voice_clone.csv "
+ "is ordered by avg WER, so do not sort that one.",
+ )
+
+ meta = parser.add_argument_group(
+ "model_info.csv columns",
+ "Scoring cannot derive these. An omitted flag leaves the published cell as it is; "
+ "passing an empty string clears it.",
+ )
+ meta.add_argument("--license", default=None, help="License, e.g. 'apache-2.0' or a URL to the model's LICENSE.")
+ meta.add_argument("--voice_cloning", default=None, choices=["yes", "no"], help="Model supports voice cloning.")
+ meta.add_argument("--batch_inference", default=None, choices=["yes", "no"], help="Model supports batched inference.")
+ meta.add_argument("--num_languages", default=None, help="Number of languages the model supports.")
+ meta.add_argument("--transformers", default=None, choices=["yes", "no"], help="Model is supported in Transformers.")
+ meta.add_argument("--model_size_b", default=None, help="Total parameters, in billions.")
+ args = parser.parse_args()
+
+ row_name = args.row_name or args.model_id
+ model_safe = args.model_id.replace("/", "-")
+ model_folder = model_safe
+ variant = args.variant
+ if variant and not variant.startswith("_"):
+ variant = f"_{variant}"
+ local_dir = args.local_dir or os.path.join(REPO_ROOT, "results")
+ model_dir = os.path.join(local_dir, model_folder)
+
+ if not args.skip_sync:
+ try:
+ sync_bucket(args.bucket, model_folder, local_dir, args.hf_token, args.clean)
+ except subprocess.CalledProcessError as exc:
+ print(
+ f"ERROR: could not sync {args.bucket}/{model_folder} (exit {exc.returncode}). "
+ f"Check the model folder exists in the bucket and that $HF_TOKEN can read it.",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+ if not os.path.isdir(model_dir):
+ print(f"ERROR: no results directory for {args.model_id}: {model_dir}", file=sys.stderr)
+ sys.exit(1)
+
+ # ── Which manifests feed which file ──────────────────────────────────────
+ target_keys = args.targets or [*TARGETS, STREAMING_KEY]
+ sidecars = {}
+ if STREAMING_KEY in target_keys:
+ sidecars = select_ttfa_sidecars(model_dir, model_safe, variant, args.engine)
+ selection, unmatched = {}, []
+ for key in [k for k in target_keys if k in TARGETS]:
+ records, skipped = select_manifests(model_dir, model_safe, TARGETS[key], variant)
+ if records:
+ selection[key] = records
+ unmatched += skipped
+
+ if not selection and not sidecars:
+ print(f"No manifests or TTFA sidecars for {args.model_id} in {model_dir} matching:")
+ print(f" targets: {', '.join(target_keys)}")
+ print(f" variant: {variant or '(none)'}")
+ print(f" engine: {args.engine or '(none)'}")
+ if unmatched:
+ print("Manifests of the right benchmark that a different --variant would select:")
+ for stem in sorted(set(unmatched)):
+ print(f" {stem}")
+ sys.exit(1)
+
+ # ── Score, one pass per SIM scale ────────────────────────────────────────
+ # Languages are pooled across targets: one call scores every manifest of that language,
+ # whatever file each ends up in.
+ by_language = {}
+ for records in selection.values():
+ for stem, language in records.items():
+ by_language.setdefault(language, set()).add(stem)
+ scored = {}
+ if by_language:
+ print(f"Scoring {sum(len(v) for v in by_language.values())} manifest(s) "
+ f"[{args.sim_backend}] ...")
+ scored = run_scoring(model_dir, args.model_id, by_language, args.sim_backend)
+
+ # The xvector SIM column needs its own pass: one score_results call reports one SIM scale.
+ scored_xvector = {}
+ legacy_by_language = {}
+ if args.sim_backend != XVECTOR_BACKEND:
+ for key, records in selection.items():
+ if not TARGETS[key].xvector_sim:
+ continue
+ for stem, language in records.items():
+ legacy_by_language.setdefault(language, set()).add(stem)
+ if legacy_by_language:
+ print(f"Scoring {sum(len(v) for v in legacy_by_language.values())} manifest(s) "
+ f"[{XVECTOR_BACKEND}, for the legacy SIM column] ...")
+ scored_xvector = run_scoring(model_dir, args.model_id, legacy_by_language, XVECTOR_BACKEND)
+
+ # ── Build the updated files ──────────────────────────────────────────────
+ metadata = {
+ column: getattr(args, arg)
+ for column, arg in METADATA_ARGS.items()
+ if getattr(args, arg) is not None
+ }
+ # 'Transformers' is published as 'Yes' or blank -- there is no 'No' in the file.
+ if metadata.get("Transformers") is not None:
+ metadata["Transformers"] = "Yes" if metadata["Transformers"] == "yes" else ""
+
+ updated = {} # filename -> new content
+ for key in [k for k in TARGETS if k in selection]:
+ target = TARGETS[key]
+ published = fetch_csv(target.filename, args.hf_token)
+ header = published.header
+ languages = header_languages(header)
+ values, unknown = collect_values(
+ target, languages, selection[key], scored, scored_xvector
+ )
+ for stem, language in unknown:
+ sys.stdout.flush() # keep the warning next to the file it is about when piped
+ print(
+ f"\nWARNING: {target.filename} has no '{language}' columns; skipping {stem}.jsonl."
+ + (f" Is '{language}' a language plus a variant? Try --variant." if not variant else ""),
+ file=sys.stderr,
+ )
+ if not values:
+ print(f"\n{target.filename}: nothing scored; skipping.")
+ continue
+ action, index, new_row = upsert(published, row_name, values, {})
+ notes = recompute_averages(header, new_row, languages)
+ show_row(header, new_row, action, target.filename, notes)
+ updated[target.filename] = render(published, index, new_row, args.sort)
+
+ if sidecars:
+ published = fetch_csv(STREAMING_FILE, args.hf_token)
+ values, notes = collect_streaming_values(published.header, sidecars)
+ # Row-level columns shared with other flags: --model_size_b also fills 'Size (B)' here.
+ extra = {}
+ if args.model_size_b is not None:
+ extra[STREAMING_SIZE_COLUMN] = args.model_size_b
+ if args.note is not None:
+ extra[STREAMING_NOTE_COLUMN] = args.note
+ action, index, new_row = upsert(published, row_name, values, extra)
+ show_row(published.header, new_row, action, STREAMING_FILE, notes)
+ updated[STREAMING_FILE] = render(published, index, new_row, args.sort)
+ elif STREAMING_KEY in (args.targets or []):
+ print(f"\n{STREAMING_FILE}: no TTFA sidecar for {args.model_id} "
+ f"(variant: {variant or '(none)'}, engine: {args.engine or '(none)'}); skipping.")
+
+ if not updated:
+ print("\nNo results to submit.")
+ sys.exit(1)
+
+ # model_info.csv: written when metadata was passed, or to give a model its first row.
+ if not args.skip_model_info:
+ published = fetch_csv(MODEL_INFO_FILE, args.hf_token)
+ exists = published.index_of(row_name) is not None
+ # A row published to a *_voice_clone file is a model that clones voices; fill that in
+ # rather than leaving the column blank, unless the flag says otherwise.
+ if "voice cloning" not in metadata and any(TARGETS[k].voice_clone for k in updated_keys(updated)):
+ if not published_value(published, row_name, "voice cloning"):
+ metadata["voice cloning"] = "yes"
+ print("\nmodel_info.csv: 'voice cloning' set to 'yes' (a voice-clone file is being "
+ "written); pass --voice_cloning to override.")
+ if metadata or not exists:
+ action, index, new_row = upsert(published, row_name, {}, metadata)
+ show_row(published.header, new_row, action, MODEL_INFO_FILE)
+ updated[MODEL_INFO_FILE] = render(published, index, new_row, args.sort)
+ else:
+ print(f"\n{MODEL_INFO_FILE}: row already published and no metadata flags given; "
+ f"leaving it alone.")
+
+ if args.out_dir:
+ os.makedirs(args.out_dir, exist_ok=True)
+ for filename, content in updated.items():
+ path = os.path.join(args.out_dir, filename)
+ with open(path, "w", encoding="utf-8") as handle:
+ handle.write(content)
+ print(f"Wrote {path}")
+
+ if not args.open_pr:
+ print(f"\nDry run - not opening a PR. {len(updated)} file(s) would change: "
+ f"{', '.join(sorted(updated))}.\nRe-run with --open_pr to submit.")
+ return
+
+ message = args.commit_message or f"Add {row_name} results"
+ api = HfApi(token=args.hf_token)
+ commit = api.create_commit(
+ repo_id=RESULTS_REPO,
+ repo_type="dataset",
+ operations=[
+ CommitOperationAdd(path_in_repo=filename, path_or_fileobj=content.encode("utf-8"))
+ for filename, content in sorted(updated.items())
+ ],
+ commit_message=message,
+ commit_description=(
+ f"Scored from `{args.bucket}` with `scripts/open_results_pr.py`.\n\n"
+ f"Files: {', '.join(sorted(updated))}"
+ ),
+ create_pr=True,
+ )
+ print(f"\nPR opened: {commit.pr_url}")
+
+
+def updated_keys(updated):
+ """Target keys behind the files written so far."""
+ return [key for key, target in TARGETS.items() if target.filename in updated]
+
+
+def published_value(published, row_name, column):
+ """The value `row_name` already has in `column`, or "" if there is no such row/column."""
+ if column not in published.header:
+ return ""
+ row_index = published.index_of(row_name)
+ column_index = published.header.index(column)
+ if row_index is None:
+ return ""
+ row = published.rows[row_index]
+ return row[column_index].strip() if len(row) > column_index else ""
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/prepare_cv3_eval.py b/scripts/prepare_cv3_eval.py
new file mode 100644
index 0000000..d3fb215
--- /dev/null
+++ b/scripts/prepare_cv3_eval.py
@@ -0,0 +1,300 @@
+"""
+Script to prepare the CV3-Eval benchmark data for the HF hub.
+
+CV3-Eval is the in-the-wild zero-shot TTS benchmark released with CosyVoice 3.
+GitHub: https://github.com/FunAudioLLM/CosyVoice (see the CV3-Eval repo)
+Paper: https://arxiv.org/pdf/2505.17589
+
+Clone the benchmark repo first; this script reads its `data/` tree in place:
+```
+git clone [email protected]:QwenAudio/CV3-Eval.git
+python scripts/prepare_cv3_eval.py bezzam/cv3_eval
+```
+
+The data is organized Kaldi-style: each leaf task dir holds three parallel files keyed by
+utterance id (`<uttid> <value>`, split on the first space) plus a `waveform/` dir:
+
+ text <uttid> text to synthesize (the WER/CER reference)
+ prompt_text <uttid> transcript of the reference clip
+ prompt_wav.scp <uttid> path to the reference clip (relative to the CV3-Eval root)
+ gt_wav.scp <uttid> path to the ground-truth clip (continuation tasks only)
+
+Rows are joined on uttid, NOT on line order. Some parent dirs (e.g. `emotion_zeroshot/en`)
+carry a concatenation of their children's meta files; this script reads the leaves only, so
+the extra per-leaf label (emotion / style) is preserved as a column.
+
+Each task becomes a config of the dataset; each language becomes a split within it:
+
+ zero_shot 11 splits (de en es fr it ja ko ru zh hard_en hard_zh) 5124 rows
+ cross_lingual_zeroshot 6 splits (to_{zh,en,ja,ko,hard_zh,hard_en}) 2524 rows
+ emotion_zeroshot 2 splits (en zh), `emotion` column: angry/happy/sad 300 rows
+ subjective_zeroshot 1 split (test) 194 rows
+ subjective_continue 2 splits (en zh), `style` column + ground_truth_audio 90 rows
+
+`zero_shot_clone_10speak` is NOT uploaded by default (pass it via --configs). It has no
+scoring recipe upstream, and it adds no new content: its target texts are byte-identical to
+`zero_shot`'s and its 10 prompt clips are the `subjective_zeroshot` ones, reused for all 2124
+texts per speaker. Embedding audio per row would duplicate ~4.5 GB of identical bytes, so it
+is emitted WITHOUT `prompt_audio` — join on the `speaker` column against `subjective_zeroshot`.
+
+Usage:
+```
+python scripts/prepare_cv3_eval.py <hf_dataset_id> [--cv3-root CV3-Eval]
+python scripts/prepare_cv3_eval.py <hf_dataset_id> --configs zero_shot emotion_zeroshot
+python scripts/prepare_cv3_eval.py <hf_dataset_id> --dry-run # parse + validate, no upload
+python scripts/prepare_cv3_eval.py <hf_dataset_id>_mini --max-samples-per-leaf 2 # small test copy
+```
+
+The copy is always pushed **private**: the benchmark is redistributed audio, and its license does
+not allow republishing it.
+"""
+
+import argparse
+from pathlib import Path
+
+from datasets import Audio, Dataset, Features, Value
+
+
+# Several `subjective_continue` scp files point at `data/subjective_zeroshot_continue/...`, a
+# directory that does not exist in the release — the audio lives under `data/subjective_continue/`.
+# Applied as a prefix rewrite when the literal path is missing.
+PATH_FIXUPS = {"data/subjective_zeroshot_continue/": "data/subjective_continue/"}
+
+# Config layout. Each entry describes one Hub config:
+# dir: task dir under `data/`
+# splits: {split name -> [leaf dirs relative to `dir`]}. More than one leaf per split means
+# the leaves are concatenated and `label_column` records which leaf a row came from
+# (uttids repeat across leaves, so ids get prefixed with the label to stay unique).
+# label_column: name of that per-leaf column, if any
+# labels: {leaf dir -> label value}; defaults to the leaf dir name
+# ground_truth: read `gt_wav.scp` into a `ground_truth_audio` Audio() column
+# prompt_audio: embed `prompt_wav.scp` as an Audio() column (default True)
+# speaker_from_dir: take a `speaker` column from the leaf's PARENT dir name (10speak only)
+CONFIGS = {
+ "zero_shot": {
+ "dir": "zero_shot",
+ "splits": {lang: [lang] for lang in
+ ["en", "zh", "hard_en", "hard_zh", "ja", "ko", "de", "es", "fr", "it", "ru"]},
+ },
+ "cross_lingual_zeroshot": {
+ "dir": "cross_lingual_zeroshot",
+ "splits": {t: [t] for t in ["to_en", "to_zh", "to_hard_en", "to_hard_zh", "to_ja", "to_ko"]},
+ },
+ "emotion_zeroshot": {
+ "dir": "emotion_zeroshot",
+ "splits": {"en": ["en/angry", "en/happy", "en/sad"], "zh": ["zh/angry", "zh/happy", "zh/sad"]},
+ "label_column": "emotion",
+ "labels": {f"{lang}/{emo}": emo for lang in ("en", "zh") for emo in ("angry", "happy", "sad")},
+ },
+ "subjective_zeroshot": {
+ "dir": "subjective_zeroshot",
+ "splits": {"test": ["."]},
+ },
+ "subjective_continue": {
+ "dir": "subjective_continue",
+ # `rhyme` names its language dirs en_rhyme / zh_rhyme; the rest use plain en / zh.
+ "splits": {
+ "en": ["emotion/en", "rhyme/en_rhyme", "speed/en", "volume/en"],
+ "zh": ["emotion/zh", "rhyme/zh_rhyme", "speed/zh", "volume/zh"],
+ },
+ "label_column": "style",
+ "labels": {f"{style}/{lang}": style
+ for style in ("emotion", "speed", "volume") for lang in ("en", "zh")}
+ | {f"rhyme/{lang}_rhyme": "rhyme" for lang in ("en", "zh")},
+ "ground_truth": True,
+ },
+ # Opt-in. Same texts as `zero_shot`, one fixed prompt per speaker → no prompt_audio (see docstring).
+ "zero_shot_clone_10speak": {
+ "dir": "zero_shot_clone_10speak",
+ "splits": None, # filled in by _expand_10speak(): {lang: [<speaker>/<lang>, ...]}
+ "label_column": "speaker",
+ "prompt_audio": False,
+ "speaker_from_dir": True,
+ },
+}
+
+DEFAULT_CONFIGS = [c for c in CONFIGS if c != "zero_shot_clone_10speak"]
+
+
+def _expand_10speak(task_dir: Path) -> dict[str, list[str]]:
+ """Build {language -> [<speaker>/<language>, ...]} from the speaker dirs present on disk."""
+ speakers = sorted(p.name for p in task_dir.iterdir() if p.is_dir())
+ splits: dict[str, list[str]] = {}
+ for speaker in speakers:
+ for lang_dir in sorted(p.name for p in (task_dir / speaker).iterdir() if p.is_dir()):
+ splits.setdefault(lang_dir, []).append(f"{speaker}/{lang_dir}")
+ return splits
+
+
+def read_keyed_file(path: Path) -> dict[str, str]:
+ """Read a `<uttid> <value>` file into {uttid: value}. Values may contain spaces."""
+ entries = {}
+ with open(path, encoding="utf-8") as f:
+ for lineno, line in enumerate(f, start=1):
+ line = line.rstrip("\n")
+ if not line.strip():
+ continue
+ uttid, _, value = line.partition(" ")
+ if not value:
+ raise ValueError(f"{path}:{lineno} expected '<uttid> <value>', got {line!r}")
+ if uttid in entries:
+ raise ValueError(f"{path}:{lineno} duplicate uttid {uttid!r}")
+ entries[uttid] = value
+ if not entries:
+ raise ValueError(f"{path} is empty")
+ return entries
+
+
+def resolve_audio(rel_path: str, cv3_root: Path) -> str:
+ """Resolve an scp path (relative to the CV3-Eval root) to an existing file, applying fixups."""
+ candidates = [rel_path]
+ for stale, current in PATH_FIXUPS.items():
+ if rel_path.startswith(stale):
+ candidates.append(current + rel_path[len(stale):])
+ for candidate in candidates:
+ resolved = cv3_root / candidate
+ if resolved.is_file():
+ return str(resolved)
+ raise FileNotFoundError(f"audio file not found for {rel_path!r} (tried: {candidates})")
+
+
+def parse_leaf(leaf_dir: Path, cv3_root: Path, *, with_prompt_audio: bool, with_ground_truth: bool) -> list[dict]:
+ """Parse one leaf task dir into records, joining `text` / `prompt_text` / scp files on uttid."""
+ texts = read_keyed_file(leaf_dir / "text")
+ prompt_texts = read_keyed_file(leaf_dir / "prompt_text")
+ prompt_wavs = read_keyed_file(leaf_dir / "prompt_wav.scp") if with_prompt_audio else {}
+ gt_wavs = read_keyed_file(leaf_dir / "gt_wav.scp") if with_ground_truth else {}
+
+ records = []
+ for uttid, text in texts.items():
+ for name, table in (("prompt_text", prompt_texts), ("prompt_wav.scp", prompt_wavs),
+ ("gt_wav.scp", gt_wavs)):
+ if table and uttid not in table:
+ raise KeyError(f"{leaf_dir}: uttid {uttid!r} present in `text` but missing from `{name}`")
+
+ record = {"id": uttid, "prompt_text": prompt_texts[uttid], "text": text}
+ if with_prompt_audio:
+ record["prompt_audio"] = resolve_audio(prompt_wavs[uttid], cv3_root)
+ if with_ground_truth:
+ record["ground_truth_audio"] = resolve_audio(gt_wavs[uttid], cv3_root)
+ records.append(record)
+ return records
+
+
+def build_split(config: dict, leaves: list[str], task_dir: Path, cv3_root: Path,
+ max_per_leaf: int | None = None) -> Dataset:
+ """Parse every leaf of a split, tag rows with the per-leaf label, and build the Dataset.
+
+ `max_per_leaf` caps rows per LEAF, not per split, so a truncated `emotion_zeroshot` still
+ carries all three emotions (and a truncated 10speak split all ten speakers).
+ """
+ with_prompt_audio = config.get("prompt_audio", True)
+ with_ground_truth = config.get("ground_truth", False)
+ label_column = config.get("label_column")
+ labels = config.get("labels", {})
+
+ records = []
+ for leaf in leaves:
+ leaf_dir = task_dir / leaf
+ rows = parse_leaf(leaf_dir, cv3_root, with_prompt_audio=with_prompt_audio,
+ with_ground_truth=with_ground_truth)
+ if max_per_leaf is not None:
+ rows = rows[:max_per_leaf]
+ if label_column:
+ # `<speaker>/<lang>` → speaker; otherwise the configured label (or the leaf name).
+ label = leaf.split("/")[0] if config.get("speaker_from_dir") else labels.get(leaf, Path(leaf).name)
+ for row in rows:
+ row[label_column] = label
+ # uttids restart at uttid_1 in every leaf — prefix so ids stay unique in the split.
+ row["id"] = f"{label}_{row['id']}"
+ records.extend(rows)
+
+ feature_dict = {"id": Value("string")}
+ if label_column:
+ feature_dict[label_column] = Value("string")
+ feature_dict["prompt_text"] = Value("string")
+ if with_prompt_audio:
+ feature_dict["prompt_audio"] = Audio()
+ feature_dict["text"] = Value("string")
+ if with_ground_truth:
+ feature_dict["ground_truth_audio"] = Audio()
+
+ ids = [r["id"] for r in records]
+ if len(set(ids)) != len(ids):
+ raise ValueError(f"duplicate ids after prefixing in {task_dir} ({leaves})")
+
+ columns = {key: [r[key] for r in records] for key in feature_dict}
+ return Dataset.from_dict(columns, features=Features(feature_dict))
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("repo_id", help="HF dataset id to push to, e.g. 'bezzam/cv3_eval'.")
+ parser.add_argument(
+ "--cv3-root",
+ default="CV3-Eval",
+ help="Path to the CV3-Eval checkout (the dir containing `data/`; scp paths are relative to it).",
+ )
+ parser.add_argument(
+ "--configs",
+ nargs="+",
+ default=DEFAULT_CONFIGS,
+ choices=list(CONFIGS),
+ help=f"Configs to upload (default: {' '.join(DEFAULT_CONFIGS)}).",
+ )
+ parser.add_argument(
+ "--max-samples-per-leaf",
+ type=int,
+ default=None,
+ help="Keep only the first N rows of each leaf task dir — for pushing a small test copy "
+ "to a scratch repo id. Capping per leaf keeps every emotion/style/speaker represented.",
+ )
+ parser.add_argument("--dry-run", action="store_true", help="Parse and validate only; do not upload.")
+ args = parser.parse_args()
+
+ cv3_root = Path(args.cv3_root)
+ data_dir = cv3_root / "data"
+ if not data_dir.is_dir():
+ raise SystemExit(f"{data_dir} not found — pass --cv3-root pointing at the CV3-Eval checkout.")
+
+ total = 0
+ for config_name in args.configs:
+ config = CONFIGS[config_name]
+ task_dir = data_dir / config["dir"]
+ if not task_dir.is_dir():
+ print(f"Skipping config '{config_name}': {task_dir} not found.")
+ continue
+
+ splits = config["splits"] or _expand_10speak(task_dir)
+ for split, leaves in splits.items():
+ missing = [leaf for leaf in leaves if not (task_dir / leaf / "text").is_file()]
+ if missing:
+ print(f"Skipping '{config_name}/{split}': no `text` file in {missing}.")
+ continue
+
+ print(f"Parsing '{config_name}/{split}' from {len(leaves)} leaf dir(s) ...")
+ dataset = build_split(config, leaves, task_dir, cv3_root, args.max_samples_per_leaf)
+ print(f" {len(dataset)} examples, columns: {', '.join(dataset.column_names)}")
+ total += len(dataset)
+
+ if args.dry_run:
+ continue
+ print(f"Pushing config '{config_name}' split '{split}' to {args.repo_id} ...")
+ dataset.push_to_hub(
+ args.repo_id,
+ config_name=config_name,
+ # Always private — the license does not permit redistributing this benchmark.
+ private=True,
+ split=split,
+ )
+ print(f" done ({config_name}/{split}).")
+
+ print(f"\n{total} examples across {len(args.configs)} config(s).")
+ if args.dry_run:
+ print("Dry run — nothing uploaded.")
+ else:
+ print(f"Uploaded to https://huggingface.co/datasets/{args.repo_id}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/prepare_seed_tts_eval.py b/scripts/prepare_seed_tts_eval.py
new file mode 100644
index 0000000..6563a25
--- /dev/null
+++ b/scripts/prepare_seed_tts_eval.py
@@ -0,0 +1,141 @@
+"""
+Script to prepare the seed TTS evaluation data for the HF hub.
+
+GitHub: https://github.com/BytedanceSpeech/seed-tts-eval
+Download link: https://drive.google.com/file/d/1GlSjVfSHkW3-leKKBlfrjuuTGqQ_xaLP/edit
+
+Download via CLI:
+```
+pip install gdown --break-system-packages
+gdown 1GlSjVfSHkW3-leKKBlfrjuuTGqQ_xaLP -O seedtts_testset.tar
+tar -xf seedtts_testset.tar
+```
+
+The test set is organized using meta files. Each line is pipe-separated:
+
+ filename | prompt text | prompt audio | text to synthesize | ground truth audio (if exists)
+
+Different tasks use different meta files. This script uploads the English and Chinese data:
+ - Zero-shot TTS: {en,zh}/meta.lst (4 fields, no ground truth)
+ - Zero-shot TTS (hard case): zh/hardcase.lst (4 fields, no ground truth, ZH only)
+ - Zero-shot voice conversion: {en,zh}/non_para_reconstruct_meta.lst (5 fields, with ground truth)
+
+Each task is pushed as a config of the dataset; each language is a split within it.
+The ZH-only hard cases live under the `tts` config as a `zh_hard` split.
+
+Usage:
+```
+python scripts/prepare_seed_tts_eval.py <hf_dataset_id> [--data-dir seedtts_testset] [--langs en zh]
+```
+"""
+
+import argparse
+from pathlib import Path
+
+from datasets import Audio, Dataset, Features, Value
+
+
+# One entry per meta file:
+# config: config name (Hub config)
+# meta: meta file relative to the language dir
+# has_ground_truth: whether the meta file has a 5th ground-truth-audio field
+# langs: languages for which this task exists
+# split: optional split-name override (defaults to the language), e.g. `zh_hard`
+TASKS = [
+ {"config": "tts", "meta": "meta.lst", "has_ground_truth": False, "langs": ["en", "zh"]},
+ {"config": "tts", "meta": "hardcase.lst", "has_ground_truth": False, "langs": ["zh"], "split": "zh_hard"},
+ {"config": "voice_conversion", "meta": "non_para_reconstruct_meta.lst", "has_ground_truth": True, "langs": ["en", "zh"]},
+]
+
+
+def parse_meta(meta_path: Path, lang_dir: Path, has_ground_truth: bool) -> list[dict]:
+ """Parse a pipe-separated meta file into a list of records with absolute audio paths."""
+ records = []
+ with open(meta_path, encoding="utf-8") as f:
+ for lineno, line in enumerate(f, start=1):
+ line = line.rstrip("\n")
+ if not line:
+ continue
+ fields = line.split("|")
+ expected = 5 if has_ground_truth else 4
+ if len(fields) != expected:
+ raise ValueError(
+ f"{meta_path}:{lineno} expected {expected} fields, got {len(fields)}: {line!r}"
+ )
+
+ record = {
+ "id": fields[0],
+ "prompt_text": fields[1],
+ "prompt_audio": str(lang_dir / fields[2]),
+ "text": fields[3],
+ }
+ if has_ground_truth:
+ record["ground_truth_audio"] = str(lang_dir / fields[4])
+ records.append(record)
+ return records
+
+
+def build_dataset(records: list[dict], has_ground_truth: bool) -> Dataset:
+ feature_dict = {
+ "id": Value("string"),
+ "prompt_text": Value("string"),
+ "prompt_audio": Audio(),
+ "text": Value("string"),
+ }
+ if has_ground_truth:
+ feature_dict["ground_truth_audio"] = Audio()
+
+ columns = {key: [r[key] for r in records] for key in feature_dict}
+ return Dataset.from_dict(columns, features=Features(feature_dict))
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("repo_id", help="HF dataset id to push to, e.g. 'username/seedtts-eval-en'")
+ parser.add_argument(
+ "--data-dir",
+ default="seedtts_testset",
+ help="Path to the extracted seedtts_testset directory (default: seedtts_testset).",
+ )
+ parser.add_argument(
+ "--langs",
+ nargs="+",
+ default=["en", "zh"],
+ help="Language subdirectories to upload (default: en zh).",
+ )
+ args = parser.parse_args()
+
+ data_dir = Path(args.data_dir)
+
+ for task in TASKS:
+ config_name = task["config"]
+ has_ground_truth = task["has_ground_truth"]
+ langs = [lang for lang in args.langs if lang in task["langs"]]
+ for lang in langs:
+ split = task.get("split", lang)
+ lang_dir = data_dir / lang
+ meta_path = lang_dir / task["meta"]
+ if not meta_path.is_file():
+ print(f"Skipping '{config_name}/{split}': {meta_path} not found.")
+ continue
+
+ print(f"Parsing '{config_name}/{split}' from {meta_path} ...")
+ records = parse_meta(meta_path, lang_dir, has_ground_truth)
+ dataset = build_dataset(records, has_ground_truth)
+ print(f" {len(dataset)} examples")
+
+ print(f"Pushing config '{config_name}' split '{split}' to {args.repo_id} ...")
+ dataset.push_to_hub(
+ args.repo_id,
+ config_name=config_name,
+ # Always private — the license does not permit redistributing this test set.
+ private=True,
+ split=split,
+ )
+ print(f" done ({config_name}/{split}).")
+
+ print(f"Uploaded to https://huggingface.co/datasets/{args.repo_id}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/run_eval_utils.py b/scripts/run_eval_utils.py
new file mode 100644
index 0000000..a1f62a8
--- /dev/null
+++ b/scripts/run_eval_utils.py
@@ -0,0 +1,210 @@
+"""Helpers shared by every backend's run_eval.py (stage 1: TTS generation).
+
+Injected into each generation job at /app/scripts/ (see `inject_run_eval` in
+scripts/tts_jobs_common.sh), which the job puts on PYTHONPATH, so a backend simply does
+`from run_eval_utils import ...`. To run a backend directly from the repo root:
+
+ PYTHONPATH=scripts python kokoro/run_eval.py ...
+
+Must stay importable without torch or `datasets` at module level: some images lack one or the other.
+"""
+
+import json
+import os
+import random
+from types import SimpleNamespace
+
+DEFAULT_WARMUP_STEPS = 2
+
+
+# ── Reproducibility / reporting ──────────────────────────────────────────────
+def set_seed(seed=42):
+ """Seed Python, NumPy and (if installed) torch, on every CUDA device."""
+ random.seed(seed)
+ try:
+ import numpy as np
+
+ np.random.seed(seed)
+ except ImportError:
+ pass
+ try:
+ import torch
+
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+ except ImportError:
+ pass
+
+
+def count_parameters(*objs):
+ """Sum unique parameters across the given nn.Modules (or the nn.Module attributes of wrappers)."""
+ import torch
+
+ modules = []
+ for o in objs:
+ if isinstance(o, torch.nn.Module):
+ modules.append(o)
+ elif o is not None:
+ modules += [m for m in vars(o).values() if isinstance(m, torch.nn.Module)]
+ seen, total = set(), 0
+ for m in modules:
+ for p in m.parameters():
+ if id(p) not in seen:
+ seen.add(id(p))
+ total += p.numel()
+ return total
+
+
+def print_model_size(*objs):
+ """Print the parameter count of `objs` (see count_parameters); silent if it finds none."""
+ n_params = count_parameters(*objs)
+ if n_params:
+ print(f"TTS model size: {n_params / 1e9:.2f}B parameters")
+
+
+# ── Dataset ──────────────────────────────────────────────────────────────────
+def load_tts_dataset(args, extra_columns=(), decode_audio=True):
+ """Load `args.dataset_path` (config `args.dataset`, split `args.split`), ready for generation.
+
+ Applies `--max_eval_samples`, adds a positional `id` when the dataset has none (it names the
+ wavs), and keeps only `id`, `args.text_column` and `extra_columns`, so nothing else triggers
+ audio decoding. `decode_audio=False` leaves `prompt_audio` as raw bytes.
+ """
+ from datasets import Audio, load_dataset
+
+ kwargs = {"split": args.split}
+ if args.dataset:
+ kwargs["name"] = args.dataset
+ dataset = load_dataset(args.dataset_path, **kwargs)
+ if args.max_eval_samples is not None and args.max_eval_samples > 0:
+ print(f"Subsampling dataset to first {args.max_eval_samples} samples!")
+ dataset = dataset.select(range(min(args.max_eval_samples, len(dataset))))
+ if "id" not in dataset.column_names:
+ dataset = dataset.add_column("id", list(range(len(dataset))))
+ keep = {"id", args.text_column, *extra_columns}
+ dataset = dataset.remove_columns([c for c in dataset.column_names if c not in keep])
+ if not decode_audio and "prompt_audio" in dataset.column_names:
+ dataset = dataset.cast_column("prompt_audio", Audio(decode=False))
+ return dataset
+
+
+# ── Output layout + manifest ─────────────────────────────────────────────────
+def output_paths(args, mode_suffix=""):
+ """Paths for one (model, dataset split): results/<model_safe>/{<manifest>.jsonl, <dataset_dir>/}.
+
+ Manifest `audio_filepath`s are relative to `model_dir`, so later stages resolve them wherever
+ the folder is copied. Creates `output_dir`.
+ """
+ model_safe = args.model_id.replace("/", "-")
+ dataset_safe = args.dataset_path.replace("/", "-")
+ model_dir = os.path.join("results", model_safe)
+ dataset_dir_name = f"{dataset_safe}_{args.dataset}_{args.split}{mode_suffix}"
+ output_dir = os.path.join(model_dir, dataset_dir_name)
+ os.makedirs(output_dir, exist_ok=True)
+ manifest_path = os.path.join(
+ model_dir,
+ f"MODEL_{model_safe}_DATASET_{dataset_safe}_{args.dataset.replace('/', '-')}_{args.split}{mode_suffix}.jsonl",
+ )
+ return SimpleNamespace(
+ model_safe=model_safe, model_dir=model_dir, dataset_dir_name=dataset_dir_name,
+ output_dir=output_dir, manifest_path=manifest_path,
+ )
+
+
+def wav_rel_path(dataset_dir_name, sample_id):
+ """Manifest `audio_filepath` of a sample's generated wav (relative to `model_dir`)."""
+ return os.path.join(dataset_dir_name, f"output_{sample_id}.wav")
+
+
+def load_done_entries(manifest_path, resume):
+ """{audio_filepath: entry} already in the manifest when resuming, else {}."""
+ done = {}
+ if resume and os.path.exists(manifest_path):
+ with open(manifest_path, encoding="utf-8") as f:
+ for line in f:
+ if line.strip():
+ entry = json.loads(line)
+ if entry.get("audio_filepath"):
+ done[entry["audio_filepath"]] = entry
+ print(f"Resuming: {len(done)} samples already in manifest.")
+ return done
+
+
+def open_manifest(manifest_path, done_entries):
+ """Open the manifest for appending (resume) or fresh writing."""
+ return open(manifest_path, "a" if done_entries else "w", encoding="utf-8")
+
+
+def manifest_entry(audio_filepath, duration, time, text, prompt_audio_filepath=None):
+ """One manifest row. `pred_text` is filled by stage 2 (ASR); `sim` by stage 3 (voice cloning)."""
+ entry = {"audio_filepath": audio_filepath, "duration": duration, "time": time, "text": text, "pred_text": ""}
+ if prompt_audio_filepath is not None:
+ entry["prompt_audio_filepath"] = prompt_audio_filepath
+ entry["sim"] = ""
+ return entry
+
+
+def write_entry(manifest_file, entry):
+ manifest_file.write(json.dumps(entry, ensure_ascii=False) + "\n")
+
+
+# ── Batching / warm-up ───────────────────────────────────────────────────────
+def pending_batches(dataset, batch_size, done_entries, dataset_dir_name):
+ """Start indices of the batches with at least one sample not yet in the manifest."""
+ ids = dataset["id"]
+ return [
+ start for start in range(0, len(ids), batch_size)
+ if not all(wav_rel_path(dataset_dir_name, sid) in done_entries for sid in ids[start : start + batch_size])
+ ]
+
+
+def warm_up(generate_fn, dataset, batch_starts, batch_size, steps=DEFAULT_WARMUP_STEPS):
+ """Run `generate_fn(batch)` untimed on the first `steps` pending batches.
+
+ Only pending batches are used, so anything warm-up writes is regenerated (and timed) by the
+ main loop, and resumed rows are never touched.
+ """
+ from tqdm import tqdm
+
+ for start in tqdm(batch_starts[:steps], desc="Warming up..."):
+ generate_fn(dataset[start : start + batch_size])
+
+
+def add_common_args(parser, batch_size=None, voice_clone=None):
+ """Add the flags every backend shares. `batch_size` / `voice_clone` add those flags when given
+ (their value is the default). Change another default with `parser.set_defaults(...)`."""
+ import argparse
+
+ parser.add_argument("--dataset_path", type=str, default="bezzam/seed_tts_eval",
+ help="Dataset repo id (scripts/prepare_seed_tts_eval.py or prepare_cv3_eval.py).")
+ parser.add_argument("--dataset", type=str, default="tts",
+ help="Dataset config: 'tts' (Seed-TTS) or 'zero_shot' (CV3-Eval).")
+ parser.add_argument("--split", type=str, default="en", help="Split / language, e.g. 'en'.")
+ parser.add_argument("--text_column", type=str, default="text",
+ help="Column holding the target text to synthesize (the WER reference).")
+ parser.add_argument("--device", type=str, default="cuda", help="'cuda', 'cpu', or 'cuda:0'.")
+ parser.add_argument("--seed", type=int, default=42, help="Random seed.")
+ parser.add_argument("--max_eval_samples", type=int, default=None,
+ help="Evaluate only the first N samples (e.g. 8 for testing).")
+ parser.add_argument("--warmup_steps", type=int, default=DEFAULT_WARMUP_STEPS,
+ help="Untimed warm-up batches before generation (excluded from RTFx).")
+ parser.add_argument("--resume", action="store_true",
+ help="Skip samples already in the manifest (resume after OOM/crash).")
+ parser.add_argument("--ttfa_probe", type=int, default=0,
+ help="Measure time-to-first-audio: N evenly spaced samples, or -1 for the whole "
+ "split; 0 disables. Writes ONLY a JSON sidecar — no wavs, no manifest.")
+ if batch_size is not None:
+ parser.add_argument("--batch_size", type=int, default=batch_size,
+ help="Samples per batch (also the manifest-writing / resume granularity).")
+ if voice_clone is not None:
+ parser.add_argument("--voice_clone", action=argparse.BooleanOptionalAction, default=voice_clone,
+ help="Clone each sample's prompt_audio/prompt_text speaker (adds SIM scoring "
+ "and the '_voice_clone' suffix). Default: the model's own voice.")
+
+
+def print_next_steps(voice_clone):
+ """Final message of stage 1, naming the remaining pipeline stages."""
+ if voice_clone:
+ print("Stage 1 (TTS generation) complete. Run stage 2 (transcribe), stage 3 (SIM), stage 4 (score) next.")
+ else:
+ print("Stage 1 (TTS generation) complete. Run stage 2 (transcribe) + stage 4 (score) next (no SIM).")
diff --git a/scripts/score_model.py b/scripts/score_model.py
new file mode 100644
index 0000000..2e62c3a
--- /dev/null
+++ b/scripts/score_model.py
@@ -0,0 +1,112 @@
+"""
+Score an already-generated TTS eval manifest for a given model.
+
+Runs directly on the host, given the `normalizer/` deps from requirements.txt.
+
+Usage:
+```
+python scripts/score_model.py --model_id microsoft/speecht5_tts
+python scripts/score_model.py --model_id microsoft/speecht5_tts --results_dir results --language en
+```
+
+If no manifest for the model is found under --results_dir, the model's folder is first synced
+(manifests only, no wavs) from the results bucket (default: hf-audio/tts_leaderboard_h200) — the
+same sync `scripts/open_results_pr.py` and `submit_jobs.sh` do. Pass --sync to re-sync even when
+local results exist, or --no_sync to never touch the bucket.
+"""
+
+import argparse
+import glob
+import os
+import subprocess
+import sys
+
+REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, REPO_ROOT) # so `from normalizer import eval_utils` resolves regardless of cwd
+
+from normalizer import eval_utils # noqa: E402
+
+RESULTS_BUCKET = "hf-audio/tts_leaderboard_h200"
+
+
+def has_local_results(results_dir, model_id, manifests=None):
+ """Whether `results_dir` already holds manifests for `model_id` (same match as score_results)."""
+ model_safe = model_id.replace("/", "-")
+ found = [
+ fp for fp in glob.glob(os.path.join(results_dir, "**", "*.jsonl"), recursive=True)
+ if f"/{model_safe}/" in fp or f"MODEL_{model_safe}_DATASET_" in fp
+ ]
+ if manifests:
+ wanted = {os.path.basename(m).removesuffix(".jsonl") for m in manifests}
+ found = [fp for fp in found if any(os.path.basename(fp).startswith(w) for w in wanted)]
+ return bool(found)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--model_id", type=str, required=True, help="Model id to score, e.g. 'microsoft/speecht5_tts'.")
+ parser.add_argument(
+ "--results_dir",
+ type=str,
+ default=os.path.join(REPO_ROOT, "results"),
+ help="Directory containing manifest jsonl files (default: results at repo root).",
+ )
+ parser.add_argument("--language", type=str, default="en", help="Language code for normalization (e.g. 'en', 'de').")
+ parser.add_argument(
+ "--multilingual",
+ action=argparse.BooleanOptionalAction,
+ default=None,
+ help="Apply compound-word boundary normalization before scoring. Default: on for "
+ "non-English alphabetic languages, off for English and CJK (scored per character).",
+ )
+ parser.add_argument("--csv_only", action="store_true", help="Suppress the per-dataset and composite printouts.")
+ parser.add_argument(
+ "--manifests",
+ nargs="+",
+ default=None,
+ help="Only score these manifest files (basenames or paths). --language applies to every "
+ "manifest scored in one call and only CJK is auto-detected, so a folder holding several "
+ "languages must be scored one language at a time, naming just that language's manifests.",
+ )
+ parser.add_argument(
+ "--sim_backend",
+ type=str,
+ default="wavlm_seed_tts",
+ choices=["xvector", "wavlm_seed_tts"],
+ help="Which SIM manifest family to score. 'wavlm_seed_tts' (default) reads the "
+ "_wavlm_seed_tts.jsonl forks the seed-tts-eval SIM model writes, falling back to the plain "
+ "manifest (WER/RTFx only) where none exists; 'xvector' reads only the plain manifests. Only "
+ "one family per call — the two SIM scales must not be averaged together.",
+ )
+ parser.add_argument("--bucket", type=str, default=RESULTS_BUCKET, help="Bucket to sync missing results from.")
+ sync_group = parser.add_mutually_exclusive_group()
+ sync_group.add_argument("--sync", action="store_true", help="Sync from the bucket even if local results exist.")
+ sync_group.add_argument("--no_sync", action="store_true", help="Never sync from the bucket.")
+ args = parser.parse_args()
+
+ if args.sync or (not args.no_sync and not has_local_results(args.results_dir, args.model_id, args.manifests)):
+ sys.path.insert(0, os.path.join(REPO_ROOT, "scripts"))
+ from open_results_pr import sync_bucket # noqa: E402
+
+ model_folder = args.model_id.replace("/", "-")
+ if not args.sync:
+ print(f"No local results for {args.model_id} in {args.results_dir}; syncing from {args.bucket}.")
+ try:
+ sync_bucket(args.bucket, model_folder, args.results_dir, os.environ.get("HF_TOKEN"))
+ except subprocess.CalledProcessError as exc:
+ print(
+ f"ERROR: could not sync {args.bucket}/{model_folder} (exit {exc.returncode}). "
+ f"Check the model folder exists in the bucket and that $HF_TOKEN can read it.",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+ eval_utils.score_results(
+ args.results_dir,
+ model_id=args.model_id,
+ multilingual=args.multilingual,
+ csv_only=args.csv_only,
+ language=args.language,
+ manifests=args.manifests,
+ sim_backend=args.sim_backend,
+ )
diff --git a/scripts/ttfa_probe.py b/scripts/ttfa_probe.py
new file mode 100644
index 0000000..bc83386
--- /dev/null
+++ b/scripts/ttfa_probe.py
@@ -0,0 +1,238 @@
+"""
+Shared time-to-first-audio (TTFA) probe for the Open TTS Leaderboard backends.
+
+TTFA answers "how long after the request does the caller have audio it can start playing?".
+It is measured as:
+
+ ttfa = (first_audio_timestamp - request_start) when the backend streams
+ (generation_finished - request_start) when it does not
+
+A model that returns a whole utterance cannot start playback until generation ends, so the
+fallback is the honest number for it. The sidecar records `streaming` so the two clocks (which
+differ by ~100x) are never silently mixed.
+
+The probe writes ONLY a JSON sidecar (no wavs, no manifest), so it is safe to run against a
+results tree that already holds completed evals.
+
+Backends integrate by building a list of jobs and one `gen` callable; see `run_probe`.
+
+IMPORTANT — batch size 1. TTFA is a per-request latency, so `gen` must synthesize exactly one
+utterance per call even when the backend's normal eval path batches. A minibatch of N makes
+"time to first audio" meaningless for any single request in it.
+"""
+
+import inspect
+import json
+import os
+import time
+
+# Rows excluded from the headline summary: the first generations pay residual warm-up and, on
+# backends that encode a reference clip, one-off kernel selection per first-seen audio shape.
+WARMUP_DISCARD = 3
+
+# Default probe size: the whole split (500 rows for CV3-Eval zero_shot/en). The median settles in
+# a few dozen rows, but a p95 needs the full split: ~25 rows above it, not the 2-3 of a 50-row run.
+DEFAULT_SAMPLES = -1
+
+# A first-chunk timestamp is NOT sufficient evidence of streaming: a buffered HTTP response can
+# arrive in several chunks that all land at the end. Real streaming means first audio arrives
+# meaningfully before generation ends, so the verdict is taken from ttfa/gen, not the plumbing.
+STREAMING_MAX_FRAC = 0.95
+
+# Rows generated to completion (for ttfa_frac_of_gen and batch-1 throughput) before the probe
+# starts aborting after first audio to buy a cheap p90/p95 tail. Only backends whose gen() accepts
+# an `early_stop` argument can abort; blocking ones are always full-generation.
+FULL_GEN_SAMPLES = 50
+
+
+def resolve_n(n, total):
+ """Number of samples to probe, given the flag and the split size; negative means the whole split."""
+ return total if n < 0 else min(n, total)
+
+
+def sample_indices(n, total):
+ """Which rows to probe: evenly spaced across the split, NOT the first n.
+
+ Some splits (e.g. CV3-Eval zero_shot/en) are ordered short-first, so a prefix would understate
+ batch-1 RTFx. Deterministic, so every model is probed on the same utterances.
+ """
+ if n < 0 or n >= total:
+ return list(range(total))
+ if n == 0:
+ return []
+ # Float step so the picks stay spread over the whole split when total % n != 0.
+ step = total / n
+ return [min(total - 1, int(i * step)) for i in range(n)]
+
+
+def _summary(values):
+ """p50/p90/p95/min/max over the non-None values, or None if there are none."""
+ values = sorted(v for v in values if v is not None)
+ if not values:
+ return None
+
+ def pct(q):
+ return values[min(len(values) - 1, int(round(q / 100.0 * (len(values) - 1))))]
+
+ return {
+ "n": len(values),
+ "p50": round(pct(50), 2),
+ "p90": round(pct(90), 2),
+ "p95": round(pct(95), 2),
+ "min": round(values[0], 2),
+ "max": round(values[-1], 2),
+ }
+
+
+def probe_filename(model_safe, dataset_safe, dataset_config, split, mode_suffix=""):
+ """Sidecar name, mirroring the manifest convention so the two sort together."""
+ config = str(dataset_config).replace("/", "-")
+ return f"TTFA_MODEL_{model_safe}_DATASET_{dataset_safe}_{config}_{split}{mode_suffix}.json"
+
+
+def run_probe(gen, jobs, *, model_id, dataset_path, dataset_config, split, out_dir,
+ mode_suffix="", sample_rate=None, n=DEFAULT_SAMPLES, extra=None, verbose=True):
+ """Measure TTFA over the first `n` jobs and write a JSON sidecar. Returns the payload.
+
+ `gen(job)` — or `gen(job, early_stop)` for a backend that can abort once it has the first
+ audio — must synthesize ONE utterance and return either:
+ (audio_1d, first_ts) — `sample_rate` then comes from this function's argument
+ (audio_1d, sample_rate, first_ts)
+
+ where `first_ts` is a `time.perf_counter()` reading taken the moment the first audio became
+ available, or None if the backend has no streaming API (the whole-utterance fallback above).
+ `audio_1d` is any float array-like (only its length is used, for the audio duration), or a
+ plain float/int giving that duration in SECONDS directly.
+
+ `jobs` is whatever `gen` accepts — this function only slices and counts it. `n` follows
+ resolve_n(): negative means every job supplied.
+ """
+ total = resolve_n(n, len(jobs))
+ # A gen() taking a second parameter can stop as soon as it has the first audio.
+ supports_early = len(inspect.signature(gen).parameters) >= 2
+ rows = []
+ for index in range(total):
+ early = supports_early and index >= FULL_GEN_SAMPLES
+ start = time.perf_counter()
+ result = gen(jobs[index], early) if supports_early else gen(jobs[index])
+ end = time.perf_counter()
+
+ if len(result) == 3:
+ audio, row_sample_rate, first = result
+ else:
+ audio, first = result
+ row_sample_rate = sample_rate
+ if not row_sample_rate and not isinstance(audio, (int, float)):
+ raise ValueError("sample_rate must be provided by gen() or passed to run_probe()")
+
+ reported = first is not None
+ audio_s = float(audio) if isinstance(audio, (int, float)) else len(audio) / float(row_sample_rate)
+ gen_s = end - start
+ ttfa_ms = ((first if reported else end) - start) * 1000.0
+ rows.append({
+ "index": index,
+ "ttfa_ms": ttfa_ms,
+ # Did the backend hand back a first-chunk timestamp at all...
+ "first_reported": reported,
+ # False => generation was aborted once the first audio arrived, so gen_s/audio_s are
+ # partial and ttfa_frac_of_gen is undefined. Only ttfa_ms is meaningful on these rows.
+ "full_generation": not early,
+ # ...and did that first audio actually arrive early? 1.00 means it landed only when
+ # generation finished, i.e. nothing was really incremental. Full rows only.
+ "ttfa_frac_of_gen": (ttfa_ms / 1000.0 / gen_s) if (gen_s and not early) else None,
+ "gen_s": gen_s,
+ "audio_s": audio_s,
+ })
+ if verbose:
+ r = rows[-1]
+ frac = r["ttfa_frac_of_gen"]
+ if early:
+ kind = "early-stop"
+ else:
+ kind = "stream" if (reported and frac is not None and frac < STREAMING_MAX_FRAC) else "whole-utterance"
+ # frac is None on early-stopped rows (and when gen_s is 0), so it cannot use a float format.
+ frac_s = f"{frac:.2f}" if frac is not None else " n/a"
+ print(f" [{index + 1}/{total}] ttfa {r['ttfa_ms']:8.1f} ms ({kind}) "
+ f"gen {r['gen_s']:5.2f}s ttfa/gen {frac_s} audio {r['audio_s']:5.2f}s", flush=True)
+
+ if not rows:
+ raise ValueError("TTFA probe ran zero samples — is the dataset split empty?")
+
+ warm = rows[WARMUP_DISCARD:] or rows
+ # Diagnostics that need a COMPLETE generation come only from the full rows; folding an
+ # early-aborted row into gen_s or rtfx would corrupt the very numbers this split preserves.
+ warm_full = [r for r in warm if r["full_generation"]]
+ # Verdict from the measurements, not from whether a timestamp was handed back.
+ fracs = [r["ttfa_frac_of_gen"] for r in warm_full if r["ttfa_frac_of_gen"] is not None]
+ median_frac = sorted(fracs)[len(fracs) // 2] if fracs else None
+ any_streaming = (
+ any(r["first_reported"] for r in warm_full)
+ and median_frac is not None
+ and median_frac < STREAMING_MAX_FRAC
+ )
+ audio_s = sum(r["audio_s"] for r in warm_full)
+ gen_s = sum(r["gen_s"] for r in warm_full)
+ payload = {
+ "model_id": model_id,
+ "dataset_path": dataset_path,
+ "dataset": dataset_config,
+ "split": split,
+ "mode_suffix": mode_suffix,
+ # TTFA is a single-request latency; batching would make it meaningless (see the module docstring).
+ "batch_size": 1,
+ "n_samples": len(rows),
+ "warmup_excluded": WARMUP_DISCARD if len(rows) > WARMUP_DISCARD else 0,
+ # False => first audio is not available before generation ends, so these values are the
+ # whole-utterance clock. Do NOT compare them against real streaming values naively.
+ "streaming": any_streaming,
+ # Median ttfa/gen over the summarised rows. ~1.0 is the signature of a buffered path,
+ # however many chunks its transport happened to split the response into.
+ "ttfa_frac_of_gen": round(median_frac, 3) if median_frac is not None else None,
+ # True when a backend DID report first-chunk timestamps that turned out not to be early:
+ # the code path looks streaming but the server is not. Worth investigating, not trusting.
+ "first_reported_but_not_early": bool(
+ any(r["first_reported"] for r in warm_full) and not any_streaming
+ ),
+ # TTFA over EVERY warm row — that is the point of early-aborting the tail.
+ "ttfa_ms": _summary([r["ttfa_ms"] for r in warm]),
+ # Throughput/diagnostics over the fully-generated rows only.
+ "gen_s": _summary([r["gen_s"] for r in warm_full]),
+ "full_generation_rows": len(warm_full),
+ "early_stopped_rows": len(warm) - len(warm_full),
+ # NOT the leaderboard RTFx: this is throughput at batch size 1, whereas the eval measures
+ # RTFx at each backend's real batch size. The two can differ by an order of magnitude.
+ "rtfx_batch1": round(audio_s / gen_s, 2) if gen_s else None,
+ "samples": rows,
+ }
+ if extra:
+ payload.update(extra)
+
+ os.makedirs(out_dir, exist_ok=True)
+ path = os.path.join(out_dir, probe_filename(
+ model_id.replace("/", "-"), dataset_path.replace("/", "-"),
+ dataset_config, split, mode_suffix))
+ with open(path, "w", encoding="utf-8") as f:
+ json.dump(payload, f, indent=1, ensure_ascii=False)
+
+ if verbose and payload["early_stopped_rows"]:
+ print(f" ({payload['full_generation_rows']} rows generated fully for the diagnostics, "
+ f"{payload['early_stopped_rows']} aborted after first audio)")
+ if any_streaming:
+ kind = f"streaming, first audio at {median_frac:.0%} of generation"
+ elif payload["first_reported_but_not_early"]:
+ # Either a single chunk was emitted (first audio IS last audio) or a buffered response
+ # arrived in chunks only at the end; the backend's chunk count in the sidecar tells which.
+ kind = (f"NOT streaming: first audio arrived at {median_frac:.0%} of generation — "
+ "either a single chunk was emitted, or chunks only landed once it had finished")
+ else:
+ kind = "whole-utterance (no streaming API)"
+ # One greppable line carrying both headline numbers, so a caller driving many probes can
+ # report them without re-reading the sidecar. submit_ttfa_jobs.sh matches on "TTFA SUMMARY".
+ t = payload["ttfa_ms"] or {}
+ rtfx = payload["rtfx_batch1"]
+ print(f"\nTTFA SUMMARY [{kind}] n={t.get('n', 0)} (warm-up excluded)"
+ f" | TTFA p50 {t.get('p50', float('nan')):.1f} ms, p90 {t.get('p90', float('nan')):.1f} ms,"
+ f" p95 {t.get('p95', float('nan')):.1f} ms"
+ f" | RTFx(batch1) {rtfx if rtfx is not None else 'n/a'}")
+ print("TTFA probe written to:", os.path.abspath(path))
+ return payload
diff --git a/scripts/tts_jobs_common.sh b/scripts/tts_jobs_common.sh
new file mode 100644
index 0000000..0e06ad5
--- /dev/null
+++ b/scripts/tts_jobs_common.sh
@@ -0,0 +1,377 @@
+#!/bin/bash
+# Shared orchestration for the per-backend TTS-eval submit_jobs.sh scripts (HF Jobs + buckets).
+#
+# A backend script sources this file, then:
+# 1. sets TTS_SPACE (+ any backend-specific env) and RUN_EVAL_INJECT
+# 2. defines generate_stage() — the stage-1 (TTS generation) job for one (model, dataset)
+# 3. optionally defines resolve_mode() — sets CLONE / MODE_SUFFIX per model (default: no clone)
+# 4. sets MODEL_CONFIGS (applying the CLI override) + optionally DATASET_CONFIGS
+# 5. calls run_pipeline
+#
+# The pipeline for each (model, dataset) is: stage 1 (generate, backend-specific) → stage 2
+# (transcribe, shared) → stage 3 (SIM, shared; voice-clone models only) → local scoring. Stages
+# run as sequential HF Jobs sharing one bucket; a model's combos run in parallel, models one after
+# another. All eval scripts are base64-injected into the jobs at runtime (the Space images only
+# carry the environment).
+#
+# Contract — before calling generate_stage()/transcribe_stage()/sim_stage(), run_pipeline sets:
+# MODEL_ID MODEL_SAFE MODEL_FOLDER MODEL_CFG (MODEL_CFG = raw config line; parse extras from it)
+# DATASET SPLIT ASR_LANG DATASET_PATH DATASET_SAFE MODE_SUFFIX CLONE BUCKET_MANIFEST
+# TTS_IMAGE NAMESPACE_ARG
+# plus every shared config var below. Backends reference these in their generate_stage().
+# NOTE: DATASET_PATH is per-combo (a DATASET_CONFIGS line may name its own dataset repo), so read
+# it inside generate_stage() — never cache it at source time.
+
+# ── Locations ────────────────────────────────────────────────────────────────
+COMMON_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+REPO_ROOT="$(cd "${COMMON_DIR}/.." && pwd)"
+BACKEND_DIR="$(cd "$(dirname "${BASH_SOURCE[1]}")" && pwd)" # the sourcing backend script's dir
+
+# ── Shared config (all env-overridable) ─────────────────────────────────────
+SPACE="${SPACE:-bezzam/evals}" # shared scorer image (stages 2 & 3)
+RESULTS_BUCKET="${RESULTS_BUCKET:-hf-audio/tts_leaderboard_h200}" # shared HF bucket (per-model folders)
+# HF namespace holding your PRIVATE copies of the eval datasets (their licenses forbid
+# redistribution; push them with scripts/prepare_{seed_tts,cv3}_eval.py). Only supplies the defaults
+# below — DATASET_PATH / CV3_EVAL_PATH (or a DATASET_CONFIGS line's 4th field) can name any repo.
+DATASET_NAMESPACE="${DATASET_NAMESPACE:-bezzam}"
+# Default dataset repo, used for every DATASET_CONFIGS line that does not name its own (4th field).
+DEFAULT_DATASET_PATH="${DATASET_PATH:-${DATASET_NAMESPACE}/seed_tts_eval}"
+# The other eval set — named explicitly by the CV3 lines of a backend's DATASET_CONFIGS.
+CV3_EVAL_PATH="${CV3_EVAL_PATH:-${DATASET_NAMESPACE}/cv3_eval}"
+ORG_NAME="${ORG_NAME:-}"
+# Stage-1 (generation) flavor. IMPORTANT: keep this the SAME (h200) for EVERY backend — RTFx is
+# measured on the generation stage, so a uniform GPU is required for RTFx to be comparable across
+# models. Backends should NOT override it; only change it deliberately for a one-off experiment.
+FLAVOR="${FLAVOR:-h200}"
+# Stage 2/3 flavors are not timed (WER/SIM are hardware-independent), so a cheaper GPU is fine.
+ASR_FLAVOR="${ASR_FLAVOR:-l4x1}" # stage 2 flavor
+SIM_FLAVOR="${SIM_FLAVOR:-l4x1}" # stage 3 flavor
+MAX_EVAL_SAMPLES="${MAX_EVAL_SAMPLES:--1}" # -1 = all; set e.g. 8 to smoke-test
+# Restrict a run to some of the backend's DATASET_CONFIGS: space-separated asr_language codes
+# (field 3 of a config line), e.g. ONLY_LANGS="de". Empty (default) runs every configured combo.
+ONLY_LANGS="${ONLY_LANGS:-}"
+ASR_BATCH_SIZE="${ASR_BATCH_SIZE:-32}" # ASR minibatch (lower if it OOMs)
+SIM_BATCH_SIZE="${SIM_BATCH_SIZE:-32}" # SIM minibatch (ignored by the wavlm_seed_tts backend)
+# Speaker-similarity embedder. 'xvector': WavLMForXVector (wavlm-base-plus-sv) — cheap but poorly
+# discriminative (decent cloning models all land in 0.93-0.97). 'wavlm_seed_tts': seed-tts-eval's
+# WavLM-Large + ECAPA-TDNN — comparable with published SIM. IMPORTANT: the two scales are NOT
+# interchangeable, so keep this the SAME for every model whose SIM you compare (score_similarity.py
+# records the embedder per row as `sim_model` and re-scores rows scored by the other one).
+SIM_BACKEND="${SIM_BACKEND:-wavlm_seed_tts}"
+# Force every row's SIM to be recomputed. REQUIRED after re-running `generate`: score_similarity.py
+# carries prior sims over keyed on `audio_filepath` (to resume crashed runs), and regeneration reuses
+# the same wav filenames, so without this the old SIM would silently be kept.
+SIM_OVERWRITE="${SIM_OVERWRITE:-false}"
+# Same opt-out for stage 2: transcribe.py skips rows that already have a `pred_text`. Set
+# ASR_OVERWRITE=true with STAGES="transcribe" to re-transcribe the bucket's existing wavs.
+ASR_OVERWRITE="${ASR_OVERWRITE:-false}"
+MAX_AUDIO_SECONDS="${MAX_AUDIO_SECONDS:-30}" # clip cap for ASR + SIM (0 = no cap)
+# Clone each sample's prompt speaker (+ SIM stage) on backends that support it; false = the model's
+# own fixed/default voice. Ignored by fixed-voice backends.
+VOICE_CLONE="${VOICE_CLONE:-false}"
+# Which stages to run (subset of: generate transcribe sim). Skip generate to re-score the bucket's
+# existing wavs, e.g. STAGES="transcribe sim" or STAGES="sim". Precedence (resolved in
+# run_pipeline): user env STAGES > backend DEFAULT_STAGES > "generate transcribe sim".
+
+# HF Jobs references a Space image as "hf.co/spaces/<id>" and pulls it. NOTE: the Space must be
+# PUBLIC (the jobs backend 500s on a private Space image). Images carry only the environment; all
+# code is injected at runtime, so there are no secrets to keep private.
+SCORER_IMAGE="hf.co/spaces/${SPACE}"
+
+# Datasets: "config split asr_language [dataset_path]". Backends may override before run_pipeline.
+# asr_language is the language hint for Qwen3-ASR (stage 2) and, for backends that take one,
+# for the TTS model too — so it must be a real language code, not a split name.
+# The optional 4th field points a single line at a different dataset repo (default:
+# DEFAULT_DATASET_PATH), so one list can mix e.g. Seed-TTS and CV3-Eval combos. It only has to
+# expose the same columns the backends read: `text` + `prompt_text`/`prompt_audio` when cloning.
+DATASET_CONFIGS=("tts en en")
+
+stage_enabled() { [[ " ${STAGES} " == *" $1 "* ]]; }
+
+# ── Injection helpers ────────────────────────────────────────────────────────
+# inject_cmd <local_file> <container_dest> → `... &&` snippet recreating the file in the job.
+inject_cmd() {
+ local b64
+ b64=$(base64 -w0 "$1")
+ echo "mkdir -p $(dirname "$2") && echo '${b64}' | base64 -d > $2 &&"
+}
+# inject_cmd_gz <local_file> <container_path> → same, but gzipped first, for large payloads: a job
+# body is ONE `bash -c` argument and Linux caps a single argument at 128 KiB (MAX_ARG_STRLEN).
+inject_cmd_gz() {
+ local b64
+ b64=$(gzip -9c "$1" | base64 -w0)
+ echo "mkdir -p $(dirname "$2") && echo '${b64}' | base64 -d | gzip -dc > $2 &&"
+}
+# inject_dir <dir_relative_to_repo_root> <container_parent> → `... &&` snippet tar+extracting a dir.
+inject_dir() {
+ local b64
+ b64=$(tar --exclude='__pycache__' --exclude='*.pyc' -czf - -C "${REPO_ROOT}" "$1" | base64 -w0)
+ echo "mkdir -p $2 && echo '${b64}' | base64 -d | tar -xzf - -C $2 &&"
+}
+
+# Snippet putting /app/scripts (shared run_eval helpers, ttfa_probe.py) on the job's PYTHONPATH,
+# keeping any PYTHONPATH the image already sets.
+SCRIPTS_PYTHONPATH='export PYTHONPATH=/app/scripts${PYTHONPATH:+:${PYTHONPATH}} &&'
+
+# inject_run_eval → `... &&` snippet recreating the sourcing backend's run_eval.py at
+# /app/<backend>/ plus the shared scripts/run_eval_utils.py it imports, on PYTHONPATH. Backends set
+# RUN_EVAL_INJECT="$(inject_run_eval)".
+inject_run_eval() {
+ echo "$(inject_cmd "${BACKEND_DIR}/run_eval.py" "/app/$(basename "${BACKEND_DIR}")/run_eval.py")" \
+ "$(inject_cmd "${REPO_ROOT}/scripts/run_eval_utils.py" /app/scripts/run_eval_utils.py)" \
+ "${SCRIPTS_PYTHONPATH}"
+}
+
+# Shared scorer-stage injects (transcribe.py / score_similarity.py live in transformers/).
+TRANSCRIBE_INJECT="$(inject_cmd "${REPO_ROOT}/transformers/transcribe.py" /app/transformers/transcribe.py)"
+SIM_INJECT="$(inject_cmd "${REPO_ROOT}/transformers/score_similarity.py" /app/transformers/score_similarity.py)"
+
+# ── Default hooks (backends override as needed) ─────────────────────────────
+# voice_clone_mode [suffix_prefix] — sets CLONE / MODE_SUFFIX / VOICE_CLONE_FLAG from VOICE_CLONE.
+# A backend variant that shares a model id passes its own prefix (e.g. "_rl"), so MODE_SUFFIX
+# becomes "_rl" or "_rl_voice_clone" (must match the suffix its run_eval.py writes).
+voice_clone_mode() {
+ if [[ "${VOICE_CLONE}" == "true" ]]; then
+ CLONE="true"; MODE_SUFFIX="${1:-}_voice_clone"; VOICE_CLONE_FLAG="--voice_clone"
+ else
+ CLONE="false"; MODE_SUFFIX="${1:-}"; VOICE_CLONE_FLAG="--no-voice_clone"
+ fi
+}
+
+# Default: backends that set SUPPORTS_VOICE_CLONE=true follow VOICE_CLONE; fixed-voice backends have
+# no SIM stage. Backends with per-model logic override this (calling voice_clone_mode as needed).
+resolve_mode() {
+ if [[ "${SUPPORTS_VOICE_CLONE:-false}" == "true" ]]; then
+ voice_clone_mode
+ else
+ CLONE="false"; MODE_SUFFIX=""; VOICE_CLONE_FLAG=""
+ fi
+}
+
+# Whether the CURRENT model (MODEL_CFG/MODEL_ID, already resolved) can synthesize $1, the dataset's
+# language code. Default: assume yes. Backends whose model list mixes languages — e.g. an
+# English-only checkpoint alongside a multilingual one — override this so incompatible
+# (model, dataset) combos are skipped instead of burning a GPU job on garbage audio.
+supports_language() { return 0; }
+
+# ── Transient-infra retry around a stage's `hf jobs run` ────────────────────
+# Parallel chains advance in lockstep, so N jobs pull the SAME Space image within seconds and the
+# registry can rate-limit the burst (429 → ErrImagePull) before any of our code runs. Retry ONLY
+# that class of failure: a job that actually started and exited non-zero must not be re-submitted.
+STAGE_RETRIES="${STAGE_RETRIES:-4}" # attempts after the first, per stage
+STAGE_RETRY_SLEEP="${STAGE_RETRY_SLEEP:-90}" # seconds before the 1st retry; doubles each time
+
+_is_transient_job_failure() {
+ grep -qEi '429 Too Many Requests|ErrImagePull|ImagePullBackOff|Back-off pulling image|image specification error' "$1"
+}
+
+# run_stage <stage_fn> — run a stage, retrying transient registry failures with exponential backoff.
+# Output is tee'd, not buffered, so the chain log still streams `hf jobs run`'s live job logs.
+run_stage() {
+ local stage_fn="$1" attempt=1 delay="${STAGE_RETRY_SLEEP}" rc out
+ out="$(mktemp "${TMPDIR:-/tmp}/tts_stage_XXXXXX.log")"
+ while :; do
+ "${stage_fn}" 2>&1 | tee "${out}"
+ rc=${PIPESTATUS[0]}
+ if [[ "${rc}" -eq 0 ]]; then
+ rm -f "${out}"
+ return 0
+ fi
+ if ! _is_transient_job_failure "${out}" || [[ "${attempt}" -gt "${STAGE_RETRIES}" ]]; then
+ _is_transient_job_failure "${out}" &&
+ echo "── ${stage_fn}: still failing to pull the image after ${STAGE_RETRIES} retries; giving up."
+ rm -f "${out}"
+ return "${rc}"
+ fi
+ echo "── ${stage_fn}: transient registry/image-pull failure (attempt ${attempt}/${STAGE_RETRIES}); retrying in ${delay}s."
+ sleep "${delay}"
+ attempt=$((attempt + 1))
+ delay=$((delay * 2))
+ : > "${out}" # only the latest attempt's output should be classified
+ done
+}
+
+# ── Shared stages 2 & 3 (identical for every backend) ───────────────────────
+transcribe_stage() {
+ local ASR_OVERWRITE_FLAG=""
+ [[ "${ASR_OVERWRITE}" == "true" ]] && ASR_OVERWRITE_FLAG=" --overwrite"
+ hf jobs run \
+ --flavor "${ASR_FLAVOR}" --timeout 4h --secrets HF_TOKEN ${NAMESPACE_ARG} \
+ --volume "hf://buckets/${RESULTS_BUCKET}:/results" "${SCORER_IMAGE}" \
+ bash -c "
+ ${TRANSCRIBE_INJECT}
+ python /app/transformers/transcribe.py --manifest_path=${BUCKET_MANIFEST} --asr_language=${ASR_LANG} --asr_batch_size=${ASR_BATCH_SIZE} --max_audio_seconds=${MAX_AUDIO_SECONDS} --device=cuda:0${ASR_OVERWRITE_FLAG}
+ "
+}
+sim_stage() {
+ local SIM_OVERWRITE_FLAG=""
+ [[ "${SIM_OVERWRITE}" == "true" ]] && SIM_OVERWRITE_FLAG=" --overwrite"
+ hf jobs run \
+ --flavor "${SIM_FLAVOR}" --timeout 4h --secrets HF_TOKEN \
+ --env PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True" ${NAMESPACE_ARG} \
+ --volume "hf://buckets/${RESULTS_BUCKET}:/results" "${SCORER_IMAGE}" \
+ bash -c "
+ ${SIM_INJECT}
+ python /app/transformers/score_similarity.py --manifest_path=${BUCKET_MANIFEST} --sim_backend=${SIM_BACKEND} --batch_size=${SIM_BATCH_SIZE} --max_audio_seconds=${MAX_AUDIO_SECONDS} --device=cuda:0${SIM_OVERWRITE_FLAG}
+ "
+}
+
+# ── Wait for a model's chains, report failures, then sync + score locally ────
+# Uses PIDS/TAGS/CHAIN_LOGS set by run_pipeline. Returns non-zero (and skips scoring) on failure.
+_wait_and_score() {
+ local i CHAIN_FAILED=0
+ # Every combo was skipped (e.g. an English-only model against a zh-only dataset list) — there is
+ # nothing to wait for, and scoring would only re-read a stale local copy.
+ if [[ ${#PIDS[@]} -eq 0 ]]; then
+ echo "No compatible (model, dataset) combos for ${MODEL_ID}; nothing submitted, skipping scoring."
+ return 0
+ fi
+ for i in "${!PIDS[@]}"; do
+ if ! wait "${PIDS[$i]}"; then
+ CHAIN_FAILED=1
+ echo "ERROR: pipeline failed for ${MODEL_ID} on ${TAGS[$i]} — last lines of ${CHAIN_LOGS[$i]}:"
+ tail -n 25 "${CHAIN_LOGS[$i]}" | sed 's/^/ /'
+ fi
+ done
+ if [[ "${CHAIN_FAILED}" -eq 1 ]]; then
+ echo "One or more job chains failed for ${MODEL_ID}; skipping scoring. See logs in ${LOG_DIR}."
+ return 1
+ fi
+ echo "All jobs finished for ${MODEL_ID}."
+ # Clear any stale local copy first: score_results globs **/*.jsonl recursively and keys by
+ # (model, dataset), so a leftover manifest would silently overwrite this run's result.
+ rm -rf "./results/${MODEL_FOLDER}"
+ mkdir -p "./results/${MODEL_FOLDER}"
+ # Only the manifests are needed for scoring; the wavs stay in the bucket. A job's last writes can
+ # take a moment to show up in the bucket, so retry until this run's manifests are all present.
+ # `timeout`: a sync can deadlock on a server-closed connection and would otherwise hang forever.
+ local attempt sync_out name
+ local -a missing=()
+ for attempt in 1 2 3 4 5; do
+ sleep 15
+ sync_out=$(timeout "${SYNC_TIMEOUT:-600}" hf buckets sync "hf://buckets/${RESULTS_BUCKET}/${MODEL_FOLDER}" "./results/${MODEL_FOLDER}" --exclude "*.wav" 2>&1) ||
+ echo "WARNING: bucket sync failed (attempt ${attempt}/5):"$'\n'"${sync_out}"
+ missing=()
+ for name in "${MANIFEST_NAMES[@]}"; do
+ # -s, not -f: an interrupted download leaves a 0-byte file behind.
+ [[ -s "./results/${MODEL_FOLDER}/${name}" ]] || missing+=("${name}")
+ done
+ [[ ${#missing[@]} -eq 0 ]] && break
+ done
+ if [[ ${#missing[@]} -gt 0 ]]; then
+ echo "WARNING: ${#missing[@]} manifest(s) of this run not found in the bucket:"
+ printf ' %s\n' "${missing[@]}"
+ else
+ echo "All ${#MANIFEST_NAMES[@]} manifest(s) present."
+ fi
+
+ # Score ONE LANGUAGE PER CALL: score_results applies `language` to every manifest it reads and
+ # only auto-detects CJK, so a single call would normalize e.g. French with the English normalizer.
+ local lang py_list
+ local -a seen_langs=()
+ for i in "${!LANGS[@]}"; do
+ [[ " ${seen_langs[*]} " == *" ${LANGS[$i]} "* ]] || seen_langs+=("${LANGS[$i]}")
+ done
+ for lang in "${seen_langs[@]}"; do
+ py_list=""
+ for i in "${!LANGS[@]}"; do
+ [[ "${LANGS[$i]}" == "${lang}" ]] || continue
+ [[ -s "./results/${MODEL_FOLDER}/${MANIFEST_NAMES[$i]}" ]] || continue
+ py_list+="'${MANIFEST_NAMES[$i]}',"
+ done
+ if [[ -z "${py_list}" ]]; then
+ echo "No manifest present for language '${lang}'; skipping its scoring."
+ continue
+ fi
+ echo "── Scoring language '${lang}'"
+ PYTHONPATH="${REPO_ROOT}" python -c "
+from normalizer.eval_utils import score_results
+score_results('$(pwd)/results/${MODEL_FOLDER}', '${MODEL_ID}', language='${lang}', manifests=[${py_list}], sim_backend='${SIM_BACKEND}')
+" || echo "WARNING: scoring failed for language '${lang}'."
+ done
+
+ # Scoring is scoped to THIS run's combos (where each manifest's language is known); list any
+ # other manifests in the folder so they don't silently disappear from the summary.
+ local unscored
+ unscored=$(find "./results/${MODEL_FOLDER}" -maxdepth 1 -name "MODEL_*.jsonl" -printf "%f\n" 2>/dev/null \
+ | grep -vxF "$(printf '%s\n' "${MANIFEST_NAMES[@]}")" || true)
+ if [[ -n "${unscored}" ]]; then
+ echo "Not scored (not part of this run — use scripts/score_model.py --language <lang>):"
+ sed 's/^/ /' <<< "${unscored}"
+ fi
+}
+
+# ── The orchestrator ─────────────────────────────────────────────────────────
+run_pipeline() {
+ STAGES="${STAGES:-${DEFAULT_STAGES:-generate transcribe sim}}" # user env > backend > global
+ TTS_IMAGE="hf.co/spaces/${TTS_SPACE}"
+ LOG_DIR="${BACKEND_DIR}/job_logs"; mkdir -p "${LOG_DIR}"
+ NAMESPACE_ARG=""; [ -n "$ORG_NAME" ] && NAMESPACE_ARG="--namespace ${ORG_NAME}"
+
+ local model_cfg cfg
+ for model_cfg in "${MODEL_CONFIGS[@]}"; do
+ MODEL_CFG="$model_cfg" # full line; generate_stage parses extras
+ read -r MODEL_ID _ <<< "$model_cfg" # MODEL_ID = first whitespace token
+ MODEL_SAFE="${MODEL_ID//\//-}"; MODEL_FOLDER="${MODEL_SAFE}"
+ resolve_mode # sets CLONE / MODE_SUFFIX (per model)
+
+ # Report the stages that will actually run: SIM is gated on CLONE below, so a fixed-voice
+ # model never submits it however STAGES is set — don't advertise it as part of the run.
+ local EFFECTIVE_STAGES="" s
+ for s in ${STAGES}; do
+ [[ "$s" == "sim" && "${CLONE}" != "true" ]] && continue
+ EFFECTIVE_STAGES+="${EFFECTIVE_STAGES:+ }$s"
+ done
+
+ echo "████████████████████████████████████████████████████████████████████████████████"
+ echo " Evaluating: ${MODEL_ID} (clone=${CLONE}, stages=${EFFECTIVE_STAGES:-none})"
+ echo "████████████████████████████████████████████████████████████████████████████████"
+
+ # LANGS + MANIFEST_NAMES are parallel to PIDS: _wait_and_score groups the finished combos
+ # by language so each is scored with its own normalizer.
+ PIDS=(); TAGS=(); CHAIN_LOGS=(); LANGS=(); MANIFEST_NAMES=()
+ for cfg in "${DATASET_CONFIGS[@]}"; do
+ local CFG_DATASET_PATH
+ read -r DATASET SPLIT ASR_LANG CFG_DATASET_PATH <<< "$cfg"
+ # Per-combo dataset repo (4th field, else the default). DATASET_SAFE feeds the manifest
+ # name, so two datasets that share a config/split name still land in distinct manifests.
+ DATASET_PATH="${CFG_DATASET_PATH:-${DEFAULT_DATASET_PATH}}"
+ DATASET_SAFE="${DATASET_PATH//\//-}"
+ # Caller-requested subset (ONLY_LANGS), checked before supports_language so the
+ # "not supported" message is never printed for a combo the caller simply skipped.
+ if [[ -n "${ONLY_LANGS}" && " ${ONLY_LANGS} " != *" ${ASR_LANG} "* ]]; then
+ echo "Skipping ${DATASET}/${SPLIT}: not in ONLY_LANGS='${ONLY_LANGS}'."
+ continue
+ fi
+ # Skip combos the model can't do at all — synthesizing Chinese with an English-only
+ # checkpoint produces English-phoneme gibberish and a meaningless (>100%) CER.
+ if ! supports_language "${ASR_LANG}"; then
+ echo "Skipping ${DATASET}/${SPLIT}: ${MODEL_ID} does not support language '${ASR_LANG}'."
+ continue
+ fi
+ BUCKET_MANIFEST="/results/${MODEL_FOLDER}/MODEL_${MODEL_SAFE}_DATASET_${DATASET_SAFE}_${DATASET}_${SPLIT}${MODE_SUFFIX}.jsonl"
+ local CHAIN_LOG="${LOG_DIR}/${MODEL_SAFE}_${DATASET}_${SPLIT}${MODE_SUFFIX}.log"
+ echo "Submitting pipeline: model=${MODEL_ID} dataset=${DATASET} split=${SPLIT} (log: ${CHAIN_LOG})"
+
+ # Sequential stages in a backgrounded subshell (combos run in parallel). `set -e`
+ # aborts the chain on the first failed stage; the waiter reports it from the log.
+ (
+ set -e
+ stage_enabled generate && run_stage generate_stage
+ stage_enabled transcribe && run_stage transcribe_stage
+ stage_enabled sim && [[ "${CLONE}" == "true" ]] && run_stage sim_stage
+ true # ensure subshell exit status is 0 when the last `&&` chain is a skipped stage
+ ) > "${CHAIN_LOG}" 2>&1 &
+ PIDS+=("$!"); TAGS+=("${DATASET}/${SPLIT}"); CHAIN_LOGS+=("${CHAIN_LOG}")
+ LANGS+=("${ASR_LANG}"); MANIFEST_NAMES+=("$(basename "${BUCKET_MANIFEST}")")
+ done
+
+ if [ -n "$ORG_NAME" ]; then
+ echo "For live status see: https://huggingface.co/organizations/${ORG_NAME}/settings/jobs"
+ else
+ echo "For live status see: https://huggingface.co/settings/jobs"
+ fi
+
+ _wait_and_score || true # keep going to the next model on failure
+ done
+}
diff --git a/scripts/upload_sim_checkpoint.py b/scripts/upload_sim_checkpoint.py
new file mode 100644
index 0000000..9f0df69
--- /dev/null
+++ b/scripts/upload_sim_checkpoint.py
@@ -0,0 +1,289 @@
+"""Mirror the seed-tts-eval SIM checkpoint (`wavlm_large_finetune.pth`) into an HF repo we own.
+
+`transformers/score_similarity.py --sim_backend wavlm_seed_tts` needs WavLM-Large + ECAPA-TDNN
+weights that upstream (microsoft/UniSpeech) only ships via Google Drive, which a job container
+cannot reliably reach; this script re-hosts the same bytes on the Hub.
+
+The file is sha256-verified against the digest pinned in score_similarity.py BEFORE upload, and the
+remote LFS digest is re-checked after.
+
+ python scripts/upload_sim_checkpoint.py # resolve source, verify, upload
+ python scripts/upload_sim_checkpoint.py --src /path/to.pth # use a local copy
+ python scripts/upload_sim_checkpoint.py --dry_run # verify + render the card, no upload
+
+Needs `hf auth login` (or HF_TOKEN) with write scope. Runs on the host — no torch required.
+"""
+
+import argparse
+import ast
+import hashlib
+import os
+import sys
+
+DEFAULT_REPO_ID = "bezzam/wavlm_large_finetune_seed_tts_eval"
+REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+SCORE_SIMILARITY = os.path.join(REPO_ROOT, "transformers", "score_similarity.py")
+
+# Upstream source of truth: microsoft/UniSpeech, downstreams/speaker_verification, the
+# "WavLM large / Fix pre-train: No" row (Vox1-O EER 0.431 — their best SV model).
+UNISPEECH_README = "https://github.com/microsoft/UniSpeech/tree/main/downstreams/speaker_verification"
+GDRIVE_FILE_ID = "1-aE1NfzpRCLxA4GUxX9ITI3F9LlbtEGP"
+GDRIVE_URL = f"https://drive.usercontent.google.com/download?id={GDRIVE_FILE_ID}&export=download&confirm=t"
+EXPECTED_SIZE = 1301926579
+
+
+def read_pinned_constants():
+ """Pull the pinned checkpoint constants out of score_similarity.py without importing it.
+
+ score_similarity.py imports torch at module scope and this script runs on the host, so it is
+ parsed rather than executed; the digest here can never drift from the one the eval enforces.
+ """
+ tree = ast.parse(open(SCORE_SIMILARITY, encoding="utf-8").read())
+ wanted = {"WAVLM_SEED_TTS_REPO_ID", "WAVLM_SEED_TTS_FILENAME", "WAVLM_SEED_TTS_SHA256"}
+ found = {}
+ for node in tree.body:
+ if isinstance(node, ast.Assign) and len(node.targets) == 1:
+ target = node.targets[0]
+ if isinstance(target, ast.Name) and target.id in wanted and isinstance(node.value, ast.Constant):
+ found[target.id] = node.value.value
+ missing = wanted - found.keys()
+ if missing:
+ raise RuntimeError(f"Could not find {sorted(missing)} in {SCORE_SIMILARITY}")
+ return found
+
+
+def sha256_of(path):
+ digest = hashlib.sha256()
+ with open(path, "rb") as f:
+ for chunk in iter(lambda: f.read(1 << 22), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def download_from_gdrive(dest):
+ """Stream the official Drive copy. `confirm=t` skips the interstitial for large files."""
+ import requests
+
+ print(f"Downloading the official checkpoint from Google Drive ({GDRIVE_FILE_ID})...")
+ with requests.get(GDRIVE_URL, stream=True, timeout=60) as r:
+ r.raise_for_status()
+ if r.headers.get("content-type", "").startswith("text/html"):
+ raise RuntimeError(
+ "Drive returned an HTML interstitial instead of the file — the share link may have "
+ f"changed. Download it manually from {UNISPEECH_README} and pass --src."
+ )
+ total, seen = int(r.headers.get("content-length", 0)), 0
+ with open(dest, "wb") as f:
+ for chunk in r.iter_content(chunk_size=1 << 22):
+ f.write(chunk)
+ seen += len(chunk)
+ if total:
+ print(f"\r {seen / 1e9:.2f} / {total / 1e9:.2f} GB", end="", flush=True)
+ print()
+ return dest
+
+
+def resolve_source(src, pinned, cache_dir):
+ """Return a local path to the checkpoint, preferring copies we already have on disk."""
+ if src:
+ print(f"Source: {src} (--src)")
+ return src
+
+ # 1. Already in the HF cache from an eval run.
+ try:
+ from huggingface_hub import hf_hub_download
+
+ path = hf_hub_download(
+ repo_id=pinned["WAVLM_SEED_TTS_REPO_ID"],
+ filename=pinned["WAVLM_SEED_TTS_FILENAME"],
+ local_files_only=True,
+ )
+ print(f"Source: {path} (cached copy of {pinned['WAVLM_SEED_TTS_REPO_ID']})")
+ return path
+ except Exception:
+ pass
+
+ # 2. Otherwise fetch from the authoritative upstream.
+ os.makedirs(cache_dir, exist_ok=True)
+ dest = os.path.join(cache_dir, pinned["WAVLM_SEED_TTS_FILENAME"])
+ if os.path.exists(dest) and os.path.getsize(dest) == EXPECTED_SIZE:
+ print(f"Source: {dest} (existing download)")
+ return dest
+ return download_from_gdrive(dest)
+
+
+def model_card(repo_id, pinned, sha256):
+ filename = pinned["WAVLM_SEED_TTS_FILENAME"]
+ return f"""---
+license: mit
+tags:
+- speaker-verification
+- speaker-similarity
+- wavlm
+- ecapa-tdnn
+- tts-evaluation
+---
+
+# WavLM-Large + ECAPA-TDNN speaker verification (seed-tts-eval SIM model)
+
+A **verbatim mirror** of Microsoft's speaker-verification checkpoint used as the SIM (speaker
+similarity) metric by seed-tts-eval, and therefore by the Seed-TTS / F5-TTS / CosyVoice line of
+papers. Re-hosted so TTS evaluation jobs can fetch it from the Hub; the weights are unmodified.
+
+## Provenance
+
+| | |
+|---|---|
+| Origin | [microsoft/UniSpeech → downstreams/speaker_verification]({UNISPEECH_README}) |
+| Row in upstream's table | **WavLM large**, *Fix pre-train:* **No** — their best SV model |
+| Reported EER | Vox1-O **0.431**, Vox1-E 0.538, Vox1-H 1.154 |
+| Upstream download | [Google Drive](https://drive.google.com/file/d/{GDRIVE_FILE_ID}/view) |
+| File | `{filename}` ({EXPECTED_SIZE:,} bytes) |
+| sha256 | `{sha256}` |
+| License | MIT, per the UniSpeech repository |
+
+*Fix pre-train: No* means the WavLM-Large backbone was fine-tuned during speaker-verification
+training, so these backbone weights do **not** equal `microsoft/wavlm-large`.
+
+This mirror exists because neither upstream URL is reachable from a job container: the Google Drive
+link requires a confirm-token dance, and the Azure blob URL in seed-tts-eval's vendored copy of the
+README has an expired SAS token.
+
+## Contents
+
+`{filename}` is a `torch.save` dict with two top-level keys:
+
+- `model` — 711 tensors: `feature_extract.model.*` (the WavLM-Large backbone, in original-WavLM
+ naming), the ECAPA-TDNN head (`feature_weight`, `layer1`-`layer4`, `conv`, `pooling`, `bn`,
+ `linear`), and `loss_calculator.projection.weight` (the training-time AM-softmax classifier,
+ unused at inference).
+- `best_valid_eer` — an unset sentinel (`100.0`); ignore it.
+
+## Usage
+
+Upstream runs this via `s3prl` + `torch.hub`. The open TTS leaderboard instead rebuilds the backbone
+as an HF `WavLMModel` and remaps the checkpoint's keys onto it — verified **bit-exact** (0.0 max
+difference across all 25 hidden states and the final 256-d embedding) against UniSpeech's original
+`WavLM.py`. See `transformers/score_similarity.py`:
+
+```bash
+python transformers/score_similarity.py \\
+ --manifest_path=<manifest>.jsonl \\
+ --sim_backend=wavlm_seed_tts \\
+ --sim_ckpt_repo={repo_id}
+```
+
+## Scale
+
+Cosine similarities from this model are **not** interchangeable with those from
+`microsoft/wavlm-base-plus-sv`. Measured on the VoxCeleb1 clips shipped with UniSpeech:
+
+| | this model | `wavlm-base-plus-sv` |
+|---|---|---|
+| same speaker | 0.60 - 0.69 | 0.89 - 0.96 |
+| different speaker | -0.17 - 0.18 | 0.60 - 0.84 |
+
+Only the values from this model are comparable with published seed-tts-eval SIM numbers.
+
+## Citation
+
+```bibtex
+@article{{chen2022wavlm,
+ title={{WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing}},
+ author={{Chen, Sanyuan and Wang, Chengyi and Chen, Zhengyang and others}},
+ journal={{IEEE Journal of Selected Topics in Signal Processing}},
+ year={{2022}}
+}}
+```
+"""
+
+
+def main(args):
+ pinned = read_pinned_constants()
+ expected_sha = pinned["WAVLM_SEED_TTS_SHA256"]
+ filename = pinned["WAVLM_SEED_TTS_FILENAME"]
+ print(f"Pinned digest (from {os.path.relpath(SCORE_SIMILARITY, REPO_ROOT)}): {expected_sha}")
+
+ path = resolve_source(args.src, pinned, args.download_dir)
+
+ size = os.path.getsize(path)
+ if size != EXPECTED_SIZE:
+ raise SystemExit(f"REFUSING: {path} is {size:,} bytes, expected {EXPECTED_SIZE:,}.")
+ print("Verifying sha256 (a few seconds for 1.3 GB)...")
+ actual = sha256_of(path)
+ if actual != expected_sha:
+ raise SystemExit(
+ f"REFUSING to upload: sha256 mismatch.\n expected {expected_sha}\n actual {actual}\n"
+ "This is not the checkpoint the eval pins. Do not publish it."
+ )
+ print(f" sha256 OK: {actual}")
+
+ card = model_card(args.repo_id, pinned, actual)
+ if args.dry_run:
+ print(f"\n--dry_run: verified, nothing uploaded. Card that would be written to {args.repo_id}:\n")
+ print(card)
+ return
+
+ from huggingface_hub import HfApi
+
+ api = HfApi()
+ who = api.whoami()
+ print(f"Authenticated as {who.get('name')}")
+
+ url = api.create_repo(repo_id=args.repo_id, private=args.private, exist_ok=True)
+ print(f"Repo ready: {url} (private={args.private})")
+
+ print(f"Uploading {filename} ({size / 1e9:.2f} GB)...")
+ api.upload_file(
+ path_or_fileobj=path,
+ path_in_repo=filename,
+ repo_id=args.repo_id,
+ commit_message=f"Mirror {filename} from microsoft/UniSpeech (sha256 {actual[:12]})",
+ )
+ api.upload_file(
+ path_or_fileobj=card.encode("utf-8"),
+ path_in_repo="README.md",
+ repo_id=args.repo_id,
+ commit_message="Add model card documenting provenance, contents and SIM scale",
+ )
+
+ # Confirm the Hub stored the exact bytes: its LFS oid IS the file's sha256.
+ info = api.model_info(args.repo_id, files_metadata=True)
+ remote = next((s for s in info.siblings if s.rfilename == filename), None)
+ lfs = getattr(remote, "lfs", None) if remote is not None else None
+ remote_sha = lfs.get("sha256") if isinstance(lfs, dict) else getattr(lfs, "sha256", None)
+ if remote_sha != actual:
+ raise SystemExit(f"Upload verification FAILED: remote sha256 {remote_sha} != {actual}")
+ print(f" remote sha256 OK: {remote_sha}")
+
+ print(
+ f"\nDone. https://huggingface.co/{args.repo_id}\n"
+ f"Point the eval at it with: --sim_ckpt_repo={args.repo_id}\n"
+ + (
+ "The repo is PRIVATE, so every job that scores SIM needs an HF_TOKEN with read access "
+ "(the sim_stage in scripts/tts_jobs_common.sh already forwards one).\n"
+ if args.private
+ else ""
+ )
+ )
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--repo_id", default=DEFAULT_REPO_ID, help=f"Destination repo (default {DEFAULT_REPO_ID}).")
+ parser.add_argument(
+ "--src",
+ default=None,
+ help="Local path to wavlm_large_finetune.pth. Default: reuse a cached copy, else download "
+ "from the official Google Drive link.",
+ )
+ parser.add_argument(
+ "--download_dir",
+ default=os.path.join(REPO_ROOT, ".cache"),
+ help="Where to put the download when no local copy exists.",
+ )
+ parser.add_argument("--private", action="store_true", help="Create the repo private (default: public).")
+ parser.add_argument("--dry_run", action="store_true", help="Verify the checkpoint and render the card; upload nothing.")
+ args = parser.parse_args()
+
+ sys.exit(main(args))
diff --git a/submit_ttfa_jobs.sh b/submit_ttfa_jobs.sh
new file mode 100755
index 0000000..4696c46
--- /dev/null
+++ b/submit_ttfa_jobs.sh
@@ -0,0 +1,404 @@
+#!/bin/bash
+# Time-to-first-audio (TTFA) probes for every TTFA_TARGETS entry, as one HF Job per target.
+#
+# Usage: HF_TOKEN=hf_... bash submit_ttfa_jobs.sh [label|model_id|backend ...]
+# HF_TOKEN=hf_... bash submit_ttfa_jobs.sh breeze-tts kokoro # just these
+# TTFA_SAMPLES=50 VOICE_CLONE=true bash submit_ttfa_jobs.sh # quick run (default: whole split)
+#
+# Separate from the per-backend submit_jobs.sh scripts because TTFA is measured on different terms:
+# * It is a PER-REQUEST latency, so it is measured at BATCH SIZE 1 (the eval measures RTFx at each
+# backend's real batch size; the two can differ by an order of magnitude).
+# * It probes ONE split (the whole of it by default, for a stable p95), not a full eval.
+# * It writes ONLY a JSON sidecar (no wavs, no manifest), so it is safe to run against models
+# whose results are already in the bucket.
+#
+# Each job runs the backend's own run_eval.py with --ttfa_probe, so the probe measures exactly the
+# code path the real eval uses.
+
+source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/scripts/tts_jobs_common.sh"
+
+# ── Probe configuration ──────────────────────────────────────────────────────
+# -1 = the whole split (500 for CV3-Eval zero_shot/en); a positive N probes N evenly spaced rows.
+# The median converges quickly; the full split is what gives a trustworthy p90/p95 tail.
+TTFA_SAMPLES="${TTFA_SAMPLES:--1}"
+# One dataset for every model, so the numbers are comparable: CV3-Eval English.
+TTFA_DATASET_PATH="${TTFA_DATASET_PATH:-${CV3_EVAL_PATH}}" # CV3_EVAL_PATH: set by tts_jobs_common.sh
+TTFA_DATASET="${TTFA_DATASET:-zero_shot}"
+TTFA_SPLIT="${TTFA_SPLIT:-en}"
+TTFA_LANG="${TTFA_LANG:-en}"
+# Probe every model in the SAME voice mode, or the numbers are not comparable: a cloning run pays
+# reference encoding that a fixed-voice run does not. Default false = each model's own non-cloning
+# voice. Backends with no clone mode ignore this.
+VOICE_CLONE="${VOICE_CLONE:-false}"
+SGLANG_PORT="${SGLANG_PORT:-30000}"
+VLLM_PORT="${VLLM_PORT:-8000}"
+
+# ── Hardware ────────────────────────────────────────────────────────────────
+# Latency is hardware-bound, so a TTFA is only meaningful next to others measured on the SAME
+# hardware. GPU probes default to TTFA_GPU_FLAVOR, NOT the eval's h200 (FLAVOR): at batch size 1
+TTFA_GPU_FLAVOR="a100-large"
+TTFA_CPU_FLAVOR="cpu-upgrade"
+#
+# TTFA_DEVICE=cpu picks a CPU flavor and passes --device=cpu to the backend. The sidecar filename
+# is suffixed with the flavor, so CPU and GPU results coexist per model.
+# NOT every backend runs on CPU (e.g. breeze-tts's fast path, and the voxtral-tts/higgs servers).
+TTFA_DEVICE="${TTFA_DEVICE:-cuda}"
+
+# TTFA_DEVICE is a TORCH device ("cuda", "cpu", "cuda:0") — TTFA_FLAVOR is the hardware. Fail fast
+# if a flavor is passed here by mistake.
+case "${TTFA_DEVICE}" in
+ cpu|cuda|cuda:[0-9]*) ;;
+ *)
+ echo "ERROR: TTFA_DEVICE='${TTFA_DEVICE}' is not a torch device." >&2
+ echo " Expected: cpu, cuda, or cuda:N." >&2
+ echo " To choose HARDWARE use TTFA_FLAVOR instead, e.g." >&2
+ echo " TTFA_FLAVOR=${TTFA_GPU_FLAVOR} bash submit_ttfa_jobs.sh ${*:-<backend>}" >&2
+ echo " TTFA_DEVICE=cpu bash submit_ttfa_jobs.sh ${*:-<backend>} # picks a cpu-* flavor" >&2
+ exit 1 ;;
+esac
+
+# TTFA_FLAVOR overrides either default; its sidecars are then not picked up by open_results_pr.py.
+if [[ "${TTFA_DEVICE}" == "cpu" ]]; then
+ FLAVOR="${TTFA_FLAVOR:-${TTFA_CPU_FLAVOR}}"
+else
+ FLAVOR="${TTFA_FLAVOR:-${TTFA_GPU_FLAVOR}}"
+fi
+
+# The sidecar suffix is the FLAVOR, which must imply the device: CPU inference on a GPU flavor
+# would be filed under __<gpu flavor> and read as a GPU result. Refuse rather than mislabel.
+case "${TTFA_DEVICE}:${FLAVOR}" in
+ cpu:cpu-*) ;;
+ cpu:*)
+ echo "ERROR: TTFA_DEVICE=cpu with a non-CPU flavor '${FLAVOR}'." >&2
+ echo " The sidecar would be tagged __${FLAVOR} and misread as a GPU measurement." >&2
+ echo " Use a cpu-* flavor, or set TTFA_FLAVOR explicitly to something CPU-named." >&2
+ exit 1 ;;
+ cuda*:cpu-*)
+ echo "ERROR: TTFA_DEVICE=${TTFA_DEVICE} on CPU flavor '${FLAVOR}' — there is no GPU there." >&2
+ exit 1 ;;
+esac
+
+# Index-less "cuda" is rejected by some backends (breeze-tts calls torch.cuda.set_device); every
+# backend's own submit_jobs.sh passes cuda:0, so match that.
+[[ "${TTFA_DEVICE}" == "cuda" ]] && TTFA_DEVICE="cuda:0"
+
+LOG_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/ttfa_job_logs"
+mkdir -p "${LOG_DIR}"
+NAMESPACE_ARG=""; [ -n "$ORG_NAME" ] && NAMESPACE_ARG="--namespace ${ORG_NAME}"
+
+# run_eval.py imports scripts/run_eval_utils.py and, for the probe, scripts/ttfa_probe.py. Gzipped
+# because one job body stacks those and run_eval.py, and must fit in a single 128 KiB `bash -c`
+# argument.
+TTFA_INJECT="$(inject_cmd_gz "${REPO_ROOT}/scripts/ttfa_probe.py" /app/scripts/ttfa_probe.py) $(inject_cmd_gz "${REPO_ROOT}/scripts/run_eval_utils.py" /app/scripts/run_eval_utils.py) ${SCRIPTS_PYTHONPATH}"
+
+# ── Targets: "label|backend_dir|space|model_id|extra flags|engine_tag" ──────
+# `label` is a free-form name you select on; `backend_dir` MUST be the real directory under the
+# repo root (several labels can share one backend, e.g. the two inflect-v2 models).
+#
+# `engine_tag` (field 6, optional) marks the SAME model measured through a DIFFERENT inference
+# engine; it is inserted before the flavor suffix so the sidecars do not overwrite each other
+# (TTFA_MODEL_fishaudio-s2-pro_..._en__sglang__a100-large.json).
+#
+# Select by label, model id, or backend dir: `bash submit_ttfa_jobs.sh inflect-micro-v2`.
+# An engine-tagged target is NOT selectable by its backend dir (it borrows another backend's
+# client); selecting by model id runs every engine for it.
+# Extra flags mirror the default MODEL_CONFIGS entry of the backend's own submit_jobs.sh. Batch
+# sizes are absent: the probe forces batch 1.
+TTFA_TARGETS=(
+ "breeze-tts|breeze-tts|bezzam/evals-breeze|BreezeBlue/Breeze-TTS-2|--language=${TTFA_LANG} --fast_all"
+ "chatterbox|chatterbox|bezzam/evals-chatterbox|ResembleAI/chatterbox|--language=${TTFA_LANG}"
+ "cosyvoice3|cosyvoice3|bezzam/evals-cosy|FunAudioLLM/Fun-CosyVoice3-0.5B-2512|--llm_checkpoint=llm.rl.pt"
+ "fishaudio-s2-pro|fishaudio-s2-pro|bezzam/evals-fish|fishaudio/s2-pro|"
+ # S2-Pro under SGLang-Omni, its streaming engine (the in-process fish-speech backend above
+ # yields once per utterance, so it only gives a whole-utterance clock). Reuses higgs/run_eval.py
+ # (a plain client of sgl-omni's /v1/audio/speech), the higgs) case below and the higgs image.
+ # Flags are S2-Pro's documented defaults; --top_k=30 is required (S2-Pro rejects >30).
+ "s2pro-sglang|higgs|${S2PRO_SGL_SPACE:-bezzam/evals-higgs}|fishaudio/s2-pro|--host=127.0.0.1 --port=${SGLANG_PORT} --max_new_tokens=2048 --temperature=0.8 --top_p=0.8 --top_k=30|sglang"
+ "index-tts|index-tts|bezzam/evals-indextts|IndexTeam/IndexTTS-2.5|--language=${TTFA_LANG}"
+ "inflect-nano-v1|inflect-nano|bezzam/evals-inflect|owensong/Inflect-Nano-v1|"
+ "inflect-micro-v2|inflect-v2|bezzam/evals-inflect-v2|owensong/Inflect-Micro-v2|"
+ "inflect-nano-v2|inflect-v2|bezzam/evals-inflect-v2|owensong/Inflect-Nano-v2|"
+ "kokoro|kokoro|bezzam/evals-kokoro|hexgrad/Kokoro-82M|"
+ # GPU only: liquid-audio hard-codes its detokenizer to CUDA (audiocpp-lfm2-audio below covers CPU).
+ "lfm2-audio|lfm2-audio|bezzam/evals-lfm2-audio|LiquidAI/LFM2.5-Audio-1.5B|--voice=us_female"
+ "magpie-tts|magpie-tts|bezzam/evals-magpie|nvidia/magpie_tts_multilingual_357m|--speaker=Sofia --language=${TTFA_LANG}"
+ "moss-tts|moss-tts|bezzam/evals-moss|OpenMOSS-Team/MOSS-TTS|"
+ "neutts-nano|neutts-nano|bezzam/evals-neutts|neuphonic/neutts-nano|"
+ # Same image, quantized backbone. NeuTTS only streams on the gguf path; the torch target above
+ # 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}"
+ "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).
+ # Qwen's own qwen-tts has no streaming API, so the target above is whole-utterance; keep both.
+ # Its own directory and Space because the two pin incompatible transformers versions.
+ # --chunk_size is pinned to the library default: it is the floor under TTFA, so numbers at a
+ # different chunk_size are not comparable (it is recorded in the sidecar).
+ "qwen3tts-fast|qwen3tts-fast|${QWEN3TTS_FAST_SPACE:-bezzam/evals-faster-qwentts}|Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice|--speaker=Aiden --mode=custom_voice --language=${TTFA_LANG} --chunk_size=12|fasterq3"
+ # faster-qwen3-tts's ggml runtime (qwentts.cpp), with its own CPU image. The only qwen3tts
+ # target that can serve TTFA_DEVICE=cpu: TTFA_DEVICE=cpu bash submit_ttfa_jobs.sh qwen3tts-ggml
+ # --quant=BF16 is the lossless GGUF, so this measures the same model as the targets above;
+ # Q8_0/Q4_K_M would be a DIFFERENT model.
+ "qwen3tts-ggml|qwen3tts-fast|${QWEN3TTS_GGML_SPACE:-bezzam/evals-ggml-qwentts}|Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice|--speaker=Aiden --mode=custom_voice --language=${TTFA_LANG} --chunk_size=12 --backend=ggml --quant=BF16|ggml"
+ # Control for the row above: the same qwentts.cpp runtime on the GPU flavor, so runtime and hardware
+ # effects can be separated. Its image differs from the CPU one only in the base image and wheels
+ # (+cu128 vs +cpu); run_eval.py refuses a wheel that does not match the device.
+ "qwen3tts-ggml-gpu|qwen3tts-fast|${QWEN3TTS_GGML_GPU_SPACE:-bezzam/evals-ggml-gpu-qwentts}|Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice|--speaker=Aiden --mode=custom_voice --language=${TTFA_LANG} --chunk_size=12 --backend=ggml --quant=BF16|ggmlgpu"
+ # Qwen3-TTS and Kokoro through Moondream's Photon runtime (see photon/run_eval.py), sharing one
+ # image. Photon's first chunk is the first AUDIBLE audio (leading silence is dropped). Flags
+ # mirror the reference targets so only the engine differs. Kokoro's number includes G2P, as the
+ # kokoro target's does. photon-kokoro also runs on CPU.
+ "photon-qwen3tts|photon|${PHOTON_SPACE:-bezzam/evals-photon}|Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice|--voice=Aiden --language=${TTFA_LANG}|photon"
+ "photon-qwen3tts-0.6b|photon|${PHOTON_SPACE:-bezzam/evals-photon}|Qwen/Qwen3-TTS-12Hz-0.6B-CustomVoice|--voice=Aiden --language=${TTFA_LANG}|photon"
+ "photon-kokoro|photon|${PHOTON_SPACE:-bezzam/evals-photon}|hexgrad/Kokoro-82M|--voice=af_heart --lang_code=a|photon"
+ # The same models through 0xShug0/audio.cpp (ggml C++), served by audiocpp_server's SSE
+ # streaming endpoint (see audiocpp/run_eval.py).
+ # The Space's image tag is per device: TTFA_DEVICE=cpu AUDIOCPP_SPACE=bezzam/evals-audiocpp-cpu ...
+ "audiocpp-voxcpm2|audiocpp|${AUDIOCPP_SPACE:-bezzam/evals-audiocpp}|openbmb/VoxCPM2||audiocpp"
+ "audiocpp-supertonic|audiocpp|${AUDIOCPP_SPACE:-bezzam/evals-audiocpp}|Supertone/supertonic-3|--language=${TTFA_LANG}|audiocpp"
+ "audiocpp-pocket-tts|audiocpp|${AUDIOCPP_SPACE:-bezzam/evals-audiocpp}|kyutai/pocket-tts||audiocpp"
+ "audiocpp-breeze-tts|audiocpp|${AUDIOCPP_SPACE:-bezzam/evals-audiocpp}|BreezeBlue/Breeze-TTS-2|--language=${TTFA_LANG}|audiocpp"
+ "audiocpp-omnivoice|audiocpp|${AUDIOCPP_SPACE:-bezzam/evals-audiocpp}|k2-fsa/OmniVoice|--language=${TTFA_LANG}|audiocpp"
+ # Streaming models that are only on the TTFA tab (no WER/RTFx backend).
+ "audiocpp-kugelaudio|audiocpp|${AUDIOCPP_SPACE:-bezzam/evals-audiocpp}|kugelaudio/kugelaudio-0-open||audiocpp"
+ "audiocpp-neutts-2e|audiocpp|${AUDIOCPP_SPACE:-bezzam/evals-audiocpp}|neuphonic/neutts-2e||audiocpp"
+ "audiocpp-audio8|audiocpp|${AUDIOCPP_SPACE:-bezzam/evals-audiocpp}|Edge0/Audio8-TTS-Preview-0.6b||audiocpp"
+ "audiocpp-lfm2-audio|audiocpp|${AUDIOCPP_SPACE:-bezzam/evals-audiocpp}|LiquidAI/LFM2.5-Audio-1.5B||audiocpp"
+ "audiocpp-soprano|audiocpp|${AUDIOCPP_SPACE:-bezzam/evals-audiocpp}|ekwek/Soprano-1.1-80M||audiocpp"
+ "audiocpp-voxcpm1|audiocpp|${AUDIOCPP_SPACE:-bezzam/evals-audiocpp}|openbmb/VoxCPM-0.5B||audiocpp"
+ "audiocpp-dots-soar|audiocpp|${AUDIOCPP_SPACE:-bezzam/evals-audiocpp}|dots-studio/dots.tts-soar||audiocpp"
+ "audiocpp-dots-mf|audiocpp|${AUDIOCPP_SPACE:-bezzam/evals-audiocpp}|dots-studio/dots.tts-mf||audiocpp"
+ # Clone-only: always probed with the row's prompt (sidecar suffixed _voice_clone).
+ "audiocpp-confucius4|audiocpp|${AUDIOCPP_SPACE:-bezzam/evals-audiocpp}|netease-youdao/Confucius4-TTS|--language=${TTFA_LANG}|audiocpp"
+ "supertonic|supertonic|bezzam/evals-super|Supertone/supertonic-3|--voice=M1 --lang=${TTFA_LANG}"
+ "transformers|transformers|bezzam/evals|microsoft/speecht5_tts|--language=${TTFA_LANG}"
+ # Second model on the shared transformers backend; not streaming (whole-utterance clock).
+ # --language is required: it sets both src_lang and tgt_lang (see _seamless_lang).
+ "seamless-m4t-v2|transformers|bezzam/evals|facebook/seamless-m4t-v2-large|--language=${TTFA_LANG}"
+ "vibevoice_realtime|vibevoice_realtime|bezzam/evals-vibevoice|microsoft/VibeVoice-Realtime-0.5B|"
+ "voxcpm2|voxcpm2|bezzam/evals-voxcpm|openbmb/VoxCPM2|"
+ # HTTP CLIENTS of an inference server the job starts itself (see the preamble in submit_one);
+ # --server_pid makes a dead server fail the wait immediately.
+ "voxtral-tts|voxtral-tts|bezzam/evals-voxtral|mistralai/Voxtral-4B-TTS-2603|--base_url=http://localhost:${VLLM_PORT} --server_pid=\${SERVER_PID}"
+ "higgs|higgs|bezzam/evals-higgs|bosonai/higgs-tts-3-4b|--host=127.0.0.1 --port=${SGLANG_PORT}"
+)
+
+# 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"
+
+submit_one() {
+ local backend="$1" space="$2" model_id="$3" extra="$4" engine="$5"
+ local model_safe="${model_id//\//-}"
+ # Sidecar suffix: engine first (when the target names one), then always the flavor.
+ local sidecar_suffix="${engine:+__${engine}}__${FLAVOR}"
+ local image="hf.co/spaces/${space}"
+ local inject preamble postamble clone_flag=""
+
+ inject="$(inject_cmd_gz "${REPO_ROOT}/${backend}/run_eval.py" "/app/${backend}/run_eval.py")"
+
+ # Every backend takes --device (run_eval_utils.add_common_args); HTTP clients (voxtral-tts,
+ # higgs) accept and ignore it, since their GPU belongs to the server process.
+ local device_flag="--device=${TTFA_DEVICE}"
+ [[ " ${NO_CLONE_FLAG} " == *" ${backend} "* ]] || \
+ clone_flag=$([[ "${VOICE_CLONE}" == "true" ]] && echo "--voice_clone" || echo "--no-voice_clone")
+
+ # HTTP-client backends start their own inference server first, as their generate_stage does.
+ # On failure the FULL server log is dumped (the engine's traceback explains the crash).
+ preamble=""; postamble=""
+
+ # CPU runs: cap every thread pool BEFORE python starts. Nested parallelism (torch intra-op
+ # threads each calling into a multi-threaded BLAS) otherwise oversubscribes the vCPUs and
+ # inflates TTFA several-fold.
+ if [[ "${TTFA_DEVICE}" == "cpu" ]]; then
+ # TTFA_CPU_THREADS wins when set (a container can report the HOST's nproc with no cpu.max).
+ preamble="
+ _cpuq=\"${TTFA_CPU_THREADS:-}\"
+ if [ -z \"\${_cpuq}\" ]; then
+ _cpuq=\$(awk '{ if (\$1==\"max\") print 0; else printf \"%d\", (\$1/\$2) }' /sys/fs/cgroup/cpu.max 2>/dev/null || echo 0)
+ [ \"\${_cpuq:-0}\" -gt 0 ] 2>/dev/null || _cpuq=\$(nproc)
+ fi
+ export OMP_NUM_THREADS=\${_cpuq} MKL_NUM_THREADS=\${_cpuq} OPENBLAS_NUM_THREADS=\${_cpuq}
+ echo \"CPU run: nproc=\$(nproc) cgroup_quota=\${_cpuq} -> OMP_NUM_THREADS=\${_cpuq}\"
+ "
+ # Guard against a quoting slip silently emptying the preamble (the probe would run uncapped).
+ if [[ "${preamble}" != *OMP_NUM_THREADS* ]]; then
+ echo "ERROR: CPU thread-cap preamble is empty or truncated — check its quoting." >&2
+ return 1
+ fi
+ fi
+
+ case "${backend}" in
+ higgs)
+ # S2-Pro checkpoints carry no `architectures`, so sgl-omni cannot infer the pipeline
+ # config: write the two-line --config its cookbook uses (not shipped in the package).
+ local serve_config=""
+ if [[ "${model_id}" == "fishaudio/s2-pro" ]]; then
+ serve_config="--config /tmp/sgl_omni_pipeline.yaml"
+ preamble="${preamble}
+ echo 'config_cls: S2ProPipelineConfig' > /tmp/sgl_omni_pipeline.yaml
+ echo 'model_path: ${model_id}' >> /tmp/sgl_omni_pipeline.yaml"
+ fi
+ preamble="${preamble}
+ set -e
+ mkdir -p /app/higgs/results
+ # /tmp: the probe writes voice-clone references into a tempfile.mkdtemp() dir, and the
+ # server refuses to read references outside the allowed root.
+ /opt/omni/bin/sgl-omni serve --model-path ${model_id} ${serve_config} --host 127.0.0.1 --port ${SGLANG_PORT} \
+ --allowed-local-media-path /tmp > /app/higgs/results/server.log 2>&1 &
+ SERVER_PID=\$!
+ trap 'kill \$SERVER_PID 2>/dev/null || true' EXIT"
+ postamble="|| { echo '--- sgl-omni serve log (full) ---'; cat /app/higgs/results/server.log; exit 1; }"
+ ;;
+ voxtral-tts)
+ # See voxtral-tts/submit_jobs.sh: the forward-compat libcuda must stay unset on h200,
+ # or every StageEngineCoreProc dies at init_device() with CUDA error 803.
+ preamble="${preamble}
+ set -e
+ unset VLLM_ENABLE_CUDA_COMPATIBILITY
+ vllm serve ${model_id} --omni --port ${VLLM_PORT} > /app/voxtral-tts/vllm_serve.log 2>&1 &
+ SERVER_PID=\$!
+ trap 'kill \$SERVER_PID 2>/dev/null || true' EXIT"
+ postamble="|| { echo '--- vllm serve log (full) ---'; cat /app/voxtral-tts/vllm_serve.log; exit 1; }"
+ ;;
+ esac
+
+ hf jobs run \
+ --flavor "${FLAVOR}" --timeout "${TTFA_TIMEOUT:-8h}" --secrets HF_TOKEN ${NAMESPACE_ARG} \
+ --volume "hf://buckets/${RESULTS_BUCKET}:/results" "${image}" \
+ bash -c "
+ ${inject}
+ ${TTFA_INJECT}
+ ${preamble}
+ cd /app/${backend} && python run_eval.py \
+ --model_id=${model_id} \
+ --dataset_path=${TTFA_DATASET_PATH} \
+ --dataset=${TTFA_DATASET} \
+ --split=${TTFA_SPLIT} \
+ --ttfa_probe=${TTFA_SAMPLES} \
+ ${device_flag} \
+ ${clone_flag} \
+ ${extra} ${postamble}
+ # Tag the sidecar with engine+flavor so probes that differ only in those do not collide.
+ for f in results/${model_safe}/TTFA_MODEL_*.json; do
+ [ -e \"\$f\" ] || continue
+ case \"\$f\" in *${sidecar_suffix}.json) ;; *) mv \"\$f\" \"\${f%.json}${sidecar_suffix}.json\" ;; esac
+ done
+ mkdir -p /results
+ cp -r results/${model_safe} /results/
+ "
+}
+
+# ── Run: one job per target, in parallel, one log each ───────────────────────
+SELECT=("$@")
+PIDS=(); TAGS=(); MIDS=(); LOGS=()
+_n_desc=$([[ "${TTFA_SAMPLES}" -lt 0 ]] && echo "the WHOLE split" || echo "${TTFA_SAMPLES} samples")
+echo "TTFA probe: ${_n_desc} of ${TTFA_DATASET_PATH}/${TTFA_DATASET}/${TTFA_SPLIT}"
+echo " flavor=${FLAVOR}, device=${TTFA_DEVICE}, batch size 1, voice_clone=${VOICE_CLONE}"
+echo " sidecars are suffixed __${FLAVOR} so results from different hardware coexist"
+echo
+
+for target in "${TTFA_TARGETS[@]}"; do
+ IFS='|' read -r label backend space model_id extra engine <<< "${target}"
+ if [ ${#SELECT[@]} -gt 0 ]; then
+ # Backend-dir matching is skipped for engine-tagged targets — see the note above TTFA_TARGETS.
+ _sel=(-e "${label}" -e "${model_id}")
+ [ -z "${engine}" ] && _sel+=(-e "${backend}")
+ printf '%s\n' "${SELECT[@]}" | grep -qxF "${_sel[@]}" || continue
+ fi
+ if [ ! -f "${REPO_ROOT}/${backend}/run_eval.py" ]; then
+ echo "ERROR: target '${label}' names backend dir '${backend}', but" >&2
+ echo " ${REPO_ROOT}/${backend}/run_eval.py does not exist." >&2
+ echo " Field 2 must be the real directory; field 1 is the free-form label." >&2
+ exit 1
+ fi
+ log="${LOG_DIR}/${label}_${model_id//\//-}.log"
+ echo "Submitting TTFA probe: ${model_id} (label=${label}, backend=${backend}, log: ${log})"
+ ( submit_one "${backend}" "${space}" "${model_id}" "${extra}" "${engine}" ) > "${log}" 2>&1 &
+ # Exact log path: two targets can share a model id (one per engine).
+ PIDS+=("$!"); TAGS+=("${label}"); MIDS+=("${model_id}"); LOGS+=("${log}")
+done
+
+if [ ${#PIDS[@]} -eq 0 ]; then
+ echo "No targets matched. Known labels:"
+ printf ' %s\n' "${TTFA_TARGETS[@]}" | cut -d'|' -f1 | tr -d '"' | sort -u
+ exit 1
+fi
+
+# _job_id <log> — the HF job id `hf jobs run` printed into <log>, or nothing.
+_job_id() {
+ grep -oE "id: [0-9a-f]{16,}" "$1" 2>/dev/null | head -1 | awk '{print $2}'
+}
+
+# _append_job_log <log> — append the HF job's own log (job id parsed from <log>) to <log>.
+_append_job_log() {
+ local jid
+ jid=$(_job_id "$1")
+ [ -n "${jid}" ] && hf jobs logs "${jid}" >> "$1" 2>/dev/null || true
+}
+
+# _job_stage <job_id> — the job's stage on HF (COMPLETED, ERROR, RUNNING, ...), or nothing if it
+# could not be read.
+_job_stage() {
+ hf jobs inspect "$1" 2>/dev/null | python3 -c \
+ "import sys, json; d = json.load(sys.stdin); d = d[0] if isinstance(d, list) else d; print((d.get('status') or {}).get('stage') or '')" \
+ 2>/dev/null
+}
+
+# _final_stage <log> — when `hf jobs run` exits non-zero, the job may still be fine: the local
+# client follows the job's log stream, and a dropped connection (e.g. a DNS blip) kills the client
+# but not the job. So ask HF for the job's real stage, polling while it is still running.
+# Prints the terminal stage, or nothing if no job id was printed or HF never answered.
+_final_stage() {
+ local jid stage misses=0
+ jid=$(_job_id "$1")
+ [ -n "${jid}" ] || return 0
+ while :; do
+ stage=$(_job_stage "${jid}")
+ case "${stage}" in
+ COMPLETED|ERROR|CANCELED|CANCELLED|DELETED) echo "${stage}"; return 0 ;;
+ "") misses=$((misses+1)); [ "${misses}" -ge 10 ] && return 0 ;; # ~5 min of no answer
+ *) misses=0 ;;
+ esac
+ sleep 30
+ done
+}
+
+echo; echo "Waiting on ${#PIDS[@]} probe job(s)..."
+FAILED=0
+for i in "${!PIDS[@]}"; do
+ _log="${LOGS[$i]}"
+ _ok=false; _stage=""
+ if wait "${PIDS[$i]}"; then
+ _ok=true
+ else
+ _stage=$(_final_stage "${_log}")
+ if [ "${_stage}" = "COMPLETED" ]; then
+ echo " (${TAGS[$i]}: the local log stream failed, but the HF job completed — using its log)"
+ _ok=true
+ fi
+ fi
+ if ${_ok}; then
+ line=$(grep -hoE "TTFA SUMMARY .*" "${_log}" 2>/dev/null | tail -1)
+ # A short job can finish before `hf jobs run`'s log stream attaches; re-fetch by job id.
+ if [ -z "${line}" ]; then
+ _append_job_log "${_log}"
+ line=$(grep -hoE "TTFA SUMMARY .*" "${_log}" 2>/dev/null | tail -1)
+ fi
+ echo " ✓ ${MIDS[$i]} [${TAGS[$i]}]: ${line:-completed, but no TTFA line found — see ${_log}}"
+ else
+ echo " ✗ ${MIDS[$i]} [${TAGS[$i]}]: FAILED (HF job stage: ${_stage:-unknown}) — last lines:"
+ # Same race as above: pull the job's own log so a failure is diagnosable.
+ _append_job_log "${_log}"
+ tail -n 12 "${_log}" 2>/dev/null | sed 's/^/ /'
+ FAILED=$((FAILED+1))
+ fi
+done
+
+echo
+echo "RTFx(batch1) above is NOT the leaderboard RTFx: TTFA requires batch size 1, while the eval"
+echo "measures RTFx at each backend's real batch size. Do not mix them."
+echo
+echo "Sidecars land in the bucket as"
+echo " TTFA_MODEL_<model>_DATASET_<dataset>_<config>_<split>[_voice_clone][__<engine>]__${FLAVOR}.json"
+[ "${FAILED}" -eq 0 ] || { echo "${FAILED} probe job(s) failed."; exit 1; }
diff --git a/supertonic/run_eval.py b/supertonic/run_eval.py
new file mode 100644
index 0000000..1aae5cb
--- /dev/null
+++ b/supertonic/run_eval.py
@@ -0,0 +1,262 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (Supertonic 3 backend, stage 1).
+
+Supertonic 3 (Supertone/supertonic-3) is a ~0.1B on-device TTS shipped as four ONNX graphs run
+with ONNX Runtime. Batching is native (`TextToSpeech.batch` from supertone-inc/supertonic's
+`helper.py`; text chunking is disabled in batch mode, fine for short eval texts). The batched
+output is zero-padded, so each sample is trimmed to its predicted duration.
+
+Fixed preset voices only (M1-M5 / F1-F5 style embeddings): the local pipeline has no zero-shot
+cloning, so the dataset's prompt columns are dropped. Output is 44.1 kHz mono.
+
+Timing: `ort.InferenceSession.run` is synchronous (outputs are on host when it returns, also
+under the CUDA EP), so `time.perf_counter()` around the batch call is the full latency.
+
+Stage 2 (`transformers/transcribe.py`) fills `pred_text` with Qwen3-ASR, and stage 4
+(`normalizer.eval_utils.score_results`) computes WER + RTFx from the manifest (no stage 3 SIM:
+fixed voice).
+"""
+
+import argparse
+import os
+import sys
+import time
+
+import numpy as np
+import onnxruntime as ort
+import soundfile as sf
+from tqdm import tqdm
+
+
+# The reference implementation lives in the cloned supertone-inc/supertonic repo
+# (py/helper.py), baked into the image at /opt/supertonic by the Dockerfile.
+sys.path.insert(0, os.environ.get("SUPERTONIC_HELPER_DIR", "/opt/supertonic/py"))
+from helper import ( # noqa: E402
+ TextToSpeech,
+ load_cfgs,
+ load_onnx_all,
+ load_text_processor,
+ load_voice_style,
+)
+
+from run_eval_utils import ( # noqa: E402
+ 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 = (
+ "duration_predictor.onnx",
+ "text_encoder.onnx",
+ "vector_estimator.onnx",
+ "vocoder.onnx",
+)
+
+
+def _build_tts(onnx_dir, device):
+ """helper.load_text_to_speech, but with the CUDA EP (upstream raises for use_gpu=True)."""
+ opts = ort.SessionOptions()
+ if device.startswith("cuda"):
+ device_id = int(device.split(":")[1]) if ":" in device else 0
+ providers = [
+ ("CUDAExecutionProvider", {"device_id": device_id}),
+ "CPUExecutionProvider",
+ ]
+ else:
+ providers = ["CPUExecutionProvider"]
+
+ cfgs = load_cfgs(onnx_dir)
+ dp_ort, text_enc_ort, vector_est_ort, vocoder_ort = load_onnx_all(onnx_dir, opts, providers)
+ text_processor = load_text_processor(onnx_dir)
+ tts = TextToSpeech(cfgs, text_processor, dp_ort, text_enc_ort, vector_est_ort, vocoder_ort)
+ # Report the registered providers: the CUDA EP silently falls back to CPU (e.g. no cuDNN).
+ for name, sess in [
+ ("duration_predictor", dp_ort),
+ ("text_encoder", text_enc_ort),
+ ("vector_estimator", vector_est_ort),
+ ("vocoder", vocoder_ort),
+ ]:
+ print(f" {name}: providers={sess.get_providers()}")
+ return tts
+
+
+def _print_model_size(onnx_dir):
+ """Sum ONNX initializer element counts across the four graphs (model size in B params)."""
+ try:
+ import onnx
+
+ n_params = 0
+ for fname in ONNX_FILES:
+ model = onnx.load(os.path.join(onnx_dir, fname), load_external_data=False)
+ for init in model.graph.initializer:
+ n = 1
+ for d in init.dims:
+ n *= d
+ n_params += n
+ print(f"TTS model size: {n_params / 1e9:.2f}B parameters (sum of ONNX initializers over {len(ONNX_FILES)} graphs)")
+ except Exception as e:
+ # Model card reports ~99M parameters across the public ONNX assets.
+ print(f"Could not compute ONNX parameter count ({e}); model card reports ~0.10B parameters.")
+
+
+def main(args):
+ # Set seed for reproducibility (the vector estimator samples latent noise via numpy).
+ set_seed(args.seed)
+
+ onnx_dir = os.path.join(args.model_dir, "onnx")
+ print(f"Loading Supertonic 3 from {onnx_dir} (device={args.device})...")
+ tts = _build_tts(onnx_dir, args.device)
+ sampling_rate = int(tts.sample_rate) # 44100
+ print(f"Loaded Supertonic 3 ({args.model_id}, sr={sampling_rate}, voice={args.voice})")
+ _print_model_size(onnx_dir)
+
+ # Fixed shipped voice style (JSON style embedding). `load_voice_style` builds a Style
+ # whose leading dim must match the text batch size, so cache one per batch size
+ # (only two sizes ever occur: batch_size and the final remainder).
+ style_path = os.path.join(args.model_dir, "voice_styles", f"{args.voice}.json")
+ if not os.path.exists(style_path):
+ raise FileNotFoundError(f"Voice style not found: {style_path} (expected M1-M5/F1-F5)")
+ style_cache = {}
+
+ def get_style(bsz):
+ if bsz not in style_cache:
+ style_cache[bsz] = load_voice_style([style_path] * bsz)
+ return style_cache[bsz]
+
+ # 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
+
+ def generate_tts(batch):
+ """Synthesize speech for a minibatch of target texts; time the batch generation for RTFx."""
+ texts_to_generate = list(batch[args.text_column])
+ minibatch_size = len(texts_to_generate)
+ langs = [args.lang] * minibatch_size
+ style = get_style(minibatch_size) # cached; loaded outside the timed region on reuse
+
+ # START TIMING (TTS batch generation; session.run is synchronous, see module docstring)
+ start = time.perf_counter()
+
+ # Returns zero-padded wavs (bsz, T_max) + per-sample durations (s).
+ wavs, durations = tts.batch(texts_to_generate, langs, style, args.total_steps, args.speed)
+
+ # END TIMING
+ runtime = time.perf_counter() - start
+ # per-sample generation time (RTFx is aggregated over the whole set at scoring time)
+ batch["generation_time_s"] = minibatch_size * [runtime / minibatch_size]
+
+ wavs = np.asarray(wavs)
+ durations = np.asarray(durations).reshape(-1)
+ gen_paths, audio_length_s = [], []
+ for b, sample_id in enumerate(batch["id"]):
+ # Trim the zero-padding to the predicted duration (as in the upstream example).
+ n_samples = int(sampling_rate * float(durations[b]))
+ audio = np.asarray(wavs[b], dtype=np.float32).reshape(-1)[:n_samples]
+ # 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)
+ sf.write(path, audio, sampling_rate)
+ gen_paths.append(rel_path)
+ audio_length_s.append(len(audio) / sampling_rate)
+
+ batch["gen_audio_filepath"] = gen_paths
+ batch["audio_length_s"] = audio_length_s
+ batch["references"] = list(batch[args.text_column]) # raw; normalized at scoring time
+ return batch
+
+ dataset = load_tts_dataset(args)
+
+ probe_out_dir = model_dir # real results dir, captured before the probe rebinds model_dir
+ # ── TTFA probe: latency only, writing nothing but a JSON sidecar ─────────
+ # TTFA is per-request, so generate_tts() is driven with one-row batches. model_dir and
+ # dataset_dir_name are rebound to a temp dir (generate_tts reads them late-bound), so no
+ # results are touched. No streaming API: `first` is None -> whole-utterance fallback.
+ # 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
+ import tempfile
+
+ model_dir = tempfile.mkdtemp(prefix="ttfa_out_")
+ dataset_dir_name = "ttfa"
+ output_dir = os.path.join(model_dir, dataset_dir_name)
+ os.makedirs(output_dir, exist_ok=True)
+
+ def _gen(job):
+ return float(generate_tts(job)["audio_length_s"][0]), None, None
+
+ columns = dataset.column_names
+ jobs = [{c: [dataset[i][c]] for c in columns}
+ for i in sample_indices(args.ttfa_probe, len(dataset))]
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=probe_out_dir, mode_suffix="", n=args.ttfa_probe, # fixed voice: no clone mode
+ extra={"device": args.device, "note": "driven at batch size 1"},
+ )
+ return
+
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ starts = pending_batches(dataset, args.batch_size, done_entries, dataset_dir_name)
+ warm_up(generate_tts, dataset, starts, args.batch_size, args.warmup_steps)
+ set_seed(args.seed) # so warm-up does not shift the latent-noise stream of the timed run
+
+ # ── Main loop: TTS → write JSONL, one batch at a time ───────────────────
+ for batch_start in tqdm(starts, desc="Generating"):
+ batch = generate_tts(dataset[batch_start : batch_start + args.batch_size])
+
+ # Append each sample to the JSONL immediately. `pred_text` is filled by stage 2 (ASR).
+ for afp, alen, gtime, ref in zip(
+ batch["gen_audio_filepath"], batch["audio_length_s"],
+ batch["generation_time_s"], batch["references"],
+ ):
+ write_entry(manifest_file, manifest_entry(afp, alen, gtime, ref))
+ 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="Supertone/supertonic-3",
+ help="HF model id (used for manifest/output naming).",
+ )
+ parser.add_argument(
+ "--model_dir",
+ type=str,
+ default="/opt/supertonic3",
+ help="Local snapshot of Supertone/supertonic-3 with onnx/ + voice_styles/ (baked at image build).",
+ )
+ parser.add_argument(
+ "--voice",
+ type=str,
+ default="M1",
+ help="Built-in voice style: one of M1-M5 / F1-F5 (JSON style embeddings shipped with the model).",
+ )
+ parser.add_argument("--lang", type=str, default="en", help="Language code (31 supported; 'na' = language-agnostic).")
+ parser.add_argument(
+ "--total_steps",
+ type=int,
+ default=8,
+ help="Denoising steps for the vector estimator (5=fast/low to 12=high quality; model default 8).",
+ )
+ parser.add_argument("--speed", type=float, default=1.05, help="Speech rate (0.7 slow to 2.0 fast; model default 1.05).")
+ add_common_args(parser, batch_size=32)
+
+ 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/supertonic/submit_jobs.sh b/supertonic/submit_jobs.sh
new file mode 100755
index 0000000..ca07b10
--- /dev/null
+++ b/supertonic/submit_jobs.sh
@@ -0,0 +1,60 @@
+#!/bin/bash
+# HF Jobs TTS eval — Supertonic backend (fixed voice: generate → transcribe → score; no SIM).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["Supertone/supertonic-3 32 M1" ...]
+# 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-super}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-super/blob/main/Dockerfile)
+DEFAULT_STAGES="generate transcribe" # no SIM (fixed voice)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id batch_size voice". ──
+generate_stage() {
+ local _ BATCH_SIZE VOICE
+ read -r _ BATCH_SIZE VOICE <<< "${MODEL_CFG}"
+ 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/supertonic && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --voice=${VOICE} \
+ --lang=${ASR_LANG} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --device=cuda:0 \
+ --batch_size=${BATCH_SIZE} \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Languages this backend can select ────────────────────────────────────────
+# The language codes from the model card's front-matter. No Chinese, so zh splits are skipped
+# (run_eval.py's --lang 'na' = language-agnostic is a fallback, not Chinese support).
+SUPERTONIC_LANGUAGES="en ko ja ar bg cs da de el es et fi fr hi hr hu id it lt lv nl pl pt ro ru sk sl sv tr uk vi"
+supports_language() { [[ " ${SUPERTONIC_LANGUAGES} " == *" $1 "* ]]; }
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment) ──
+DATASET_CONFIGS=(
+ "tts en en"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ja ja ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ko ko ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot de de ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot fr fr ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot it it ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ru ru ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id batch_size voice" (CLI args override) ──────────────────
+MODEL_CONFIGS=("Supertone/supertonic-3 32 M1")
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/transformers/run_eval.py b/transformers/run_eval.py
new file mode 100644
index 0000000..36955fb
--- /dev/null
+++ b/transformers/run_eval.py
@@ -0,0 +1,685 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (Transformers backend, stage 1).
+
+Synthesizes the target text in batches (generation is timed for RTFx). With `--voice_clone`
+(off by default) the dataset's reference prompt audio/text condition the output speaker.
+
+Stage 2 (`transformers/transcribe.py`) transcribes the wavs, stage 3 (`score_similarity.py`,
+voice cloning only) scores SIM, and stage 4 (local scoring) computes WER + RTFx, as for every backend.
+
+Voice cloning is supported for VOICE_CLONE_FAMILIES; other models fall back to their default voice
+(and skip SIM). Prompt wavs are saved under `output_dir/prompts/` for the SIM stage.
+
+Per-family notes: SpeechT5 needs a speaker embedding + HiFi-GAN vocoder (`--speecht5_*`).
+VITS/MMS and FastSpeech2 synthesize one sample at a time (batch padding causes a hum).
+SeamlessM4T-v2 stays batched and trims each row to its `waveform_lengths`. VibeVoice returns already-trimmed per-sample waveforms and needs `diffusers`.
+"""
+
+import argparse
+import os
+
+import numpy as np
+import soundfile as sf
+import torch
+from torch.nn.attention import SDPBackend, sdpa_kernel
+from tqdm import tqdm
+
+from transformers import (
+ AutoConfig,
+ AutoModelForSpeechSeq2Seq,
+ AutoModelForTextToWaveform,
+ AutoProcessor,
+ CompileConfig,
+ SpeechT5ForTextToSpeech,
+ SpeechT5HifiGan,
+ FastSpeech2ConformerTokenizer
+)
+
+from run_eval_utils import (
+ add_common_args,
+ load_done_entries,
+ load_tts_dataset,
+ manifest_entry,
+ open_manifest,
+ output_paths,
+ pending_batches,
+ print_model_size,
+ print_next_steps,
+ set_seed,
+ warm_up,
+ wav_rel_path,
+ write_entry,
+)
+
+
+torch.set_float32_matmul_precision("high")
+
+# Families that support `--voice_clone` (substrings of `config.model_type`). Keep in sync with
+# VOICE_CLONE_MODELS in transformers/submit_jobs.sh.
+VOICE_CLONE_FAMILIES = ("dia", "higgs", "vibevoice")
+
+# ISO 639-1 (as passed by the eval scripts) -> ISO 639-3 (SeamlessM4T) for the 36 languages
+# SeamlessM4T v2 can SPEAK (fewer than it can translate). `cmn` is simplified Mandarin.
+SEAMLESS_LANGUAGE_CODES = {
+ "ar": "arb", "bn": "ben", "ca": "cat", "cs": "ces", "cy": "cym", "da": "dan",
+ "de": "deu", "en": "eng", "es": "spa", "et": "est", "fa": "pes", "fi": "fin",
+ "fr": "fra", "hi": "hin", "id": "ind", "it": "ita", "ja": "jpn", "ko": "kor",
+ "mt": "mlt", "nl": "nld", "pl": "pol", "pt": "por", "ro": "ron", "ru": "rus",
+ "sk": "slk", "sv": "swe", "sw": "swh", "te": "tel", "th": "tha", "tl": "tgl",
+ "tr": "tur", "uk": "ukr", "ur": "urd", "uz": "uzn", "vi": "vie", "zh": "cmn",
+}
+SEAMLESS_SPEECH_CODES = frozenset(SEAMLESS_LANGUAGE_CODES.values())
+
+
+def _seamless_lang(language):
+ """Translate the pipeline's language code to the one SeamlessM4T expects.
+
+ Unmapped values pass through (a raw Seamless code is accepted), but the result must be speakable;
+ otherwise `generate()` fails late with a misleading error.
+ """
+ code = SEAMLESS_LANGUAGE_CODES.get(language.lower(), language)
+ if code not in SEAMLESS_SPEECH_CODES:
+ raise ValueError(
+ f"SeamlessM4T cannot synthesize speech for --language={language!r} (resolved to "
+ f"{code!r}). It supports {len(SEAMLESS_SPEECH_CODES)} languages for speech output; pass "
+ "one of these ISO 639-1 codes (or its ISO 639-3 equivalent): "
+ f"{', '.join(sorted(SEAMLESS_LANGUAGE_CODES))}."
+ )
+ return code
+
+
+def load_tts_model(args, torch_dtype):
+ """Load the TTS model under evaluation, its processor, and (for SpeechT5) the vocoder + speaker embedding.
+
+ Returns (config, model, processor, extras) where `extras` holds SpeechT5-specific objects
+ (`vocoder`, `speaker_embeddings`) or is empty for other models.
+ """
+ config = AutoConfig.from_pretrained(args.model_id, revision=args.revision)
+ extras = {}
+
+ # Validate the language before loading weights (otherwise it only fails inside generate()).
+ if "seamless" in config.model_type:
+ _seamless_lang(args.language)
+
+ if "speecht5" in config.model_type:
+ # SpeechT5 is an encoder-decoder TTS that needs a speaker embedding and a separate HiFi-GAN
+ # vocoder, and generates via `generate_speech` (not the generic `generate`). Load in float32
+ # for output quality — it is small and the stop-token threshold is sensitive to low precision.
+ from datasets import load_dataset
+
+ model = SpeechT5ForTextToSpeech.from_pretrained(args.model_id, revision=args.revision).to(args.device)
+ vocoder = SpeechT5HifiGan.from_pretrained(args.speecht5_vocoder).to(args.device)
+ xvectors = load_dataset("parquet", data_files=args.speecht5_speaker_embeddings, split="train")
+ speaker = torch.tensor(xvectors[args.speecht5_speaker_index]["xvector"]).unsqueeze(0).to(args.device)
+ extras = {"vocoder": vocoder, "speaker_embeddings": speaker}
+ elif "dia" in config.model_type:
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
+ args.model_id,
+ dtype=torch_dtype,
+ device_map=args.device,
+ attn_implementation=args.attn_implementation,
+ )
+ else:
+ # Bark, Seamless, FastSpeech2, and VITS only support eager attention.
+ eager_only = any(f in config.model_type for f in ("bark", "seamless", "fastspeech2", "vits"))
+ attn_impl = "eager" if eager_only else args.attn_implementation
+ # FastSpeech2 and VITS require float32; lower precision causes dtype mismatches or numerical errors.
+ model_dtype = torch.float32 if ("fastspeech2" in config.model_type or "vits" in config.model_type) else torch_dtype
+ if "vibevoice" in config.model_type:
+ # Only the LM backbone (`text_config`) has attention; the tokenizers reject anything but
+ # eager, so route the requested implementation to the backbone only.
+ attn_impl = {"": "eager", "text_config": args.attn_implementation}
+ model = AutoModelForTextToWaveform.from_pretrained(
+ args.model_id,
+ dtype=model_dtype,
+ device_map=args.device,
+ attn_implementation=attn_impl,
+ )
+ model.eval()
+ print_model_size(model)
+
+ processor_kwargs = {"device_map": args.device} if "higgs" in config.model_type else {}
+ if "fastspeech2" in config.model_type:
+ # FastSpeech2ConformerWithHifiGan uses a tokenizer from a separate repo.
+ processor = FastSpeech2ConformerTokenizer.from_pretrained("espnet/fastspeech2_conformer")
+ else:
+ processor = AutoProcessor.from_pretrained(args.model_id, revision=args.revision, **processor_kwargs)
+ return config, model, processor, extras
+
+
+def build_gen_kwargs(args, config, model):
+ """Assemble generation kwargs per model family."""
+ gen_kwargs = {}
+ if model.can_generate():
+ # Greedy decoding for reproducible WER. GREEDY_UNSAFE_FAMILIES opt out: under greedy they
+ # stop emitting EOS and run to the token cap, so they use their checkpoint's sampling defaults.
+ GREEDY_UNSAFE_FAMILIES = ("dia", "bark", "csm")
+ if not any(family in config.model_type for family in GREEDY_UNSAFE_FAMILIES):
+ gen_kwargs["do_sample"] = False
+ gen_kwargs["temperature"] = 0.0
+ # Bark sets max_new_tokens internally per stage and rejects it as an explicit kwarg.
+ if "bark" not in config.model_type:
+ gen_kwargs["max_new_tokens"] = args.max_new_tokens
+ # `min_new_tokens` pins the length for families that do not stop on their own; for the
+ # NO_MIN_TOKENS_FAMILIES `--max_new_tokens` is only a cap and they stop at EOS.
+ NO_MIN_TOKENS_FAMILIES = ("higgs", "qwen3_omni", "qwen2_5_omni", "dia", "bark", "seamless", "vibevoice")
+ if not any(family in config.model_type for family in NO_MIN_TOKENS_FAMILIES):
+ gen_kwargs["min_new_tokens"] = args.max_new_tokens
+ if "csm" in config.model_type:
+ gen_kwargs["output_audio"] = True
+ # Sampling follows the checkpoint's generation_config (do_sample=True, temperature=0.9);
+ # the model card's greedy example is a latency benchmark, not the inference default.
+ if "seamless" in config.model_type:
+ # Output language; src_lang is a processor kwarg, set at tokenization below.
+ gen_kwargs["tgt_lang"] = _seamless_lang(args.language)
+ if "qwen3_omni" in config.model_type:
+ # The bare greedy kwargs above only reach the "thinker" (text) stage. The "talker"
+ # (audio) stage is deliberately left at its checkpoint sampling defaults: greedy talker
+ # decoding fails to emit EOS on some prompts. Don't add talker_do_sample=False.
+ gen_kwargs["speaker"] = args.qwen_omni_speaker
+ # The bare `max_new_tokens` never overrides the thinker's default; only the prefixed
+ # kwarg does. Audio length is bounded by the talker's own `talker_max_new_tokens`.
+ del gen_kwargs["max_new_tokens"]
+ gen_kwargs["thinker_max_new_tokens"] = args.max_new_tokens
+ if "qwen2_5_omni" in config.model_type:
+ # As with Qwen3-Omni, the talker keeps its sampling defaults; don't add talker_do_sample=False.
+ # Qwen2.5-Omni uses title-case speaker names and only supports Ethan/Chelsie (no Aiden).
+ speaker = args.qwen_omni_speaker.capitalize()
+ if speaker not in ["Ethan", "Chelsie"]:
+ print("Warning: Qwen2.5-Omni only supports Ethan/Chelsie; forcing speaker=Ethan.")
+ speaker = "Ethan"
+ gen_kwargs["speaker"] = speaker
+ del gen_kwargs["max_new_tokens"]
+ elif args.max_new_tokens:
+ raise ValueError("`max_new_tokens` should only be set for auto-regressive models.")
+
+ if args.torch_compile is not None:
+ if model.can_generate():
+ gen_kwargs["compile_config"] = CompileConfig(mode=args.torch_compile, fullgraph=args.compile_fullgraph)
+ model.generation_config.cache_implementation = "static"
+ else:
+ model = torch.compile(model, mode=args.torch_compile, fullgraph=args.compile_fullgraph)
+ if args.warmup_steps is None or args.warmup_steps < 1:
+ print("`--torch_compile` is enabled; forcing `--warmup_steps=10` to trigger compilation.")
+ args.warmup_steps = 10
+ return gen_kwargs, model
+
+
+def apply_tts_chat_template(processor, config, texts, prompt_texts=None, prompt_audio_paths=None):
+ """Apply the processor chat template (if any), returning either texts or pre-tokenized inputs.
+
+ When `prompt_texts`/`prompt_audio_paths` are provided (voice cloning), the dia, higgs and
+ vibevoice families condition generation on the reference prompt audio (dia/higgs additionally
+ take its transcript; vibevoice's template has no slot for one).
+ """
+ voice_clone = prompt_texts is not None and prompt_audio_paths is not None
+
+ if "dia" in config.model_type:
+ # Dia requires a speaker-turn tag prefix; it does not use a chat template.
+ if voice_clone:
+ # Prepend the prompt transcript to the target text; the prompt audio is passed as
+ # `audio=` to the processor by the caller and stripped from the output via
+ # `get_audio_prompt_len` at decode time.
+ return [f"[S1] {pt} [S1] {text}" for pt, text in zip(prompt_texts, texts)], None
+ return [f"[S1] {text}" for text in texts], None
+
+ if getattr(processor, "chat_template", None) is None:
+ return texts, None
+
+ if "csm" in config.model_type:
+ # CSM uses a speaker id as the "role" rather than user/assistant.
+ return [
+ processor.apply_chat_template(
+ [{"role": "0", "content": [{"type": "text", "text": text}]}],
+ tokenize=False,
+ add_generation_prompt=True,
+ return_dict=False,
+ )
+ for text in texts
+ ], None
+ if "higgs" in config.model_type:
+ if voice_clone:
+ # Zero-shot voice cloning: the prompt transcript + prompt audio are supplied as a
+ # user/assistant turn pair before the target user turn (Higgs Audio v2 convention).
+ conversations = [
+ [
+ {"role": "system", "content": [{"type": "text", "text": "Generate audio following instruction."}]},
+ {"role": "user", "content": [{"type": "text", "text": pt}]},
+ {"role": "assistant", "content": [{"type": "audio", "url": pa}]},
+ {"role": "user", "content": [{"type": "text", "text": text}]},
+ ]
+ for text, pt, pa in zip(texts, prompt_texts, prompt_audio_paths)
+ ]
+ else:
+ conversations = [
+ [
+ {"role": "system", "content": [{"type": "text", "text": "Generate audio following instruction."}]},
+ {"role": "user", "content": text},
+ ]
+ for text in texts
+ ]
+ inputs = processor.apply_chat_template(
+ conversations,
+ tokenize=True,
+ add_generation_prompt=True,
+ return_dict=True,
+ processor_kwargs={"return_tensors": "pt", "sampling_rate": 24000},
+ )
+ return texts, inputs
+ if "vibevoice" in config.model_type:
+ # The "role" is a speaker id (always "0" here). Cloning uses only the reference audio (no
+ # transcript slot), loaded and resampled by apply_chat_template.
+ conversations = [
+ [
+ {
+ "role": "0",
+ "content": [{"type": "text", "text": text}]
+ + ([{"type": "audio", "url": pa}] if voice_clone else []),
+ }
+ ]
+ for text, pa in zip(texts, prompt_audio_paths or [None] * len(texts))
+ ]
+ inputs = processor.apply_chat_template(
+ conversations,
+ tokenize=True,
+ add_generation_prompt=True,
+ return_dict=True,
+ # librosa is pinned because the "auto" audio backend picks torchcodec whenever it is
+ # importable, even without usable FFmpeg libs. The prompts are wavs written above.
+ processor_kwargs={"return_tensors": "pt", "padding": True, "load_audio_backend": "librosa"},
+ )
+ return texts, inputs
+ if "qwen3_omni" in config.model_type or "qwen2_5_omni" in config.model_type:
+ # Qwen Omni models (2.5 and 3) require this exact system prompt for audio output,
+ # and the user turn must explicitly ask to read the text aloud verbatim.
+ system_text = (
+ "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of "
+ "perceiving auditory and visual inputs, as well as generating text and speech."
+ )
+ inputs = processor.apply_chat_template(
+ [
+ [
+ {"role": "system", "content": [{"type": "text", "text": system_text}]},
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": (
+ "Please read the following text aloud exactly as written, with no "
+ f"additional commentary:\n\n{text}"
+ ),
+ }
+ ],
+ },
+ ]
+ for text in texts
+ ],
+ tokenize=True,
+ add_generation_prompt=True,
+ return_dict=True,
+ # `padding` is required for --batch_size > 1 (batched audio generation needs a real
+ # attention_mask; see transformers#47186).
+ processor_kwargs={"return_tensors": "pt", "padding": True},
+ )
+ return texts, inputs
+ return [
+ processor.apply_chat_template(
+ [{"role": "user", "content": text}],
+ tokenize=False,
+ add_generation_prompt=True,
+ return_dict=False,
+ )
+ for text in texts
+ ], None
+
+
+def main(args):
+ # Set seed due to randomness in some models (e.g. VibeVoice's acoustic tokenizer sampling)
+ set_seed(args.seed)
+ torch.backends.cudnn.deterministic = True
+
+ torch_dtype = getattr(torch, args.dtype)
+ config, model, processor, extras = load_tts_model(args, torch_dtype)
+
+ # Voice cloning is only wired up for the families in VOICE_CLONE_FAMILIES.
+ voice_clone = args.voice_clone
+ if voice_clone and not any(family in config.model_type for family in VOICE_CLONE_FAMILIES):
+ print(
+ f"Warning: --voice_clone is not supported for model_type '{config.model_type}'; "
+ "falling back to the model's default voice (--no-voice_clone)."
+ )
+ voice_clone = False
+ mode_suffix = "_voice_clone" if voice_clone else ""
+
+ is_speecht5 = "speecht5" in config.model_type
+ is_fastspeech2 = "fastspeech2" in config.model_type
+ is_vits = "vits" in config.model_type
+ is_seamless = "seamless" in config.model_type
+ is_vibevoice = "vibevoice" in config.model_type
+ # SpeechT5, FastSpeech2, and VITS use direct forward passes, not `generate`, so skip gen-kwargs.
+ gen_kwargs = {}
+ if not is_speecht5 and not is_fastspeech2 and not is_vits:
+ gen_kwargs, model = build_gen_kwargs(args, config, model)
+
+ sampling_rate = 16_000
+ if "qwen3_omni" in config.model_type or "qwen2_5_omni" in config.model_type:
+ # feature_extractor.sampling_rate is 16kHz (input audio), but talker output is fixed 24kHz.
+ sampling_rate = 24_000
+ elif "fastspeech2" in config.model_type:
+ # FastSpeech2ConformerWithHifiGan outputs at 22050 Hz.
+ sampling_rate = 22_050
+ elif "vits" in config.model_type:
+ # VITS/MMS sampling rate is stored in model config.
+ sampling_rate = getattr(config, "sampling_rate", 16_000)
+ elif "bark" in config.model_type:
+ # Bark outputs at 24kHz; its processor has no feature_extractor with a sampling_rate.
+ sampling_rate = 24_000
+ elif "seamless" in config.model_type:
+ # SeamlessM4Tv2 outputs at 16kHz.
+ sampling_rate = 16_000
+ elif getattr(processor, "feature_extractor", None) is not None and hasattr(
+ processor.feature_extractor, "sampling_rate"
+ ):
+ sampling_rate = processor.feature_extractor.sampling_rate
+
+ # Layout: results/<model_safe>/ MODEL_<safe>_DATASET_<dsid>.jsonl + <dsid>/output_<id>.wav
+ # Manifest paths are relative to model_dir so downstream stages resolve them wherever it is copied.
+ paths = output_paths(args, mode_suffix)
+ model_dir, dataset_dir_name, output_dir = paths.model_dir, paths.dataset_dir_name, paths.output_dir
+ # Reference prompt wavs are persisted here so the SIM stage (score_similarity.py) can read them.
+ prompt_dir = os.path.join(output_dir, "prompts")
+ if voice_clone:
+ os.makedirs(prompt_dir, exist_ok=True)
+
+ def generate_tts(batch):
+ """Synthesize speech for a minibatch of target texts; time the batch generation for RTFx."""
+ texts_to_generate = list(batch[args.text_column])
+ minibatch_size = len(texts_to_generate)
+
+ # Voice cloning: persist each reference prompt wav (once) and collect per-sample
+ # prompt transcripts, paths (higgs / vibevoice) and raw arrays (dia) aligned with the batch.
+ prompt_texts = prompt_audio_paths = prompt_arrays = None
+ if voice_clone:
+ prompt_texts = list(batch["prompt_text"])
+ prompt_audio_paths, prompt_arrays = [], []
+ for sample_id, prompt_audio in zip(batch["id"], batch["prompt_audio"]):
+ arr = np.asarray(prompt_audio["array"], dtype=np.float32)
+ sr = int(prompt_audio["sampling_rate"])
+ pp = os.path.join(prompt_dir, f"prompt_{sample_id}.wav")
+ if not os.path.exists(pp):
+ sf.write(pp, arr, sr)
+ prompt_audio_paths.append(os.path.abspath(pp))
+ if "dia" in config.model_type:
+ # Dia's processor expects the reference audio at 44100 Hz.
+ if sr != 44_100:
+ import librosa
+
+ arr = librosa.resample(arr, orig_sr=sr, target_sr=44_100)
+ prompt_arrays.append(arr)
+
+ # START TIMING (TTS batch generation)
+ torch.cuda.synchronize(device=args.device)
+ start_event = torch.cuda.Event(enable_timing=True)
+ end_event = torch.cuda.Event(enable_timing=True)
+ start_event.record()
+
+ if args.torch_compile is not None:
+ sdpa_backends = [SDPBackend.MATH]
+ else:
+ sdpa_backends = [SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION, SDPBackend.MATH]
+
+ if is_vits:
+ # VITS / MMS-TTS: process each sample individually to avoid padding-induced hum.
+ outputs = []
+ for text in texts_to_generate:
+ inp = processor([text], return_tensors="pt").to(args.device)
+ with torch.no_grad(), sdpa_kernel(sdpa_backends):
+ outputs.append(model(**inp).waveform[0])
+ elif is_fastspeech2:
+ # FastSpeech2: process each sample individually to avoid padding-induced hum.
+ outputs = []
+ for text in texts_to_generate:
+ inp = processor([text], return_tensors="pt").to(args.device)
+ with torch.no_grad(), sdpa_kernel(sdpa_backends):
+ outputs.append(model(inp["input_ids"], return_dict=True)["waveform"][0])
+ elif is_speecht5:
+ # SpeechT5: batched mel-spectrogram generation + HiFi-GAN vocoding in one call.
+ # A single speaker embedding is broadcast to the whole batch by generate_speech.
+ inputs = processor(text=texts_to_generate, padding=True, return_tensors="pt").to(args.device)
+ with sdpa_kernel(sdpa_backends):
+ waveforms, lengths = model.generate_speech(
+ inputs["input_ids"],
+ extras["speaker_embeddings"],
+ attention_mask=inputs["attention_mask"],
+ vocoder=extras["vocoder"],
+ return_output_lengths=True,
+ )
+ outputs = [waveforms[i, : lengths[i]] for i in range(len(lengths))]
+ else:
+ # 1. Pre-processing. Pad to full batch size under torch.compile to avoid recompilations.
+ padding_size = None
+ if minibatch_size != args.batch_size and args.torch_compile is not None:
+ padding_size = args.batch_size - minibatch_size
+ texts_to_generate.extend([texts_to_generate[-1]] * padding_size)
+
+ texts_to_generate, inputs = apply_tts_chat_template(
+ processor, config, texts_to_generate, prompt_texts, prompt_audio_paths
+ )
+ if inputs is None: # not pre-tokenized by the chat template (higgs / vibevoice / Qwen-Omni are)
+ # BarkProcessor passes padding internally; passing it explicitly causes a conflict.
+ # SeamlessM4T requires src_lang to tokenize text input.
+ proc_kwargs = {}
+ if "bark" not in config.model_type:
+ proc_kwargs["padding"] = True
+ if is_seamless:
+ proc_kwargs["src_lang"] = _seamless_lang(args.language)
+ if voice_clone and "dia" in config.model_type:
+ # Dia conditions on the reference audio via the `audio=` arg; the prompt tokens
+ # are stripped from the output by `get_audio_prompt_len` at decode time.
+ proc_kwargs["audio"] = prompt_arrays
+ inputs = processor(text=texts_to_generate, **proc_kwargs, return_tensors="pt")
+ if is_vibevoice:
+ # The reference waveform (`input_values`) comes out of the feature extractor in
+ # float32 while the acoustic tokenizer runs in the model's dtype, so the cast is
+ # part of the move here (what the model card does with `.to(device, model.dtype)`).
+ # BatchFeature.to() only casts floating-point tensors, so input_ids stay integral.
+ inputs = inputs.to(args.device, model.dtype)
+ else:
+ inputs = inputs.to(args.device)
+
+ # 2. Model inference
+ with sdpa_kernel(sdpa_backends):
+ if "qwen3_omni" in config.model_type or "qwen2_5_omni" in config.model_type:
+ # generate() returns (text_ids, audio) — we only need the audio.
+ _, pred_waveform = model.generate(**inputs, **gen_kwargs)
+ else:
+ pred_waveform = model.generate(**inputs, **gen_kwargs)
+
+ # 3. Post-processing
+ seamless_lengths = None
+ if is_seamless:
+ # generate() returns (waveform, waveform_lengths); split before the padding trim.
+ # `.reshape(-1)` handles batch size 1, where lengths is 0-dim.
+ pred_waveform, seamless_lengths = pred_waveform[0], pred_waveform[1].reshape(-1)
+
+ if padding_size is not None:
+ # Batched Qwen-Omni returns a list of per-sample waveforms, which slices like a
+ # sequence; every other backend returns a tensor, which needs the ellipsis.
+ pred_waveform = (
+ pred_waveform[:-padding_size]
+ if isinstance(pred_waveform, (list, tuple))
+ else pred_waveform[:-padding_size, ...]
+ )
+ if seamless_lengths is not None:
+ seamless_lengths = seamless_lengths[:-padding_size]
+
+ if config.model_type == "dia":
+ prompt_len = processor.get_audio_prompt_len(inputs["decoder_attention_mask"])
+ outputs = processor.batch_decode(pred_waveform, audio_prompt_len=prompt_len)
+ elif "higgs" in config.model_type:
+ outputs = processor.batch_decode(pred_waveform)
+ elif "qwen3_omni" in config.model_type or "qwen2_5_omni" in config.model_type:
+ # A batch yields a list of already-trimmed waveforms; a single sample a `(1, 1, N)`
+ # tensor. Normalize both to a list of 1-D tensors.
+ waveforms = pred_waveform if isinstance(pred_waveform, (list, tuple)) else [pred_waveform]
+ outputs = [w.reshape(-1) for w in waveforms]
+ elif is_vibevoice:
+ # One already-trimmed (1, num_samples) tensor per row; flatten so len() counts samples.
+ # None means no audio was generated: keep the row as short silence (scores 100% WER).
+ outputs = []
+ for sample_id, waveform in zip(batch["id"], pred_waveform):
+ if waveform is None:
+ print(f"Warning: VibeVoice generated no audio for sample {sample_id}.")
+ waveform = torch.zeros(sampling_rate // 10)
+ outputs.append(waveform.reshape(-1))
+ elif is_seamless:
+ # Rows are padded to the longest; pad units vocode to an audible buzz that would
+ # also inflate `audio_length_s`/RTFx, so cut each row to its reported length.
+ outputs = [
+ pred_waveform[i, : min(int(seamless_lengths[i]), pred_waveform.shape[-1])]
+ for i in range(minibatch_size)
+ ]
+ else:
+ outputs = pred_waveform
+
+ # END TIMING
+ end_event.record()
+ torch.cuda.synchronize(device=args.device)
+ runtime = start_event.elapsed_time(end_event) / 1000.0
+ # per-sample generation time (RTFx is aggregated over the whole set at the end)
+ batch["generation_time_s"] = minibatch_size * [runtime / minibatch_size]
+
+ gen_paths, audio_length_s = [], []
+ for audio, sample_id in zip(outputs, batch["id"]):
+ # 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)
+ if is_vibevoice or not hasattr(processor, "save_audio"):
+ # Processors without save_audio, plus VibeVoice (different save_audio signature).
+ sf.write(path, audio.reshape(-1).detach().to(torch.float32).cpu().numpy(), sampling_rate)
+ else:
+ processor.save_audio(audio, saving_path=path)
+ gen_paths.append(rel_path)
+ audio_length_s.append(len(audio) / sampling_rate)
+
+ batch["gen_audio_filepath"] = gen_paths
+ batch["audio_length_s"] = audio_length_s
+ batch["references"] = list(batch[args.text_column]) # raw; normalized at scoring time
+ if voice_clone:
+ # Store the path relative to model_dir (the manifest's dir); the full paths handed to the
+ # model as reference audio are the absolute `prompt_audio_paths` written above.
+ batch["prompt_audio_filepath"] = [
+ os.path.join(dataset_dir_name, "prompts", f"prompt_{sid}.wav") for sid in batch["id"]
+ ]
+ return batch
+
+ dataset = load_tts_dataset(args, extra_columns=("prompt_text", "prompt_audio") if voice_clone else ())
+
+ probe_out_dir = model_dir # real results dir, captured before the probe rebinds model_dir
+ # ── TTFA probe: latency only, writing nothing but a JSON sidecar ─────────
+ # TTFA is per-request, so the probe drives generate_tts() with one-row batches and returns
+ # before the main loop. `model_dir`/`dataset_dir_name` are rebound to a temp dir (generate_tts
+ # closes over them late-bound) so nothing lands in the results tree. No streaming API, so
+ # `first` is None (whole-utterance fallback). 0 = off; N > 0 = N evenly spaced; N < 0 = whole split.
+ if args.ttfa_probe != 0:
+ # Imported lazily: ttfa_probe is only injected by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+ import tempfile
+
+ model_dir = tempfile.mkdtemp(prefix="ttfa_out_")
+ dataset_dir_name = "ttfa"
+ output_dir = os.path.join(model_dir, dataset_dir_name)
+ os.makedirs(os.path.join(output_dir, "prompts"), exist_ok=True)
+
+ def _gen(job):
+ result = generate_tts(job)
+ duration = result["audio_length_s"][0]
+ return float(duration), None, None
+
+ columns = dataset.column_names
+ jobs = [{c: [dataset[i][c]] for c in columns}
+ for i in sample_indices(args.ttfa_probe, len(dataset))]
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=probe_out_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ extra={"device": args.device, "note": "driven at batch size 1"},
+ )
+ return
+
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ # Only batches with a sample missing from the manifest are (re)generated.
+ starts = pending_batches(dataset, args.batch_size, done_entries, dataset_dir_name)
+ warm_up(generate_tts, dataset, starts, args.batch_size, args.warmup_steps)
+
+ # ── Main loop: TTS → write JSONL, one batch at a time ───────────────────
+ for batch_start in tqdm(starts, desc="Generating"):
+ batch = generate_tts(dataset[batch_start : batch_start + args.batch_size])
+ for i, (afp, alen, gtime, ref) in enumerate(zip(
+ batch["gen_audio_filepath"], batch["audio_length_s"], batch["generation_time_s"], batch["references"],
+ )):
+ write_entry(manifest_file, manifest_entry(
+ afp, alen, gtime, ref,
+ prompt_audio_filepath=batch["prompt_audio_filepath"][i] if voice_clone else None,
+ ))
+ manifest_file.flush()
+
+ manifest_file.close()
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(voice_clone)
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument("--model_id", type=str, required=True, help="TTS model id, loadable with 🤗 Transformers.")
+ add_common_args(parser, batch_size=32, voice_clone=False)
+ parser.add_argument(
+ "--language",
+ type=str,
+ default="en",
+ help="Language of the text being synthesized, as an ISO 639-1 code ('en', 'zh', 'ru'). "
+ "Used by SeamlessM4T (mapped via SEAMLESS_LANGUAGE_CODES).",
+ )
+ parser.add_argument("--max_new_tokens", type=int, default=8192, help="Max tokens for TTS generation.")
+ parser.add_argument("--torch_compile", type=str, default=None, help="torch.compile mode, e.g. 'max-autotune'.")
+ parser.add_argument("--compile_fullgraph", action="store_true", help="Full-graph compilation.")
+ parser.add_argument("--dtype", type=str, default="bfloat16", help="Model dtype, e.g. 'bfloat16'.")
+ parser.add_argument("--attn_implementation", type=str, default="sdpa", help="Attention impl ('sdpa'/'eager'/...).")
+ parser.add_argument("--revision", type=str, default=None, help="TTS model revision.")
+
+ # ── SpeechT5-specific (ignored for other models) ─────────────────────
+ parser.add_argument(
+ "--speecht5_vocoder", type=str, default="microsoft/speecht5_hifigan", help="HiFi-GAN vocoder for SpeechT5."
+ )
+ parser.add_argument(
+ "--speecht5_speaker_embeddings",
+ type=str,
+ default="https://huggingface.co/datasets/Matthijs/cmu-arctic-xvectors/resolve/refs%2Fconvert%2Fparquet/default/validation/0000.parquet",
+ help="Parquet of x-vector speaker embeddings for SpeechT5.",
+ )
+ parser.add_argument(
+ "--speecht5_speaker_index", type=int, default=7306, help="Row index of the speaker x-vector to use."
+ )
+
+ # ── Qwen3-Omni-specific (ignored for other models) ────────────────────
+ parser.add_argument(
+ "--qwen_omni_speaker",
+ type=str,
+ default="aiden",
+ choices=["ethan", "chelsie", "aiden"],
+ help="Talker voice for Qwen3-Omni's audio output. Aiden not available for Qwen2.5-Omni (only Ethan/Chelsie).",
+ )
+
+ args = parser.parse_args()
+
+ print("*" * 100)
+ print(f"Evaluating TTS model {args.model_id} on {args.dataset_path} / {args.dataset} / {args.split}")
+ print("*" * 100)
+
+ main(args)
diff --git a/transformers/score_similarity.py b/transformers/score_similarity.py
new file mode 100644
index 0000000..d767625
--- /dev/null
+++ b/transformers/score_similarity.py
@@ -0,0 +1,660 @@
+"""
+Speaker similarity (SIM) for the Open TTS Leaderboard (stage 3, voice cloning only).
+
+Embeds each generated wav and its reference prompt (`prompt_audio_filepath`) with a
+speaker-verification model and writes their cosine similarity into the manifest's `sim` field.
+`normalizer.eval_utils.score_results` then reports the mean SIM alongside WER + RTFx.
+
+Backends (`--sim_backend`); the two scales are NOT comparable:
+
+ `wavlm_seed_tts` (default)
+ seed-tts-eval's SIM model (WavLM-Large + ECAPA-TDNN, UniSpeech `wavlm_large_finetune.pth`),
+ comparable with published Seed-TTS / F5-TTS / CosyVoice SIM. Runs one clip at a time, like
+ upstream. Pure transformers + torch: the backbone is an HF `WavLMModel` with the checkpoint's
+ weights remapped onto it (no s3prl / torch.hub).
+
+ `xvector`
+ HF `WavLMForXVector` (microsoft/wavlm-base-plus-sv). Cheap, but compressed: different speakers
+ already score ~0.80, so it is too narrow to rank strong cloning models. Writes `sim` in place.
+
+Resumable: a row is re-scored unless it already has a numeric `sim` from the requested backend
+(recorded as `sim_model`). `--overwrite` forces every row. Progress is saved every `--save_every` rows.
+"""
+
+import argparse
+import json
+import os
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from transformers.audio_utils import load_audio
+
+from transformers import AutoFeatureExtractor, WavLMConfig, WavLMForXVector, WavLMModel
+
+DEFAULT_XVECTOR_MODEL_ID = "microsoft/wavlm-base-plus-sv"
+
+# SIM checkpoint from microsoft/UniSpeech (downstreams/speaker_verification, "WavLM large / Fix
+# pre-train: No"; https://drive.google.com/file/d/1-aE1NfzpRCLxA4GUxX9ITI3F9LlbtEGP/view), mirrored
+# on the Hub by scripts/upload_sim_checkpoint.py (which parses these three constants) and pinned by the
+# digest of the official file.
+WAVLM_SEED_TTS_REPO_ID = "bezzam/wavlm_large_finetune_seed_tts_eval"
+WAVLM_SEED_TTS_FILENAME = "wavlm_large_finetune.pth"
+WAVLM_SEED_TTS_SHA256 = "51f07e3b94d9e0262a6a675ef5a087be3dd09e8c62e9d886827f44f82fe7f94b"
+# Config only (config.json, ~2 KB) — the weights all come from the checkpoint above.
+WAVLM_BACKBONE_CONFIG_ID = "microsoft/wavlm-large"
+
+# Assumed `sim_model` for rows that have a `sim` but no `sim_model` field.
+LEGACY_SIM_MODEL = DEFAULT_XVECTOR_MODEL_ID
+# The xvector backend writes `sim` into the manifest in place; any other backend writes a separate
+# `<manifest>_<backend>.jsonl` so both scales coexist. Keep the suffix in sync with
+# `normalizer.eval_utils.score_results`.
+LEGACY_SIM_BACKEND = "xvector"
+
+
+def sim_manifest_path(manifest_path, sim_backend):
+ """Where `sim_backend`'s scores belong: the manifest itself for the legacy backend, else a fork."""
+ if sim_backend == LEGACY_SIM_BACKEND:
+ return manifest_path
+ stem, ext = os.path.splitext(manifest_path)
+ return f"{stem}_{sim_backend}{ext}"
+
+
+def _min_samples_for_embedding(wavlm, min_frames=2):
+ """Shortest waveform (in samples) whose WavLM conv frontend emits at least `min_frames` frames.
+
+ Below this, both heads crash (time-axis InstanceNorm / TDNN need >1 frame). For WavLM-Large this
+ is 720 samples (45 ms at 16 kHz). It is the hard floor, not a quality threshold.
+ """
+ length_of = wavlm._get_feat_extract_output_lengths
+ lo, hi = 1, 16_000
+ while int(length_of(hi)) < min_frames:
+ hi *= 2
+ while lo < hi: # binary search for the smallest length reaching min_frames
+ mid = (lo + hi) // 2
+ if int(length_of(mid)) >= min_frames:
+ hi = mid
+ else:
+ lo = mid + 1
+ return lo
+
+
+# ══════════════════════════════════════════════════════════════════════════════════════════════
+# Backend 1 — HF WavLMForXVector
+# ══════════════════════════════════════════════════════════════════════════════════════════════
+class XVectorEmbedder:
+ """WavLM + TDNN x-vector head via `WavLMForXVector`. Batches freely (padding is masked)."""
+
+ max_batch_size = None # no constraint
+
+ def __init__(self, model_id, device, dtype):
+ self.name = model_id
+ self.feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)
+ self.model = WavLMForXVector.from_pretrained(model_id, dtype=dtype).to(device).eval()
+ self.sampling_rate = self.feature_extractor.sampling_rate # 16_000
+ self.device = device
+ self.min_samples = _min_samples_for_embedding(self.model.wavlm)
+
+ def __call__(self, speech):
+ inputs = self.feature_extractor(
+ speech, sampling_rate=self.sampling_rate, return_tensors="pt", padding=True
+ ).to(self.device)
+ inputs = inputs.to(self.model.dtype)
+ with torch.no_grad():
+ embeddings = self.model(**inputs).embeddings
+ return F.normalize(embeddings, dim=-1).float().cpu()
+
+
+# ══════════════════════════════════════════════════════════════════════════════════════════════
+# Backend 2 — WavLM-Large + ECAPA-TDNN (seed-tts-eval canonical)
+#
+# ECAPA-TDNN head transcribed from UniSpeech (MIT):
+# https://github.com/microsoft/UniSpeech/blob/main/downstreams/speaker_verification/models/
+# Module/parameter names match upstream so the checkpoint loads with `strict=True`. The 25 hidden
+# states come from an HF `WavLMModel` (same tensors/order as upstream's s3prl front end).
+# ══════════════════════════════════════════════════════════════════════════════════════════════
+class Res2Conv1dReluBn(nn.Module):
+ """in_channels == out_channels == channels."""
+
+ def __init__(self, channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=True, scale=4):
+ super().__init__()
+ assert channels % scale == 0, f"{channels} % {scale} != 0"
+ self.scale = scale
+ self.width = channels // scale
+ self.nums = scale if scale == 1 else scale - 1
+
+ self.convs = nn.ModuleList(
+ nn.Conv1d(self.width, self.width, kernel_size, stride, padding, dilation, bias=bias)
+ for _ in range(self.nums)
+ )
+ self.bns = nn.ModuleList(nn.BatchNorm1d(self.width) for _ in range(self.nums))
+
+ def forward(self, x):
+ out = []
+ spx = torch.split(x, self.width, 1)
+ for i in range(self.nums):
+ sp = spx[i] if i == 0 else sp + spx[i]
+ # Order: conv -> relu -> bn
+ sp = self.convs[i](sp)
+ sp = self.bns[i](F.relu(sp))
+ out.append(sp)
+ if self.scale != 1:
+ out.append(spx[self.nums])
+ return torch.cat(out, dim=1)
+
+
+class Conv1dReluBn(nn.Module):
+ def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=True):
+ super().__init__()
+ self.conv = nn.Conv1d(in_channels, out_channels, kernel_size, stride, padding, dilation, bias=bias)
+ self.bn = nn.BatchNorm1d(out_channels)
+
+ def forward(self, x):
+ return self.bn(F.relu(self.conv(x)))
+
+
+class SE_Connect(nn.Module):
+ """The SE connection of the 1D case."""
+
+ def __init__(self, channels, se_bottleneck_dim=128):
+ super().__init__()
+ self.linear1 = nn.Linear(channels, se_bottleneck_dim)
+ self.linear2 = nn.Linear(se_bottleneck_dim, channels)
+
+ def forward(self, x):
+ out = x.mean(dim=2)
+ out = F.relu(self.linear1(out))
+ out = torch.sigmoid(self.linear2(out))
+ return x * out.unsqueeze(2)
+
+
+class SE_Res2Block(nn.Module):
+ """SE-Res2Block of the ECAPA-TDNN architecture."""
+
+ def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation, scale, se_bottleneck_dim):
+ super().__init__()
+ self.Conv1dReluBn1 = Conv1dReluBn(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
+ self.Res2Conv1dReluBn = Res2Conv1dReluBn(out_channels, kernel_size, stride, padding, dilation, scale=scale)
+ self.Conv1dReluBn2 = Conv1dReluBn(out_channels, out_channels, kernel_size=1, stride=1, padding=0)
+ self.SE_Connect = SE_Connect(out_channels, se_bottleneck_dim)
+
+ self.shortcut = None
+ if in_channels != out_channels:
+ self.shortcut = nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=1)
+
+ def forward(self, x):
+ residual = x
+ if self.shortcut:
+ residual = self.shortcut(x)
+
+ x = self.Conv1dReluBn1(x)
+ x = self.Res2Conv1dReluBn(x)
+ x = self.Conv1dReluBn2(x)
+ x = self.SE_Connect(x)
+
+ return x + residual
+
+
+class AttentiveStatsPool(nn.Module):
+ """Attentive weighted mean and standard deviation pooling."""
+
+ def __init__(self, in_dim, attention_channels=128, global_context_att=False):
+ super().__init__()
+ self.global_context_att = global_context_att
+
+ # Conv1d with stride == 1 rather than Linear, so inputs need no transpose.
+ in_channels = in_dim * 3 if global_context_att else in_dim
+ self.linear1 = nn.Conv1d(in_channels, attention_channels, kernel_size=1) # W and b in the paper
+ self.linear2 = nn.Conv1d(attention_channels, in_dim, kernel_size=1) # V and k in the paper
+
+ def forward(self, x):
+ if self.global_context_att:
+ context_mean = torch.mean(x, dim=-1, keepdim=True).expand_as(x)
+ context_std = torch.sqrt(torch.var(x, dim=-1, keepdim=True) + 1e-10).expand_as(x)
+ x_in = torch.cat((x, context_mean, context_std), dim=1)
+ else:
+ x_in = x
+
+ # DON'T use ReLU here — upstream found it hard to converge.
+ alpha = torch.tanh(self.linear1(x_in))
+ alpha = torch.softmax(self.linear2(alpha), dim=2)
+ mean = torch.sum(alpha * x, dim=2)
+ residuals = torch.sum(alpha * (x**2), dim=2) - mean**2
+ std = torch.sqrt(residuals.clamp(min=1e-9))
+ return torch.cat([mean, std], dim=1)
+
+
+class WavLMEcapaTdnn(nn.Module):
+ """ECAPA-TDNN over a softmax-weighted sum of WavLM-Large's 25 hidden states.
+
+ Equivalent to upstream's `ECAPA_TDNN_SMALL(feat_dim=1024, feat_type='wavlm_large')`, with the
+ s3prl front end replaced by `wavlm` (an HF `WavLMModel`). Head parameter names match the
+ checkpoint; the backbone lives under `wavlm.*` and is loaded separately.
+ """
+
+ def __init__(self, wavlm, feat_dim=1024, channels=512, emb_dim=256):
+ super().__init__()
+ self.wavlm = wavlm
+ self.feat_num = 1 + wavlm.config.num_hidden_layers # 25 for WavLM-Large
+ self.feature_weight = nn.Parameter(torch.zeros(self.feat_num))
+
+ self.instance_norm = nn.InstanceNorm1d(feat_dim)
+ self.channels = [channels] * 4 + [1536]
+
+ self.layer1 = Conv1dReluBn(feat_dim, self.channels[0], kernel_size=5, padding=2)
+ self.layer2 = SE_Res2Block(self.channels[0], self.channels[1], kernel_size=3, stride=1, padding=2, dilation=2, scale=8, se_bottleneck_dim=128)
+ self.layer3 = SE_Res2Block(self.channels[1], self.channels[2], kernel_size=3, stride=1, padding=3, dilation=3, scale=8, se_bottleneck_dim=128)
+ self.layer4 = SE_Res2Block(self.channels[2], self.channels[3], kernel_size=3, stride=1, padding=4, dilation=4, scale=8, se_bottleneck_dim=128)
+
+ self.conv = nn.Conv1d(channels * 3, self.channels[-1], kernel_size=1)
+ self.pooling = AttentiveStatsPool(self.channels[-1], attention_channels=128, global_context_att=False)
+ self.bn = nn.BatchNorm1d(self.channels[-1] * 2)
+ self.linear = nn.Linear(self.channels[-1] * 2, emb_dim)
+
+ def get_feat(self, wav):
+ with torch.no_grad():
+ hidden_states = self.wavlm(wav, output_hidden_states=True).hidden_states
+ x = torch.stack(hidden_states, dim=0) # (25, B, T, C)
+ norm_weights = F.softmax(self.feature_weight, dim=-1).view(-1, 1, 1, 1)
+ x = (norm_weights * x).sum(dim=0) # (B, T, C)
+ x = torch.transpose(x, 1, 2) + 1e-6 # (B, C, T)
+ return self.instance_norm(x)
+
+ def forward(self, wav):
+ x = self.get_feat(wav)
+
+ out1 = self.layer1(x)
+ out2 = self.layer2(out1)
+ out3 = self.layer3(out2)
+ out4 = self.layer4(out3)
+
+ out = torch.cat([out2, out3, out4], dim=1)
+ out = F.relu(self.conv(out))
+ out = self.bn(self.pooling(out))
+ return self.linear(out)
+
+
+def _convert_wavlm_backbone_state_dict(orig, target_keys):
+ """Remap original-WavLM (`feature_extract.model.*`) parameter names onto HF `WavLMModel` ones.
+
+ Same correspondence as transformers' `convert_wavlm_original_pytorch_checkpoint_to_pytorch.py`,
+ spelled out explicitly so an unknown name fails loudly. `target_keys` (the destination key set)
+ picks the weight-norm spelling and is used to assert exact coverage.
+ """
+ prefix = "feature_extract.model."
+ # torch >= 2.1 `nn.utils.parametrizations.weight_norm` stores weight_g/weight_v as
+ # `parametrizations.weight.original0/1`; older `nn.utils.weight_norm` uses `weight_g`/`weight_v`.
+ parametrized = "encoder.pos_conv_embed.conv.parametrizations.weight.original0" in target_keys
+ pos_conv_g = "parametrizations.weight.original0" if parametrized else "weight_g"
+ pos_conv_v = "parametrizations.weight.original1" if parametrized else "weight_v"
+
+ def convert(key):
+ # Feature encoder: Sequential(conv, dropout, Sequential(transpose, layer_norm, transpose), gelu)
+ if key.startswith("feature_extractor.conv_layers."):
+ rest = key[len("feature_extractor.conv_layers.") :]
+ layer_id, sub = rest.split(".", 1)
+ if sub == "0.weight":
+ return f"feature_extractor.conv_layers.{layer_id}.conv.weight"
+ if sub.startswith("2.1."):
+ return f"feature_extractor.conv_layers.{layer_id}.layer_norm.{sub[len('2.1.'):]}"
+ return None
+ if key.startswith("layer_norm."):
+ return f"feature_projection.layer_norm.{key[len('layer_norm.'):]}"
+ if key.startswith("post_extract_proj."):
+ return f"feature_projection.projection.{key[len('post_extract_proj.'):]}"
+ if key == "mask_emb":
+ return "masked_spec_embed"
+ if key.startswith("encoder.pos_conv.0."):
+ suffix = key[len("encoder.pos_conv.0.") :]
+ mapped = {"bias": "bias", "weight_g": pos_conv_g, "weight_v": pos_conv_v}.get(suffix)
+ return f"encoder.pos_conv_embed.conv.{mapped}" if mapped else None
+ if key.startswith("encoder.layer_norm."):
+ return key
+ if key.startswith("encoder.layers."):
+ rest = key[len("encoder.layers.") :]
+ layer_id, sub = rest.split(".", 1)
+ out = f"encoder.layers.{layer_id}."
+ for src, dst in (
+ ("self_attn.q_proj.", "attention.q_proj."),
+ ("self_attn.k_proj.", "attention.k_proj."),
+ ("self_attn.v_proj.", "attention.v_proj."),
+ ("self_attn.out_proj.", "attention.out_proj."),
+ ("self_attn.grep_linear.", "attention.gru_rel_pos_linear."),
+ ("self_attn.relative_attention_bias.", "attention.rel_attn_embed."),
+ ("self_attn_layer_norm.", "layer_norm."),
+ ("final_layer_norm.", "final_layer_norm."),
+ ("fc1.", "feed_forward.intermediate_dense."),
+ ("fc2.", "feed_forward.output_dense."),
+ ):
+ if sub.startswith(src):
+ return out + dst + sub[len(src) :]
+ if sub == "self_attn.grep_a":
+ return out + "attention.gru_rel_pos_const"
+ return None
+ return None
+
+ converted, unmapped = {}, []
+ for key, value in orig.items():
+ if not key.startswith(prefix):
+ continue
+ mapped = convert(key[len(prefix) :])
+ if mapped is None:
+ unmapped.append(key)
+ else:
+ converted[mapped] = value
+
+ if unmapped:
+ raise RuntimeError(f"Unmapped WavLM backbone keys in checkpoint: {sorted(unmapped)[:10]}")
+ missing = sorted(target_keys - converted.keys())
+ unexpected = sorted(converted.keys() - target_keys)
+ if missing or unexpected:
+ raise RuntimeError(
+ f"WavLM backbone key mismatch after conversion — missing {len(missing)}: {missing[:10]}; "
+ f"unexpected {len(unexpected)}: {unexpected[:10]}"
+ )
+ return converted
+
+
+def _resolve_wavlm_seed_tts_checkpoint(path, repo_id, filename, expected_sha256):
+ """Return a local path to `wavlm_large_finetune.pth`, downloading + digest-checking if needed."""
+ if path:
+ return path
+
+ from huggingface_hub import hf_hub_download
+
+ resolved = hf_hub_download(repo_id=repo_id, filename=filename)
+ if expected_sha256:
+ import hashlib
+
+ digest = hashlib.sha256()
+ with open(resolved, "rb") as f:
+ for chunk in iter(lambda: f.read(1 << 22), b""):
+ digest.update(chunk)
+ actual = digest.hexdigest()
+ if actual != expected_sha256:
+ raise RuntimeError(
+ f"Checksum mismatch for {repo_id}/{filename}: expected {expected_sha256}, got {actual}. "
+ "The mirror may have been re-uploaded; verify it before trusting any SIM numbers."
+ )
+ return resolved
+
+
+class WavLMSeedTtsEmbedder:
+ """seed-tts-eval's SIM model: WavLM-Large + ECAPA-TDNN, one clip per forward pass.
+
+ No batching: instance norm and attentive pooling take time-axis statistics, so padding would
+ shift the embeddings of shorter clips. Upstream also embeds one clip at a time.
+ """
+
+ max_batch_size = 1
+ sampling_rate = 16_000
+
+ def __init__(self, checkpoint_path, config_id, device, dtype):
+ self.name = f"wavlm_large_finetune+ecapa_tdnn ({os.path.basename(checkpoint_path)})"
+ self.device = device
+
+ config = WavLMConfig.from_pretrained(config_id)
+ config.apply_spec_augment = False
+ config.layerdrop = 0.0 # eval() already disables it; make it explicit
+ backbone = WavLMModel(config)
+
+ state_dict = torch.load(checkpoint_path, map_location="cpu", weights_only=True)["model"]
+ backbone.load_state_dict(
+ _convert_wavlm_backbone_state_dict(state_dict, set(backbone.state_dict())), strict=True
+ )
+
+ self.model = WavLMEcapaTdnn(backbone, feat_dim=config.hidden_size)
+ # `loss_calculator.*` is the training-time AM-softmax speaker classifier; inference only
+ # needs the 256-d embedding the head produces, so it has no counterpart here.
+ head = {
+ k: v
+ for k, v in state_dict.items()
+ if not k.startswith("feature_extract.") and not k.startswith("loss_calculator.")
+ }
+ missing, unexpected = self.model.load_state_dict(head, strict=False)
+ # The backbone (`wavlm.*`) is already loaded, so it is the only expected "missing" group.
+ stray = [k for k in missing if not k.startswith("wavlm.")]
+ if stray or unexpected:
+ raise RuntimeError(f"ECAPA head key mismatch — missing {stray[:10]}; unexpected {list(unexpected)[:10]}")
+
+ self.model.to(device=device, dtype=dtype).eval()
+ self.min_samples = _min_samples_for_embedding(backbone)
+
+ def __call__(self, speech):
+ assert len(speech) == 1, "WavLMSeedTtsEmbedder embeds one clip at a time"
+ wav = torch.from_numpy(speech[0]).float().unsqueeze(0)
+ # WavLM-Large was pre-trained on layer-normalized waveforms (`WavLMConfig.normalize` is
+ # True for the large model), which is what s3prl applies before the forward pass.
+ wav = F.layer_norm(wav, wav.shape)
+ wav = wav.to(device=self.device, dtype=self.model.linear.weight.dtype)
+ with torch.no_grad():
+ embeddings = self.model(wav)
+ return F.normalize(embeddings, dim=-1).float().cpu()
+
+
+def build_embedder(args, torch_dtype):
+ if args.sim_backend == "xvector":
+ return XVectorEmbedder(args.sim_model_id or DEFAULT_XVECTOR_MODEL_ID, args.device, torch_dtype)
+ checkpoint_path = _resolve_wavlm_seed_tts_checkpoint(
+ args.sim_ckpt, args.sim_ckpt_repo, args.sim_ckpt_file, args.sim_ckpt_sha256
+ )
+ return WavLMSeedTtsEmbedder(checkpoint_path, args.wavlm_config_id, args.device, torch_dtype)
+
+
+def main(args):
+ torch_dtype = getattr(torch, args.dtype)
+
+ # ── Read manifest ────────────────────────────────────────────────────────
+ with open(args.manifest_path, encoding="utf-8") as f:
+ entries = [json.loads(line) for line in f if line.strip()]
+ if not entries:
+ raise ValueError(f"No entries found in manifest {args.manifest_path}")
+ print(f"Scoring speaker similarity for {len(entries)} samples from {args.manifest_path}")
+
+ out_path = args.output_manifest_path or sim_manifest_path(args.manifest_path, args.sim_backend)
+ if out_path != args.manifest_path:
+ print(f"Writing scores to {out_path} (the source manifest is left untouched)")
+ # Rebuild the fork from the source manifest every run, carrying over only previous sims, so
+ # upstream fields (`pred_text`, `duration`, ...) stay in sync with re-run earlier stages.
+ if os.path.exists(out_path):
+ with open(out_path, encoding="utf-8") as f:
+ prior = {}
+ for line in f:
+ if not line.strip():
+ continue
+ e = json.loads(line)
+ if e.get("audio_filepath") is not None:
+ prior[e["audio_filepath"]] = (e.get("sim"), e.get("sim_model"))
+ carried = 0
+ for e in entries:
+ hit = prior.get(e.get("audio_filepath"))
+ if hit and isinstance(hit[0], (int, float)):
+ e["sim"], e["sim_model"] = hit
+ carried += 1
+ print(f" carried over {carried} existing score(s) from the previous run")
+
+ # Wav paths are relative to the manifest's directory (the fork lives there too); absolute or
+ # unresolvable paths are used as-is. Mirrors transcribe.py.
+ manifest_dir = os.path.dirname(os.path.abspath(args.manifest_path))
+
+ def _resolve(p):
+ if not p or os.path.isabs(p):
+ return p
+ cand = os.path.join(manifest_dir, p)
+ return cand if os.path.exists(cand) else p
+
+ # ── Speaker-verification model ─────────────────────────────────────────────
+ embedder = build_embedder(args, torch_dtype)
+ print(f"SIM backend: {args.sim_backend} — {embedder.name}")
+ batch_size = args.batch_size
+ if embedder.max_batch_size and batch_size > embedder.max_batch_size:
+ print(
+ f" note: the {args.sim_backend} backend is length-sensitive, so batch_size is pinned to "
+ f"{embedder.max_batch_size} (requested {batch_size}) to match the reference implementation."
+ )
+ batch_size = embedder.max_batch_size
+
+ sim_sr = embedder.sampling_rate
+ max_samples = int(args.max_audio_seconds * sim_sr) if args.max_audio_seconds > 0 else None
+
+ def load_clip(path):
+ """Read one clip at the embedder's sample rate, capped to --max_audio_seconds."""
+ speech = load_audio(path, sampling_rate=sim_sr)
+ if max_samples is not None:
+ # Cap length: very long (runaway) clips OOM WavLM; a few seconds suffice for SIM.
+ speech = speech[:max_samples]
+ return speech
+
+ def rewrite_manifest():
+ with open(out_path, "w", encoding="utf-8") as f:
+ for e in entries:
+ f.write(json.dumps(e, ensure_ascii=False) + "\n")
+
+ # Only score rows that have a reference and (unless --overwrite) no usable sim yet. A sim from a
+ # different backend is not usable: the two scales are incompatible, so it must be recomputed.
+ def needs_scoring(e):
+ if not e.get("prompt_audio_filepath"):
+ return False
+ if args.overwrite or not isinstance(e.get("sim"), (int, float)):
+ return True
+ return e.get("sim_model", LEGACY_SIM_MODEL) != embedder.name
+
+ todo = [i for i, e in enumerate(entries) if needs_scoring(e)]
+ # Batch clips of similar length together so padding=True wastes less memory/compute
+ # (otherwise one long clip pads its whole batch up to its length).
+ todo.sort(key=lambda i: entries[i].get("duration") or 0.0)
+ skipped = len(entries) - len(todo)
+ if skipped:
+ print(f"Resuming/skipping: {skipped} rows already scored by this backend or missing a reference.")
+
+ # ── Score in minibatches; fill `sim` and persist every --save_every rows ───
+ done = 0
+ too_short = [] # (audio_filepath, n_samples) for rows the embedder cannot process at all
+ for start in range(0, len(todo), args.save_every):
+ chunk = todo[start : start + args.save_every]
+ for b in range(0, len(chunk), batch_size):
+ idxs = chunk[b : b + batch_size]
+ gen_speech = [load_clip(_resolve(entries[i]["audio_filepath"])) for i in idxs]
+ ref_speech = [load_clip(_resolve(entries[i]["prompt_audio_filepath"])) for i in idxs]
+
+ # Too-short clips would crash the embedder (see _min_samples_for_embedding); give them
+ # `sim: null`, which eval_utils skips when averaging.
+ keep = [
+ k
+ for k in range(len(idxs))
+ if len(gen_speech[k]) >= embedder.min_samples and len(ref_speech[k]) >= embedder.min_samples
+ ]
+ for k in range(len(idxs)):
+ if k not in keep:
+ i = idxs[k]
+ entries[i]["sim"] = None
+ entries[i]["sim_model"] = embedder.name
+ entries[i]["sim_note"] = (
+ f"clip shorter than the {embedder.min_samples}-sample minimum the speaker "
+ f"embedder needs ({len(gen_speech[k])} generated / {len(ref_speech[k])} "
+ f"reference samples at {sim_sr} Hz); no SIM computed"
+ )
+ too_short.append((entries[i]["audio_filepath"], len(gen_speech[k])))
+
+ if keep:
+ gen_emb = embedder([gen_speech[k] for k in keep])
+ ref_emb = embedder([ref_speech[k] for k in keep])
+ sims = F.cosine_similarity(gen_emb, ref_emb, dim=-1)
+ for k, sim in zip(keep, sims.tolist()):
+ entries[idxs[k]]["sim"] = round(float(sim), 6)
+ entries[idxs[k]]["sim_model"] = embedder.name
+ done += len(idxs)
+ rewrite_manifest() # persist progress so a crash doesn't lose completed chunks
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ print(f" scored {done}/{len(todo)}")
+
+ if too_short:
+ print(
+ f"WARNING: {len(too_short)} row(s) were too short to embed (< {embedder.min_samples} "
+ f"samples = {embedder.min_samples / sim_sr * 1000:.0f} ms) and have sim=null; the mean "
+ f"SIM is over the remaining rows. Usually a degenerate/near-empty generation:"
+ )
+ for name, n in too_short[:10]:
+ print(f" {os.path.basename(name)} ({n} samples)")
+
+ if not todo and out_path != args.manifest_path:
+ # Nothing to score, but still write the fork: it may not exist yet, or the rebuilt entries
+ # may carry fresher upstream fields (e.g. re-transcribed `pred_text`).
+ rewrite_manifest()
+
+ print("Manifest updated with speaker similarity:", os.path.abspath(out_path))
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--manifest_path", type=str, required=True, help="JSONL manifest to read samples from.")
+ parser.add_argument(
+ "--output_manifest_path",
+ type=str,
+ default=None,
+ help="Where to write the scored manifest. Default: in place for the xvector backend, else alongside it as <manifest>_<sim_backend>.jsonl so both "
+ "SIM scales coexist. Must stay in the manifest's directory — wav paths are relative to it.",
+ )
+ parser.add_argument(
+ "--sim_backend",
+ type=str,
+ default="wavlm_seed_tts",
+ choices=["xvector", "wavlm_seed_tts"],
+ help="Speaker embedder. 'wavlm_seed_tts' (default): seed-tts-eval's WavLM-Large + "
+ "ECAPA-TDNN — comparable with published SIM and far more discriminative. 'xvector': HF "
+ "WavLMForXVector (--sim_model_id). The two scales are not interchangeable.",
+ )
+ parser.add_argument(
+ "--sim_model_id",
+ type=str,
+ default=DEFAULT_XVECTOR_MODEL_ID,
+ help=f"xvector backend only: speaker-verification model (default {DEFAULT_XVECTOR_MODEL_ID}).",
+ )
+ parser.add_argument(
+ "--sim_ckpt",
+ type=str,
+ default=None,
+ help=f"wavlm_seed_tts backend only: local path to {WAVLM_SEED_TTS_FILENAME}. "
+ f"Default: download from the pinned Hub mirror ({WAVLM_SEED_TTS_REPO_ID}).",
+ )
+ parser.add_argument("--sim_ckpt_repo", type=str, default=WAVLM_SEED_TTS_REPO_ID, help="Hub repo holding the wavlm_seed_tts checkpoint.")
+ parser.add_argument("--sim_ckpt_file", type=str, default=WAVLM_SEED_TTS_FILENAME, help="Filename of the wavlm_seed_tts checkpoint in --sim_ckpt_repo.")
+ parser.add_argument(
+ "--sim_ckpt_sha256",
+ type=str,
+ default=WAVLM_SEED_TTS_SHA256,
+ help="Expected sha256 of the downloaded wavlm_seed_tts checkpoint ('' to skip the check).",
+ )
+ parser.add_argument("--wavlm_config_id", type=str, default=WAVLM_BACKBONE_CONFIG_ID, help="Repo to read the WavLM-Large config.json from (weights come from the checkpoint).")
+ parser.add_argument(
+ "--batch_size",
+ type=int,
+ default=32,
+ help="Minibatch size for embedding extraction. Lower it if long clips OOM. Pinned to 1 for "
+ "the wavlm_seed_tts backend, whose pooling is padding-sensitive.",
+ )
+ parser.add_argument(
+ "--save_every",
+ type=int,
+ default=64,
+ help="Rewrite the manifest every N scored rows (crash-resume granularity).",
+ )
+ parser.add_argument(
+ "--overwrite",
+ action="store_true",
+ help="Re-score every row even if it already has a sim from this backend (default: resume).",
+ )
+ parser.add_argument(
+ "--max_audio_seconds",
+ type=float,
+ default=30.0,
+ help="Truncate each clip to at most this many seconds before embedding (0 = no cap). "
+ "Bounds GPU memory: WavLM OOMs on very long/runaway clips, and a speaker embedding "
+ "needs only a few seconds of audio.",
+ )
+ parser.add_argument("--device", type=str, default="cuda", help="'cuda', 'cpu', or 'cuda:0'.")
+ parser.add_argument("--dtype", type=str, default="float32", help="Model dtype, e.g. 'float32'.")
+ args = parser.parse_args()
+
+ main(args)
diff --git a/transformers/submit_jobs.sh b/transformers/submit_jobs.sh
new file mode 100755
index 0000000..baad6fe
--- /dev/null
+++ b/transformers/submit_jobs.sh
@@ -0,0 +1,115 @@
+#!/bin/bash
+# HF Jobs TTS eval — Transformers backend (generate → transcribe → SIM* → score; *voice-clone only).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["microsoft/speecht5_tts 32 " ...]
+# 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:-${SPACE}}"
+RUN_EVAL_INJECT="$(inject_run_eval)"
+
+# ── Voice cloning (dia / higgs / vibevoice families): clone the reference speaker + score SIM ──
+# VOICE_CLONE=true requests cloning; it is only applied to clone-capable models.
+VOICE_CLONE_MODELS=("dia" "higgs" "vibevoice") # keep in sync with run_eval.py's VOICE_CLONE_FAMILIES
+model_supports_voice_clone() {
+ local id_lc="${1,,}" pat
+ for pat in "${VOICE_CLONE_MODELS[@]}"; do [[ "$id_lc" == *"$pat"* ]] && return 0; done
+ return 1
+}
+# Effective clone mode = requested AND supported (mirrors run_eval.py). run_pipeline uses CLONE to gate SIM.
+resolve_mode() {
+ if [[ "${VOICE_CLONE}" == "true" ]] && ! model_supports_voice_clone "${MODEL_ID}"; then
+ echo "Warning: VOICE_CLONE=true but ${MODEL_ID} does not support cloning; using default voice (skips SIM)."
+ VOICE_CLONE=false voice_clone_mode
+ else
+ voice_clone_mode
+ fi
+}
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id batch_size max_new_tokens" (max_new_tokens optional). ──
+generate_stage() {
+ local _ BATCH_SIZE MAX_NEW_TOKENS MAX_NEW_TOKENS_ARG=""
+ read -r _ BATCH_SIZE MAX_NEW_TOKENS <<< "${MODEL_CFG}"
+ [[ -n "${MAX_NEW_TOKENS}" ]] && MAX_NEW_TOKENS_ARG="--max_new_tokens=${MAX_NEW_TOKENS}"
+ 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/transformers && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --language=${ASR_LANG} \
+ --device=cuda:0 \
+ --batch_size=${BATCH_SIZE} \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} \
+ ${VOICE_CLONE_FLAG} \
+ ${MAX_NEW_TOKENS_ARG} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# english only
+DATASET_CONFIGS=(
+ "tts en en"
+ "zero_shot en en ${CV3_EVAL_PATH}"
+)
+
+# # english and chinese (Vibevoice)
+# DATASET_CONFIGS=(
+# "tts en en"
+# "zero_shot en en ${CV3_EVAL_PATH}"
+# "tts zh zh"
+# "zero_shot zh zh ${CV3_EVAL_PATH}"
+# )
+
+# # facebook/seamless-m4t-v2-large and qwen3 omni
+# DATASET_CONFIGS=(
+# "tts en en"
+# "tts zh zh"
+# "zero_shot en en ${CV3_EVAL_PATH}"
+# "zero_shot fr fr ${CV3_EVAL_PATH}"
+# "zero_shot es es ${CV3_EVAL_PATH}"
+# "zero_shot zh zh ${CV3_EVAL_PATH}"
+# "zero_shot ja ja ${CV3_EVAL_PATH}"
+# "zero_shot ko ko ${CV3_EVAL_PATH}"
+# "zero_shot de de ${CV3_EVAL_PATH}"
+# "zero_shot it it ${CV3_EVAL_PATH}"
+# "zero_shot ru ru ${CV3_EVAL_PATH}"
+# )
+
+# # bosonai/higgs-tts-2-3b-base 32
+# DATASET_CONFIGS=(
+# "tts en en"
+# "tts zh zh"
+# "zero_shot en en ${CV3_EVAL_PATH}"
+# "zero_shot de de ${CV3_EVAL_PATH}"
+# "zero_shot zh zh ${CV3_EVAL_PATH}"
+# "zero_shot ko ko ${CV3_EVAL_PATH}"
+# )
+
+# ── Models: "model_id batch_size max_new_tokens" (max_new_tokens optional; CLI args override) ──
+MODEL_CONFIGS=(
+ # "microsoft/speecht5_tts 32 "
+ # "Qwen/Qwen3-Omni-30B-A3B-Instruct 32 "
+ # "Qwen/Qwen2.5-Omni-3B 32 "
+ # "Qwen/Qwen2.5-Omni-7B 32 "
+ # "sesame/csm-1b 32 2048" # 2048 is predefined max length
+ # "suno/bark 32 "
+ # "suno/bark-small 32 "
+ # "facebook/seamless-m4t-v2-large 32 " # batched; rows are trimmed with waveform_lengths (pad units buzz)
+ # "facebook/mms-tts-eng 32 "
+ # "espnet/fastspeech2_conformer_with_hifigan 32 "
+ ## -- SUPPORT VOICE CLONING (set VOICE_CLONE=true)
+ # "bosonai/higgs-tts-2-3b-base 32 "
+ # "nari-labs/Dia-1.6B-0626 32 3072" # 3072 is predefined max length
+ # # VibeVoice: 512 caps audio to ~30s to prevent runaway generation
+ # "vibevoice/VibeVoice-1.5B-hf 32 512"
+ # "vibevoice/VibeVoice-7B-hf 32 512"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/transformers/transcribe.py b/transformers/transcribe.py
new file mode 100644
index 0000000..142e7b2
--- /dev/null
+++ b/transformers/transcribe.py
@@ -0,0 +1,138 @@
+"""
+ASR transcription for the Open TTS Leaderboard (stage 2).
+
+Fills `pred_text` in a stage-1 manifest with Qwen3-ASR, in place and resumably. The ASR call
+mirrors `transcribe()` in `transformers/run_eval.py`.
+"""
+
+import argparse
+import json
+import os
+
+import torch
+from transformers.audio_utils import load_audio
+
+from transformers import AutoModelForMultimodalLM, AutoProcessor
+
+DEFAULT_ASR_MODEL_ID = "Qwen/Qwen3-ASR-1.7B-hf"
+
+
+def main(args):
+ torch_dtype = getattr(torch, args.dtype)
+
+ # ── Read manifest ────────────────────────────────────────────────────────
+ with open(args.manifest_path, encoding="utf-8") as f:
+ entries = [json.loads(line) for line in f if line.strip()]
+ if not entries:
+ raise ValueError(f"No entries found in manifest {args.manifest_path}")
+ print(f"Transcribing {len(entries)} samples from {args.manifest_path}")
+
+ # Wav paths are relative to the manifest's directory; absolute or unresolvable paths are used as-is.
+ manifest_dir = os.path.dirname(os.path.abspath(args.manifest_path))
+
+ def _resolve(p):
+ if not p or os.path.isabs(p):
+ return p
+ cand = os.path.join(manifest_dir, p)
+ return cand if os.path.exists(cand) else p
+
+ # ── Resume: decide what's left BEFORE paying for the ASR model ───────────
+ # Only transcribe rows without a prediction (unless --overwrite). Checked before the model load
+ # so re-running a finished split is ~free.
+ todo = list(range(len(entries)))
+ if not args.overwrite:
+ todo = [i for i in todo if not entries[i].get("pred_text")]
+ if len(todo) < len(entries):
+ print(f"Resuming: {len(entries) - len(todo)} already transcribed, {len(todo)} remaining.")
+ if not todo:
+ print("Nothing to transcribe; manifest already complete:", os.path.abspath(args.manifest_path))
+ return
+
+ # ── ASR model ─────────────────────────────────────────────────────────────
+ asr_processor = AutoProcessor.from_pretrained(args.asr_model_id)
+ asr_model = AutoModelForMultimodalLM.from_pretrained(
+ args.asr_model_id, dtype=torch_dtype, device_map=args.device
+ )
+ asr_model.eval()
+ asr_sr = 16_000
+ if getattr(asr_processor, "feature_extractor", None) is not None and hasattr(
+ asr_processor.feature_extractor, "sampling_rate"
+ ):
+ asr_sr = asr_processor.feature_extractor.sampling_rate
+
+ # Cap clip length: a runaway generation padded into a batch can OOM the ASR encoder, and
+ # anything that long is degenerate and scores as an error anyway.
+ max_samples = int(args.max_audio_seconds * asr_sr) if args.max_audio_seconds > 0 else None
+
+ def transcribe(paths):
+ speech = [load_audio(path, sampling_rate=asr_sr) for path in paths]
+ if max_samples is not None:
+ speech = [s[:max_samples] for s in speech]
+ lang = args.asr_language or None # '' => None => Qwen3-ASR auto-detects
+ language = [lang] * len(speech)
+ inputs = asr_processor.apply_transcription_request(speech, language=language).to(
+ asr_model.device, asr_model.dtype
+ )
+ with torch.no_grad():
+ output_ids = asr_model.generate(**inputs, max_new_tokens=args.asr_max_new_tokens)
+ generated_ids = output_ids[:, inputs["input_ids"].shape[1]:]
+ return asr_processor.decode(generated_ids, return_format="transcription_only")
+
+ def rewrite_manifest():
+ with open(args.manifest_path, "w", encoding="utf-8") as f:
+ for e in entries:
+ f.write(json.dumps(e, ensure_ascii=False) + "\n")
+
+ # Batch clips of similar length together so padding=longest wastes less memory/compute, and
+ # any capped long clips cluster into a few batches rather than inflating every batch.
+ todo.sort(key=lambda i: entries[i].get("duration") or 0.0)
+
+ # ── Transcribe in ASR minibatches; fill pred_text and persist after each chunk ─
+ for start in range(0, len(todo), args.asr_batch_size):
+ idxs = todo[start : start + args.asr_batch_size]
+ preds = transcribe([_resolve(entries[i]["audio_filepath"]) for i in idxs])
+ for i, pred in zip(idxs, preds):
+ entries[i]["pred_text"] = pred
+ rewrite_manifest() # persist progress so a crash doesn't lose completed chunks
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ print(f" transcribed {min(start + args.asr_batch_size, len(todo))}/{len(todo)}")
+
+ print("Manifest updated with transcriptions:", os.path.abspath(args.manifest_path))
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--manifest_path", type=str, required=True, help="JSONL manifest to transcribe (pred_text filled in place).")
+ parser.add_argument("--asr_model_id", type=str, default=DEFAULT_ASR_MODEL_ID, help="ASR model used to transcribe for WER.")
+ parser.add_argument(
+ "--asr_language",
+ type=str,
+ default="en",
+ help="Language hint for the ASR model. Pass '' (empty) to let Qwen3-ASR auto-detect.",
+ )
+ parser.add_argument("--asr_max_new_tokens", type=int, default=256, help="Max tokens for ASR transcription.")
+ parser.add_argument(
+ "--max_audio_seconds",
+ type=float,
+ default=30.0,
+ help="Truncate each clip to at most this many seconds before transcribing (0 = no cap). "
+ "Bounds ASR-encoder memory: a runaway TTS generation can be minutes long and OOM the "
+ "conv frontend (a batch is padded to its longest clip). Mirrors score_similarity.py.",
+ )
+ parser.add_argument(
+ "--asr_batch_size",
+ type=int,
+ default=32,
+ help="Minibatch size for ASR transcription (clips are padded to the longest in the batch).",
+ )
+ parser.add_argument(
+ "--overwrite",
+ action="store_true",
+ help="Re-transcribe every row even if it already has a pred_text (default: resume, skip filled rows).",
+ )
+ parser.add_argument("--device", type=str, default="cuda", help="'cuda', 'cpu', or 'cuda:0'.")
+ parser.add_argument("--dtype", type=str, default="bfloat16", help="ASR model dtype, e.g. 'bfloat16'.")
+ args = parser.parse_args()
+
+ main(args)
diff --git a/vibevoice_realtime/run_eval.py b/vibevoice_realtime/run_eval.py
new file mode 100644
index 0000000..26df312
--- /dev/null
+++ b/vibevoice_realtime/run_eval.py
@@ -0,0 +1,331 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (VibeVoice-Realtime backend, stage 1).
+
+The streaming API asserts batch_size == 1, so generation is a per-sample loop inside
+`generate_tts`; `--batch_size` only chunks the dataset for manifest writing / resume. Each chunk
+is timed with CUDA events and per-sample time = chunk time / chunk size.
+"""
+
+import argparse
+import copy
+import os
+import time
+
+import numpy as np
+import soundfile as sf
+import torch
+from huggingface_hub import hf_hub_download
+from tqdm import tqdm
+
+
+from transformers.cache_utils import DynamicCache
+from transformers.modeling_outputs import BaseModelOutputWithPast
+from vibevoice.modular.modeling_vibevoice_streaming_inference import (
+ VibeVoiceStreamingForConditionalGenerationInference,
+)
+from vibevoice.processor.vibevoice_streaming_processor import VibeVoiceStreamingProcessor
+# Queue-backed streamer for observing first audio during generate(); TTFA probe only.
+from vibevoice.modular.streamer import AudioStreamer
+
+from run_eval_utils import (
+ add_common_args, load_done_entries, load_tts_dataset, manifest_entry, open_manifest, output_paths,
+ pending_batches, print_model_size, print_next_steps, set_seed, warm_up, wav_rel_path, write_entry,
+)
+
+torch.set_float32_matmul_precision("high")
+
+# Voice presets = cached prefill states (.pt) for the streaming model, hosted on the HF Hub.
+VOICE_REPO = "bezzam/vibevoice_samples"
+VOICE_DIR = "realtime_model/voices/streaming_model"
+
+BASE_VOICES = [
+ "en-Carter_man", "en-Davis_man", "en-Emma_woman", "en-Frank_man", "en-Grace_woman", "en-Mike_man",
+ "in-Samuel_man",
+ "de-Spk0_man", "de-Spk1_woman",
+ "fr-Spk0_man", "fr-Spk1_woman",
+ "it-Spk0_woman", "it-Spk1_man",
+ "jp-Spk0_man", "jp-Spk1_woman",
+ "kr-Spk0_woman", "kr-Spk1_man",
+ "nl-Spk0_man", "nl-Spk1_woman",
+ "pl-Spk0_man", "pl-Spk1_woman",
+ "pt-Spk0_woman", "pt-Spk1_man",
+ "sp-Spk0_woman", "sp-Spk1_man",
+]
+
+EXPERIMENTAL_VOICES = {
+ "de": ["de-Spk2_woman", "de-Spk3_man", "de-Spk4_woman", "de-Spk5_man", "de-Spk6_man"],
+ "fr": ["fr-Spk2_man", "fr-Spk3_woman", "fr-Spk4_woman", "fr-Spk5_man"],
+ "jp": ["jp-Spk2_woman", "jp-Spk3_woman", "jp-Spk4_woman", "jp-Spk5_man"],
+ "kr": ["kr-Spk2_woman", "kr-Spk3_man"],
+ "pl": ["pl-Spk2_man", "pl-Spk3_woman"],
+ "pt": ["pt-Spk2_woman", "pt-Spk3_man", "pt-Spk4_man", "pt-Spk5_woman"],
+ "sp": ["sp-Spk2_woman", "sp-Spk3_man", "sp-Spk4_woman", "sp-Spk5_man"],
+}
+
+AVAILABLE_VOICES = BASE_VOICES + [v for voices in EXPERIMENTAL_VOICES.values() for v in voices]
+SAMPLE_RATE = 24000
+
+
+def voice_repo_path(speaker):
+ """Path of `speaker`'s cached prefill states inside VOICE_REPO (experimental ones are nested per language)."""
+ if speaker in BASE_VOICES:
+ return f"{VOICE_DIR}/{speaker}.pt"
+ return f"{VOICE_DIR}/experimental_voices/{speaker.split('-', 1)[0]}/{speaker}.pt"
+
+
+def main(args):
+ # Set seed for reproducibility (the diffusion head samples internally).
+ seed = args.seed
+ set_seed(seed)
+ torch.backends.cudnn.deterministic = True
+
+ torch_dtype = getattr(torch, args.dtype)
+ processor = VibeVoiceStreamingProcessor.from_pretrained(args.model_id)
+ model = VibeVoiceStreamingForConditionalGenerationInference.from_pretrained(
+ args.model_id,
+ torch_dtype=torch_dtype,
+ device_map=args.device,
+ attn_implementation=args.attn_implementation,
+ )
+ model.eval()
+ model.set_ddpm_inference_steps(num_steps=args.ddpm_steps)
+ print(
+ f"Loaded VibeVoice-Realtime model {args.model_id} "
+ f"(speaker={args.speaker}, cfg_scale={args.cfg_scale}, ddpm_steps={args.ddpm_steps})"
+ )
+
+ # Report parameter count (dedup by id in case submodules share parameters).
+ print_model_size(model)
+
+ # ── Fixed voice preset: cached prefill states from the HF Hub ────────────
+ if args.speaker not in AVAILABLE_VOICES:
+ raise ValueError(f"Unknown speaker '{args.speaker}'. Choose from: {', '.join(AVAILABLE_VOICES)}")
+ voice_path = hf_hub_download(
+ repo_id=VOICE_REPO,
+ filename=voice_repo_path(args.speaker),
+ repo_type="dataset",
+ )
+ with torch.serialization.safe_globals([BaseModelOutputWithPast, DynamicCache]):
+ all_prefilled_outputs = torch.load(voice_path, map_location=args.device, weights_only=True)
+ print(f"Using voice preset '{args.speaker}': {voice_path}")
+
+ # 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
+
+ def prepare_inputs(text):
+ """Seed and build one generate() input dict (shared by the eval and the TTFA probe)."""
+ # Re-seed per sample so diffusion sampling is reproducible regardless of chunking.
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+
+ clean_text = text.replace("’", "'").replace("“", '"').replace("”", '"')
+ inputs = processor.process_input_with_cached_prompt(
+ text=clean_text,
+ cached_prompt=all_prefilled_outputs,
+ padding=True,
+ return_tensors="pt",
+ return_attention_mask=True,
+ )
+ for k, v in inputs.items():
+ if torch.is_tensor(v):
+ inputs[k] = v.to(args.device)
+ return inputs
+
+ def synth_one(text):
+ """Synthesize one utterance, returning the finished waveform."""
+ inputs = prepare_inputs(text)
+
+ outputs = model.generate(
+ **inputs,
+ max_new_tokens=None,
+ cfg_scale=args.cfg_scale,
+ tokenizer=processor.tokenizer,
+ generation_config={"do_sample": False},
+ verbose=False, # keep the outer "Generating" tqdm as the only progress output
+ # generate() consumes/mutates the cached prompt states, so give it a copy.
+ all_prefilled_outputs=copy.deepcopy(all_prefilled_outputs),
+ )
+
+ if outputs.speech_outputs and outputs.speech_outputs[0] is not None:
+ audio = outputs.speech_outputs[0]
+ audio = np.asarray(audio.detach().to(torch.float32).cpu()).reshape(-1)
+ else:
+ print(f"Warning: no audio generated for text: {text[:60]}...")
+ audio = np.zeros(int(0.1 * SAMPLE_RATE), dtype=np.float32)
+ return audio
+
+ def generate_tts(batch):
+ """Synthesize a chunk of target texts (per-sample loop); time the chunk for RTFx."""
+ texts_to_generate = list(batch[args.text_column])
+ minibatch_size = len(texts_to_generate)
+
+ # START TIMING (TTS chunk generation)
+ torch.cuda.synchronize(device=args.device)
+ start_event = torch.cuda.Event(enable_timing=True)
+ end_event = torch.cuda.Event(enable_timing=True)
+ start_event.record()
+
+ # No batched API (generate() asserts batch_size == 1): loop per sample.
+ wavs = [synth_one(text) for text in texts_to_generate]
+
+ # END TIMING
+ end_event.record()
+ torch.cuda.synchronize(device=args.device)
+ runtime = start_event.elapsed_time(end_event) / 1000.0
+ # per-sample generation time (RTFx is aggregated over the whole set at scoring time)
+ batch["generation_time_s"] = minibatch_size * [runtime / minibatch_size]
+
+ gen_paths, audio_length_s = [], []
+ for audio, sample_id in zip(wavs, batch["id"]):
+ # 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)
+ sf.write(path, audio, SAMPLE_RATE)
+ gen_paths.append(rel_path)
+ audio_length_s.append(len(audio) / SAMPLE_RATE)
+
+ batch["gen_audio_filepath"] = gen_paths
+ batch["audio_length_s"] = audio_length_s
+ batch["references"] = list(batch[args.text_column]) # raw; normalized at scoring time
+ return batch
+
+ dataset = load_tts_dataset(args)
+
+ # ── TTFA probe: latency only, writing nothing but a JSON sidecar ─────────
+ if args.ttfa_probe != 0:
+ # Imported lazily: ttfa_probe.py is only injected by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+ import threading
+
+ chunk_counts = [] # chunks per utterance
+
+ def _gen(job, early_stop):
+ """One generation with an audio_streamer attached, timestamping the first chunk."""
+ inputs = prepare_inputs(job["text"])
+ streamer = AudioStreamer(batch_size=1, stop_signal=None, timeout=None)
+ stop_event = threading.Event()
+ errors = []
+
+ def _run():
+ try:
+ model.generate(
+ **inputs,
+ max_new_tokens=None,
+ cfg_scale=args.cfg_scale,
+ tokenizer=processor.tokenizer,
+ generation_config={"do_sample": False},
+ audio_streamer=streamer,
+ # Honoured between diffusion steps, so an early-stopped row aborts the
+ # generation instead of leaving it running for the rest of the probe.
+ stop_check_fn=stop_event.is_set,
+ verbose=False,
+ all_prefilled_outputs=copy.deepcopy(all_prefilled_outputs),
+ )
+ except Exception as exc: # surfaced on the consuming thread below
+ errors.append(exc)
+ finally:
+ # Ensure get_stream(0) never blocks forever if generate() crashes.
+ streamer.end()
+
+ thread = threading.Thread(target=_run, daemon=True)
+ thread.start()
+
+ first, chunks = None, []
+ try:
+ for chunk in streamer.get_stream(0):
+ if first is None:
+ first = time.perf_counter()
+ chunk = np.asarray(
+ chunk.detach().to(torch.float32).cpu() if torch.is_tensor(chunk) else chunk,
+ dtype=np.float32,
+ ).reshape(-1)
+ chunks.append(chunk)
+ if early_stop:
+ break
+ finally:
+ stop_event.set()
+ streamer.end()
+ thread.join()
+ if errors:
+ raise errors[0]
+
+ chunk_counts.append(len(chunks))
+ audio = np.concatenate(chunks) if chunks else np.zeros(0, dtype=np.float32)
+ return audio, SAMPLE_RATE, first
+
+ run_probe(
+ _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,
+ # chunks_per_utterance distinguishes "no incremental output" (1 chunk) from late delivery.
+ extra={"device": args.device, "note": "driven at batch size 1, audio_streamer attached",
+ "chunks_per_utterance": chunk_counts},
+ )
+ return
+
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ starts = pending_batches(dataset, args.batch_size, done_entries, dataset_dir_name)
+ # Generation is per-sample, so warm up on one sample per step (the first of each pending chunk).
+ warm_up(generate_tts, dataset, starts, 1, args.warmup_steps)
+
+ # ── Main loop: TTS → write JSONL, one chunk at a time ───────────────────
+ for batch_start in tqdm(starts, desc="Generating"):
+ batch = generate_tts(dataset[batch_start : batch_start + args.batch_size])
+
+ # Append each sample to the JSONL immediately. `pred_text` is filled by stage 2 (ASR).
+ for afp, alen, gtime, ref in zip(
+ batch["gen_audio_filepath"], batch["audio_length_s"],
+ batch["generation_time_s"], batch["references"],
+ ):
+ write_entry(manifest_file, manifest_entry(afp, alen, gtime, ref))
+ 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="microsoft/VibeVoice-Realtime-0.5B",
+ help="VibeVoice-Realtime model id, loadable with the `vibevoice` package.",
+ )
+ parser.add_argument(
+ "--speaker",
+ type=str,
+ default="en-Carter_man",
+ choices=AVAILABLE_VOICES,
+ help="Fixed voice preset (cached prefill states from bezzam/vibevoice_samples). Must match "
+ "the dataset's language: the en-* presets read non-English text with an English voice, which "
+ "makes the WER/CER meaningless. Non-en presets are upstream's EXPERIMENTAL voices.",
+ )
+ parser.add_argument("--cfg_scale", type=float, default=1.5, help="Classifier-free guidance scale.")
+ parser.add_argument("--ddpm_steps", type=int, default=5, help="DDPM inference steps for the diffusion head.")
+ parser.add_argument("--dtype", type=str, default="bfloat16", help="Model dtype, e.g. 'bfloat16'.")
+ parser.add_argument("--attn_implementation", type=str, default="sdpa", help="Attention impl ('sdpa'/'eager').")
+ add_common_args(parser)
+ parser.add_argument(
+ "--batch_size",
+ type=int,
+ default=32,
+ help="Chunk size for manifest writing/resume ONLY — generation itself is per-sample "
+ "(the streaming API asserts batch_size == 1).",
+ )
+
+ 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/vibevoice_realtime/submit_jobs.sh b/vibevoice_realtime/submit_jobs.sh
new file mode 100755
index 0000000..48b58bb
--- /dev/null
+++ b/vibevoice_realtime/submit_jobs.sh
@@ -0,0 +1,64 @@
+#!/bin/bash
+# HF Jobs TTS eval — VibeVoice-Realtime backend (fixed voice: generate → transcribe → score).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["microsoft/VibeVoice-Realtime-0.5B 32" ...]
+# 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-vibevoice}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-vibevoice/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)"
+
+# ── Language → voice preset ──────────────────────────────────────────────────
+declare -A VIBEVOICE_VOICES=( [en]=en-Carter_man [de]=de-Spk0_man [fr]=fr-Spk0_man [it]=it-Spk1_man \
+ [ja]=jp-Spk0_man [ko]=kr-Spk1_man [nl]=nl-Spk0_man [pl]=pl-Spk0_man \
+ [pt]=pt-Spk1_man [es]=sp-Spk1_man )
+supports_language() { [[ -n "${VIBEVOICE_VOICES[$1]:-}" ]]; }
+# Setting VIBEVOICE_SPEAKER forces one preset for every combo — only sensible for a single-language run.
+VIBEVOICE_SPEAKER="${VIBEVOICE_SPEAKER:-}"
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id batch_size". ──
+# The streaming API asserts batch_size == 1; --batch_size only chunks manifest writing / resume.
+generate_stage() {
+ local _ BATCH_SIZE SPEAKER
+ read -r _ BATCH_SIZE <<< "${MODEL_CFG}"
+ SPEAKER="${VIBEVOICE_SPEAKER:-${VIBEVOICE_VOICES[${ASR_LANG}]}}"
+ 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/vibevoice_realtime && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --speaker=${SPEAKER} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --device=cuda:0 \
+ --batch_size=${BATCH_SIZE} \
+ --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}"
+ "zero_shot fr fr ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ja ja ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ko ko ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot de de ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot it it ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id batch_size" (CLI args override; speaker comes from VIBEVOICE_VOICES) ──
+MODEL_CONFIGS=(
+ "microsoft/VibeVoice-Realtime-0.5B 32"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/voxcpm2/run_eval.py b/voxcpm2/run_eval.py
new file mode 100644
index 0000000..f384f5f
--- /dev/null
+++ b/voxcpm2/run_eval.py
@@ -0,0 +1,287 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (VoxCPM2 backend, stage 1).
+
+VoxCPM2 (openbmb/VoxCPM2): ~2B tokenizer-free TTS, 48 kHz output. With `--voice_clone` each
+sample is cloned from the dataset's `prompt_audio`/`prompt_text` (written to wavs, since
+`generate()` takes a path); by default (`--no-voice_clone`) VoxCPM2 picks its own speaker (no SIM).
+
+`VoxCPM.generate()` takes a single text, so texts are synthesized one at a time inside
+`generate_tts(batch)`; `--batch_size` only sets manifest-writing / resume granularity, and
+per-sample time = batch time / batch size.
+"""
+
+import argparse
+import inspect
+import logging
+import os
+import time
+import warnings
+
+import numpy as np
+import soundfile as sf
+import torch
+from tqdm import tqdm
+
+from run_eval_utils import (
+ add_common_args,
+ load_done_entries,
+ load_tts_dataset,
+ manifest_entry,
+ open_manifest,
+ output_paths,
+ pending_batches,
+ print_model_size,
+ print_next_steps,
+ set_seed,
+ warm_up,
+ write_entry,
+)
+
+# voxcpm pulls in chatty deps (modelscope, funasr, transformers); keep warnings/info out
+# of the way so the outer "Generating" tqdm is the only progress output.
+warnings.filterwarnings("ignore")
+for _name in ("modelscope", "funasr"):
+ logging.getLogger(_name).setLevel(logging.WARNING)
+try:
+ from transformers.utils import logging as _hf_logging
+
+ _hf_logging.set_verbosity_error()
+except Exception:
+ pass
+
+from voxcpm import VoxCPM # noqa: E402
+
+torch.set_float32_matmul_precision("high")
+
+
+def main(args):
+ # Set seed for reproducibility (VoxCPM samples internally: LM sampling + diffusion).
+ seed = args.seed
+ set_seed(seed)
+ torch.backends.cudnn.deterministic = True
+
+ # Load the checkpoint baked into the image, else pull from the Hub. The ZipEnhancer prompt
+ # denoiser is skipped (`enable_denoiser/load_denoiser=False`).
+ if os.path.isdir(args.checkpoint_path):
+ init_kwargs = {"voxcpm_model_path": args.checkpoint_path, "enable_denoiser": False}
+ if "device" in inspect.signature(VoxCPM.__init__).parameters:
+ init_kwargs["device"] = args.device
+ model = VoxCPM(**init_kwargs)
+ else:
+ print(f"Checkpoint dir {args.checkpoint_path} not found; downloading {args.model_id} from the Hub.")
+ fp_kwargs = {"load_denoiser": False}
+ if "device" in inspect.signature(VoxCPM.from_pretrained).parameters:
+ fp_kwargs["device"] = args.device
+ model = VoxCPM.from_pretrained(args.model_id, **fp_kwargs)
+ sampling_rate = int(getattr(model.tts_model, "sample_rate", 48000)) # VoxCPM2: 48 kHz
+ print(f"Loaded VoxCPM2 model {args.model_id} (sr={sampling_rate}, cfg_value={args.cfg_value}, "
+ f"inference_timesteps={args.inference_timesteps})")
+
+ # VoxCPM is a wrapper around nn.Module components: count their unique params.
+ try:
+ print_model_size(model)
+ except Exception as e:
+ print(f"Could not determine model size: {e}")
+
+ # 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.
+ # Keep the two modes' audio separate so voice-clone and auto-voice runs don't overwrite.
+ mode_suffix = "_voice_clone" if args.voice_clone else ""
+ paths = output_paths(args, mode_suffix)
+ model_dir, dataset_dir_name, output_dir = paths.model_dir, paths.dataset_dir_name, paths.output_dir
+
+ # `generate()` takes the cloning reference as a file path; prompts are written here (under
+ # `results/` so stage 3 can read them back to score speaker similarity).
+ prompt_dir = os.path.join(output_dir, "prompts")
+ if args.voice_clone:
+ os.makedirs(prompt_dir, exist_ok=True)
+
+ def generate_tts(batch):
+ """Synthesize a minibatch one utterance at a time; time the whole loop for RTFx."""
+ texts_to_generate = list(batch[args.text_column])
+ minibatch_size = len(texts_to_generate)
+
+ # Write the cloning prompts to wavs BEFORE timing (I/O is not generation).
+ if args.voice_clone:
+ prompt_rel_paths, prompt_full_paths, prompt_texts = [], [], list(batch["prompt_text"])
+ for sample_id, prompt_audio in zip(batch["id"], batch["prompt_audio"]):
+ prel = os.path.join(dataset_dir_name, "prompts", f"prompt_{sample_id}.wav")
+ ppath = os.path.join(model_dir, prel)
+ if not os.path.exists(ppath):
+ sf.write(ppath, np.asarray(prompt_audio["array"], dtype=np.float32), prompt_audio["sampling_rate"])
+ prompt_rel_paths.append(prel)
+ prompt_full_paths.append(ppath)
+ else:
+ prompt_rel_paths = [None] * minibatch_size
+ prompt_full_paths = [None] * minibatch_size
+ prompt_texts = [None] * minibatch_size
+
+ # START TIMING (TTS generation for the whole minibatch)
+ torch.cuda.synchronize(device=args.device)
+ start_event = torch.cuda.Event(enable_timing=True)
+ end_event = torch.cuda.Event(enable_timing=True)
+ start_event.record()
+
+ wavs = []
+ for text, prompt_text, prompt_path in zip(texts_to_generate, prompt_texts, prompt_full_paths):
+ # Re-seed per sample so generation is reproducible regardless of batch layout.
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+ # Voice-cloning mode passes the per-sample reference audio/text; auto-voice mode
+ # (prompt_wav_path/prompt_text=None) lets VoxCPM2 pick its own speaker.
+ wav = model.generate(
+ text=text,
+ prompt_wav_path=prompt_path,
+ prompt_text=prompt_text,
+ cfg_value=args.cfg_value,
+ inference_timesteps=args.inference_timesteps,
+ normalize=args.normalize,
+ denoise=False, # denoiser not loaded (enable_denoiser=False)
+ retry_badcase=not args.no_retry_badcase,
+ )
+ wavs.append(np.asarray(wav).reshape(-1))
+
+ # END TIMING
+ end_event.record()
+ torch.cuda.synchronize(device=args.device)
+ runtime = start_event.elapsed_time(end_event) / 1000.0
+ # per-sample generation time (RTFx is aggregated over the whole set at scoring time)
+ batch["generation_time_s"] = minibatch_size * [runtime / minibatch_size]
+
+ gen_paths, audio_length_s = [], []
+ for audio, sample_id in zip(wavs, batch["id"]):
+ # Store the path relative to model_dir (the manifest's dir); write to the full path.
+ rel_path = os.path.join(dataset_dir_name, f"output_{sample_id}.wav")
+ sf.write(os.path.join(model_dir, rel_path), audio, sampling_rate)
+ gen_paths.append(rel_path)
+ audio_length_s.append(len(audio) / sampling_rate)
+
+ batch["gen_audio_filepath"] = gen_paths
+ batch["prompt_audio_filepath"] = prompt_rel_paths
+ batch["audio_length_s"] = audio_length_s
+ batch["references"] = list(batch[args.text_column]) # raw; normalized at scoring time
+ return batch
+
+ # For voice cloning also keep the reference `prompt_audio`/`prompt_text`.
+ dataset = load_tts_dataset(args, extra_columns=("prompt_text", "prompt_audio") if args.voice_clone else ())
+
+ # ── TTFA probe: one request at a time via generate_streaming(); writes only a JSON sidecar ──
+ # Prompt clips go to a temp dir so the results tree is untouched.
+ # 0 = off; N > 0 = N evenly spaced samples; N < 0 = the whole split (see scripts/ttfa_probe.py).
+ if args.ttfa_probe != 0:
+ # Imported lazily: ttfa_probe.py is only injected by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+ import tempfile
+
+ output_dir = tempfile.mkdtemp(prefix="ttfa_out_")
+ os.makedirs(os.path.join(output_dir, "prompts"), exist_ok=True)
+
+ chunk_counts = [] # chunks per utterance
+
+ def _gen(job, early_stop):
+ """One generation via generate_streaming() (same arguments as the eval), timestamping the first chunk."""
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+ prompt_path = prompt_text = None
+ if args.voice_clone:
+ prompt_path = os.path.join(output_dir, "prompts", f"prompt_{job['id'][0]}.wav")
+ pa = job["prompt_audio"][0]
+ sf.write(prompt_path, np.asarray(pa["array"], dtype=np.float32), pa["sampling_rate"])
+ prompt_text = job["prompt_text"][0]
+ first, chunks = None, []
+ for chunk in model.generate_streaming(
+ text=job[args.text_column][0],
+ prompt_wav_path=prompt_path,
+ prompt_text=prompt_text,
+ cfg_value=args.cfg_value,
+ inference_timesteps=args.inference_timesteps,
+ normalize=args.normalize,
+ denoise=False,
+ retry_badcase=not args.no_retry_badcase,
+ ):
+ if first is None:
+ first = time.perf_counter()
+ chunks.append(np.asarray(chunk).reshape(-1))
+ if early_stop:
+ break
+ chunk_counts.append(len(chunks))
+ if not chunks:
+ return np.zeros(1, dtype=np.float32), sampling_rate, None
+ return np.concatenate(chunks), sampling_rate, first
+
+ columns = dataset.column_names
+ jobs = [{c: [dataset[i][c]] for c in columns}
+ for i in sample_indices(args.ttfa_probe, len(dataset))]
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=model_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ # chunks_per_utterance distinguishes "no incremental output" (1 chunk) from late delivery.
+ extra={"device": args.device, "note": "driven at batch size 1, generate_streaming()",
+ "chunks_per_utterance": chunk_counts},
+ )
+ return
+
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ starts = pending_batches(dataset, args.batch_size, done_entries, dataset_dir_name)
+ warm_up(generate_tts, dataset, starts, 1, args.warmup_steps) # serial model: warm up on single samples
+
+ # ── Main loop: TTS → write JSONL, one batch at a time ───────────────────
+ for batch_start in tqdm(starts, desc="Generating"):
+ batch = generate_tts(dataset[batch_start : batch_start + args.batch_size])
+
+ # Append each sample to the JSONL immediately. `pred_text` is filled by stage 2 (ASR);
+ # `sim` by stage 3 (speaker similarity, voice-clone only).
+ for afp, ppath, alen, gtime, ref in zip(
+ batch["gen_audio_filepath"], batch["prompt_audio_filepath"], batch["audio_length_s"],
+ batch["generation_time_s"], batch["references"],
+ ):
+ write_entry(manifest_file, manifest_entry(afp, alen, gtime, ref, ppath if args.voice_clone else None))
+ manifest_file.flush()
+
+ manifest_file.close()
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(args.voice_clone)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ add_common_args(parser, batch_size=32, voice_clone=False)
+
+ parser.add_argument(
+ "--model_id",
+ type=str,
+ default="openbmb/VoxCPM2",
+ help="VoxCPM model id, loadable with the `voxcpm` package.",
+ )
+ parser.add_argument(
+ "--checkpoint_path",
+ type=str,
+ default="/opt/models/VoxCPM2",
+ help="Local dir with the VoxCPM2 weights (baked at image build); falls back to the Hub if missing.",
+ )
+ parser.add_argument("--cfg_value", type=float, default=2.0, help="LM guidance scale (model-card default 2.0).")
+ parser.add_argument(
+ "--inference_timesteps", type=int, default=10, help="Diffusion steps (model-card default 10; higher = quality)."
+ )
+ parser.add_argument(
+ "--normalize", action="store_true", help="Apply voxcpm's external text normalization (wetext) before synthesis."
+ )
+ parser.add_argument(
+ "--no_retry_badcase",
+ action="store_true",
+ help="Disable voxcpm's retry-on-badcase (default: retry up to 3x when output is degenerately long).",
+ )
+
+ 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/voxcpm2/submit_jobs.sh b/voxcpm2/submit_jobs.sh
new file mode 100644
index 0000000..77aa8c0
--- /dev/null
+++ b/voxcpm2/submit_jobs.sh
@@ -0,0 +1,60 @@
+#!/bin/bash
+# HF Jobs TTS eval — VoxCPM2 backend (generate → transcribe → SIM* → score; *voice-clone only).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["openbmb/VoxCPM2 32" ...]
+# 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-voxcpm}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-voxcpm/blob/main/Dockerfile)
+# gen FLAVOR (h200) is set centrally in tts_jobs_common.sh for RTFx comparability — don't override.
+RUN_EVAL_INJECT="$(inject_run_eval)"
+SUPPORTS_VOICE_CLONE=true # VOICE_CLONE=true clones each sample's reference speaker + scores SIM
+
+# ── Stage 1: TTS generation. MODEL_CFG = "model_id batch_size". ──
+generate_stage() {
+ local _ BATCH_SIZE
+ read -r _ BATCH_SIZE <<< "${MODEL_CFG}"
+ 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/voxcpm2 && python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --device=cuda:0 \
+ --batch_size=${BATCH_SIZE} \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} \
+ ${VOICE_CLONE_FLAG} &&
+ mkdir -p /results &&
+ cp -r results/${MODEL_SAFE} /results/
+ "
+}
+
+# ── Datasets: "config split asr_language [dataset_path]" (comment/uncomment to pick) ────────
+# VoxCPM2 infers the language from the text (no language tag) and covers every language below, so
+# there is no `supports_language` gate; asr_language is only the stage-2 ASR hint.
+DATASET_CONFIGS=(
+ "tts en en"
+ "tts zh zh"
+ "zero_shot en en ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot zh zh ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ja ja ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ko ko ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot de de ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot fr fr ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot it it ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot ru ru ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+
+# ── Models: "model_id batch_size" (CLI args override) ────────────────────────
+MODEL_CONFIGS=(
+ "openbmb/VoxCPM2 32"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline
diff --git a/voxtral-tts/run_eval.py b/voxtral-tts/run_eval.py
new file mode 100644
index 0000000..fdb6d71
--- /dev/null
+++ b/voxtral-tts/run_eval.py
@@ -0,0 +1,342 @@
+"""
+TTS synthesis for the Open TTS Leaderboard (Voxtral TTS backend, stage 1).
+
+Voxtral-4B-TTS-2603 (mistralai/Voxtral-4B-TTS-2603) is Mistral's ~4B open-weights TTS. It is
+served as the model card prescribes, with `vllm serve <model> --omni` (started by
+voxtral-tts/submit_jobs.sh in the same container), and this script is an HTTP client of the
+OpenAI-compatible `/v1/audio/speech` endpoint. Each minibatch of requests is POSTed concurrently
+(the server's continuous batching schedules them together) and the batch wall-clock time is used
+for RTFx (per-sample time = batch time / batch size).
+
+Fixed voice only (`--voice`, default `casual_male`): the open-source checkpoint lacks the audio
+tokenizer's encoder weights, so cloning from `prompt_audio` is impossible and there is no SIM stage.
+Sampling uses the server's stage defaults; the endpoint exposes no per-request sampling knobs.
+"""
+
+import argparse
+import io
+import json
+import os
+import struct
+import time
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+
+import httpx
+import soundfile as sf
+from tqdm import tqdm
+
+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, warm_up, wav_rel_path, write_entry,
+)
+
+
+def _report_param_count(model_id):
+ """Print the model size in B parameters, summed from the `consolidated.safetensors` header
+ (a cache hit: the server just loaded it); falls back to the model-card figure."""
+ try:
+ if Path(model_id).is_dir():
+ path = str(Path(model_id) / "consolidated.safetensors")
+ else:
+ from huggingface_hub import hf_hub_download
+
+ path = hf_hub_download(model_id, "consolidated.safetensors")
+ with open(path, "rb") as f:
+ header_len = struct.unpack("<Q", f.read(8))[0]
+ header = json.loads(f.read(header_len))
+ n_params = 0
+ for name, meta in header.items():
+ if name == "__metadata__":
+ continue
+ count = 1
+ for dim in meta.get("shape", []):
+ count *= dim
+ n_params += count
+ print(f"TTS model size: {n_params / 1e9:.2f}B parameters (from consolidated.safetensors header)")
+ except Exception as e:
+ print(
+ "TTS model size: ~4B parameters per the model card "
+ f"(Ministral-3-3B backbone + acoustic transformer + audio codec); header parse failed: {e}"
+ )
+
+
+def _server_alive(pid):
+ """True if the `vllm serve` process is still running (pid=None → unknown, assume alive)."""
+ if pid is None:
+ return True
+ try:
+ os.kill(pid, 0)
+ return True
+ except OSError:
+ return False
+
+
+def _wait_for_server(base_url, timeout_s, server_pid=None):
+ """Block until the vLLM server's /health endpoint answers. If `server_pid` is given, a dead
+ server process aborts the wait immediately instead of burning the whole timeout."""
+ print(f"Waiting for vLLM server at {base_url} (timeout {timeout_s}s, pid={server_pid})...", flush=True)
+ deadline = time.monotonic() + timeout_s
+ while time.monotonic() < deadline:
+ try:
+ if httpx.get(f"{base_url}/health", timeout=5.0).status_code == 200:
+ print("vLLM server is up.")
+ return
+ except httpx.HTTPError:
+ pass
+ if not _server_alive(server_pid):
+ raise RuntimeError(
+ f"`vllm serve` (pid {server_pid}) exited before the server became healthy — "
+ "see the vllm serve log printed below."
+ )
+ time.sleep(5.0)
+ raise RuntimeError(
+ f"vLLM server at {base_url} did not become healthy within {timeout_s}s — "
+ "see the vllm serve log printed below."
+ )
+
+
+def main(args):
+ _wait_for_server(args.base_url, args.server_startup_timeout, args.server_pid)
+
+ print(f"Serving Voxtral TTS model {args.model_id} via `vllm serve --omni` (voice={args.voice})")
+ _report_param_count(args.model_id)
+
+ # Layout: results/<model_safe>/ MODEL_<safe>_DATASET_<dsid>.jsonl + <dsid>/output_<id>.wav
+ # where <dsid> = <dataset_safe>_<dataset>_<split>. Manifest paths are relative to model_dir so
+ # later stages resolve them wherever the folder is copied (local or HF bucket).
+ mode_suffix = ""
+ paths = output_paths(args, mode_suffix)
+ model_dir, dataset_dir_name = paths.model_dir, paths.dataset_dir_name
+
+ # One client with a connection pool sized for the concurrent minibatch.
+ client = httpx.Client(
+ base_url=args.base_url,
+ timeout=httpx.Timeout(args.request_timeout, connect=30.0),
+ limits=httpx.Limits(max_connections=args.batch_size, max_keepalive_connections=args.batch_size),
+ )
+
+ def build_payload(text):
+ """One /v1/audio/speech request body (model-card format, preset voice)."""
+ return {
+ "input": text,
+ "model": args.model_id,
+ "response_format": "wav",
+ "voice": args.voice,
+ }
+
+ def post_one(payload):
+ r = client.post("/v1/audio/speech", json=payload)
+ r.raise_for_status()
+ return r.content # encoded wav bytes
+
+ # Canonical RIFF/WAVE header length, skipped when timestamping the first audio chunk so an
+ # eagerly flushed header does not count as audio. Raw PCM has no header.
+ WAV_HEADER_BYTES = 44
+ VOXTRAL_SAMPLE_RATE = 24_000 # model card: 24 kHz mono
+
+ # Streaming dialects to try on /v1/audio/speech, most capable first (as in higgs/run_eval.py).
+ # vLLM-Omni streams only with stream=true AND response_format="pcm"; the last entry is the
+ # buffered request, so the probe still yields a whole-utterance number otherwise.
+ STREAM_MODES = ({"stream": True, "response_format": "pcm"}, {"stream": True}, {})
+ stream_mode = [None] # index into STREAM_MODES; pinned after the first request that works
+
+ def post_one_streaming(payload, path, early_stop=False):
+ """POST reading the body INCREMENTALLY: (bytes, first_audio_ts, n_chunks, content_type).
+
+ Used only by the TTFA probe; the batched (RTFx) path keeps the buffered `post_one`. The
+ dialect is negotiated once against STREAM_MODES and then pinned. (`/v1/audio/speech/stream`
+ is a WebSocket endpoint, not a POST route.) `first_audio_ts` is None when the body arrived
+ as a single chunk, so the probe falls back to the whole-utterance clock.
+ """
+ rejected = None
+ for index in range(stream_mode[0] or 0, len(STREAM_MODES)):
+ extra = STREAM_MODES[index]
+ first, total, n_chunks, parts = None, 0, 0, []
+ # Raw PCM carries no container header, so its very first byte is already audio.
+ skip_bytes = 0 if extra.get("response_format") == "pcm" else WAV_HEADER_BYTES
+ with client.stream("POST", path, json={**payload, **extra}) as r:
+ # A 4xx while the dialect is still unknown means this server build does not
+ # accept these fields: try the next one instead of failing the job.
+ if r.status_code >= 400 and stream_mode[0] is None and index + 1 < len(STREAM_MODES):
+ rejected = r.read()[:300]
+ print(f" [ttfa] server rejected {extra} ({r.status_code}): {rejected}\n"
+ f" trying {STREAM_MODES[index + 1]}", flush=True)
+ continue
+ r.raise_for_status()
+ content_type = r.headers.get("content-type", "")
+ if stream_mode[0] is None:
+ stream_mode[0] = index
+ print(f" [ttfa] streaming route: {path} {extra or 'none (buffered)'} "
+ f"-> {content_type}", flush=True)
+ for chunk in r.iter_bytes():
+ if not chunk:
+ continue
+ n_chunks += 1
+ total += len(chunk)
+ parts.append(chunk)
+ if first is None and total > skip_bytes:
+ first = time.perf_counter()
+ if early_stop:
+ # Leaving the `with` block closes the connection.
+ break
+ if n_chunks <= 1 and not early_stop:
+ first = None
+ return b"".join(parts), first, n_chunks, content_type
+ raise RuntimeError(f"No usable /v1/audio/speech streaming dialect (last rejection: {rejected})")
+
+ def _audio_seconds(blob):
+ """Duration of a response body; headerless PCM falls back to 24 kHz mono 16-bit."""
+ try:
+ info = sf.info(io.BytesIO(blob))
+ return info.frames / info.samplerate
+ except Exception:
+ return len(blob) / float(2 * VOXTRAL_SAMPLE_RATE)
+
+ def generate_tts(batch):
+ """Synthesize speech for a minibatch of target texts; time the batch generation for RTFx."""
+ texts_to_generate = list(batch[args.text_column])
+ minibatch_size = len(texts_to_generate)
+ payloads = [build_payload(t) for t in texts_to_generate]
+
+ # START TIMING (TTS batch generation). Wall clock: the GPU work happens in the server,
+ # with the whole minibatch in flight concurrently.
+ start = time.perf_counter()
+ with ThreadPoolExecutor(max_workers=minibatch_size) as pool:
+ wav_blobs = list(pool.map(post_one, payloads))
+ runtime = time.perf_counter() - start
+
+ # per-sample generation time (RTFx is aggregated over the whole set at scoring time)
+ batch["generation_time_s"] = minibatch_size * [runtime / minibatch_size]
+
+ gen_paths, audio_length_s = [], []
+ for blob, sample_id in zip(wav_blobs, batch["id"]):
+ # 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)
+ with open(path, "wb") as f:
+ f.write(blob) # server returns a complete wav; store as-is
+ info = sf.info(io.BytesIO(blob))
+ gen_paths.append(rel_path)
+ audio_length_s.append(info.frames / info.samplerate)
+
+ batch["gen_audio_filepath"] = gen_paths
+ batch["audio_length_s"] = audio_length_s
+ batch["references"] = list(batch[args.text_column]) # raw; normalized at scoring time
+ return batch
+
+ # Keep only `id` and the target text, so nothing triggers audio decoding.
+ dataset = load_tts_dataset(args)
+
+ probe_out_dir = model_dir # real results dir, captured before the probe rebinds model_dir
+ # ── TTFA probe: latency only, writing nothing but a JSON sidecar ─────────
+ # TTFA is per-request, so the probe sends one streaming request at a time and returns before
+ # the batched path; WER/RTFx runs never reach this branch.
+ # 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 only injected by submit_ttfa_jobs.sh.
+ from ttfa_probe import run_probe, sample_indices
+ stream_chunks = [] # per-sample chunk counts, reported in the sidecar
+
+ endpoints_used = []
+
+ def _gen(job, early_stop):
+ payload = build_payload(job[args.text_column][0])
+ blob, first, n_chunks, ctype = post_one_streaming(
+ payload, "/v1/audio/speech", early_stop)
+ stream_chunks.append(n_chunks)
+ endpoints_used.append(
+ f"/v1/audio/speech {STREAM_MODES[stream_mode[0] or 0]} [{ctype}]")
+ return _audio_seconds(blob), None, first
+
+ columns = dataset.column_names
+ jobs = [{c: [dataset[i][c]] for c in columns}
+ for i in sample_indices(args.ttfa_probe, len(dataset))]
+
+ run_probe(
+ _gen, jobs,
+ model_id=args.model_id, dataset_path=args.dataset_path,
+ dataset_config=args.dataset, split=args.split,
+ out_dir=probe_out_dir, mode_suffix=mode_suffix, n=args.ttfa_probe,
+ # No "device": this backend is an HTTP client; the GPU belongs to the server.
+ extra={"note": "driven at batch size 1, one request in flight",
+ "voice": args.voice,
+ # Chunks per response; 1 everywhere means the server buffered.
+ "response_chunks": stream_chunks,
+ "endpoints": endpoints_used},
+ )
+ return
+
+ manifest_path = paths.manifest_path
+ done_entries = load_done_entries(manifest_path, args.resume)
+ manifest_file = open_manifest(manifest_path, done_entries)
+
+ starts = pending_batches(dataset, args.batch_size, done_entries, dataset_dir_name)
+ warm_up(generate_tts, dataset, starts, args.batch_size, args.warmup_steps)
+
+ # ── Main loop: TTS → write JSONL, one batch at a time ───────────────────
+ for batch_start in tqdm(starts, desc="Generating"):
+ batch = generate_tts(dataset[batch_start : batch_start + args.batch_size])
+
+ # Append each sample to the JSONL immediately. `pred_text` is filled by stage 2 (ASR).
+ for afp, alen, gtime, ref in zip(
+ batch["gen_audio_filepath"], batch["audio_length_s"],
+ batch["generation_time_s"], batch["references"],
+ ):
+ write_entry(manifest_file, manifest_entry(afp, alen, gtime, ref))
+ manifest_file.flush()
+
+ manifest_file.close()
+ client.close()
+ print("Results saved at path:", os.path.abspath(manifest_path))
+ print_next_steps(False)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument(
+ "--model_id",
+ type=str,
+ default="mistralai/Voxtral-4B-TTS-2603",
+ help="Voxtral TTS model id, as served by `vllm serve <model_id> --omni`.",
+ )
+ parser.add_argument(
+ "--base_url",
+ type=str,
+ default="http://localhost:8000",
+ help="Base URL of the running `vllm serve --omni` server.",
+ )
+ parser.add_argument(
+ "--voice",
+ type=str,
+ default="casual_male",
+ help="Preset voice (casual_male, neutral_female, ...; 20 available).",
+ )
+ add_common_args(parser, batch_size=32)
+ parser.add_argument(
+ "--server_startup_timeout",
+ type=int,
+ default=3600,
+ help="Seconds to wait for the server's /health (first run includes the ~9 GB weight download).",
+ )
+ parser.add_argument(
+ "--server_pid",
+ type=int,
+ default=None,
+ help="PID of the backgrounded `vllm serve`; if it dies during startup the wait aborts at once.",
+ )
+ parser.add_argument(
+ "--request_timeout",
+ type=float,
+ default=600.0,
+ help="Per-request read timeout in seconds for /v1/audio/speech.",
+ )
+
+ 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/voxtral-tts/submit_jobs.sh b/voxtral-tts/submit_jobs.sh
new file mode 100644
index 0000000..f18f2ef
--- /dev/null
+++ b/voxtral-tts/submit_jobs.sh
@@ -0,0 +1,66 @@
+#!/bin/bash
+# HF Jobs TTS eval — Voxtral TTS backend (fixed voice: generate → transcribe → score; no SIM).
+# Runs locally; submits HF Jobs. Usage: HF_TOKEN=hf_... bash submit_jobs.sh ["mistralai/Voxtral-4B-TTS-2603 32" ...]
+# Shared orchestration (stages 2/3, injection, logging, scoring) lives in scripts/tts_jobs_common.sh.
+#
+# The Voxtral image is vLLM-Omni: stage 1 serves the model with `vllm serve <model> --omni` inside
+# the job and run_eval.py is an HTTP client of its /v1/audio/speech endpoint (it waits for /health
+# before generating). Voice cloning from prompt_audio is unsupported on the open checkpoint, so this
+# backend is fixed-voice (casual_male preset) → no SIM stage.
+source "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/scripts/tts_jobs_common.sh"
+
+# ── Backend config ───────────────────────────────────────────────────────────
+TTS_SPACE="${TTS_SPACE:-bezzam/evals-voxtral}" # stage-1 image (Dockerfile in the Space: https://huggingface.co/spaces/bezzam/evals-voxtral/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)"
+
+# ── Stage 1: serve with vLLM-Omni, then run the HTTP client. MODEL_CFG = "model_id batch_size". ──
+generate_stage() {
+ local _ BATCH_SIZE
+ read -r _ BATCH_SIZE <<< "${MODEL_CFG}"
+ 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/voxtral-tts
+ # The h200 driver is not older than the image's CUDA, so the forward-compat libcuda must
+ # stay off (with it, every engine stage dies at init with 'Error 803').
+ unset VLLM_ENABLE_CUDA_COMPATIBILITY
+ vllm serve ${MODEL_ID} --omni --port 8000 > /app/voxtral-tts/vllm_serve.log 2>&1 &
+ VLLM_PID=\$!
+ # --server_pid lets run_eval.py abort as soon as the server dies. On failure dump the
+ # whole serve log: the engine-core traceback is what explains the crash.
+ python run_eval.py \
+ --model_id=${MODEL_ID} \
+ --base_url=http://localhost:8000 \
+ --server_pid=\${VLLM_PID} \
+ --dataset_path=${DATASET_PATH} \
+ --dataset=${DATASET} \
+ --split=${SPLIT} \
+ --batch_size=${BATCH_SIZE} \
+ --max_eval_samples=${MAX_EVAL_SAMPLES} \
+ || { echo '--- vllm serve log (full) ---'; cat /app/voxtral-tts/vllm_serve.log; exit 1; }
+ 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}"
+ "zero_shot fr fr ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot es es ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot it it ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+ "zero_shot de de ${CV3_EVAL_PATH:-bezzam/cv3_eval}"
+)
+
+# ── Models: "model_id batch_size" (CLI args override) ────────────────────────
+MODEL_CONFIGS=(
+ "mistralai/Voxtral-4B-TTS-2603 32"
+)
+[[ $# -gt 0 ]] && MODEL_CONFIGS=("$@")
+
+run_pipeline