Skip to content

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

Python
35.1 KB
Raw Blame
#!/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 SUPPORTED_LANGUAGES (see "Datasets") and MODEL_CONFIGS (applying the CLI override)
#   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) → stage 4 (UTMOS, shared)
# → 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 (each dataset has its own 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 Seed-TTS / CV3 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 can name any repo.
DATASET_NAMESPACE="${DATASET_NAMESPACE:-hf-audio}"
# Seed-TTS repo; also the repo of a raw DATASET_CONFIGS line without a 4th field.
DEFAULT_DATASET_PATH="${DATASET_PATH:-${DATASET_NAMESPACE}/seed_tts_eval}"
# The other eval sets (registry under "Datasets" below).
CV3_EVAL_PATH="${CV3_EVAL_PATH:-${DATASET_NAMESPACE}/cv3_eval}"
# MiniMax is CC BY-SA 4.0, so everyone uses the one public copy (scripts/prepare_minimax_eval.py).
MINIMAX_EVAL_PATH="${MINIMAX_EVAL_PATH:-hf-audio/minimax_eval}"
# Neyshekar (Persian) is CC0, so everyone uses the one public copy (scripts/prepare_neyshekar_eval.py).
NEYSHEKAR_EVAL_PATH="${NEYSHEKAR_EVAL_PATH:-hf-audio/neyshekar_eval}"
# ZTTS2-Eval Mini (coreset panels of ZTTS2-Eval; Clean CC-BY-4.0, In-The-Wild CC-BY-NC-SA-4.0)
ZTTS2_EVAL_MINI_PATH="${ZTTS2_EVAL_MINI_PATH:-hf-audio/ztts2_eval_mini}"
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
KOMOS_FLAVOR="${KOMOS_FLAVOR:-l4x1}"         # optional Korean MOS stage
UTMOS_FLAVOR="${UTMOS_FLAVOR:-l4x1}"         # stage 4 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 datasets / languages (see "Datasets" below), e.g.
# ONLY_DATASETS="minimax" ONLY_LANGS="de fr". Datasets by registry name (seed_tts cv3 minimax neyshekar
# ztts2_mini_clean ztts2_mini_itw) or repo name (minimax_eval; ztts2_eval_mini covers both ZTTS2 panels).
# Empty (default) runs every dataset and supported language, except the opt-in ztts2_mini_itw (run it by
# naming it here).
ONLY_LANGS="${ONLY_LANGS:-}"
ONLY_DATASETS="${ONLY_DATASETS:-}"
# DRY_RUN=true: print the (model, dataset, split) combos a run would submit, and submit nothing.
DRY_RUN="${DRY_RUN:-false}"
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. Forced when `generate` runs: score_similarity.py carries
# prior sims over keyed on `audio_filepath` (to resume crashed runs), and regeneration reuses the same
# wav filenames, so the old SIM would otherwise silently be kept. Set it yourself only when re-scoring
# without `generate` (e.g. STAGES="sim" after a generate run that skipped SIM).
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}"
# Same for stage 4 (forced when `generate` runs).
UTMOS_OVERWRITE="${UTMOS_OVERWRITE:-false}"
# Languages (asr_language) that get stage 4; keep in sync with UTMOS_LANGUAGES in normalizer/eval_utils.py.
UTMOS_LANGS="${UTMOS_LANGS:-en}"
# Same for the optional `komos` stage, which only runs on Korean (ko) splits.
KOMOS_OVERWRITE="${KOMOS_OVERWRITE:-false}"
MAX_AUDIO_SECONDS="${MAX_AUDIO_SECONDS:-30}" # clip cap for ASR + SIM + UTMOS + KOMOS (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 utmos komos). 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 utmos".

