File size: 8,317 Bytes
c3efd49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Benchmark suite for voice model evaluation."""
import torch
import json
from pathlib import Path
from datetime import datetime
from typing import Dict, Any, List, Optional, Callable
import logging

from .metrics import MetricCalculator

logger = logging.getLogger(__name__)


class BenchmarkSuite:
    """
    Comprehensive benchmark suite for voice models.
    
    Evaluates models on multiple metrics and persists results.
    """
    
    def __init__(self, output_dir: str = "results"):
        """
        Initialize benchmark suite.
        
        Args:
            output_dir: Directory to save benchmark results
        """
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        
        self.metric_calculator = MetricCalculator()
        self.results_history = []
        
        logger.info(f"Initialized BenchmarkSuite with output_dir={output_dir}")
    
    def run_benchmark(
        self,
        model_fn: Callable,
        test_data: List[Dict[str, Any]],
        model_name: str = "model",
        checkpoint_path: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Run complete benchmark on a model.
        
        Args:
            model_fn: Model inference function
            test_data: List of test samples with audio and transcriptions
            model_name: Name identifier for the model
            checkpoint_path: Path to model checkpoint
        
        Returns:
            Dictionary containing all benchmark results
        """
        logger.info(f"Running benchmark for {model_name} on {len(test_data)} samples")
        
        start_time = datetime.now()
        
        # Collect predictions and references
        predictions = []
        references = []
        audio_pairs = []
        latencies = []
        
        for sample in test_data:
            input_audio = sample['audio']
            reference_text = sample.get('transcription', '')
            reference_audio = sample.get('reference_audio', input_audio)
            
            # Measure inference latency
            import time
            start = time.perf_counter()
            output = model_fn(input_audio)
            end = time.perf_counter()
            latencies.append((end - start) * 1000)
            
            # Extract prediction
            if isinstance(output, dict):
                pred_text = output.get('transcription', '')
                pred_audio = output.get('audio', input_audio)
            else:
                pred_text = ''
                pred_audio = output if isinstance(output, torch.Tensor) else input_audio
            
            predictions.append(pred_text)
            references.append(reference_text)
            audio_pairs.append((pred_audio, reference_audio))
        
        # Compute metrics
        results = self.compute_metrics(
            predictions=predictions,
            references=references,
            audio_pairs=audio_pairs
        )
        
        # Add latency metrics
        results['inference_time_ms'] = sum(latencies) / len(latencies) if latencies else 0.0
        results['samples_per_second'] = len(test_data) / (sum(latencies) / 1000) if latencies else 0.0
        
        # Add metadata
        results['timestamp'] = start_time.isoformat()
        results['model_name'] = model_name
        results['model_checkpoint'] = checkpoint_path
        results['num_samples'] = len(test_data)
        
        # Save results
        self._save_results(results, model_name)
        self.results_history.append(results)
        
        logger.info(f"Benchmark complete. WER: {results.get('word_error_rate', 'N/A'):.4f}")
        
        return results
    
    def compute_metrics(
        self,
        predictions: List[str],
        references: List[str],
        audio_pairs: Optional[List[tuple]] = None
    ) -> Dict[str, float]:
        """
        Compute all metrics for predictions.
        
        Args:
            predictions: List of predicted transcriptions
            references: List of reference transcriptions
            audio_pairs: Optional list of (generated, reference) audio pairs
        
        Returns:
            Dictionary of metric names and values
        """
        metrics = {}
        
        # Text-based metrics
        if predictions and references:
            try:
                metrics['word_error_rate'] = self.metric_calculator.compute_word_error_rate(
                    predictions, references
                )
            except Exception as e:
                logger.warning(f"Failed to compute WER: {e}")
                metrics['word_error_rate'] = float('nan')
            
            try:
                metrics['character_error_rate'] = self.metric_calculator.compute_character_error_rate(
                    predictions, references
                )
            except Exception as e:
                logger.warning(f"Failed to compute CER: {e}")
                metrics['character_error_rate'] = float('nan')
        
        # Audio-based metrics
        if audio_pairs:
            mcd_scores = []
            pesq_scores = []
            
            for gen_audio, ref_audio in audio_pairs:
                if isinstance(gen_audio, torch.Tensor) and isinstance(ref_audio, torch.Tensor):
                    try:
                        mcd = self.metric_calculator.compute_mel_cepstral_distortion(
                            gen_audio, ref_audio
                        )
                        mcd_scores.append(mcd)
                    except Exception as e:
                        logger.warning(f"Failed to compute MCD: {e}")
                    
                    try:
                        pesq = self.metric_calculator.compute_perceptual_quality(
                            gen_audio, ref_audio
                        )
                        pesq_scores.append(pesq)
                    except Exception as e:
                        logger.warning(f"Failed to compute PESQ: {e}")
            
            if mcd_scores:
                metrics['mel_cepstral_distortion'] = sum(mcd_scores) / len(mcd_scores)
            if pesq_scores:
                metrics['perceptual_evaluation_speech_quality'] = sum(pesq_scores) / len(pesq_scores)
        
        return metrics
    
    def _save_results(self, results: Dict[str, Any], model_name: str) -> None:
        """
        Save benchmark results to file.
        
        Args:
            results: Results dictionary
            model_name: Model identifier
        """
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"benchmark_{model_name}_{timestamp}.json"
        filepath = self.output_dir / filename
        
        # Convert any non-serializable values
        serializable_results = {}
        for key, value in results.items():
            if isinstance(value, (int, float, str, bool, type(None))):
                serializable_results[key] = value
            elif isinstance(value, datetime):
                serializable_results[key] = value.isoformat()
            else:
                serializable_results[key] = str(value)
        
        with open(filepath, 'w') as f:
            json.dump(serializable_results, f, indent=2)
        
        logger.info(f"Results saved to {filepath}")
    
    def load_results(self, filepath: str) -> Dict[str, Any]:
        """
        Load benchmark results from file.
        
        Args:
            filepath: Path to results file
        
        Returns:
            Results dictionary
        """
        with open(filepath, 'r') as f:
            results = json.load(f)
        
        return results
    
    def get_latest_results(self, model_name: Optional[str] = None) -> Optional[Dict[str, Any]]:
        """
        Get the most recent benchmark results.
        
        Args:
            model_name: Optional model name filter
        
        Returns:
            Latest results dictionary or None
        """
        if not self.results_history:
            return None
        
        if model_name:
            filtered = [r for r in self.results_history if r.get('model_name') == model_name]
            return filtered[-1] if filtered else None
        
        return self.results_history[-1]