Spaces:
Running on Zero
Running on Zero
Download src/core/cpu_lab.py from QUD-Technologies/quranic-universal-aligner: direct link, hf CLI and curl.
- Browser
- Download file 18.6 kB
-
https://huggingface.co/spaces/QUD-Technologies/quranic-universal-aligner/resolve/main/src/core/cpu_lab.py
- Command line
-
hf download hf://spaces/QUD-Technologies/quranic-universal-aligner/src/core/cpu_lab.py
-
curl -L -o cpu_lab.py https://huggingface.co/spaces/QUD-Technologies/quranic-universal-aligner/resolve/main/src/core/cpu_lab.py
18.6 kB
| """In-worker CPU benchmark lab — dev-only, gated by ``CPU_LAB_ENABLED``. | |
| Runs the two real inference stages (boundary-head segmentation, w2v2-CTC | |
| recognition) inside the persistent CPU worker against Space-local audio, one | |
| knob set at a time, and reports per-stage wall time plus the stages' own | |
| metrics. Deploying once and sweeping knobs through this is the difference | |
| between a 2-minute restart per data point and a single request per sweep. | |
| Output identity travels with every timing: each variant reports a digest of | |
| what the stage produced, so a knob that changes results cannot be mistaken for | |
| one that only changes speed. | |
| The lab never runs on a request path — ``routes_cpulab`` is the only caller and | |
| it is off unless the Space variable says otherwise. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import os | |
| import time | |
| from contextlib import contextmanager, suppress | |
| from pathlib import Path | |
| from src.core.space_profile import segmenter_params | |
| # Audio the Space ships with, by the key the bench driver uses. | |
| LAB_AUDIO = {"84": "84.mp3", "67": "67.mp3", "7": "7.mp3", "juz30": "Juz' 30.mp3"} | |
| SEGMENTER_KEY = "segmentation.boundary_head@v1" | |
| RECOGNIZER_KEY = "recognition.w2v2_ctc@v3" | |
| _audio_cache: dict[str, tuple] = {} | |
| #: The ASR stage's fixed input: regions produced once, under the deployment's | |
| #: own settings. A seg variant must never overwrite it — every ASR variant has | |
| #: to transcribe the same regions or their token digests are not comparable and | |
| #: their speech seconds are not equal. | |
| _regions_cache: dict[str, object] = {} | |
| # --------------------------------------------------------------------------- | |
| # Host facts | |
| # --------------------------------------------------------------------------- | |
| def _read(path: str) -> str: | |
| try: | |
| with open(path) as f: | |
| return f.read().strip() | |
| except Exception as e: | |
| return f"err: {type(e).__name__}" | |
| def host_facts() -> dict: | |
| """What the container actually has: CPU model, quota, thread env, torch config.""" | |
| import torch | |
| model_name, flags = "", "" | |
| try: | |
| with open("/proc/cpuinfo") as f: | |
| for line in f: | |
| if line.startswith("model name") and not model_name: | |
| model_name = line.split(":", 1)[1].strip() | |
| if line.startswith("flags") and not flags: | |
| flags = line.split(":", 1)[1].strip() | |
| except Exception: | |
| pass | |
| wanted = ("avx2", "avx512f", "avx512_bf16", "avx512_vnni", "amx_bf16", "amx_int8", "avx_vnni") | |
| return { | |
| # Which worker answered. With a pool of more than one, a sweep that | |
| # means to change every worker has to prove it reached each of them. | |
| "pid": os.getpid(), | |
| "cpu_model": model_name, | |
| "isa": {f: (f in flags.split()) for f in wanted}, | |
| "affinity": len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else None, | |
| "cgroup_cpu_max": _read("/sys/fs/cgroup/cpu.max"), | |
| "cgroup_cpu_stat": _read("/sys/fs/cgroup/cpu.stat")[:400], | |
| "cgroup_memory_max": _read("/sys/fs/cgroup/memory.max"), | |
| "env": { | |
| k: os.environ.get(k) | |
| for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", | |
| "KMP_BLOCKTIME", "KMP_AFFINITY", "OMP_WAIT_POLICY", | |
| "MALLOC_ARENA_MAX", "LD_PRELOAD", "CPU_DTYPE") | |
| if os.environ.get(k) is not None | |
| }, | |
| "torch": { | |
| "version": torch.__version__, | |
| "num_threads": torch.get_num_threads(), | |
| "interop_threads": torch.get_num_interop_threads(), | |
| "mkldnn": torch.backends.mkldnn.is_available(), | |
| "parallel_info": torch.__config__.parallel_info().strip().splitlines(), | |
| }, | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Inputs | |
| # --------------------------------------------------------------------------- | |
| def _load_audio(key: str): | |
| """Decode one Space-local clip to 16 kHz mono, cached across variants.""" | |
| if key in _audio_cache: | |
| return _audio_cache[key] | |
| name = LAB_AUDIO.get(key) | |
| if name is None: | |
| raise ValueError(f"unknown lab audio {key!r}; have {sorted(LAB_AUDIO)}") | |
| path = Path(__file__).resolve().parents[2] / "data" / name | |
| if not path.exists(): | |
| raise FileNotFoundError(f"{path} is not on this Space") | |
| from src.core.audio_decode import get_decoded_16k | |
| samples, sr = get_decoded_16k(str(path)) | |
| _audio_cache[key] = (samples, sr) | |
| return samples, sr | |
| def _deploy(dtype: str, seg_batch: int, batching: dict | None): | |
| from qua_sdk.deploy.presets import BatchingConfig, DeployConfig | |
| cfg = DeployConfig( | |
| name="cpu_lab", device="cpu", dtype=dtype, torch_compile=False, | |
| batching=BatchingConfig(**(batching or {})), | |
| ) | |
| cfg.segmentation_batch_size = seg_batch | |
| return cfg | |
| def _digest(obj) -> str: | |
| return hashlib.sha256( | |
| json.dumps(obj, sort_keys=True, ensure_ascii=False, default=str).encode() | |
| ).hexdigest()[:16] | |
| # --------------------------------------------------------------------------- | |
| # Knobs | |
| # --------------------------------------------------------------------------- | |
| def _cpu_stat() -> dict: | |
| """cgroup CPU accounting — how much of the run was spent being throttled. | |
| The container has a 16-CPU quota and torch runs 16 threads, so any other | |
| activity in the Space pushes the cgroup over its period budget and the | |
| kernel parks every thread. That shows up as wall time no knob explains. | |
| """ | |
| out = {} | |
| for line in _read("/sys/fs/cgroup/cpu.stat").splitlines(): | |
| parts = line.split() | |
| if len(parts) == 2 and parts[1].isdigit(): | |
| out[parts[0]] = int(parts[1]) | |
| return out | |
| def _apply_threads(threads: int | None, interop: int | None) -> dict: | |
| import torch | |
| if threads: | |
| torch.set_num_threads(int(threads)) | |
| if interop: | |
| # Only settable before the first parallel work; report what stuck. | |
| with suppress(RuntimeError): | |
| torch.set_num_interop_threads(int(interop)) | |
| return {"threads": torch.get_num_threads(), "interop": torch.get_num_interop_threads()} | |
| def _reload_models(dtype: str, model: str = "Base") -> float: | |
| """Drop cached weights and reload at fp32. | |
| A dtype sweep must not reuse weights an earlier variant already cast: bf16 | |
| rounding is destructive, and an fp32 pass over down-cast weights would be | |
| measured as fp32 while producing bf16-grade output. | |
| """ | |
| from qua_sdk.registry import resolve | |
| t0 = time.perf_counter() | |
| resolve(SEGMENTER_KEY).invalidate() | |
| resolve(RECOGNIZER_KEY).invalidate() | |
| resolve(SEGMENTER_KEY).preload(segmenter_params()) | |
| resolve(RECOGNIZER_KEY).preload(model) | |
| return time.perf_counter() - t0 | |
| def _apply_backend(backend: str, model: str, threads: int, dtype: str, | |
| options: dict | None = None) -> dict: | |
| """Swap both stages' modules for ``backend``; returns per-stage build cost. | |
| The replacement is cast to the serving dtype here rather than by the SDK, | |
| and the cached entry's device/dtype fields are then pinned to match — so | |
| the SDK's own move step sees nothing to do and never tries to cast a | |
| prepacked or compiled module out from under the backend. | |
| """ | |
| if backend == "torch": | |
| return {} | |
| import torch | |
| from qua_sdk.components.recognition.runtimes.eager import resolve_model | |
| from qua_sdk.registry import resolve | |
| from src.core.cpu_backends import build_asr, build_seg | |
| # The backend wraps the module the SDK would have cast, so the cast has to | |
| # happen first — pinning device/dtype below stops the SDK from casting the | |
| # wrapper afterwards. | |
| torch_dtype = {"bfloat16": torch.bfloat16, "float32": torch.float32}.get( | |
| dtype, torch.float32) | |
| info: dict = {} | |
| recognizer = resolve(RECOGNIZER_KEY) | |
| repo_id, revision = resolve_model(model) | |
| entry = recognizer._cache[f"{repo_id}@{revision}"] | |
| entry["model"] = entry["model"].to(torch.device("cpu"), dtype=torch_dtype) | |
| entry["model"], info["asr_build_s"] = build_asr( | |
| entry["model"], backend, threads, model, options) | |
| entry["device"], entry["dtype"] = torch.device("cpu"), torch_dtype | |
| segmenter = resolve(SEGMENTER_KEY) | |
| loaded = next(iter(segmenter._loaded.values())) | |
| loaded.encoder = loaded.encoder.to(torch.device("cpu"), dtype=torch_dtype) | |
| loaded.encoder, info["seg_build_s"] = build_seg( | |
| loaded.encoder, loaded.layer, backend, threads, options) | |
| loaded.device, loaded.dtype = torch.device("cpu"), torch_dtype | |
| return {k: round(v, 2) for k, v in info.items()} | |
| # --------------------------------------------------------------------------- | |
| # Stages | |
| # --------------------------------------------------------------------------- | |
| def _encoder_windows(chunk_s: float | None, overlap_s: float | None): | |
| """Temporarily retune the encoder's window geometry. | |
| ``CHUNK_S``/``OVERLAP_S`` are module constants in the SDK, not deploy | |
| knobs, and they set how much of the clip is encoded twice: 2 s of overlap | |
| on a 20 s window is 11% recompute. Measuring whether that trade is priced | |
| right means moving them, so the lab moves them and puts them back. | |
| """ | |
| from qua_sdk.components.segmentation.runtimes.boundary_head import encoder as EN | |
| before = (EN.CHUNK_S, EN.OVERLAP_S) | |
| if chunk_s: | |
| EN.CHUNK_S = float(chunk_s) | |
| if overlap_s is not None: | |
| EN.OVERLAP_S = float(overlap_s) | |
| try: | |
| yield | |
| finally: | |
| EN.CHUNK_S, EN.OVERLAP_S = before | |
| def _run_seg(samples, sr, deploy, pad_left_ms: int, pad_right_ms: int) -> tuple[dict, object]: | |
| from qua_sdk.observe import collect_stage_metrics | |
| from qua_sdk.registry import resolve | |
| from qua_sdk.schemas import Audio | |
| segmenter = resolve(SEGMENTER_KEY) | |
| params = segmenter_params(pad_left_ms=pad_left_ms, pad_right_ms=pad_right_ms) | |
| segmenter.preload(params) | |
| audio = Audio.from_array(samples, sr) | |
| t0 = time.perf_counter() | |
| with collect_stage_metrics() as metrics: | |
| regions = segmenter.segment(audio, params, deploy=deploy) | |
| wall = time.perf_counter() - t0 | |
| bounds = [(round(r.start_s, 3), round(r.end_s, 3)) for r in regions.regions] | |
| return { | |
| "wall_s": round(wall, 3), | |
| "metrics": dict(metrics or {}), | |
| "n_regions": len(bounds), | |
| "speech_s": round(sum(e - s for s, e in bounds), 2), | |
| "digest": _digest(bounds), | |
| }, regions | |
| def _run_asr(samples, sr, regions, deploy, model: str) -> dict: | |
| from qua_sdk.components.recognition.spec import RecognitionParams | |
| from qua_sdk.observe import collect_stage_metrics | |
| from qua_sdk.registry import resolve | |
| from qua_sdk.schemas import Audio | |
| recognizer = resolve(RECOGNIZER_KEY) | |
| recognizer.preload(model) | |
| audio = Audio.from_array(samples, sr) | |
| t0 = time.perf_counter() | |
| with collect_stage_metrics() as metrics: | |
| emissions = recognizer.transcribe( | |
| audio, regions, RecognitionParams(model=model), deploy=deploy) | |
| wall = time.perf_counter() - t0 | |
| m = dict(metrics or {}) | |
| batches = m.pop("batches", []) or [] | |
| return { | |
| "wall_s": round(wall, 3), | |
| "metrics": m, | |
| "n_batches": len(batches), | |
| "feat_s": round(sum(b.get("feat_time", 0) for b in batches), 3), | |
| "infer_s": round(sum(b.get("infer_time", 0) for b in batches), 3), | |
| "decode_s": round(sum(b.get("decode_time", 0) for b in batches), 3), | |
| "batch_sizes": [b.get("size") for b in batches], | |
| "max_seq_len": max((b.get("seq_len", 0) for b in batches), default=0), | |
| "pad_waste": round( | |
| sum(b.get("pad_waste", 0) * b.get("size", 0) for b in batches) | |
| / max(1, sum(b.get("size", 0) for b in batches)), 4), | |
| "n_tokens": sum(len(t) for t in emissions.tokens), | |
| "digest": _digest(emissions.tokens), | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Entry point | |
| # --------------------------------------------------------------------------- | |
| def _normalize(v: dict) -> dict: | |
| """One variant's full knob set, defaults filled in.""" | |
| return { | |
| "name": v.get("name") or "?", | |
| "stage": v.get("stage", "both"), | |
| "dtype": v.get("dtype", os.environ.get("CPU_DTYPE", "bfloat16")), | |
| "backend": v.get("backend", "torch"), | |
| "seg_batch": int(v.get("seg_batch", 8)), | |
| "model": v.get("model", "Base"), | |
| "threads": v.get("threads"), | |
| "interop": v.get("interop"), | |
| "warmup": bool(v.get("warmup", False)), | |
| "options": v.get("options") or {}, | |
| "chunk_s": v.get("chunk_s"), | |
| "overlap_s": v.get("overlap_s"), | |
| "pad_left_ms": int(v.get("pad_left_ms", 100)), | |
| "pad_right_ms": int(v.get("pad_right_ms", 200)), | |
| "batching": {k: v[k] for k in | |
| ("strategy", "max_batch_seconds", "max_pad_waste", | |
| "min_batch_size", "naive_batch_size") if k in v}, | |
| } | |
| def _warm(cfg: dict, samples, sr, audio_key: str, deploy) -> None: | |
| """Run each measured stage once, discarded, over a short slice of the clip.""" | |
| head = samples[: min(len(samples), 60 * sr)] | |
| if cfg["stage"] in ("seg", "both"): | |
| with _encoder_windows(cfg["chunk_s"], cfg["overlap_s"]): | |
| _run_seg(head, sr, deploy, cfg["pad_left_ms"], cfg["pad_right_ms"]) | |
| if cfg["stage"] in ("asr", "both"): | |
| regions = _regions_cache.get(audio_key) | |
| if regions is not None: | |
| from qua_sdk.schemas import Regions | |
| few = Regions(regions=regions.regions[:24], | |
| is_complete=regions.is_complete, | |
| audio_duration_s=regions.audio_duration_s) | |
| _run_asr(samples, sr, few, deploy, cfg["model"]) | |
| def _one_round(cfg: dict, row: dict, samples, sr, audio_key: str, key: str) -> None: | |
| """Prepare the worker for one variant and run its stage(s) once.""" | |
| # Every measurement starts from freshly loaded float32 weights: bf16 | |
| # casting and quantization are both destructive in place. | |
| row["reload_s"] = round(_reload_models(cfg["dtype"], cfg["model"]), 2) | |
| row["applied"] = _apply_threads(cfg["threads"], cfg["interop"]) | |
| row["build"] = _apply_backend( | |
| cfg["backend"], cfg["model"], row["applied"]["threads"], cfg["dtype"], | |
| cfg["options"]) | |
| deploy = _deploy(cfg["dtype"], cfg["seg_batch"], cfg["batching"]) | |
| # A compiled or prepacked backend pays its build on first call, and every | |
| # round reloads the weights — so the build lands inside every round unless | |
| # it is burned first. The warm-up cost is reported separately. | |
| if cfg["warmup"]: | |
| t0 = time.perf_counter() | |
| _warm(cfg, samples, sr, audio_key, deploy) | |
| row["warmup_s"] = round(time.perf_counter() - t0, 2) | |
| before = _cpu_stat() | |
| if cfg["stage"] in ("seg", "both"): | |
| with _encoder_windows(cfg["chunk_s"], cfg["overlap_s"]): | |
| seg, _regions = _run_seg(samples, sr, deploy, | |
| cfg["pad_left_ms"], cfg["pad_right_ms"]) | |
| row.setdefault("seg", {})[key] = seg | |
| if cfg["stage"] in ("asr", "both"): | |
| row.setdefault("asr", {})[key] = _run_asr( | |
| samples, sr, _regions_cache[audio_key], deploy, cfg["model"]) | |
| after = _cpu_stat() | |
| row.setdefault("throttle", {})[key] = { | |
| k: after.get(k, 0) - before.get(k, 0) | |
| for k in ("nr_throttled", "throttled_usec", "usage_usec")} | |
| def run_lab(spec: dict) -> dict: | |
| """Execute a variant sweep inside this worker and return its measurements. | |
| ``spec`` = ``{audio, repeats, variants: [{name, stage, ...knobs}]}``. | |
| Each variant is a full knob set, not a delta — a sweep is readable only if | |
| every row states what it ran. | |
| Repeats are rounds over the whole variant list, not consecutive runs of one | |
| variant. This host is shared and cgroup-throttled, so a slow stretch lands | |
| on one block of consecutive runs and reads as a property of whatever knob | |
| was being measured; interleaving spreads it across all of them. | |
| ``persist`` leaves the last variant's models installed in the worker instead | |
| of restoring the deployment's own. That turns this route into a switch for | |
| the *end-to-end* path: a bench can then compare two backends inside one | |
| container, which is the only way to compare them at all on short clips — | |
| two containers running the identical configuration have measured 2.4x apart. | |
| """ | |
| audio_key = str(spec.get("audio", "84")) | |
| repeats = int(spec.get("repeats", 1)) | |
| variants = [_normalize(v) for v in | |
| (spec.get("variants") or [{"name": "default", "stage": "both"}])] | |
| t_dec = time.perf_counter() | |
| samples, sr = _load_audio(audio_key) | |
| decode_s = round(time.perf_counter() - t_dec, 3) | |
| # The ASR stage's input, produced once under the deployment's own settings | |
| # and before any variant has touched the models. | |
| if any(c["stage"] in ("asr", "both") for c in variants) and audio_key not in _regions_cache: | |
| _reload_models(os.environ.get("CPU_DTYPE", "bfloat16")) | |
| _, base = _run_seg(samples, sr, _deploy(os.environ.get("CPU_DTYPE", "bfloat16"), | |
| 8, None), 100, 200) | |
| _regions_cache[audio_key] = base | |
| rows = [dict(cfg) for cfg in variants] | |
| for r in range(repeats): | |
| for cfg, row in zip(variants, rows, strict=True): | |
| if row.get("error"): | |
| continue | |
| try: | |
| _one_round(cfg, row, samples, sr, audio_key, f"run{r}") | |
| except Exception as e: | |
| import traceback | |
| row["error"] = f"{type(e).__name__}: {e}" | |
| row["traceback"] = traceback.format_exc()[-1500:] | |
| import torch | |
| if not spec.get("persist"): | |
| # Leave the worker exactly as a real request expects to find it — both | |
| # the models and the thread count, since a variant may have moved either. | |
| _reload_models(os.environ.get("CPU_DTYPE", "bfloat16")) | |
| torch.set_num_threads( | |
| int(os.environ.get("OMP_NUM_THREADS") or torch.get_num_threads())) | |
| return { | |
| "audio": audio_key, | |
| "audio_min": round(len(samples) / sr / 60, 2), | |
| "decode_s": decode_s, | |
| "repeats": repeats, | |
| "persisted": bool(spec.get("persist")), | |
| "host": host_facts(), | |
| "results": rows, | |
| } | |