# 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 ─────────────────────────────────────────────────────────────────
# A backend lists the languages its model speaks (SUPPORTED_LANGUAGES); run_pipeline expands every dataset
# into its splits from the registry below and keeps the splits in a supported language, so adding a
# dataset or a language never touches a backend.
#   SUPPORTED_LANGUAGES="en zh fr"           # default (empty): every language
#   DATASETS="seed_tts cv3 minimax"          # optional, to leave a whole dataset out (default: all but OPT_IN_DATASETS)
# Backends with per-model or per-mode rules override supports_language() (calling
# language_supported for the SUPPORTED_LANGUAGES check). A run can be narrowed further with ONLY_DATASETS
# (registry names, or the repo names) and ONLY_LANGS.
#
# Registry: dataset_repo <name> is the dataset repo; dataset_splits <name> its "config/split" entries. The
# split doubles as the language code (Qwen3-ASR hint for stage 2, and the TTS language for backends that
# take one); "config/split:lang" names the language when they differ. `case`, not associative arrays, so
# this runs on macOS bash 3.2. Escape hatch for a one-off set: append raw
# "config split asr_language [dataset_path]" lines to DATASET_CONFIGS before run_pipeline.
DATASET_NAMES="seed_tts cv3 minimax neyshekar ztts2_mini_clean ztts2_mini_itw"   # every dataset, in expansion order
dataset_repo() {
    case "$1" in
        seed_tts)   echo "${DEFAULT_DATASET_PATH}" ;;
        cv3)        echo "${CV3_EVAL_PATH}" ;;
        minimax)    echo "${MINIMAX_EVAL_PATH}" ;;
        neyshekar)  echo "${NEYSHEKAR_EVAL_PATH}" ;;
        ztts2_mini_clean|ztts2_mini_itw) echo "${ZTTS2_EVAL_MINI_PATH}" ;;
    esac
}
dataset_splits() {
    case "$1" in
        seed_tts)   printf 'tts/%s ' en zh ;;
        cv3)        printf 'zero_shot/%s ' en zh ja ko de fr es it ru ;;
        # MiniMax multilingual (100 sentences/language): every language but uk (Qwen3-ASR has no Ukrainian).
        minimax)    printf 'tts/%s ' en zh yue ja ko fr de es it pt ru nl pl cs ro el fi tr ar hi id th vi ;;
        neyshekar)  printf 'tts/%s ' fa ;;
        # ZTTS2-Eval Mini: one repo, two panels run (and reported) as separate datasets. Clean (FLEURS-R,
        # 35 splits) and In-The-Wild (VoxBlink2, 20 splits). Tagalog is `fil` for both (the ITW split is `tl`).
        ztts2_mini_clean) printf 'clean/%s ' en zh de es fr it ja ko ru pt ar hi tr pl id th fil nl vi cs sv da \
                              fi el hu ro uk nb he bg hr sk ca ms fa ;;
        ztts2_mini_itw)   printf 'in_the_wild/%s ' en zh de es fr it ja ko ru pt ar hi id tr tl:fil pl th nl uk vi ;;
    esac
}
# Opt-in datasets: wired in, but not run by default (not on the leaderboard yet); a run includes one only
# when ONLY_DATASETS names it (by registry name, or ztts2_eval_mini for both ZTTS2 panels), e.g.
# ONLY_DATASETS="ztts2_mini_itw".
OPT_IN_DATASETS="ztts2_mini_itw"
DATASETS=""
for _name in ${DATASET_NAMES}; do
    [[ " ${OPT_IN_DATASETS} " == *" ${_name} "* ]] || DATASETS+="${DATASETS:+ }${_name}"
done
unset _name
SUPPORTED_LANGUAGES=""
DATASET_CONFIGS=()

# expand_datasets → appends one "config split asr_language dataset_path name" line to DATASET_CONFIGS per split of
# every dataset in DATASETS (registry order), plus any opt-in dataset ONLY_DATASETS names. Language gating
# happens per model, in run_pipeline.
expand_datasets() {
    local name entry config split lang
    for name in ${DATASETS}; do
        [[ " ${DATASET_NAMES} " == *" ${name} "* ]] ||
            { echo "ERROR: unknown dataset '${name}' in DATASETS (known: ${DATASET_NAMES})." >&2; exit 1; }
    done
    for name in ${DATASET_NAMES}; do
        if [[ " ${DATASETS} " != *" ${name} "* ]]; then
            [[ " ${OPT_IN_DATASETS} " == *" ${name} "* ]] || continue
            [[ " ${ONLY_DATASETS} " == *" ${name} "* || " ${ONLY_DATASETS} " == *" $(basename "$(dataset_repo "${name}")") "* ]] || continue
        fi
        for entry in $(dataset_splits "${name}"); do
            config="${entry%%/*}"; split="${entry#*/}"; lang="${split#*:}"; split="${split%%:*}"
            DATASET_CONFIGS+=("${config} ${split} ${lang} $(dataset_repo "${name}") ${name}")
        done
    done
}

