Evaluation scripts for the Open TTS Leaderboard: https://huggingface.co/spaces/hf-audio/open_tts_leaderboard
Python
Phonon: voice cloning from precomputed reference voices (#25)
Dave9dd06fb9bfa0
diff --git a/phonon/run_eval.py b/phonon/run_eval.pyindex 3ac95c2..746208e 100644--- a/phonon/run_eval.py+++ b/phonon/run_eval.py@@ -2,7 +2,10 @@Follows paradee/run_eval.py's serial generation and common manifest conventions.Downloads a pinned public Q8 checkpoint, or accepts an existing local checkpoint.-CPU completion timing is diagnostic, not official H200 RTFx. No cloning/SIM.+CPU completion timing is diagnostic, not official H200 RTFx.+Voice cloning (`--voice_clone`) conditions each row on a precomputed voice file for its reference+clip: the speaker encoder is not part of the released checkpoints. The files are pinned like the+checkpoints, and each is checked against the SHA-256 of the clip it was computed from.The separate TTFA path measures 500 CV3 English requests on cpu-upgrade,using the blocking API by default or an explicitly selected streaming API."""@@ -21,6 +24,7 @@ import sysimport timeimport wavefrom pathlib import Path+from types import SimpleNamespacefrom run_eval_utils import (add_common_args,@@ -42,6 +46,11 @@ MODEL_REVISIONS = {"gradium/phonon-40m-es": "f0d2f39c9b58ad4c19a189e3ba989ee4df393cc5",}+# Voice cloning: voices/<SHA-256 of a reference clip>.safetensors holds that clip's speaker latents,+# and index.json maps "<dataset>/<config>/<split>" to {row id: SHA-256}.+CLONE_VOICES_REPO = "gradium/phonon-leaderboard-clone-voices"+CLONE_VOICES_REVISION = "371ec7081c59ca7a50b6c2bdf819409b74bd3e7a"+def file_hash(path):with open(path, "rb") as source:@@ -380,7 +389,27 @@ def run_ttfa(args, checkpoint, distribution, hashes, runtime_hashes, quality_rooreturn sidecar+def load_clone_voices(args):+ """This split's voice files and row index, downloaded at the pinned revision."""+ from huggingface_hub import hf_hub_download, snapshot_download++ revision = args.clone_voices_revision or CLONE_VOICES_REVISION+ if not revision or not re.fullmatch(r"[0-9a-f]{40}", revision):+ raise ValueError("Supply an immutable clone voices revision.")+ split = f"{args.dataset_path.split('/')[-1]}/{args.dataset}/{args.split}"+ index_path = hf_hub_download(args.clone_voices_repo, "index.json", repo_type="dataset", revision=revision)+ keys = json.loads(Path(index_path).read_text()).get(split)+ if not keys:+ raise ValueError(f"The clone voices have no rows for {split}.")+ root = snapshot_download(args.clone_voices_repo, repo_type="dataset", revision=revision,+ allow_patterns=[f"voices/{key}.safetensors" for key in sorted(set(keys.values()))])+ return SimpleNamespace(keys=keys, root=Path(root), provenance={+ "repo": args.clone_voices_repo, "revision": revision, "index_sha256": file_hash(index_path)})++def main(args):+ if args.voice_clone and (args.ttfa_probe or args.voice != "default"):+ raise ValueError("Voice cloning replaces the preset voice and has no TTFA path.")if args.device != "cpu" or args.split not in ("en", "fr", "de", "es"):raise ValueError("This q8_0 path supports English, French, German and Spanish on CPU only.")if args.ttfa_probe and args.split != "en":@@ -468,8 +497,9 @@ def main(args):for path in (output_root / "results", output_root / "results" / args.model_id.replace("/", "-")):if path.is_symlink():raise ValueError("Existing output directories must not be symlinks.")+ clone = load_clone_voices(args) if args.voice_clone else Noneos.chdir(output_root)- paths = output_paths(args)+ paths = output_paths(args, "_voice_clone" if clone else "")manifest_path = Path(paths.manifest_path)provenance_path = manifest_path.with_suffix(".run.json")attempt_path = manifest_path.with_suffix(".lock")@@ -486,6 +516,8 @@ def main(args):("voice", "temperature", "seed", "eos_threshold", "rewrites", "conditions", "threads")},"device": "cpu", "quant": "q8_0", "official_h200_rtfx": False,}+ if clone:+ provenance["clone_voices"] = clone.provenanceif manifest_path.exists() and not args.resume:raise FileExistsError("Existing manifest: inspect it before explicitly resuming.")if provenance_path.exists():@@ -508,7 +540,12 @@ def main(args):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))))- dataset = dataset.select_columns(["id", args.text_column])+ dataset = dataset.select_columns(["id", args.text_column] + (["prompt_audio"] if clone else []))+ if clone:+ from datasets import Audio++ # The reference clip's own bytes: hashed against its voice file, and kept for SIM.+ dataset = dataset.cast_column("prompt_audio", Audio(decode=False))if not len(dataset):raise ValueError("The selected dataset contains no samples.")done = load_done_entries(str(manifest_path), args.resume)@@ -516,7 +553,7 @@ def main(args):entries = [json.loads(line) for line in manifest_path.read_text().splitlines() if line.strip()]if len(entries) != len(done):raise ValueError("Existing manifest contains duplicate or invalid paths.")- rows = {}+ rows, prompts = {}, {}for row in dataset:sample_id, text = str(row["id"]), row[args.text_column]if "/" in sample_id or "\\" in sample_id or not isinstance(text, str) or not text.strip():@@ -525,6 +562,12 @@ def main(args):if relative in rows:raise ValueError("Dataset IDs must be unique.")rows[relative] = text+ if clone:+ clip = row["prompt_audio"]["bytes"]+ if not clip or clone.keys.get(sample_id) != hashlib.sha256(clip).hexdigest():+ raise ValueError(f"Row {sample_id}'s reference clip is not the one its voice was computed from.")+ prompts[relative] = (os.path.join(paths.dataset_dir_name, "prompts", f"prompt_{sample_id}.wav"),+ clip, clone.keys[sample_id])if not set(done) <= set(rows):raise ValueError("Existing manifest differs from the selected dataset rows.")for relative, entry in done.items():@@ -544,10 +587,21 @@ def main(args):attempt.write(str(os.getpid()))tts = load_tts(args, checkpoint, distribution, mimi["sample_rate"])-- def synth_one(text):+ registered = set()++ def voice_for(relative):+ """The preset voice, or this row's reference voice (registered on first use, untimed)."""+ if not clone:+ return args.voice+ key = prompts[relative][2]+ if key not in registered:+ tts.add_voice(key, str(clone.root / "voices" / f"{key}.safetensors"))+ registered.add(key)+ return key++ def synth_one(text, voice):start = time.perf_counter()- audio = tts.synth(text, voice=args.voice, temperature=args.temperature,+ audio = tts.synth(text, voice=voice, temperature=args.temperature,seed=args.seed, cfg_coef=None)elapsed = time.perf_counter() - startif not math.isfinite(elapsed) or elapsed <= 0:@@ -556,13 +610,19 @@ def main(args):# Repeat the first text for untimed warmups; continuation reuses prior warmups.for _ in range(0 if done else args.warmup_steps):- synth_one(pending[0][1])+ synth_one(pending[0][1], voice_for(pending[0][0]))with open_manifest(str(manifest_path), done) as manifest:for relative, text in pending:- audio, elapsed = synth_one(text) # raw text, including brackets/whitespace+ audio, elapsed = synth_one(text, voice_for(relative)) # raw text, including brackets/whitespacetarget = Path(paths.model_dir) / relativeduration = write_audio(target, audio, tts.sample_rate)- entry = manifest_entry(relative, duration, elapsed, text)+ prompt_path = None+ if clone:+ # SIM compares the output with this reference clip, written unchanged.+ prompt_path, clip, _ = prompts[relative]+ (Path(paths.model_dir) / prompt_path).parent.mkdir(exist_ok=True)+ (Path(paths.model_dir) / prompt_path).write_bytes(clip)+ entry = manifest_entry(relative, duration, elapsed, text, prompt_audio_filepath=prompt_path)entry.update(device="cpu", cpu_generation_time_s=elapsed, official_h200_rtfx=False,timing_scope="generation_complete", audio_sha256=file_hash(target))write_entry(manifest, entry)@@ -570,7 +630,7 @@ def main(args):os.fsync(manifest.fileno())attempt_path.unlink()print("Stage 1 complete; CPU timing is diagnostic, not official H200 RTFx.")- print_next_steps(voice_clone=False)+ print_next_steps(voice_clone=bool(clone))if __name__ == "__main__":@@ -592,6 +652,8 @@ if __name__ == "__main__":parser.add_argument("--ttfa_mode", choices=("blocking", "streaming"), default="blocking",help="TTFA API path; streaming measures first chunks through ptts.TTS.stream.")parser.add_argument("--ttfa_text_sha256", help="Optional expected ordered CV3 ID/raw-text SHA256.")- add_common_args(parser)+ parser.add_argument("--clone_voices_repo", default=CLONE_VOICES_REPO, help="Dataset repo of reference voice files.")+ parser.add_argument("--clone_voices_revision", help="Immutable commit of it; defaults to the evaluated one.")+ add_common_args(parser, voice_clone=False)parser.set_defaults(device="cpu", dataset_path=None, seed=4242424242424242)main(parser.parse_args())diff --git a/phonon/submit_jobs.sh b/phonon/submit_jobs.shindex 63698d4..86a2155 100644--- a/phonon/submit_jobs.sh+++ b/phonon/submit_jobs.sh@@ -1,12 +1,13 @@#!/bin/bash-# English, French, German and Spanish, fixed voice. Usage: bash phonon/submit_jobs.sh [model_id ...]+# English, French, German and Spanish, fixed voice or, with VOICE_CLONE=true, voice cloning.+# Usage: bash phonon/submit_jobs.sh [model_id ...]set -euo pipefailsource "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/scripts/tts_jobs_common.sh"TTS_SPACE="${PHONON_SPACE:-Steveeeeeeen/evals-phonon-040}"RUN_EVAL_INJECT="$(inject_run_eval)"-DEFAULT_STAGES="generate transcribe utmos"-SUPPORTS_VOICE_CLONE=false+DEFAULT_STAGES="generate transcribe sim utmos" # sim runs only when cloning+SUPPORTS_VOICE_CLONE=trueSTAGE_RETRIES=0# Exception to the shared h200 gen flavor: the Q8 ptts runtime is CPU-only (no GPU path), so an# h200 would sit idle. Its RTFx is therefore a CPU number, not directly comparable with the h200 models.@@ -20,8 +21,9 @@ generate_stage() {[[ "$DATASET" != zero_shot ]] || revision="${PHONON_CV3_DATASET_REVISION:-}"local args=(--model_id "$MODEL_ID" --dataset_path "$DATASET_PATH"--dataset "$DATASET" --split "$SPLIT" --device cpu --threads "$PHONON_THREADS"- --warmup_steps 2 --max_eval_samples "$MAX_EVAL_SAMPLES")+ --warmup_steps 2 --max_eval_samples "$MAX_EVAL_SAMPLES" "$VOICE_CLONE_FLAG")[[ -z "$revision" ]] || args+=(--dataset_revision "$revision")+ [[ -z "${PHONON_CLONE_VOICES_REVISION:-}" ]] || args+=(--clone_voices_revision "$PHONON_CLONE_VOICES_REVISION")printf -v runner '%q ' python3 /app/phonon/run_eval.py "${args[@]}"command="set -euo pipefail${RUN_EVAL_INJECT} true || exit 1@@ -29,7 +31,7 @@ generate_stage() {${runner} --output_root /tmp/phononmkdir -p '/results/${MODEL_FOLDER}'source_model=/tmp/phonon/results/${MODEL_SAFE}- cp -r \"\$source_model/${DATASET_SAFE}_${DATASET}_${SPLIT}\" '/results/${MODEL_FOLDER}/'+ cp -r \"\$source_model/${DATASET_SAFE}_${DATASET}_${SPLIT}${MODE_SUFFIX}\" '/results/${MODEL_FOLDER}/'cp \"\$source_model/$(basename "${BUCKET_MANIFEST%.jsonl}.run.json")\" '${BUCKET_MANIFEST%.jsonl}.run.json'cp \"\$source_model/$(basename "$BUCKET_MANIFEST")\" '${BUCKET_MANIFEST}'"@@ -59,17 +61,15 @@ for value in "$TTS_SPACE" "$RESULTS_BUCKET" "$DEFAULT_DATASET_PATH" "$CV3_EVAL_P[[ "$value" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || fail "Use namespace/name resources."done[[ "$PHONON_THREADS" =~ ^[1-8]$ ]] || fail "Use 1–8 CPU threads."-[[ "$VOICE_CLONE" == false ]] || fail "Voice cloning is unsupported."for model in "${MODEL_CONFIGS[@]}"; docase "$model" ingradium/phonon-31m-en|gradium/phonon-40m-en|gradium/phonon-40m-fr|gradium/phonon-40m-de|gradium/phonon-40m-es) ;;*) fail "Select a released checkpoint." ;;esacdone-case "${STAGES:-$DEFAULT_STAGES}" in- generate|"generate transcribe"|"generate transcribe utmos"|transcribe|utmos|"transcribe utmos") ;;- *) fail "Supported stages: generate, 'generate transcribe', 'generate transcribe utmos', transcribe, utmos, or 'transcribe utmos'." ;;-esac+# Any in-order subset of the four stages.+[[ " ${STAGES:-$DEFAULT_STAGES} " =~ ^\ (generate\ )?(transcribe\ )?(sim\ )?(utmos\ )?$ ]] \+ && [[ -n "${STAGES:-$DEFAULT_STAGES}" ]] || fail "Use an in-order subset of: generate transcribe sim utmos."run_pipelinestatus=0