File size: 9,179 Bytes
c39225b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#!/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()