File size: 11,577 Bytes
afd2cc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
#!/usr/bin/env python
"""
Benchmark script to compare performance between standard Transformers
and CTranslate2 optimized translation models.
"""

import argparse
import json
import logging
import os
import sys
import time
from typing import Dict, List, Tuple

import numpy as np
import torch
import tqdm

# Add project root to path for imports
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Import our models
try:
    from app.models.translation_model import TranslationModel  # Standard model
    from app.models.translation_model_ct2 import TranslationModelCT2  # CTranslate2 model
except ImportError:
    logger.error("Could not import translation models. Make sure you're running this script from the project root.")
    sys.exit(1)

# Test sentences for various languages
TEST_SENTENCES = {
    "en-es": [
        "Hello, how are you today?",
        "I would like to book a flight to Madrid for next week.",
        "The quick brown fox jumps over the lazy dog.",
        "Artificial intelligence is transforming the way we live and work.",
        "Please contact our customer service if you have any questions."
    ],
    "en-fr": [
        "Hello, how are you today?",
        "I would like to book a flight to Paris for next week.",
        "The quick brown fox jumps over the lazy dog.",
        "Artificial intelligence is transforming the way we live and work.",
        "Please contact our customer service if you have any questions."
    ],
    "en-de": [
        "Hello, how are you today?",
        "I would like to book a flight to Berlin for next week.",
        "The quick brown fox jumps over the lazy dog.",
        "Artificial intelligence is transforming the way we live and work.",
        "Please contact our customer service if you have any questions."
    ],
    "en-dra": [
        "Hello, how are you today?",
        "I would like to book a flight to Chennai for next week.",
        "The quick brown fox jumps over the lazy dog.",
        "Artificial intelligence is transforming the way we live and work.",
        "Please contact our customer service if you have any questions."
    ]
}

def benchmark_standard_model(
    src_lang: str,
    tgt_lang: str,
    sentences: List[str],
    num_runs: int = 5,
    warm_up: int = 2
) -> Dict:
    """Benchmark the standard Transformers model."""
    logger.info(f"Benchmarking standard Transformers model for {src_lang}-{tgt_lang}")
    
    # Initialize model
    model = TranslationModel()
    
    # Warm-up runs
    logger.info(f"Performing {warm_up} warm-up runs...")
    for _ in range(warm_up):
        for sentence in sentences[:2]:  # Use only first 2 sentences for warm-up
            model.translate(sentence, src_lang, tgt_lang)
    
    # Actual benchmark
    logger.info(f"Performing {num_runs} benchmark runs...")
    times = []
    translations = []
    
    for run in range(num_runs):
        run_times = []
        run_translations = []
        
        for sentence in tqdm.tqdm(sentences, desc=f"Run {run+1}/{num_runs}"):
            start_time = time.time()
            translation = model.translate(sentence, src_lang, tgt_lang)
            elapsed_time = time.time() - start_time
            
            run_times.append(elapsed_time)
            run_translations.append(translation)
        
        times.append(run_times)
        
        # Only keep translations from the first run
        if run == 0:
            translations = run_translations
    
    # Calculate statistics
    all_times = np.array(times).flatten()
    stats = {
        "mean_time": float(np.mean(all_times)),
        "median_time": float(np.median(all_times)),
        "std_dev": float(np.std(all_times)),
        "min_time": float(np.min(all_times)),
        "max_time": float(np.max(all_times)),
        "total_time": float(np.sum(all_times)),
        "num_sentences": len(sentences) * num_runs,
        "translations": translations
    }
    
    return stats

def benchmark_ct2_model(
    src_lang: str,
    tgt_lang: str,
    sentences: List[str],
    num_runs: int = 5,
    warm_up: int = 2
) -> Dict:
    """Benchmark the CTranslate2 optimized model."""
    logger.info(f"Benchmarking CTranslate2 model for {src_lang}-{tgt_lang}")
    
    # Initialize model
    model = TranslationModelCT2()
    
    # Warm-up runs
    logger.info(f"Performing {warm_up} warm-up runs...")
    for _ in range(warm_up):
        for sentence in sentences[:2]:  # Use only first 2 sentences for warm-up
            model.translate(sentence, src_lang, tgt_lang)
    
    # Actual benchmark
    logger.info(f"Performing {num_runs} benchmark runs...")
    times = []
    translations = []
    
    for run in range(num_runs):
        run_times = []
        run_translations = []
        
        for sentence in tqdm.tqdm(sentences, desc=f"Run {run+1}/{num_runs}"):
            start_time = time.time()
            translation = model.translate(sentence, src_lang, tgt_lang)
            elapsed_time = time.time() - start_time
            
            run_times.append(elapsed_time)
            run_translations.append(translation)
        
        times.append(run_times)
        
        # Only keep translations from the first run
        if run == 0:
            translations = run_translations
    
    # Calculate statistics
    all_times = np.array(times).flatten()
    stats = {
        "mean_time": float(np.mean(all_times)),
        "median_time": float(np.median(all_times)),
        "std_dev": float(np.std(all_times)),
        "min_time": float(np.min(all_times)),
        "max_time": float(np.max(all_times)),
        "total_time": float(np.sum(all_times)),
        "num_sentences": len(sentences) * num_runs,
        "translations": translations
    }
    
    return stats

