#!/usr/bin/env python3 """Reproducible batch capacity benchmark; synthetic speech, not an accuracy eval.""" from __future__ import annotations import argparse import gc import hashlib import json import platform import resource import statistics import sys from pathlib import Path import numpy as np import soundfile as sf import torch from batch_inference import AudioInput, BatchEngine def percentile(values, quantile): return float(np.percentile(values, quantile)) def gpu_memory(device): if device == "cuda": return torch.cuda.max_memory_allocated() if device == "mps": return torch.mps.driver_allocated_memory() return None def run_benchmark( model_dir, sample, *, device, hardware_label, batch_sizes=(1, 2, 4, 8), repeats=3, cpu_threads=6, beam=True, decode_workers=1, dtype="auto", large_workloads=False, checkpoint_path=None, workload_names=None, ): reference, rate = sf.read(sample, dtype="float32") if rate != 16000 or reference.ndim != 1: raise ValueError("Benchmark fixture must be 16 kHz mono") if repeats < 1: raise ValueError("At least one repeat is required") fixture = np.concatenate([reference, np.zeros(4000, dtype=np.float32)]) def audio(seconds): count = int(seconds * 16000) return np.tile(fixture, (count + len(fixture) - 1) // len(fixture))[:count] workloads = {"8x30s": [30] * 8, "mixed": [6, 12, 20, 30, 68], "1x240s": [240]} if large_workloads: workloads = { "128x30s": [30] * 128, "mixed-large": [6, 12, 20, 30, 68] * 20, "1x3600s": [3600], } if workload_names: workloads = {name: workloads[name] for name in workload_names} engine = BatchEngine( model_dir, device=device, batch_size=max(batch_sizes), cpu_threads=cpu_threads, greedy=not beam, decode_workers=decode_workers, dtype=dtype, ) records = [] def checkpoint(): if checkpoint_path: Path(checkpoint_path).write_text( json.dumps( { "hardware": hardware_label, "completed": False, "records": records, }, indent=2, ) + "\n" ) for name, durations in workloads.items(): inputs = [ AudioInput(str(i), audio(seconds), 16000) for i, seconds in enumerate(durations) ] # Feature extraction remains inside each measured end-to-end call. baseline_texts = None for size in batch_sizes: try: engine.transcribe(inputs, batch_size=size) trials = [] if device == "cuda": torch.cuda.reset_peak_memory_stats() for _ in range(repeats): result = engine.transcribe(inputs, batch_size=size) trials.append(result["stats"]) except RuntimeError as error: if "out of memory" not in str(error).lower(): raise record = { "hardware": hardware_label, "device": device, "dtype": str(engine.dtype), "workload": name, "batch_size": size, "status": "oom", "error": str(error), } records.append(record) print(json.dumps(record), flush=True) checkpoint() gc.collect() if device == "mps": torch.mps.empty_cache() elif device == "cuda": torch.cuda.empty_cache() continue total = sum(durations) end_times = [t["total_seconds"] for t in trials] acoustic_times = [t["acoustic_seconds"] for t in trials] preprocessing = [t["preprocessing_seconds"] for t in trials] decoding = [t["decode_seconds"] for t in trials] rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss record = { "status": "ok", "hardware": hardware_label, "device": device, "dtype": str(engine.dtype), "workload": name, "input_seconds": total, "input_durations": durations, "batch_size": size, "mode": "beam" if beam else "greedy", "decode_workers": decode_workers, "cpu_threads": torch.get_num_threads(), "repeats": repeats, "median_total_seconds": statistics.median(end_times), "p95_total_seconds": percentile(end_times, 95), "median_acoustic_seconds": statistics.median(acoustic_times), "median_preprocess_seconds": statistics.median(preprocessing), "median_decode_seconds": statistics.median(decoding), "audio_seconds_per_wall_second": total / statistics.median(end_times), "acoustic_audio_seconds_per_wall_second": total / statistics.median(acoustic_times), "chunks": trials[-1]["chunks"], "batch_sizes": trials[-1]["batch_sizes"], "padding_fraction": trials[-1]["padding_fraction"], "rss_process_high_water_bytes": rss if sys.platform == "darwin" else rss * 1024, "gpu_memory_bytes": gpu_memory(device), "trials": trials, } texts = [r["text"] for r in result["results"]] if baseline_texts is None: baseline_texts = texts record["transcripts_equal_to_first_batch_size"] = texts == baseline_texts record["matching_recordings"] = sum( a == b for a, b in zip(texts, baseline_texts, strict=True) ) records.append(record) print( json.dumps({k: v for k, v in record.items() if k != "trials"}), flush=True, ) checkpoint() return { "hardware": hardware_label, "platform": platform.platform(), "torch": torch.__version__, "python": sys.version, "cuda": torch.version.cuda, "fixture": "repeated synthetic English speech", "model_load_seconds": engine.load_seconds, "gpu_memory_note": "CUDA peak allocated; MPS driver allocation after run, not peak", "rss_note": "process lifetime high-water mark; cumulative across configurations", "records": records, "completed": True, "engine_sha256": hashlib.sha256( Path(__file__).with_name("batch_inference.py").read_bytes() ).hexdigest(), } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--model-dir", required=True) parser.add_argument("--sample", required=True) parser.add_argument("--device", choices=["cpu", "mps", "cuda"], required=True) parser.add_argument("--hardware-label", required=True) parser.add_argument("--batch-sizes", nargs="+", type=int, default=[1, 2, 4, 8]) parser.add_argument("--repeats", type=int, default=3) parser.add_argument("--cpu-threads", type=int, default=6) parser.add_argument("--greedy", action="store_true") parser.add_argument("--decode-workers", type=int, default=1) parser.add_argument("--dtype", choices=["auto", "fp32", "bf16"], default="auto") parser.add_argument("--output", required=True) parser.add_argument( "--large-workloads", action="store_true", help="Use enough chunks to exercise batch sizes through 128", ) parser.add_argument("--workloads", nargs="+", help="Subset of named workloads") args = parser.parse_args() result = run_benchmark( args.model_dir, args.sample, device=args.device, hardware_label=args.hardware_label, batch_sizes=args.batch_sizes, repeats=args.repeats, cpu_threads=args.cpu_threads, beam=not args.greedy, decode_workers=args.decode_workers, dtype=args.dtype, large_workloads=args.large_workloads, checkpoint_path=args.output, workload_names=args.workloads, ) Path(args.output).write_text(json.dumps(result, indent=2) + "\n") if __name__ == "__main__": main()