utmos_language() { [[ " ${UTMOS_LANGS} " == *" $1 "* ]]; }
# ZTTS2-Eval Mini lines are transcribed with ZTTS2-Eval's ASR choice (transcribe.py --asr_profile ztts2:
# Whisper-large-v3 / Qwen3-ASR routed per language); every other dataset keeps Qwen3-ASR.
asr_profile() { if [[ "${DATASET_PATH##*/}" == "ztts2_eval_mini" ]]; then echo ztts2; else echo leaderboard; fi; }
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}} &&'

# Snippet pinning Hub model downloads in the job (every stage): scripts/hf_pin/sitecustomize.py, first
# on PYTHONPATH, maps a download of a repo listed in model_revisions.json at `main` to its pinned
# commit and logs `[hf-pin] UNPINNED <repo>` for unlisted ones (HF_PIN_STRICT=true refuses them).
# Maintain the list with scripts/pin_revisions.py.
HF_PIN_STRICT="${HF_PIN_STRICT:-false}"
HF_PIN_INJECT="$(inject_cmd_gz "${REPO_ROOT}/scripts/hf_pin/sitecustomize.py" /app/hf_pin/sitecustomize.py) $(inject_cmd_gz "${REPO_ROOT}/model_revisions.json" /app/hf_pin/model_revisions.json) export HF_PIN_STRICT=${HF_PIN_STRICT} PYTHONPATH=/app/hf_pin\${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, with the Hub
# downloads pinned (HF_PIN_INJECT). Backends set RUN_EVAL_INJECT="$(inject_run_eval)".
inject_run_eval() {
    echo "${HF_PIN_INJECT}" \
         "$(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="${HF_PIN_INJECT} $(inject_cmd "${REPO_ROOT}/transformers/transcribe.py" /app/transformers/transcribe.py)"
SIM_INJECT="${HF_PIN_INJECT} $(inject_cmd "${REPO_ROOT}/transformers/score_similarity.py" /app/transformers/score_similarity.py)"
UTMOS_INJECT="${HF_PIN_INJECT} $(inject_cmd "${REPO_ROOT}/transformers/score_utmos.py" /app/transformers/score_utmos.py)"

KOMOS_INJECT="${HF_PIN_INJECT} $(inject_cmd "${REPO_ROOT}/transformers/score_komos.py" /app/transformers/score_komos.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: it is in SUPPORTED_LANGUAGES (empty = every language). 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.
language_supported() { [[ -z "${SUPPORTED_LANGUAGES// }" || " ${SUPPORTED_LANGUAGES} " == *" $1 "* ]]; }
supports_language() { language_supported "$1"; }

# ── 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")"   # Xs must be last: BSD/macOS mktemp keeps a ".log" suffix literal
    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
}

# ── Wait for stage-1 bucket uploads ─────────────────────────────────────────
# `hf jobs run` can return before the job's /results writes reach the bucket, so stage 2 would read
# a missing manifest or wavs. Poll until the manifest and every wav it lists are in the bucket.
BUCKET_WAIT_TIMEOUT="${BUCKET_WAIT_TIMEOUT:-900}"   # seconds

wait_for_bucket() {
    local rel="${BUCKET_MANIFEST#/results/}" deadline=$((SECONDS + BUCKET_WAIT_TIMEOUT)) want have
    while (( SECONDS < deadline )); do
        want=$(hf buckets cp "hf://buckets/${RESULTS_BUCKET}/${rel}" - 2>/dev/null |
            grep -oE '"(audio|prompt_audio)_filepath": "[^"]+"' | cut -d'"' -f4 | sort -u) || true
        if [[ -n "${want}" ]]; then
            have=$(hf buckets list "${RESULTS_BUCKET}/${MODEL_FOLDER}" -R 2>/dev/null |
                awk '{print $NF}' | sed "s|^${MODEL_FOLDER}/||" | sort -u) || true
            [[ -z "$(comm -23 <(echo "${want}") <(echo "${have}"))" ]] && return 0
        fi
        sleep 30
    done
    echo "── ${rel}: stage-1 outputs still not in the bucket after ${BUCKET_WAIT_TIMEOUT}s; giving up."
    return 1
}