def benchmark_batch(
    src_lang: str,
    tgt_lang: str,
    sentences: List[str],
    num_runs: int = 5,
    warm_up: int = 2
) -> Dict:
    """Benchmark batch translation with CTranslate2."""
    logger.info(f"Benchmarking CTranslate2 batch translation for {src_lang}-{tgt_lang}")
    
    # Initialize model
    model = TranslationModelCT2()
    
    # Warm-up runs
    logger.info(f"Performing {warm_up} warm-up runs...")
    for _ in range(warm_up):
        model.translate_batch(sentences[:2], src_lang, tgt_lang)
    
    # Actual benchmark
    logger.info(f"Performing {num_runs} benchmark runs...")
    times = []
    translations = []
    
    for run in range(num_runs):
        start_time = time.time()
        batch_translations = model.translate_batch(sentences, src_lang, tgt_lang)
        elapsed_time = time.time() - start_time
        
        times.append(elapsed_time)
        
        # Only keep translations from the first run
        if run == 0:
            translations = batch_translations
    
    # Calculate statistics
    stats = {
        "mean_time": float(np.mean(times)),
        "median_time": float(np.median(times)),
        "std_dev": float(np.std(times)),
        "min_time": float(np.min(times)),
        "max_time": float(np.max(times)),
        "total_time": float(np.sum(times)),
        "num_sentences": len(sentences),
        "num_batches": num_runs,
        "translations": translations
    }
    
    return stats

def run_benchmarks(
    lang_pairs: List[Tuple[str, str]],
    num_runs: int = 5,
    warm_up: int = 2,
    output_file: str = "benchmark_results.json"
) -> Dict:
    """Run benchmarks for specified language pairs."""
    device = "cuda" if torch.cuda.is_available() else "cpu"
    logger.info(f"Running benchmarks on {device}")
    
    results = {
        "device": device,
        "cuda_available": torch.cuda.is_available(),
        "cuda_version": torch.version.cuda if torch.cuda.is_available() else None,
        "num_runs": num_runs,
        "warm_up_runs": warm_up,
        "language_pairs": {}
    }
    
    for src_lang, tgt_lang in lang_pairs:
        model_key = f"{src_lang}-{tgt_lang}"
        
        if model_key not in TEST_SENTENCES:
            logger.warning(f"No test sentences available for {model_key}, skipping...")
            continue
            
        logger.info(f"Benchmarking {model_key}...")
        
        sentences = TEST_SENTENCES[model_key]
        
        # Run standard model benchmark
        standard_stats = benchmark_standard_model(
            src_lang, tgt_lang, sentences, num_runs, warm_up
        )
        
        # Run CTranslate2 model benchmark
        ct2_stats = benchmark_ct2_model(
            src_lang, tgt_lang, sentences, num_runs, warm_up
        )
        
        # Run batch translation benchmark
        batch_stats = benchmark_batch(
            src_lang, tgt_lang, sentences, num_runs, warm_up
        )
        
        # Calculate speedup
        speedup = standard_stats["mean_time"] / ct2_stats["mean_time"]
        batch_speedup = standard_stats["mean_time"] * len(sentences) / batch_stats["mean_time"]
        
        results["language_pairs"][model_key] = {
            "standard_model": standard_stats,
            "ct2_model": ct2_stats,
            "batch_translation": batch_stats,
            "speedup": float(speedup),
            "batch_speedup": float(batch_speedup)
        }
        
        # Print summary
        logger.info(f"\nResults for {model_key}:")
        logger.info(f"  Standard model average time: {standard_stats['mean_time']:.4f}s")
        logger.info(f"  CTranslate2 model average time: {ct2_stats['mean_time']:.4f}s")
        logger.info(f"  Batch translation average time: {batch_stats['mean_time']:.4f}s (for {len(sentences)} sentences)")
        logger.info(f"  Speedup: {speedup:.2f}x")
        logger.info(f"  Batch speedup: {batch_speedup:.2f}x")
    
    # Save results to file
    with open(output_file, "w") as f:
        json.dump(results, f, indent=2)
        
    logger.info(f"Benchmark results saved to {output_file}")
    
    return results

def main():
    """Main entry point for the benchmark script."""
    parser = argparse.ArgumentParser(
        description="Benchmark translation models performance"
    )
    
    parser.add_argument(
        "--lang-pairs", 
        type=str, 
        nargs="+",
        default=["en-es", "en-fr", "en-de", "en-dra"],
        help="Language pairs to benchmark (e.g., 'en-es en-fr')"
    )
    parser.add_argument(
        "--runs", 
        type=int, 
        default=5,
        help="Number of benchmark runs"
    )
    parser.add_argument(
        "--warm-up", 
        type=int, 
        default=2,
        help="Number of warm-up runs"
    )
    parser.add_argument(
        "--output", 
        type=str, 
        default="benchmark_results.json",
        help="Output file for benchmark results"
    )
    
    args = parser.parse_args()
    
    # Parse language pairs
    lang_pairs = []
    for pair in args.lang_pairs:
        if "-" in pair:
            src, tgt = pair.split("-")
            lang_pairs.append((src, tgt))
        else:
            logger.warning(f"Invalid language pair format: {pair}, skipping...")
    
    if not lang_pairs:
        logger.error("No valid language pairs specified")
        return 1
    
    # Run benchmarks
    run_benchmarks(
        lang_pairs=lang_pairs,
        num_runs=args.runs,
        warm_up=args.warm_up,
        output_file=args.output
    )
    
    return 0

if __name__ == "__main__":
    sys.exit(main())