#!/usr/bin/env python3 """ benchmark.py Comprehensive Benchmark Suite for Notesoop-STT-Ko-v2: - Supports NVIDIA CUDA, Apple Silicon MPS, and Multi-core CPU - Tracks Peak System RAM & GPU VRAM (CUDA max_memory_allocated / MPS memory) - Evaluates RTF (Real-Time Factor), Speedup Factor, and Character/Word Error Rates (CER/WER) - Benchmarks on Sample Audio or Official Zeroth-Korean Test Set """ from __future__ import annotations import argparse import gc import json import os import sys import threading import time from pathlib import Path from typing import Optional, List, Dict, Any _ROOT = Path(__file__).resolve().parent _SRC = _ROOT / "src" if str(_SRC) not in sys.path: sys.path.insert(0, str(_SRC)) if str(_ROOT) not in sys.path: sys.path.insert(0, str(_ROOT)) import numpy as np import psutil import torch from transcribe import EmbeddingGemmaSTTV2, load_audio, auto_detect_device, sync_device, empty_device_cache from dataset import normalize_text class UnifiedResourceTracker: """ Tracks peak host RAM and GPU VRAM allocation across NVIDIA CUDA and Apple Silicon MPS. """ def __init__(self, device: torch.device, interval: float = 0.05): self.device = device self.interval = interval self.stop_event = threading.Event() self.thread: Optional[threading.Thread] = None self.process = psutil.Process(os.getpid()) self.peak_ram_mb: float = 0.0 self.peak_vram_mb: float = 0.0 def _monitor(self): while not self.stop_event.is_set(): try: mem = self.process.memory_info().rss / (1024.0 * 1024.0) if mem > self.peak_ram_mb: self.peak_ram_mb = mem except Exception: pass if self.device.type == "cuda": try: vram = torch.cuda.memory_allocated(self.device) / (1024.0 * 1024.0) if vram > self.peak_vram_mb: self.peak_vram_mb = vram except Exception: pass elif self.device.type == "mps" and hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): try: vram = torch.mps.current_allocated_memory() / (1024.0 * 1024.0) if vram > self.peak_vram_mb: self.peak_vram_mb = vram except Exception: pass self.stop_event.wait(self.interval) def __enter__(self): empty_device_cache(self.device) if self.device.type == "cuda": torch.cuda.reset_peak_memory_stats(self.device) self.peak_ram_mb = self.process.memory_info().rss / (1024.0 * 1024.0) self.peak_vram_mb = 0.0 self.stop_event.clear() self.thread = threading.Thread(target=self._monitor, daemon=True) self.thread.start() return self def __exit__(self, exc_type, exc_val, exc_tb): self.stop_event.set() if self.thread is not None: self.thread.join(timeout=1.0) if self.device.type == "cuda": peak_cuda = torch.cuda.max_memory_allocated(self.device) / (1024.0 * 1024.0) if peak_cuda > self.peak_vram_mb: self.peak_vram_mb = peak_cuda elif self.device.type == "mps" and hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): peak_mps = torch.mps.current_allocated_memory() / (1024.0 * 1024.0) if peak_mps > self.peak_vram_mb: self.peak_vram_mb = peak_mps def compute_cer(pred: str, target: str) -> float: """Character Error Rate using Levenshtein distance.""" pred_c = pred.replace(" ", "") target_c = target.replace(" ", "") if not target_c: return 0.0 if not pred_c else 1.0 dp = np.zeros((len(target_c) + 1, len(pred_c) + 1), dtype=np.int32) for i in range(len(target_c) + 1): dp[i][0] = i for j in range(len(pred_c) + 1): dp[0][j] = j for i in range(1, len(target_c) + 1): for j in range(1, len(pred_c) + 1): cost = 0 if target_c[i - 1] == pred_c[j - 1] else 1 dp[i][j] = min( dp[i - 1][j] + 1, # deletion dp[i][j - 1] + 1, # insertion dp[i - 1][j - 1] + cost # substitution ) return float(dp[len(target_c)][len(pred_c)]) / float(len(target_c)) def compute_wer(pred: str, target: str) -> float: """Word Error Rate.""" pred_words = pred.split() target_words = target.split() if not target_words: return 0.0 if not pred_words else 1.0 dp = np.zeros((len(target_words) + 1, len(pred_words) + 1), dtype=np.int32) for i in range(len(target_words) + 1): dp[i][0] = i for j in range(len(pred_words) + 1): dp[0][j] = j for i in range(1, len(target_words) + 1): for j in range(1, len(pred_words) + 1): cost = 0 if target_words[i - 1] == pred_words[j - 1] else 1 dp[i][j] = min( dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost ) return float(dp[len(target_words)][len(pred_words)]) / float(len(target_words)) def run_audio_benchmark( engine: EmbeddingGemmaSTTV2, audio_path: str, ground_truth: Optional[str] = None, batch_size: int = 4, warmup: bool = True ) -> Dict[str, Any]: """Runs a single or batched benchmark for an audio file.""" _, dur = load_audio(audio_path) # Warmup pass if warmup: print("🔥 Warming up inference pipeline...") engine.transcribe(audio_path, duration_limit=min(5.0, dur), batch_size=batch_size) print(f"📊 Benchmarking '{Path(audio_path).name}' ({dur:.2f}s audio)...") with UnifiedResourceTracker(engine.device) as tracker: t0 = time.perf_counter() pred_text, rtf = engine.transcribe( audio_path=audio_path, batch_size=batch_size ) elapsed = time.perf_counter() - t0 speedup = dur / max(elapsed, 1e-5) cer = compute_cer(pred_text, ground_truth) if ground_truth else None wer = compute_wer(pred_text, ground_truth) if ground_truth else None results = { "audio_file": Path(audio_path).name, "duration_sec": dur, "elapsed_sec": elapsed, "speedup_x": speedup, "rtf": rtf, "peak_ram_mb": tracker.peak_ram_mb, "peak_vram_mb": tracker.peak_vram_mb, "cer": cer, "wer": wer, "transcript": pred_text } print("\n" + "=" * 70) print("🏁 Benchmark Results Summary:") print(f" • Compute Device : {engine.device.type.upper()} ({engine.dev_str})") print(f" • Audio Duration : {dur:.2f}s ({dur/60:.2f} min)") print(f" • Total Inference : {elapsed:.2f}s") print(f" • Real-Time Speedup : {speedup:.2f}x faster (RTF: {rtf:.4f})") print(f" • Peak System RAM : {tracker.peak_ram_mb:.1f} MB") print(f" • Peak GPU VRAM : {tracker.peak_vram_mb:.1f} MB") if cer is not None: print(f" • CER (Character) : {cer * 100:.2f}%") print(f" • WER (Word) : {wer * 100:.2f}%") print("-" * 70) print(f"📝 Transcript Preview : \"{pred_text[:120]}{'...' if len(pred_text) > 120 else ''}\"") print("=" * 70 + "\n") return results def main(): parser = argparse.ArgumentParser(description="Notesoop-STT-Ko-v2 Benchmark Suite") parser.add_argument("--audio", type=str, default="sample_audio.wav", help="Path to audio file") parser.add_argument("--ground_truth", type=str, default=None, help="Path to reference ground truth text or string") parser.add_argument("--device", type=str, default="auto", choices=["auto", "cuda", "mps", "cpu"], help="Compute device") parser.add_argument("--batch_size", type=int, default=4, help="Batch size for audio chunks (set 8~16 for CUDA)") parser.add_argument("--kenlm", action="store_true", default=True, help="Enable KenLM rescoring") parser.add_argument("--no_kenlm", dest="kenlm", action="store_false", help="Disable KenLM") parser.add_argument("--output_json", type=str, default=None, help="Save result dictionary to JSON file") args = parser.parse_args() engine = EmbeddingGemmaSTTV2( device=args.device, use_kenlm=args.kenlm ) gt_text = None if args.ground_truth: gt_path = Path(args.ground_truth) if gt_path.exists(): gt_text = gt_path.read_text(encoding="utf-8").strip() else: gt_text = args.ground_truth.strip() res = run_audio_benchmark( engine=engine, audio_path=args.audio, ground_truth=gt_text, batch_size=args.batch_size ) if args.output_json: out_p = Path(args.output_json) out_p.parent.mkdir(parents=True, exist_ok=True) with open(out_p, "w", encoding="utf-8") as f: json.dump(res, f, ensure_ascii=False, indent=2) print(f"📁 Benchmark JSON saved to: {out_p.resolve()}") if __name__ == "__main__": main()