# ── Wait for stage-2 transcripts before SIM ─────────────────────────────────
# SIM forks the manifest (pred_text included), and a transcribe job's in-place writes can reach the
# bucket after `hf jobs run` returns: a SIM job started then forks the untranscribed copy, which
# scores as 100% WER. Poll until the bucket manifest is transcribed, by the rule scoring uses
# (normalizer.eval_utils.untranscribed_fraction): stage 1 writes `"pred_text": ""` on every row and
# transcribe.py stamps each row it fills with `asr_model`; at most 20% empty, unstamped rows.
wait_for_transcripts() {
    local rel="${BUCKET_MANIFEST#/results/}" deadline=$((SECONDS + BUCKET_WAIT_TIMEOUT))
    while (( SECONDS < deadline )); do
        hf buckets cp "hf://buckets/${RESULTS_BUCKET}/${rel}" - 2>/dev/null | python3 -c '
import json, sys
rows = [json.loads(line) for line in sys.stdin if line.strip()]
missing = sum(1 for r in rows if not (r.get("pred_text") or "").strip() and "asr_model" not in r)
sys.exit(0 if rows and missing <= 0.2 * len(rows) else 1)' && return 0
        sleep 30
    done
    echo "── ${rel}: transcripts still not in the bucket after ${BUCKET_WAIT_TIMEOUT}s; giving up before SIM."
    return 1
}

# ── Shared stages 2-4 (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_profile=$(asr_profile)${ASR_OVERWRITE_FLAG}
        "
}
sim_stage() {
    local SIM_OVERWRITE_FLAG=""
    { [[ "${SIM_OVERWRITE}" == "true" ]] || stage_enabled generate; } && SIM_OVERWRITE_FLAG=" --overwrite"
    # In-job backstop for the bucket gate: the job's mount can still serve the untranscribed copy.
    local SIM_WAIT_FLAG=""
    stage_enabled transcribe && SIM_WAIT_FLAG=" --wait_for_transcripts=${BUCKET_WAIT_TIMEOUT}"
    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}${SIM_WAIT_FLAG}
        "
}
utmos_stage() {
    local UTMOS_OVERWRITE_FLAG=""
    { [[ "${UTMOS_OVERWRITE}" == "true" ]] || stage_enabled generate; } && UTMOS_OVERWRITE_FLAG=" --overwrite"
    hf jobs run \
        --flavor "${UTMOS_FLAVOR}" --timeout 4h --secrets HF_TOKEN ${NAMESPACE_ARG} \
        --volume "hf://buckets/${RESULTS_BUCKET}:/results" "${SCORER_IMAGE}" \
        bash -c "
            ${UTMOS_INJECT}
            python /app/transformers/score_utmos.py --manifest_paths ${BUCKET_MANIFEST} --max_audio_seconds=${MAX_AUDIO_SECONDS} --device=cuda:0${UTMOS_OVERWRITE_FLAG}
        "
}

