Evaluation scripts for the Open TTS Leaderboard: https://huggingface.co/spaces/hf-audio/open_tts_leaderboard
Python
Add Phonon 31M and 40M English TTS evaluation (#16)
Steven Zheng14d1bb410694
diff --git a/phonon/run_eval.py b/phonon/run_eval.pynew file mode 100644index 0000000..d4df8fd--- /dev/null+++ b/phonon/run_eval.py@@ -0,0 +1,592 @@+"""Fixed-preset Phonon stage 1, using the released ptts 0.4.0 API.++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.+The separate TTFA path measures 500 CV3 English requests on cpu-upgrade,+using the blocking API by default or an explicitly selected streaming API.+"""++import argparse+import array+import hashlib+import importlib.metadata+import json+import math+import os+import platform+import re+import struct+import sys+import time+import wave+from pathlib import Path++from run_eval_utils import (+ add_common_args,+ load_done_entries,+ manifest_entry,+ open_manifest,+ output_paths,+ print_next_steps,+ wav_rel_path,+ write_entry,+)+++MODEL_REVISIONS = {+ "gradium/phonon-31m-en": "52433c46975bfa13144c56204c9f4ee1c5b148aa",+ "gradium/phonon-40m-en": "9b95393286eaeeebf1330b2ae90a14a2074c415d",+}+++def file_hash(path):+ with open(path, "rb") as source:+ return hashlib.file_digest(source, "sha256").hexdigest()+++def write_audio(path, audio, sample_rate):+ """Match the evaluated rc1 path's mono PCM16 conversion, outside the timer."""+ view = memoryview(audio)+ if (view.ndim, view.itemsize, view.format) not in ((1, 4, "f"), (1, 4, "=f")):+ raise ValueError("Expected mono float32 audio.")+ if not len(view) or any(not math.isfinite(value) for value in view):+ raise ValueError("Expected nonempty, finite audio.")+ pcm = array.array("h", (round(max(-1.0, min(1.0, value)) * 32767) for value in view))+ if sys.byteorder != "little":+ pcm.byteswap()+ with open(path, "xb") as target, wave.open(target, "wb") as output:+ output.setnchannels(1)+ output.setsampwidth(2)+ output.setframerate(sample_rate)+ output.writeframes(pcm.tobytes())+ return len(view) / sample_rate+++def check_cpu_isa():+ """The Linux x86-64 wheel requires v3 instructions before native import."""+ if platform.system() != "Linux" or platform.machine().lower() not in ("x86_64", "amd64"):+ return+ try:+ cpuinfo = Path("/proc/cpuinfo").read_text()+ except OSError as error:+ raise ValueError("Cannot verify the x86-64-v3 CPU required by the Linux wheel.") from error+ rows = [set(line.split(":", 1)[1].split()) for line in cpuinfo.splitlines()+ if ":" in line and line.split(":", 1)[0].strip() == "flags"]+ flags = set.intersection(*rows) if rows else set()+ required = {"cx16", "lahf_lm", "popcnt", "pni", "ssse3", "sse4_1", "sse4_2",+ "avx", "avx2", "bmi1", "bmi2", "f16c", "fma", "movbe", "xsave"}+ if not required.issubset(flags) or not {"abm", "lzcnt"}.intersection(flags):+ raise ValueError("The Linux ptts wheel requires x86-64-v3 CPU instructions.")+++def gguf_tensor_elements(path):+ """Count stored logical tensor elements (parameters and buffers) from GGUF v3.++ Quantized storage bytes do not change this dimension-product count. It is not+ a count of unique or trainable parameters and excludes external voice assets.+ Read only bounded metadata/descriptors, stopping before the tensor payload.+ """+ with open(path, "rb", buffering=0) as source:+ def read(size):+ if size < 0 or source.tell() + size > 16 * 1024 * 1024:+ raise ValueError("GGUF header exceeds the bounded metadata size.")+ value = source.read(size)+ if len(value) != size:+ raise ValueError("Truncated GGUF header.")+ return value++ def integer(code):+ return struct.unpack("<" + code, read(struct.calcsize("<" + code)))[0]++ def string(limit=1024 * 1024):+ size = integer("Q")+ if size > limit:+ raise ValueError("GGUF string exceeds the bounded metadata size.")+ return read(size).decode("utf-8")++ def skip_value(kind, depth=0):+ if depth > 8:+ raise ValueError("GGUF metadata nesting exceeds the supported depth.")+ sizes = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4,+ 7: 1, 10: 8, 11: 8, 12: 8}+ if kind in sizes:+ value = read(sizes[kind])+ if kind == 7 and value not in (b"\x00", b"\x01"):+ raise ValueError("Invalid GGUF boolean metadata.")+ elif kind == 8:+ string()+ elif kind == 9:+ item_kind, count = integer("I"), integer("Q")+ if item_kind not in range(13) or count > 1_000_000:+ raise ValueError("Invalid or oversized GGUF metadata array.")+ for _ in range(count):+ skip_value(item_kind, depth + 1)+ else:+ raise ValueError("Unsupported GGUF metadata type.")++ if read(4) != b"GGUF" or integer("I") != 3:+ raise ValueError("Expected a little-endian GGUF v3 checkpoint.")+ tensors, metadata = integer("Q"), integer("Q")+ if not 1 <= tensors <= 100_000 or metadata > 100_000:+ raise ValueError("Invalid or oversized GGUF header counts.")+ keys = set()+ for _ in range(metadata):+ key = string(65535)+ if not key or key in keys:+ raise ValueError("Empty or duplicate GGUF metadata key.")+ keys.add(key)+ skip_value(integer("I"))+ names, total = set(), 0+ for _ in range(tensors):+ name, rank = string(1024), integer("I")+ if not name or name in names or not 1 <= rank <= 4:+ raise ValueError("Invalid or duplicate GGUF tensor descriptor.")+ names.add(name)+ dimensions = [integer("Q") for _ in range(rank)]+ if any(not 1 <= value <= 2**32 for value in dimensions):+ raise ValueError("Invalid GGUF tensor dimension.")+ elements = math.prod(dimensions)+ total += elements+ if total > 2**63 - 1:+ raise ValueError("GGUF tensor element count exceeds the supported bound.")+ integer("I") # Quantization type affects bytes, not logical dimensions.+ integer("Q") # Payload offset; no tensor payload is read.+ return total, tensors+++def load_tts(args, checkpoint, distribution, sample_rate, *, verify_native=False):+ check_cpu_isa()+ elements, tensors = gguf_tensor_elements(checkpoint / "model.q8.gguf")+ print(f"TTS model size: {elements / 1e6:.2f}M parameters and buffers "+ f"({elements:,} elements in {tensors:,} GGUF tensors)")+ import ptts++ if (getattr(ptts, "__version__", None) != "0.4.0"+ or Path(ptts.__file__).resolve() != Path(distribution.locate_file("ptts/__init__.py")).resolve()):+ raise ValueError("Imported ptts differs from the recorded 0.4.0 runtime.")+ if verify_native:+ native = sys.modules.get("ptts._ptts")+ native_paths = {+ Path(distribution.locate_file(name)).resolve()+ for name in distribution.files or ()+ if name.parts[0] == "ptts" and name.suffix in (".so", ".pyd")+ }+ if (native is None or not getattr(native, "__file__", None)+ or Path(native.__file__).resolve() not in native_paths):+ raise ValueError("Loaded ptts native module differs from the recorded runtime.")+ ptts.set_num_threads(args.threads)+ if ptts.get_num_threads() != args.threads:+ raise ValueError("Runtime did not retain the requested thread count.")+ tts = ptts.TTS(model=str(checkpoint), device="cpu", quant="q8_0", voice=args.voice,+ temperature=args.temperature, seed=args.seed, cfg_coef=None,+ eos_threshold=args.eos_threshold, lang=args.split, rewrites=args.rewrites,+ conditions=args.conditions)+ if (tts.device, tts.quant, tts.sample_rate) != ("cpu", "q8_0", sample_rate):+ raise ValueError("Loaded runtime differs from the requested CPU/checkpoint settings.")+ return tts+++def validate_ttfa(payload, provenance, probe):+ """A completed, matching sidecar is reusable without another synthesis request."""+ streaming_mode = provenance["protocol"]["blocking"] is False+ full_rows = 50 if streaming_mode else 500+ expected = {+ "model_id": provenance["model_id"], "dataset_path": provenance["dataset"]["dataset_path"],+ "dataset": "zero_shot", "split": "en",+ "mode_suffix": "",+ "batch_size": 1, "n_samples": 500, "warmup_excluded": 3,+ "full_generation_rows": full_rows - 3, "early_stopped_rows": 500 - full_rows,+ "phonon_provenance": provenance,+ }+ if any(payload.get(key) != value for key, value in expected.items()):+ raise ValueError("Existing TTFA sidecar has different inputs or protocol.")+ rows = payload.get("samples", [])+ if len(rows) != 500:+ raise ValueError("TTFA requires all 500 completed measurements.")+ for index, row in enumerate(rows):+ full = index < full_rows+ if (row.get("index") != index or row.get("full_generation") is not full+ or row.get("first_reported") is not streaming_mode+ or any(not isinstance(row.get(key), (int, float))+ or isinstance(row[key], bool)+ or not math.isfinite(row[key]) or row[key] <= 0+ for key in ("ttfa_ms", "gen_s", "audio_s"))+ or row["ttfa_ms"] > row["gen_s"] * 1000 + 1e-6):+ raise ValueError("TTFA sidecar contains an incomplete or invalid measurement.")+ fraction = row["ttfa_ms"] / (row["gen_s"] * 1000)+ recorded = row.get("ttfa_frac_of_gen")+ if ((full and (not isinstance(recorded, (int, float))+ or isinstance(recorded, bool) or not math.isfinite(recorded)+ or not math.isclose(recorded, fraction)))+ or (not full and recorded is not None)+ or (not streaming_mode and not math.isclose(fraction, 1.0))):+ raise ValueError("TTFA sidecar first-audio fractions differ from its measured rows.")+ warm = rows[3:]+ warm_full = [row for row in warm if row["full_generation"]]+ fractions = sorted(row["ttfa_frac_of_gen"] for row in warm_full)+ median = fractions[len(fractions) // 2]+ streaming = streaming_mode and median < probe.STREAMING_MAX_FRAC+ if (payload.get("ttfa_ms") != probe._summary([row["ttfa_ms"] for row in warm])+ or payload.get("gen_s") != probe._summary([row["gen_s"] for row in warm_full])+ or payload.get("streaming") is not streaming+ or payload.get("ttfa_frac_of_gen") != round(median, 3)+ or payload.get("first_reported_but_not_early") is not (streaming_mode and not streaming)+ or payload.get("rtfx_batch1") != round(+ sum(row["audio_s"] for row in warm_full) / sum(row["gen_s"] for row in warm_full), 2)):+ raise ValueError("TTFA sidecar summaries differ from its measured rows.")+++def run_ttfa(args, checkpoint, distribution, hashes, runtime_hashes, quality_root):+ """One selected API path; no quality outputs, extra warmups, uploads or scoring."""+ import ttfa_probe as probe++ mode = getattr(args, "ttfa_mode", "blocking")+ if mode not in ("blocking", "streaming"):+ raise ValueError("Select blocking or streaming TTFA explicitly.")+ streaming_mode = mode == "streaming"+ if streaming_mode and (probe.FULL_GEN_SAMPLES != 50 or probe.WARMUP_DISCARD != 3):+ raise ValueError("Streaming TTFA requires the shared 50-full, three-discard protocol.")+ suffix = "__ptts-stream__cpu-upgrade" if streaming_mode else "__cpu-upgrade"+ if not getattr(args, "ttfa_output_root", None):+ raise ValueError("Supply a distinct private --ttfa_output_root.")+ output_root = Path(args.ttfa_output_root).expanduser().resolve()+ if any((parent / ".git").exists() for parent in (output_root, *output_root.parents)):+ raise ValueError("Keep TTFA output outside every Git checkout.")+ for other in (checkpoint, quality_root):+ if output_root == other or other in output_root.parents or output_root in other.parents:+ raise ValueError("TTFA, checkpoint and quality output roots must be separate.")+ if not any(Path(name).suffix in (".so", ".pyd") for name in runtime_hashes):+ raise ValueError("TTFA requires a recorded ptts native-library hash.")+ os.umask(0o077)+ output_root.mkdir(parents=True, exist_ok=True, mode=0o700)+ if output_root.stat().st_mode & 0o077:+ raise ValueError("Private TTFA output root must have mode 0700.")+ model_safe = args.model_id.replace("/", "-")+ output = output_root / "results" / model_safe+ for path in (output.parent, output):+ if path.is_symlink() or not path.resolve().is_relative_to(output_root):+ raise ValueError("TTFA paths must remain inside the private output root.")+ output.mkdir(parents=True, exist_ok=True, mode=0o700)+ sidecar = output / probe.probe_filename(+ model_safe, args.dataset_path.replace("/", "-"), "zero_shot", "en", suffix,+ )+ provenance_path, lock = sidecar.with_suffix(".run.json"), sidecar.with_suffix(".lock")+ for path in (sidecar, provenance_path, lock):+ if path.is_symlink() or not path.resolve().is_relative_to(output_root):+ raise ValueError("TTFA files must remain inside the private output root.")++ from datasets import load_dataset++ dataset = load_dataset(args.dataset_path, name="zero_shot", split="en", revision=args.dataset_revision)+ if len(dataset) != 500:+ raise ValueError("The full pinned CV3 English split must contain exactly 500 rows.")+ if "id" not in dataset.column_names:+ dataset = dataset.add_column("id", list(range(len(dataset))))+ dataset = dataset.select_columns(["id", args.text_column])+ inventory = [{"id": str(row["id"]), "text": row[args.text_column]} for row in dataset]+ if (len({row["id"] for row in inventory}) != 500+ or any(not isinstance(row["text"], str) or not row["text"].strip() for row in inventory)):+ raise ValueError("CV3 must contain unique IDs and nonempty raw target text.")+ text_hash = hashlib.sha256(json.dumps(+ inventory, ensure_ascii=False, separators=(",", ":"), sort_keys=True,+ ).encode()).hexdigest()+ expected_text_hash = getattr(args, "ttfa_text_sha256", None)+ if expected_text_hash and expected_text_hash != text_hash:+ raise ValueError("CV3 raw ID/text inventory differs from its expected SHA256.")+ provenance = {+ "model_id": args.model_id, "checkpoint_files_sha256": hashes,+ "runtime_version": distribution.version, "runtime_files_sha256": runtime_hashes,+ "python_version": sys.version, "runner_sha256": file_hash(Path(__file__).resolve()),+ "shared_probe_sha256": file_hash(Path(probe.__file__).resolve()),+ "shared_helpers_sha256": file_hash(Path(manifest_entry.__code__.co_filename).resolve()),+ "dataset": {key: getattr(args, key) for key in+ ("dataset_path", "dataset_revision", "dataset", "split", "text_column")},+ "ordered_id_text_sha256": text_hash,+ "settings": {key: getattr(args, key) for key in+ ("voice", "temperature", "seed", "eos_threshold", "rewrites", "conditions", "threads")},+ "thread_pools": {key: os.environ.get(key) for key in+ ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS")},+ "device": "cpu", "flavor": "cpu-upgrade", "quant": "q8_0", "sample_rate": 24000,+ "protocol": {"samples": 500, "batch_size": 1, "warmup_excluded": 3,+ "additional_warmup_calls": 0, "blocking": not streaming_mode},+ "official_h200_rtfx": False,+ }+ if streaming_mode:+ provenance["protocol"].update(streaming_api="ptts.TTS.stream", full_generation_samples=50)+ if sidecar.exists():+ if not provenance_path.exists() or json.loads(provenance_path.read_text()) != provenance:+ raise ValueError("Completed TTFA provenance differs from this request.")+ validate_ttfa(json.loads(sidecar.read_text()), provenance, probe)+ print(f"Reusing completed TTFA measurements: {sidecar}")+ return sidecar+ if lock.exists() or provenance_path.exists():+ raise FileExistsError("Earlier TTFA attempt is incomplete or uncertain; inspect it before any retry.")+ with lock.open("x") as attempt:+ attempt.write(str(os.getpid()))+ with provenance_path.open("x") as target:+ json.dump(provenance, target, indent=2, sort_keys=True)+ tts = load_tts(args, checkpoint, distribution, 24000, verify_native=True)++ def generate(job):+ audio = tts.synth(job["text"], voice=args.voice, temperature=args.temperature,+ seed=args.seed, cfg_coef=None)+ view = memoryview(audio)+ if ((view.ndim, view.itemsize, view.format) not in ((1, 4, "f"), (1, 4, "=f"))+ or not len(view)):+ raise ValueError("Expected completed mono float32 audio.")+ # The worker's smoke checks finite samples; do not scan audio inside the TTFA clock.+ return audio, 24000, None++ def generate_stream(job, early_stop):+ samples, first = 0, None+ with tts.stream(job["text"], voice=args.voice, temperature=args.temperature,+ seed=args.seed, cfg_coef=None) as stream:+ if stream.sample_rate != 24000:+ raise ValueError("Expected 24 kHz streaming audio.")+ for chunk in stream:+ view = memoryview(chunk)+ if (view.ndim, view.itemsize, view.format) not in ((1, 4, "f"), (1, 4, "=f")):+ raise ValueError("Expected mono float32 streaming chunks.")+ if not len(view):+ continue+ if first is None:+ first = time.perf_counter()+ samples += len(view)+ if early_stop:+ break+ if first is None:+ raise ValueError("Streaming generation returned no audio.")+ # Count samples without concatenating or scanning PCM within the clock.+ return samples / 24000, 24000, first++ payload = probe.run_probe(+ generate_stream if streaming_mode else generate, inventory,+ model_id=args.model_id, dataset_path=args.dataset_path,+ dataset_config="zero_shot", split="en", out_dir=str(output), n=500,+ mode_suffix=suffix,+ # Hardware/engine tags belong to the filename; the publication script uses+ # mode_suffix only for a model variant or voice-clone mode.+ extra={"mode_suffix": "", "device": "cpu", "flavor": "cpu-upgrade",+ "phonon_provenance": provenance},+ )+ validate_ttfa(payload, provenance, probe)+ with sidecar.open("rb") as target:+ os.fsync(target.fileno())+ lock.unlink()+ return sidecar+++def main(args):+ if args.device != "cpu" or args.split != "en":+ raise ValueError("This q8_0 path supports English CPU only; A100/CUDA TTFA is unavailable.")+ if getattr(args, "ttfa_mode", "blocking") not in ("blocking", "streaming"):+ raise ValueError("Select blocking or streaming TTFA explicitly.")+ if args.ttfa_probe and (getattr(args, "ttfa_flavor", "cpu-upgrade") != "cpu-upgrade"+ or args.ttfa_probe not in (-1, 500) or args.dataset != "zero_shot"+ or args.max_eval_samples not in (None, -1, 500)):+ raise ValueError("TTFA requires cpu-upgrade and all 500 CV3 zero_shot/en samples.")+ if args.threads < 1 or args.warmup_steps < 0 or not 0 <= args.seed < 2**64:+ raise ValueError("Invalid thread, warmup or seed setting.")+ if not all(math.isfinite(v) and v >= 0 for v in (args.temperature, args.eos_threshold)):+ raise ValueError("Temperature and EOS threshold must be finite and nonnegative.")+ for value in (args.model_id, args.dataset_path):+ if (not value or not re.fullmatch(r"[\w.-]+/[\w.-]+", value)+ or any(part in (".", "..") for part in value.split("/"))):+ raise ValueError("Use namespace/name model labels and Hub datasets.")+ if Path(args.dataset_path).exists():+ raise ValueError("Local datasets cannot satisfy an immutable Hub revision pin.")+ if args.dataset not in ("tts", "zero_shot") or not re.fullmatch(r"[\w-]+", args.voice):+ raise ValueError("Select a standard dataset configuration and an explicit preset name.")++ if not args.dataset_revision:+ from huggingface_hub import HfApi++ args.dataset_revision = HfApi().dataset_info(args.dataset_path).sha+ if not re.fullmatch(r"[0-9a-f]{40}", args.dataset_revision):+ raise ValueError("Supply the full immutable dataset revision.")+ if not args.checkpoint_path:+ from huggingface_hub import snapshot_download++ revision = getattr(args, "model_revision", None) or MODEL_REVISIONS.get(args.model_id)+ if not revision or not re.fullmatch(r"[0-9a-f]{40}", revision):+ raise ValueError("Supply an immutable model revision for an unlisted checkpoint.")+ args.checkpoint_path = snapshot_download(+ args.model_id, revision=revision,+ allow_patterns=["config.json", "tokenizer.json", "model.q8.gguf",+ "default-voice.safetensors", "voices/*.safetensors"],+ )+ checkpoint = Path(args.checkpoint_path).expanduser().resolve(strict=True)+ if not checkpoint.is_dir():+ raise ValueError("Checkpoint must be an existing local directory.")+ voice_file = "default-voice.safetensors" if args.voice == "default" else f"voices/{args.voice}.safetensors"+ names = ("config.json", "tokenizer.json", "model.q8.gguf", voice_file)+ hashes = {name: file_hash(checkpoint / name) for name in names}+ config = json.loads((checkpoint / "config.json").read_text())+ mimi = config["mimi"]+ if mimi["channels"] != 1 or mimi["sample_rate"] != 24000 or config["lsd_decode_steps"] != 1:+ raise ValueError("Expected the mono 24 kHz, one-decode-step checkpoint layout.")+ conditions = {row["name"]: row for row in config["conditioners"]}+ if set(args.conditions) != set(conditions):+ raise ValueError("Conditions must match the checkpoint's declared names.")+ for name, value in args.conditions.items():+ condition = conditions[name]+ if condition["type"] == "lut":+ valid = value in condition["lut"]["possible_values"]+ elif condition["type"] == "continuous":+ valid = isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)+ else:+ valid = False+ if not valid:+ raise ValueError("Conditions must match the checkpoint's declared values.")+ distribution = importlib.metadata.distribution("ptts")+ if distribution.version != "0.4.0":+ raise ValueError("Install the compatible ptts 0.4.0 runtime separately.")+ runtime_hashes = {+ str(name): file_hash(distribution.locate_file(name))+ for name in distribution.files or ()+ if name.parts[0] == "ptts" and name.suffix in (".py", ".pyi", ".so", ".pyd")+ }++ output_root = Path(args.output_root).expanduser().resolve()+ if any((parent / ".git").exists() for parent in (output_root, *output_root.parents)):+ raise ValueError("Keep private output outside every Git checkout.")+ if (output_root == checkpoint or checkpoint in output_root.parents+ or output_root in checkpoint.parents):+ raise ValueError("Output must be separate from the checkpoint.")+ if args.ttfa_probe:+ return run_ttfa(args, checkpoint, distribution, hashes, runtime_hashes, output_root)+ os.umask(0o077)+ output_root.mkdir(parents=True, exist_ok=True, mode=0o700)+ if output_root.stat().st_mode & 0o077:+ raise ValueError("Private output root must have mode 0700.")+ 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.")+ os.chdir(output_root)+ paths = output_paths(args)+ manifest_path = Path(paths.manifest_path)+ provenance_path = manifest_path.with_suffix(".run.json")+ attempt_path = manifest_path.with_suffix(".lock")+ for path in (Path(paths.model_dir), Path(paths.output_dir), manifest_path, provenance_path, attempt_path):+ if path.is_symlink() or not path.resolve().is_relative_to(output_root):+ raise ValueError("Output paths must stay inside the private output root.")+ provenance = {+ "model_id": args.model_id, "checkpoint_files_sha256": hashes,+ "runtime_version": distribution.version, "runtime_files_sha256": runtime_hashes,+ "runner_sha256": file_hash(Path(__file__).resolve()),+ "dataset": {key: getattr(args, key) for key in+ ("dataset_path", "dataset_revision", "dataset", "split", "text_column")},+ "settings": {key: getattr(args, key) for key in+ ("voice", "temperature", "seed", "eos_threshold", "rewrites", "conditions", "threads")},+ "device": "cpu", "quant": "q8_0", "official_h200_rtfx": False,+ }+ if manifest_path.exists() and not args.resume:+ raise FileExistsError("Existing manifest: inspect it before explicitly resuming.")+ if provenance_path.exists():+ if json.loads(provenance_path.read_text()) != provenance:+ raise ValueError("Existing output has different generation inputs.")+ elif manifest_path.exists():+ raise ValueError("Cannot resume a manifest without matching provenance.")+ else:+ with provenance_path.open("x") as output:+ json.dump(provenance, output, indent=2, sort_keys=True)++ # The common loader currently omits revision; keep this one pinned load inline.+ from datasets import load_dataset++ if Path(args.dataset_path).exists():+ raise ValueError("Local datasets cannot satisfy an immutable Hub revision pin.")+ dataset = load_dataset(args.dataset_path, name=args.dataset, split=args.split,+ revision=args.dataset_revision)+ if args.max_eval_samples is not None and args.max_eval_samples > 0:+ 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])+ if not len(dataset):+ raise ValueError("The selected dataset contains no samples.")+ done = load_done_entries(str(manifest_path), args.resume)+ if manifest_path.exists():+ 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 = {}+ 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():+ raise ValueError("Expected safe sample IDs and nonempty raw text.")+ relative = wav_rel_path(paths.dataset_dir_name, sample_id)+ if relative in rows:+ raise ValueError("Dataset IDs must be unique.")+ rows[relative] = text+ if not set(done) <= set(rows):+ raise ValueError("Existing manifest differs from the selected dataset rows.")+ for relative, entry in done.items():+ if entry["text"] != rows[relative] or file_hash(Path(paths.model_dir) / relative) != entry["audio_sha256"]:+ raise ValueError("Resume reference or audio differs from the completed entry.")+ pending = [(relative, text) for relative, text in rows.items() if relative not in done]+ if any((Path(paths.model_dir) / relative).exists() for relative, _ in pending):+ raise FileExistsError("Unrecorded WAV exists; inspect the interrupted attempt before resuming.")+ if attempt_path.exists():+ raise FileExistsError("An earlier attempt is active or uncertain; inspect its lock before resuming.")+ if not pending:+ print("All selected samples are already complete; no model loaded.")+ return++ # Exclusive admission; failures retain this marker for explicit inspection.+ with attempt_path.open("x") as attempt:+ attempt.write(str(os.getpid()))++ tts = load_tts(args, checkpoint, distribution, mimi["sample_rate"])++ def synth_one(text):+ start = time.perf_counter()+ audio = tts.synth(text, voice=args.voice, temperature=args.temperature,+ seed=args.seed, cfg_coef=None)+ elapsed = time.perf_counter() - start+ if not math.isfinite(elapsed) or elapsed <= 0:+ raise ValueError("Expected positive, finite generation time.")+ return audio, elapsed++ # 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])+ with open_manifest(str(manifest_path), done) as manifest:+ for relative, text in pending:+ audio, elapsed = synth_one(text) # raw text, including brackets/whitespace+ target = Path(paths.model_dir) / relative+ duration = write_audio(target, audio, tts.sample_rate)+ entry = manifest_entry(relative, duration, elapsed, text)+ 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)+ manifest.flush()+ 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)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--model_id", required=True, help="Public model repository, also used as the output label.")+ parser.add_argument("--model_revision", help="Immutable model commit; defaults to the evaluated release.")+ parser.add_argument("--checkpoint_path", help="Optional existing local q8 checkpoint directory.")+ parser.add_argument("--voice", default="default", help="Bundled default voice, or a local preset name.")+ parser.add_argument("--output_root", required=True, help="Private directory outside Git; results/ is created within it.")+ parser.add_argument("--dataset_revision", help="Immutable dataset commit; resolves current Hub revision if omitted.")+ parser.add_argument("--temperature", type=float, default=0.3)+ parser.add_argument("--eos_threshold", type=float, default=4.0)+ parser.add_argument("--conditions", type=json.loads, default={"num_speakers": "1", "duration_delta": 0.0})+ parser.add_argument("--rewrites", choices=("default", "all", "none"), default="default")+ parser.add_argument("--threads", type=int, default=1)+ parser.add_argument("--ttfa_output_root", help="Separate private root for TTFA sidecars only.")+ parser.add_argument("--ttfa_flavor", choices=("cpu-upgrade", "a100"), default="cpu-upgrade",+ help="Only cpu-upgrade is supported by this local q8_0 path.")+ 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.set_defaults(device="cpu", dataset_path=None, seed=4242424242424242)+ main(parser.parse_args())diff --git a/phonon/submit_jobs.sh b/phonon/submit_jobs.shnew file mode 100644index 0000000..162ae48--- /dev/null+++ b/phonon/submit_jobs.sh@@ -0,0 +1,72 @@+#!/bin/bash+# English, fixed voice. Usage: bash phonon/submit_jobs.sh [model_id ...]+set -euo pipefail+source "$(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+STAGE_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.+FLAVOR=cpu-upgrade+PHONON_THREADS="${PHONON_THREADS:-1}"+supports_language() { [[ "$1" == en ]]; }++generate_stage() {+ local revision="${PHONON_SEED_DATASET_REVISION:-}" runner command+ [[ "$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")+ [[ -z "$revision" ]] || args+=(--dataset_revision "$revision")+ printf -v runner '%q ' python3 /app/phonon/run_eval.py "${args[@]}"+ command="set -euo pipefail+ ${RUN_EVAL_INJECT} true || exit 1+ umask 077+ for existing in '${BUCKET_MANIFEST}' '${BUCKET_MANIFEST%.jsonl}.run.json' \+ '/results/${MODEL_FOLDER}/${DATASET_SAFE}_${DATASET}_${SPLIT}'; do+ test ! -e \"\$existing\" || { echo 'Quality artifacts already exist; inspect before rerunning.' >&2; exit 1; }+ done+ work_dir=\$(mktemp -d /tmp/phonon-quality.XXXXXXXX)+ ${runner} --output_root \"\$work_dir\"+ mkdir -p '/results/${MODEL_FOLDER}'+ source_model=\"\$work_dir/results/${MODEL_SAFE}\"+ cp -r \"\$source_model/${DATASET_SAFE}_${DATASET}_${SPLIT}\" '/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}'+ "+ local -a job=(hf jobs run --flavor "$FLAVOR" --timeout 2h --secrets HF_TOKEN)+ [[ -z "$ORG_NAME" ]] || job+=(--namespace "$ORG_NAME")+ "${job[@]}" --volume "hf://buckets/${RESULTS_BUCKET}:/results" "$TTS_IMAGE" bash -c "$command"+}++DATASET_CONFIGS=(+ "tts en en"+ "zero_shot en en ${CV3_EVAL_PATH}"+)+MODEL_CONFIGS=(+ "gradium/phonon-31m-en"+ "gradium/phonon-40m-en"+)+[[ $# -eq 0 ]] || MODEL_CONFIGS=("$@")++fail() { echo "Phonon: $*" >&2; exit 1; }+for value in "$TTS_SPACE" "$RESULTS_BUCKET" "$DEFAULT_DATASET_PATH" "$CV3_EVAL_PATH"; do+ [[ "$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[@]}"; do+ [[ "$model" == gradium/phonon-31m-en || "$model" == gradium/phonon-40m-en ]] || fail "Select a released English checkpoint."+done+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++run_pipeline+status=0+for pid in "${PIDS[@]}"; do wait "$pid" || status=1; done+exit "$status"diff --git a/scripts/open_results_pr.py b/scripts/open_results_pr.pyindex 516d1ab..cb0b339 100644--- a/scripts/open_results_pr.py+++ b/scripts/open_results_pr.py@@ -14,6 +14,9 @@ Files written (all in that dataset repo):cv3_voice_clone.csv CV3-Eval, cloning each prompt (WER, RTFx, SIM, UTMOS + averages)streaming.csv time-to-first-audio, CPU and GPU (TTFA, RTFx at batch 1)+Every file but model_info.csv also has a free-text `Note` column, filled by --note (e.g. hardware+caveats); a results file gets the column the first time a note is published to it.+Nothing is pushed unless --open_pr is passed: the default is a dry run that prints the rows.Usage:@@ -37,6 +40,10 @@ Usage:--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+ # a note on every file the run writes (here: RTFx/TTFA measured on CPU, not H200)+ python scripts/open_results_pr.py --model_id gradium/phonon-31m-en \+ --note "Evaluated on CPU (cpu-upgrade): RTFx is not comparable with H200" --open_pr+# re-use results already synced locally (e.g. by submit_jobs.sh)python scripts/open_results_pr.py --model_id openbmb/VoxCPM2 --skip_sync"""@@ -119,9 +126,10 @@ TTFA_PREFIX = "TTFA_"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"]+# Free-text column of every published file but model_info.csv (--note).+NOTE_COLUMN = "Note"# 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)"@@ -456,6 +464,19 @@ def add_utmos_columns(published, languages):header = header + [f"{lang} UTMOS" for lang in languages if lang in UTMOS_COLUMN_LANGUAGES]if any(column.startswith("avg ") for column in header):header.append("avg UTMOS")+ return extend_header(published, header)+++def add_note_column(published):+ """Append the `Note` column to a header without one."""+ if NOTE_COLUMN in published.header:+ return published+ return extend_header(published, published.header + [NOTE_COLUMN])+++def extend_header(published, header):+ """The file rewritten under the longer `header`, every row padded with blanks. A whole-file+ rewrite, so only done the first time a file gets the new columns."""buffer = io.StringIO(newline="")writer = csv.writer(buffer, lineterminator=published.eol or "\n")writer.writerow(header)@@ -595,7 +616,8 @@ def main():parser.add_argument("--note",default=None,- help=f"{STREAMING_FILE} 'Note' column. Omitted leaves it as published; '' clears it.",+ help=f"'Note' column of every file written but {MODEL_INFO_FILE} (added to a results file "+ "that has none yet). Omitted leaves it as published; '' clears it.",)parser.add_argument("--bucket", default=RESULTS_BUCKET, help="Override the source bucket.")parser.add_argument(@@ -755,8 +777,14 @@ def main():continueif any(column.endswith(" UTMOS") for column in values):published = add_utmos_columns(published, languages)- header = published.header- action, index, new_row = upsert(published, row_name, values, {})+ # An empty --note only clears an existing note; it never adds the column.+ extra = {}+ if args.note:+ published = add_note_column(published)+ if args.note is not None and NOTE_COLUMN in published.header:+ extra[NOTE_COLUMN] = args.note+ header = published.header+ action, index, new_row = upsert(published, row_name, values, extra)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)@@ -769,7 +797,7 @@ def main():if args.model_size_b is not None:extra[STREAMING_SIZE_COLUMN] = args.model_size_bif args.note is not None:- extra[STREAMING_NOTE_COLUMN] = args.note+ extra[NOTE_COLUMN] = args.noteaction, 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)diff --git a/submit_ttfa_jobs.sh b/submit_ttfa_jobs.shindex 38c6c4b..6cc9b8a 100755--- a/submit_ttfa_jobs.sh+++ b/submit_ttfa_jobs.sh@@ -82,6 +82,21 @@ esac# backend's own submit_jobs.sh passes cuda:0, so match that.[[ "${TTFA_DEVICE}" == "cuda" ]] && TTFA_DEVICE="cuda:0"+# Phonon is CPU-only and opt-in; keep it out of the default GPU target list.+PHONON_SELECTED=false+for selected in "$@"; do+ case "$selected" in+ phonon|phonon-31m-en|phonon-40m-en|gradium/phonon-31m-en|gradium/phonon-40m-en) PHONON_SELECTED=true ;;+ esac+done+PHONON_TTFA_MODE="${PHONON_TTFA_MODE:-streaming}"+if ${PHONON_SELECTED}; then+ [[ "$TTFA_DEVICE:$FLAVOR:$TTFA_DATASET:$TTFA_SPLIT:$TTFA_LANG:$VOICE_CLONE" == cpu:cpu-upgrade:zero_shot:en:en:false \+ && ( "$TTFA_SAMPLES" == -1 || "$TTFA_SAMPLES" == 500 ) ]] || {+ echo "Phonon requires CPU/cpu-upgrade, all 500 CV3 English samples, and no voice cloning." >&2; exit 1;+ }+fi+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}"@@ -187,9 +202,40 @@ TTFA_TARGETS=("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}")+if ${PHONON_SELECTED}; then+ TTFA_TARGETS+=(+ "phonon-31m-en|phonon|${PHONON_SPACE:-Steveeeeeeen/evals-phonon-040}|gradium/phonon-31m-en||"+ "phonon-40m-en|phonon|${PHONON_SPACE:-Steveeeeeeen/evals-phonon-040}|gradium/phonon-40m-en||"+ )+fi# 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 paradee photon qwen3tts qwen3tts-fast supertonic vibevoice_realtime voxtral-tts"+NO_CLONE_FLAG="inflect-nano inflect-v2 kokoro lfm2-audio magpie-tts paradee phonon photon qwen3tts qwen3tts-fast supertonic vibevoice_realtime voxtral-tts"++# run_eval.py writes to its own output roots (outside Git, mode 0700) and names the sidecar itself,+# so Phonon skips the generic run/rename/copy below; `preamble` is submit_one's CPU thread cap.+submit_phonon() {+ local model_id="$1" space="$2" inject="$3" preamble="$4" model_safe="${1//\//-}" dataset_safe="${TTFA_DATASET_PATH//\//-}"+ local engine="" runner+ [[ "$PHONON_TTFA_MODE" != streaming ]] || engine="__ptts-stream"+ local filename="TTFA_MODEL_${model_safe}_DATASET_${dataset_safe}_zero_shot_en${engine}__cpu-upgrade.json"+ local args=(--model_id "$model_id" --dataset_path "$TTFA_DATASET_PATH"+ --dataset zero_shot --split en --device cpu --ttfa_probe 500 --ttfa_flavor cpu-upgrade+ --ttfa_mode "$PHONON_TTFA_MODE" --max_eval_samples -1 --warmup_steps 0)+ [[ -z "${TTFA_DATASET_REVISION:-}" ]] || args+=(--dataset_revision "$TTFA_DATASET_REVISION")+ printf -v runner '%q ' python /app/phonon/run_eval.py "${args[@]}"+ local command="set -euo pipefail+ ${inject}+ ${TTFA_INJECT} true || exit 1+ ${preamble}+ ${runner} --threads \"\${_cpuq}\" --output_root /tmp/phonon/quality --ttfa_output_root /tmp/phonon/ttfa+ mkdir -p '/results/${model_safe}'+ cp '/tmp/phonon/ttfa/results/${model_safe}/${filename}' '/results/${model_safe}/'+ "+ local -a job=(hf jobs run --flavor cpu-upgrade --timeout 1h --secrets HF_TOKEN)+ [[ -z "$ORG_NAME" ]] || job+=(--namespace "$ORG_NAME")+ "${job[@]}" --volume "hf://buckets/${RESULTS_BUCKET}:/results" "hf.co/spaces/${space}" bash -c "$command"+}submit_one() {local backend="$1" space="$2" model_id="$3" extra="$4" engine="$5"@@ -239,6 +285,11 @@ submit_one() {fifi+ if [[ "${backend}" == phonon ]]; then+ submit_phonon "${model_id}" "${space}" "${inject}" "${preamble}"+ return+ fi+case "${backend}" infishaudio-drama-3)# Explicit TTFA_FLAVOR / TTFA_DEVICE=cpu: the FP8 experts need sm_89+ (Triton rejects fp8e4nv on A100).