Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Commit ·
a65ea12
1
Parent(s): 57e0d5a
custom eval update
Browse filesFiles changed (7)
- app.py+38-14
- backends/custom_eval.pyAdded+96
- backends/universal.py+10-1
- evaluation/orchestrator.py+45-4
- job_queue.py+18-1
- remote_jobs.py+7-21
- scripts/run_hf_remote_job_uv.py+11-1
177 unmodified lines17817918018118218342 unmodified lines226227228229230231232233234235236237238239240241242243180 unmodified lines42442542642742842943043143243343443543671 unmodified lines508509510511512513514177 unmodified linesif not on_hub:return styled_error(f"Model '{model_id}' {err_msg}")try:job_id, position, err, awaiting_mod = job_queue.enqueue(model_id,42 unmodified linesreturn styled_warning(err)if awaiting_mod:return styled_message(f"Request <code>{job_id}</code> recorded for <strong>{model_id}</strong>. "f"<strong>A moderator must approve</strong> it before evaluation starts "f"(see the <strong>Moderate</strong> tab). "f"Approx. backlog awaiting approval: <strong>{position}</strong>.")return styled_message(f"Queued job <code>{job_id}</code> for <strong>{model_id}</strong>. "f"Approx. position in queue: <strong>{position}</strong>. "f"Evaluation runs in the background; refresh the <strong>Leaderboard</strong> tab "f"after a few minutes to see WER when the job finishes.")180 unmodified linesmax_length=8000,)script_input = gr.Code(label="Optional custom uv-run script (only run if a moderator approves it)",language="python",lines=12,)gr.Markdown("Custom scripts are **not** executed on this Space. They are stored with your submission ""and run on a Hub Job **only** after a moderator explicitly approves using that script.")with gr.Row():is_gated_input = gr.Checkbox(label="This is a gated repo", value=False)71 unmodified linesvalue=None,)mod_run_custom_script = gr.Checkbox(label="Run submitter's custom script on approval (if provided)",value=False,)with gr.Row():177 unmodified lines17817918018118218318418518618718818919019119242 unmodified lines235236237238239240241242243244245246247248249250251252253254255256257258180 unmodified lines43944044144244344444544644744844945045145245345445545645745845946071 unmodified lines532533534535536537538177 unmodified linesif not on_hub:return styled_error(f"Model '{model_id}' {err_msg}")script_hint = ""if (custom_script or "").strip():if not job_queue.custom_script_defines_evaluate(custom_script):script_hint = ("<p style='color:orange'><strong>Note:</strong> Your custom script should define ""<code>evaluate(file: pathlib.Path) -> str</code> at the top level. ""It will be called once per sample during evaluation.</p>")try:job_id, position, err, awaiting_mod = job_queue.enqueue(model_id,42 unmodified linesreturn styled_warning(err)if awaiting_mod:return (script_hint+ styled_message(f"Request <code>{job_id}</code> recorded for <strong>{model_id}</strong>. "f"<strong>A moderator must approve</strong> it before evaluation starts "f"(see the <strong>Moderate</strong> tab). "f"Approx. backlog awaiting approval: <strong>{position}</strong>."))return (script_hint+ styled_message(f"Queued job <code>{job_id}</code> for <strong>{model_id}</strong>. "f"Approx. position in queue: <strong>{position}</strong>. "f"Evaluation runs in the background; refresh the <strong>Leaderboard</strong> tab "f"after a few minutes to see WER when the job finishes."))180 unmodified linesmax_length=8000,)script_input = gr.Code(label="Optional custom evaluator (Python)",language="python",lines=12,)gr.Markdown("Define a function that transcribes one WAV file:\n\n""```python\n""from pathlib import Path\n\n""def evaluate(file: Path) -> str:\n"" # return the transcription for this audio file\n"" ...\n""```\n\n""It is called **once per audio sample** inside the existing eval loop. ""Put any extra Python dependencies in the requirements box above. ""Custom evaluators are **not** run on this Space; they run on a Hub Job ""**only** after a moderator approves them.")with gr.Row():is_gated_input = gr.Checkbox(label="This is a gated repo", value=False)71 unmodified linesvalue=None,)mod_run_custom_script = gr.Checkbox(label="Use submitter's custom evaluate() function (if provided)",value=False,)with gr.Row():
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Load a user-submitted custom evaluator script and wrap it as a transcriber callable.
The script must define::
from pathlib import Path def evaluate(file: Path) -> str: ...
Each packed benchmark sample is written to a temporary WAV file and passed to``evaluate`` once per sample inside the existing eval loop."""
from __future__ import annotations
import importlib.utilimport osimport shutilimport tempfilefrom collections.abc import Callablefrom pathlib import Path
def build_transcriber_from_custom_script( script_text: str,) -> tuple[Callable[..., str], Callable[[], None]]: """ Load ``script_text`` as a module and return ``(transcribe, cleanup)``.
``transcribe(audio_np, sampling_rate)`` writes a temp WAV and calls ``evaluate(path)`` on the loaded module. """ import soundfile as sf
script_text = (script_text or "").strip() if not script_text: raise RuntimeError("Custom script is empty.")
fd, script_path = tempfile.mkstemp(prefix="ffasr_custom_eval_", suffix=".py") try: with os.fdopen(fd, "w", encoding="utf-8") as f: f.write(script_text) except Exception: try: os.unlink(script_path) except FileNotFoundError: pass raise
spec = importlib.util.spec_from_file_location("ffasr_user_eval", script_path) if spec is None or spec.loader is None: try: os.unlink(script_path) except FileNotFoundError: pass raise RuntimeError("Could not load custom evaluator script.")
mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod)
evaluate_fn = getattr(mod, "evaluate", None) if not callable(evaluate_fn): try: os.unlink(script_path) except FileNotFoundError: pass raise RuntimeError( "Custom script must define `evaluate(file: pathlib.Path) -> str`." )
wav_dir = tempfile.mkdtemp(prefix="ffasr_custom_wav_") counter = {"i": 0}
def transcribe(audio_np, sampling_rate: int) -> str: counter["i"] += 1 wav_path = Path(wav_dir) / f"sample_{counter['i']:08d}.wav" sf.write(str(wav_path), audio_np, int(sampling_rate), subtype="PCM_16") try: text = evaluate_fn(wav_path) finally: try: wav_path.unlink() except FileNotFoundError: pass return str(text or "")
transcribe._num_params = 0 # type: ignore[attr-defined]
def cleanup() -> None: shutil.rmtree(wav_dir, ignore_errors=True) try: os.unlink(script_path) except FileNotFoundError: pass
return transcribe, cleanup229 unmodified lines2302312322332342354 unmodified lines240241242243244245246229 unmodified linesreturn batchdef _generate(model, batch: dict, max_new_tokens: int, language: str):"""Try language-aware generate first (Whisper path); fall back to plain generate."""batch = _normalize_input_features_layout(model, batch)4 unmodified lines# Cohere's remote generate() path can leave decoder_attention_mask as None,# then HF generation tries `decoder_attention_mask.new_ones(...)` and crashes.# Passing an explicit one-token decoder mask keeps generation state valid.src = batch.get("input_features") or batch.get("input_values")if src is not None and hasattr(src, "shape"):try:batch = dict(batch)229 unmodified lines2302312322332342352362372382392402412422432444 unmodified lines249250251252253254255229 unmodified linesreturn batchdef _encoder_tensor_from_batch(batch: dict):"""Return encoder inputs without using ``or`` on tensors (ambiguous bool)."""if batch.get("input_features") is not None:return batch["input_features"]if batch.get("input_values") is not None:return batch["input_values"]return Nonedef _generate(model, batch: dict, max_new_tokens: int, language: str):"""Try language-aware generate first (Whisper path); fall back to plain generate."""batch = _normalize_input_features_layout(model, batch)4 unmodified lines# Cohere's remote generate() path can leave decoder_attention_mask as None,# then HF generation tries `decoder_attention_mask.new_ones(...)` and crashes.# Passing an explicit one-token decoder mask keeps generation state valid.src = _encoder_tensor_from_batch(batch)if src is not None and hasattr(src, "shape"):try:batch = dict(batch)
56 unmodified lines5758596061621 unmodified line64656667686970717217 unmodified lines90919293949513 unmodified lines10911011111211311411555 unmodified lines17117217317417517647 unmodified lines22422522622722822940 unmodified lines27027127227327427551 unmodified lines32732832933033133250 unmodified lines38338438538638738821 unmodified lines4104114124134144157 unmodified lines4234244254264274284294302 unmodified lines4334344354364374384392 unmodified lines44244344444556 unmodified linesreturn max(0, v)def _zerogpu_run_segment(payload: dict[str, Any]) -> dict[str, Any]:"""Single ZeroGPU segment: build model, transcribe ``[start:end)`` for one condition."""model_id = str(payload["model_id"])1 unmodified linecondition_key = str(payload["condition_key"])start = int(payload["start"])end = int(payload["end"])device_str, device_int = resolve_eval_devices()transcribe, cleanup = build_transcriber(family_id, model_id, device_str, device_int)try:num_params = int(getattr(transcribe, "_num_params", 0) or 0)preds, refs, audio_s, infer_s, n_done = accumulate_predictions_for_slice(17 unmodified linesmodel_id: str,family_id: str = "auto",progress_cb: Callable[[int, int, str], None] | None = None,) -> dict:device_str, device_int = resolve_eval_devices()13 unmodified linesexcept Exception:passtranscribe, cleanup = build_transcriber(family_id, model_id, device_str, device_int)try:# Backends attach `transcribe._num_params` via `_model_utils.attach_params`; defaults to 0# if the backend couldn't introspect a module.55 unmodified linesprogress_cb: Callable[[int, int, str], None] | None = None,*,segment_samples: int,) -> dict:"""Same semantics as ``_run_evaluation_core_segmented`` but without ``spaces.GPU``:47 unmodified lines"condition_key": condition_key,"start": start,"end": end,}out = _zerogpu_run_segment(payload)if first_num_params is None:40 unmodified linessegment_samples: int,gpu_duration_s: int,gpu_size: str,) -> dict:"""Long evaluations: each slice of ``segment_samples`` runs under its own ``spaces.GPU``51 unmodified lines"condition_key": condition_key,"start": start,"end": end,}out = wrapped_seg(payload)if first_num_params is None:50 unmodified linesmodel_id: str,family_id: str = "auto",progress_cb: Callable[[int, int, str], None] | None = None,) -> dict:"""Evaluate `model_id` on all packed conditions using the selected family backend.21 unmodified lines``progress_cb(samples_done_across_all_conditions, samples_total_across_all_conditions, current_condition_key)``periodically during the run.Returns wer_clean, wer_noisy, wer_reverberant, wer_real, wer_difficult, num_samples, model_id, eval_family, plus timing."""apply_cpu_thread_settings_once()7 unmodified linesfamily_id=family_id,progress_cb=progress_cb,segment_samples=seg,)return _run_evaluation_core(model_id, family_id=family_id, progress_cb=progress_cb)eff = _effective_gpu_duration_s()size = os.environ.get("FFASR_ZEROGPU_GPU_SIZE", "large").strip().lower()2 unmodified linesif seg <= 0:wrapped = _spaces_gpu_wrapped(eff, size)return wrapped(model_id, family_id=family_id, progress_cb=progress_cb)return _run_evaluation_core_segmented(model_id,2 unmodified linessegment_samples=seg,gpu_duration_s=eff,gpu_size=size,)56 unmodified lines5758596061626364656667686970717273747576771 unmodified line79808182838485868788899017 unmodified lines10810911011111211311413 unmodified lines12812913013113213313413513655 unmodified lines19219319419519619719847 unmodified lines24624724824925025125240 unmodified lines29329429529629729829951 unmodified lines35135235335435535635750 unmodified lines40840941041141241341421 unmodified lines4364374384394404414424434447 unmodified lines4524534544554564574584594604614624634644652 unmodified lines4684694704714724734744754764774784792 unmodified lines48248348448548656 unmodified linesreturn max(0, v)def _build_transcriber(family_id: str,model_id: str,device_str: str,device_int: int,custom_script: str = "",) -> tuple[Callable[..., str], Callable[[], None]]:"""Family backend transcriber, or user ``evaluate(Path)`` script when provided."""if (custom_script or "").strip():from backends.custom_eval import build_transcriber_from_custom_scriptreturn build_transcriber_from_custom_script(custom_script)return build_transcriber(family_id, model_id, device_str, device_int)def _zerogpu_run_segment(payload: dict[str, Any]) -> dict[str, Any]:"""Single ZeroGPU segment: build model, transcribe ``[start:end)`` for one condition."""model_id = str(payload["model_id"])1 unmodified linecondition_key = str(payload["condition_key"])start = int(payload["start"])end = int(payload["end"])custom_script = str(payload.get("custom_script") or "")device_str, device_int = resolve_eval_devices()transcribe, cleanup = _build_transcriber(family_id, model_id, device_str, device_int, custom_script=custom_script)try:num_params = int(getattr(transcribe, "_num_params", 0) or 0)preds, refs, audio_s, infer_s, n_done = accumulate_predictions_for_slice(17 unmodified linesmodel_id: str,family_id: str = "auto",progress_cb: Callable[[int, int, str], None] | None = None,custom_script: str = "",) -> dict:device_str, device_int = resolve_eval_devices()13 unmodified linesexcept Exception:passtranscribe, cleanup = _build_transcriber(family_id, model_id, device_str, device_int, custom_script=custom_script)try:# Backends attach `transcribe._num_params` via `_model_utils.attach_params`; defaults to 0# if the backend couldn't introspect a module.55 unmodified linesprogress_cb: Callable[[int, int, str], None] | None = None,*,segment_samples: int,custom_script: str = "",) -> dict:"""Same semantics as ``_run_evaluation_core_segmented`` but without ``spaces.GPU``:47 unmodified lines"condition_key": condition_key,"start": start,"end": end,"custom_script": custom_script,}out = _zerogpu_run_segment(payload)if first_num_params is None:40 unmodified linessegment_samples: int,gpu_duration_s: int,gpu_size: str,custom_script: str = "",) -> dict:"""Long evaluations: each slice of ``segment_samples`` runs under its own ``spaces.GPU``51 unmodified lines"condition_key": condition_key,"start": start,"end": end,"custom_script": custom_script,}out = wrapped_seg(payload)if first_num_params is None:50 unmodified linesmodel_id: str,family_id: str = "auto",progress_cb: Callable[[int, int, str], None] | None = None,custom_script: str = "",) -> dict:"""Evaluate `model_id` on all packed conditions using the selected family backend.21 unmodified lines``progress_cb(samples_done_across_all_conditions, samples_total_across_all_conditions, current_condition_key)``periodically during the run.When ``custom_script`` is non-empty, it must define ``evaluate(file: pathlib.Path) -> str``;that function is called once per packed sample (via a temp WAV) instead of the family backend.Returns wer_clean, wer_noisy, wer_reverberant, wer_real, wer_difficult, num_samples, model_id, eval_family, plus timing."""apply_cpu_thread_settings_once()7 unmodified linesfamily_id=family_id,progress_cb=progress_cb,segment_samples=seg,custom_script=custom_script,)return _run_evaluation_core(model_id,family_id=family_id,progress_cb=progress_cb,custom_script=custom_script,)eff = _effective_gpu_duration_s()size = os.environ.get("FFASR_ZEROGPU_GPU_SIZE", "large").strip().lower()2 unmodified linesif seg <= 0:wrapped = _spaces_gpu_wrapped(eff, size)return wrapped(model_id,family_id=family_id,progress_cb=progress_cb,custom_script=custom_script,)return _run_evaluation_core_segmented(model_id,2 unmodified linessegment_samples=seg,gpu_duration_s=eff,gpu_size=size,custom_script=custom_script,)
137 unmodified lines1381391401411421431118 unmodified lines1262126312641265126612671268137 unmodified linesreturn sdef _bool_to_csv(flag: bool) -> str:return "1" if flag else "0"1118 unmodified linesreturn ("<div class='next-up-panel' style='font-size:0.9em'>"f"<p><strong>Next models to evaluate</strong> ({len(queued)} shown):</p>"f"<ol style='margin:0.25rem 0 0 1.1rem'>{items}</ol></motionmotionmotionmotiondiv>")137 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601118 unmodified lines1279128012811282128312841285137 unmodified linesreturn sdef custom_script_defines_evaluate(text: str) -> bool:"""Best-effort check that the script defines a top-level ``evaluate`` function."""s = (text or "").strip()if not s:return Truetry:import asttree = ast.parse(s)except SyntaxError:return Falsereturn any(isinstance(node, ast.FunctionDef) and node.name == "evaluate"for node in tree.body)def _bool_to_csv(flag: bool) -> str:return "1" if flag else "0"1118 unmodified linesreturn ("<div class='next-up-panel' style='font-size:0.9em'>"f"<p><strong>Next models to evaluate</strong> ({len(queued)} shown):</p>"f"<ol style='margin:0.25rem 0 0 1.1rem'>{items}</ol></div>")
186 unmodified lines18718818919019119219319419519619719819920020120220320420520620725 unmodified lines23323423523623723818 unmodified lines257258259260261262263264265266267268186 unmodified lines)script = _worker_script_path()custom_script_path: str | None = Noneif run_custom_script and (custom_script or "").strip():import tempfilefd, custom_script_path = tempfile.mkstemp(prefix=f"ffasr_custom_{space_job_id}_", suffix=".py")try:with os.fdopen(fd, "w", encoding="utf-8") as f:f.write(custom_script.strip())except Exception:os.unlink(custom_script_path)raisescript = custom_script_pathelif not os.path.isfile(script):raise RuntimeError(f"Remote worker script not found: {script}")deps = _select_deps(model_id, family_id)25 unmodified lines"FFASR_REMOTE_EVAL_GIT_BRANCH": eval_branch,"HF_HUB_DISABLE_PROGRESS_BARS": "1",}secrets = {"HF_TOKEN": bucket_tok}api = HfApi(token=jobs_tok)18 unmodified linesif last_err is not None:raise last_errraise RuntimeError("submit_eval_job: unreachable")finally:if custom_script_path and os.path.isfile(custom_script_path):try:os.unlink(custom_script_path)except Exception:passdef inspect_job_once(hf_job_id: str, *, token: str | None = None) -> JobInfo:186 unmodified lines18718818919019119219325 unmodified lines21922022122222322422522622722822923018 unmodified lines249250251252253254186 unmodified lines)script = _worker_script_path()if not os.path.isfile(script):raise RuntimeError(f"Remote worker script not found: {script}")deps = _select_deps(model_id, family_id)25 unmodified lines"FFASR_REMOTE_EVAL_GIT_BRANCH": eval_branch,"HF_HUB_DISABLE_PROGRESS_BARS": "1",}if run_custom_script and (custom_script or "").strip():import base64env["FFASR_CUSTOM_SCRIPT_B64"] = base64.b64encode(custom_script.strip().encode("utf-8")).decode("ascii")secrets = {"HF_TOKEN": bucket_tok}api = HfApi(token=jobs_tok)18 unmodified linesif last_err is not None:raise last_errraise RuntimeError("submit_eval_job: unreachable")def inspect_job_once(hf_job_id: str, *, token: str | None = None) -> JobInfo:
15 unmodified lines16171819202191 unmodified lines11311411511611711811915 unmodified linesfrom __future__ import annotationsimport ioimport jsonimport os91 unmodified linesfrom storage import HF_BUCKET_ID, upload_to_bucketapply_cpu_thread_settings_once()result = run_evaluation(model_id, family_id=family_id, progress_cb=None)artifact = build_artifact(model_id=model_id,family_id=family_id,15 unmodified lines1617181920212291 unmodified lines11411511611711811912012112212312412512612712812915 unmodified linesfrom __future__ import annotationsimport base64import ioimport jsonimport os91 unmodified linesfrom storage import HF_BUCKET_ID, upload_to_bucketapply_cpu_thread_settings_once()custom_b64 = os.environ.get("FFASR_CUSTOM_SCRIPT_B64", "").strip()custom_script = (base64.b64decode(custom_b64).decode("utf-8") if custom_b64 else "")result = run_evaluation(model_id,family_id=family_id,progress_cb=None,custom_script=custom_script,)artifact = build_artifact(model_id=model_id,family_id=family_id,
app.py+38-14
backends/custom_eval.pyAdded+96
backends/universal.py+10-1
evaluation/orchestrator.py+45-4
job_queue.py+18-1
remote_jobs.py+7-21
scripts/run_hf_remote_job_uv.py+11-1