# Separate job/environment: KOMOS requires Transformers 5 and must not change UTMOS/ASR deps.
komos_stage() {
    local KOMOS_OVERWRITE_FLAG=""
    { [[ "${KOMOS_OVERWRITE}" == "true" ]] || stage_enabled generate; } && KOMOS_OVERWRITE_FLAG=" --overwrite"
    hf jobs run \
        --flavor "${KOMOS_FLAVOR}" --timeout 4h --secrets HF_TOKEN ${NAMESPACE_ARG} \
        --volume "hf://buckets/${RESULTS_BUCKET}:/results" "${SCORER_IMAGE}" \
        bash -c "
            ${KOMOS_INJECT}
            python -m pip install uv &&
            uv venv --python python /tmp/komos-env &&
            uv pip install --python /tmp/komos-env/bin/python 'torch==2.8.0' --index-url https://download.pytorch.org/whl/cu128 &&
            uv pip install --python /tmp/komos-env/bin/python 'komos==0.0.2' &&
            /tmp/komos-env/bin/python /app/transformers/score_komos.py --manifest_paths ${BUCKET_MANIFEST} --max_rows=${MAX_EVAL_SAMPLES} --max_audio_seconds=${MAX_AUDIO_SECONDS} --device=cuda:0${KOMOS_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 i in "${!MANIFEST_NAMES[@]}"; do
            name="${MANIFEST_NAMES[$i]}"
            # -s, not -f: an interrupted download leaves a 0-byte file behind.
            [[ -s "./results/${MODEL_FOLDER}/${name}" ]] || missing+=("${name}")
            stage_enabled utmos && utmos_language "${LANGS[$i]}" && [[ ! -s "./results/${MODEL_FOLDER}/UTMOS_${name%.jsonl}.json" ]] &&
                missing+=("UTMOS_${name%.jsonl}.json")
            stage_enabled komos && [[ "${LANGS[$i]}" == ko ]] && [[ ! -s "./results/${MODEL_FOLDER}/KOMOS_${name%.jsonl}.json" ]] &&
                missing+=("KOMOS_${name%.jsonl}.json")
        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 utmos}}"   # 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}"
    expand_datasets

    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=()
        local -a UNSUPPORTED=()
        for cfg in "${DATASET_CONFIGS[@]}"; do
            local CFG_DATASET_PATH DATASET_NAME
            # DATASET_NAME: the registry name (5th field; empty for an ad-hoc DATASET_CONFIGS line).
            read -r DATASET SPLIT ASR_LANG CFG_DATASET_PATH DATASET_NAME <<< "$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_DATASETS: registry or repo names; ONLY_LANGS), skipped silently.
            if [[ -n "${ONLY_DATASETS}" && " ${ONLY_DATASETS} " != *" ${DATASET_PATH##*/} "* &&
                  ( -z "${DATASET_NAME}" || " ${ONLY_DATASETS} " != *" ${DATASET_NAME} "* ) ]]; then
                continue
            fi
            [[ -n "${ONLY_LANGS}" && " ${ONLY_LANGS} " != *" ${ASR_LANG} "* ]] && continue
            # 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
                [[ " ${UNSUPPORTED[*]} " == *" ${ASR_LANG} "* ]] || UNSUPPORTED+=("${ASR_LANG}")
                continue
            fi
            BUCKET_MANIFEST="/results/${MODEL_FOLDER}/MODEL_${MODEL_SAFE}_DATASET_${DATASET_SAFE}_${DATASET}_${SPLIT}${MODE_SUFFIX}.jsonl"
            if [[ "${DRY_RUN}" == "true" ]]; then
                echo "Would submit: ${DATASET_PATH##*/}/${DATASET}/${SPLIT}  (language ${ASR_LANG}) -> $(basename "${BUCKET_MANIFEST}")"
                continue
            fi
            # The dataset repo name is in the log name: Seed-TTS and MiniMax share the `tts` config and
            # split names, and their combos run in parallel.
            local CHAIN_LOG="${LOG_DIR}/${MODEL_SAFE}_${DATASET_PATH##*/}_${DATASET}_${SPLIT}${MODE_SUFFIX}.log"
            echo "Submitting pipeline: model=${MODEL_ID} dataset=${DATASET_PATH##*/}/${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 && wait_for_bucket
                stage_enabled transcribe && run_stage transcribe_stage
                # Not an `&&` list: under `set -e` a failing wait_for_transcripts must end the chain.
                if stage_enabled sim && [[ "${CLONE}" == "true" ]]; then
                    if stage_enabled transcribe; then wait_for_transcripts; fi
                    run_stage sim_stage
                fi
                stage_enabled utmos && utmos_language "${ASR_LANG}" && run_stage utmos_stage
                stage_enabled komos && [[ "${ASR_LANG}" == ko ]] && run_stage komos_stage
                true   # ensure subshell exit status is 0 when the last `&&` chain is a skipped stage
            ) > "${CHAIN_LOG}" 2>&1 &
            PIDS+=("$!"); TAGS+=("${DATASET_PATH##*/}/${DATASET}/${SPLIT}"); CHAIN_LOGS+=("${CHAIN_LOG}")
            LANGS+=("${ASR_LANG}"); MANIFEST_NAMES+=("$(basename "${BUCKET_MANIFEST}")")
        done
        [[ ${#UNSUPPORTED[@]} -gt 0 ]] && echo "Skipped the splits in languages ${MODEL_ID} does not support: ${UNSUPPORTED[*]}"
        if [[ "${DRY_RUN}" == "true" ]]; then
            echo "DRY_RUN=true: nothing submitted."
            continue
        fi

        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 || PIPELINE_FAILED=1   # keep going to the next model on failure
    done
    # Exit status for callers (e.g. scripts/schedule_runs.py): non-zero if any model's chains or
    # scoring failed, so a partly failed run is not recorded as done.
    return "${PIPELINE_FAILED:-0}"
}