Trouter-Library commited on
Commit
0574c09
·
verified ·
1 Parent(s): 9e7df3d

Create inference/benchmark.py

Browse files
Files changed (1) hide show
  1. inference/benchmark.py +422 -0
inference/benchmark.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Helion-2.5-Rnd Benchmark Runner
4
+ Comprehensive benchmarking suite for performance testing
5
+ """
6
+
7
+ import argparse
8
+ import json
9
+ import logging
10
+ import statistics
11
+ import time
12
+ from collections import defaultdict
13
+ from concurrent.futures import ThreadPoolExecutor, as_completed
14
+ from datetime import datetime
15
+ from pathlib import Path
16
+ from typing import Dict, List, Optional
17
+
18
+ import numpy as np
19
+
20
+ from inference.client import HelionClient
21
+
22
+ logging.basicConfig(level=logging.INFO)
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class BenchmarkRunner:
27
+ """Run comprehensive benchmarks on Helion model"""
28
+
29
+ def __init__(
30
+ self,
31
+ base_url: str = "http://localhost:8000",
32
+ output_dir: str = "./benchmark_results"
33
+ ):
34
+ """
35
+ Initialize benchmark runner
36
+
37
+ Args:
38
+ base_url: API base URL
39
+ output_dir: Directory for results
40
+ """
41
+ self.client = HelionClient(base_url=base_url)
42
+ self.output_dir = Path(output_dir)
43
+ self.output_dir.mkdir(parents=True, exist_ok=True)
44
+
45
+ self.results = {
46
+ 'timestamp': datetime.now().isoformat(),
47
+ 'base_url': base_url,
48
+ 'tests': {}
49
+ }
50
+
51
+ def benchmark_latency(
52
+ self,
53
+ num_requests: int = 100,
54
+ prompt_lengths: List[int] = [128, 512, 2048],
55
+ max_tokens: int = 256
56
+ ) -> Dict:
57
+ """
58
+ Benchmark inference latency
59
+
60
+ Args:
61
+ num_requests: Number of requests per test
62
+ prompt_lengths: Different prompt lengths to test
63
+ max_tokens: Maximum tokens to generate
64
+
65
+ Returns:
66
+ Latency benchmark results
67
+ """
68
+ logger.info("Running latency benchmark...")
69
+
70
+ results = {}
71
+
72
+ for prompt_len in prompt_lengths:
73
+ logger.info(f"Testing prompt length: {prompt_len}")
74
+
75
+ # Generate test prompt
76
+ test_prompt = "Hello world. " * (prompt_len // 13)
77
+
78
+ latencies = []
79
+ first_token_latencies = []
80
+
81
+ for i in range(num_requests):
82
+ try:
83
+ start_time = time.time()
84
+
85
+ response = self.client.complete(
86
+ prompt=test_prompt,
87
+ max_tokens=max_tokens,
88
+ temperature=0.7,
89
+ stream=False
90
+ )
91
+
92
+ end_time = time.time()
93
+ latency = (end_time - start_time) * 1000 # Convert to ms
94
+
95
+ latencies.append(latency)
96
+
97
+ if i % 10 == 0:
98
+ logger.info(f" Progress: {i+1}/{num_requests}")
99
+
100
+ except Exception as e:
101
+ logger.error(f"Request failed: {e}")
102
+
103
+ if latencies:
104
+ results[f"prompt_{prompt_len}"] = {
105
+ 'num_samples': len(latencies),
106
+ 'mean_ms': statistics.mean(latencies),
107
+ 'median_ms': statistics.median(latencies),
108
+ 'std_dev_ms': statistics.stdev(latencies) if len(latencies) > 1 else 0,
109
+ 'min_ms': min(latencies),
110
+ 'max_ms': max(latencies),
111
+ 'p50_ms': np.percentile(latencies, 50),
112
+ 'p90_ms': np.percentile(latencies, 90),
113
+ 'p95_ms': np.percentile(latencies, 95),
114
+ 'p99_ms': np.percentile(latencies, 99)
115
+ }
116
+
117
+ return results
118
+
119
+ def benchmark_throughput(
120
+ self,
121
+ duration_seconds: int = 60,
122
+ concurrent_requests: int = 10,
123
+ prompt_length: int = 512,
124
+ max_tokens: int = 128
125
+ ) -> Dict:
126
+ """
127
+ Benchmark throughput with concurrent requests
128
+
129
+ Args:
130
+ duration_seconds: How long to run test
131
+ concurrent_requests: Number of concurrent requests
132
+ prompt_length: Prompt length for testing
133
+ max_tokens: Maximum tokens to generate
134
+
135
+ Returns:
136
+ Throughput benchmark results
137
+ """
138
+ logger.info(f"Running throughput benchmark for {duration_seconds}s...")
139
+
140
+ test_prompt = "The quick brown fox jumps over the lazy dog. " * (prompt_length // 45)
141
+
142
+ start_time = time.time()
143
+ end_time = start_time + duration_seconds
144
+
145
+ completed_requests = 0
146
+ failed_requests = 0
147
+ total_tokens = 0
148
+ latencies = []
149
+
150
+ def make_request():
151
+ try:
152
+ req_start = time.time()
153
+ response = self.client.complete(
154
+ prompt=test_prompt,
155
+ max_tokens=max_tokens,
156
+ temperature=0.7
157
+ )
158
+ req_end = time.time()
159
+
160
+ return {
161
+ 'success': True,
162
+ 'latency': req_end - req_start,
163
+ 'tokens': len(response.split()) # Approximate
164
+ }
165
+ except Exception as e:
166
+ return {'success': False, 'error': str(e)}
167
+
168
+ with ThreadPoolExecutor(max_workers=concurrent_requests) as executor:
169
+ while time.time() < end_time:
170
+ futures = [executor.submit(make_request) for _ in range(concurrent_requests)]
171
+
172
+ for future in as_completed(futures):
173
+ result = future.result()
174
+
175
+ if result['success']:
176
+ completed_requests += 1
177
+ latencies.append(result['latency'] * 1000)
178
+ total_tokens += result.get('tokens', 0)
179
+ else:
180
+ failed_requests += 1
181
+
182
+ actual_duration = time.time() - start_time
183
+
184
+ return {
185
+ 'duration_seconds': actual_duration,
186
+ 'concurrent_requests': concurrent_requests,
187
+ 'completed_requests': completed_requests,
188
+ 'failed_requests': failed_requests,
189
+ 'requests_per_second': completed_requests / actual_duration,
190
+ 'total_tokens': total_tokens,
191
+ 'tokens_per_second': total_tokens / actual_duration,
192
+ 'avg_latency_ms': statistics.mean(latencies) if latencies else 0,
193
+ 'p95_latency_ms': np.percentile(latencies, 95) if latencies else 0
194
+ }
195
+
196
+ def benchmark_context_length(
197
+ self,
198
+ context_lengths: List[int] = [1024, 4096, 16384, 65536],
199
+ num_samples: int = 10
200
+ ) -> Dict:
201
+ """
202
+ Benchmark performance across different context lengths
203
+
204
+ Args:
205
+ context_lengths: List of context lengths to test
206
+ num_samples: Number of samples per length
207
+
208
+ Returns:
209
+ Context length benchmark results
210
+ """
211
+ logger.info("Running context length benchmark...")
212
+
213
+ results = {}
214
+
215
+ for ctx_len in context_lengths:
216
+ logger.info(f"Testing context length: {ctx_len}")
217
+
218
+ # Generate long context
219
+ base_text = "This is a test sentence for context length benchmarking. "
220
+ long_prompt = base_text * (ctx_len // len(base_text))
221
+ long_prompt = long_prompt[:ctx_len] + "\n\nSummarize the above text:"
222
+
223
+ latencies = []
224
+
225
+ for i in range(num_samples):
226
+ try:
227
+ start_time = time.time()
228
+
229
+ response = self.client.complete(
230
+ prompt=long_prompt,
231
+ max_tokens=256,
232
+ temperature=0.5
233
+ )
234
+
235
+ end_time = time.time()
236
+ latencies.append((end_time - start_time) * 1000)
237
+
238
+ except Exception as e:
239
+ logger.error(f"Context length {ctx_len} failed: {e}")
240
+
241
+ if latencies:
242
+ results[f"context_{ctx_len}"] = {
243
+ 'mean_latency_ms': statistics.mean(latencies),
244
+ 'median_latency_ms': statistics.median(latencies),
245
+ 'std_dev_ms': statistics.stdev(latencies) if len(latencies) > 1 else 0
246
+ }
247
+
248
+ return results
249
+
250
+ def benchmark_generation_quality(
251
+ self,
252
+ test_prompts: Optional[List[str]] = None,
253
+ num_samples: int = 5
254
+ ) -> Dict:
255
+ """
256
+ Benchmark generation quality with diverse prompts
257
+
258
+ Args:
259
+ test_prompts: Custom test prompts
260
+ num_samples: Number of samples per prompt type
261
+
262
+ Returns:
263
+ Quality benchmark results
264
+ """
265
+ logger.info("Running generation quality benchmark...")
266
+
267
+ if test_prompts is None:
268
+ test_prompts = [
269
+ "Explain quantum computing in simple terms:",
270
+ "Write a Python function to calculate fibonacci numbers:",
271
+ "Translate 'Hello, how are you?' to Spanish, French, and German:",
272
+ "Solve: If x + 5 = 12, what is x?",
273
+ "Write a haiku about artificial intelligence:"
274
+ ]
275
+
276
+ results = {}
277
+
278
+ for i, prompt in enumerate(test_prompts):
279
+ logger.info(f"Testing prompt {i+1}/{len(test_prompts)}")
280
+
281
+ responses = []
282
+
283
+ for _ in range(num_samples):
284
+ try:
285
+ response = self.client.complete(
286
+ prompt=prompt,
287
+ max_tokens=512,
288
+ temperature=0.7
289
+ )
290
+ responses.append(response)
291
+ except Exception as e:
292
+ logger.error(f"Generation failed: {e}")
293
+
294
+ if responses:
295
+ results[f"prompt_{i+1}"] = {
296
+ 'prompt': prompt[:50] + "...",
297
+ 'num_responses': len(responses),
298
+ 'avg_length': statistics.mean([len(r) for r in responses]),
299
+ 'sample_response': responses[0][:200] + "..."
300
+ }
301
+
302
+ return results
303
+
304
+ def run_all_benchmarks(self, quick_mode: bool = False) -> Dict:
305
+ """
306
+ Run all benchmark suites
307
+
308
+ Args:
309
+ quick_mode: Run faster with fewer samples
310
+
311
+ Returns:
312
+ Complete benchmark results
313
+ """
314
+ logger.info("Starting comprehensive benchmark suite...")
315
+
316
+ if quick_mode:
317
+ logger.info("Running in quick mode (fewer samples)")
318
+
319
+ # Latency benchmark
320
+ logger.info("\n=== Latency Benchmark ===")
321
+ self.results['tests']['latency'] = self.benchmark_latency(
322
+ num_requests=20 if quick_mode else 100,
323
+ prompt_lengths=[128, 512] if quick_mode else [128, 512, 2048]
324
+ )
325
+
326
+ # Throughput benchmark
327
+ logger.info("\n=== Throughput Benchmark ===")
328
+ self.results['tests']['throughput'] = self.benchmark_throughput(
329
+ duration_seconds=30 if quick_mode else 60,
330
+ concurrent_requests=5 if quick_mode else 10
331
+ )
332
+
333
+ # Context length benchmark
334
+ logger.info("\n=== Context Length Benchmark ===")
335
+ self.results['tests']['context_length'] = self.benchmark_context_length(
336
+ context_lengths=[1024, 4096] if quick_mode else [1024, 4096, 16384],
337
+ num_samples=5 if quick_mode else 10
338
+ )
339
+
340
+ # Generation quality
341
+ logger.info("\n=== Generation Quality Benchmark ===")
342
+ self.results['tests']['generation_quality'] = self.benchmark_generation_quality(
343
+ num_samples=2 if quick_mode else 5
344
+ )
345
+
346
+ return self.results
347
+
348
+ def save_results(self, filename: Optional[str] = None):
349
+ """
350
+ Save benchmark results to file
351
+
352
+ Args:
353
+ filename: Output filename
354
+ """
355
+ if filename is None:
356
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
357
+ filename = f"benchmark_{timestamp}.json"
358
+
359
+ output_path = self.output_dir / filename
360
+
361
+ with open(output_path, 'w') as f:
362
+ json.dump(self.results, f, indent=2)
363
+
364
+ logger.info(f"Results saved to {output_path}")
365
+
366
+ def print_summary(self):
367
+ """Print benchmark summary"""
368
+ logger.info("\n" + "="*60)
369
+ logger.info("BENCHMARK SUMMARY")
370
+ logger.info("="*60)
371
+
372
+ if 'latency' in self.results['tests']:
373
+ logger.info("\nLatency Results:")
374
+ for prompt_type, metrics in self.results['tests']['latency'].items():
375
+ logger.info(f" {prompt_type}:")
376
+ logger.info(f" Mean: {metrics['mean_ms']:.2f}ms")
377
+ logger.info(f" P95: {metrics['p95_ms']:.2f}ms")
378
+ logger.info(f" P99: {metrics['p99_ms']:.2f}ms")
379
+
380
+ if 'throughput' in self.results['tests']:
381
+ logger.info("\nThroughput Results:")
382
+ metrics = self.results['tests']['throughput']
383
+ logger.info(f" Requests/sec: {metrics['requests_per_second']:.2f}")
384
+ logger.info(f" Tokens/sec: {metrics['tokens_per_second']:.2f}")
385
+ logger.info(f" Avg Latency: {metrics['avg_latency_ms']:.2f}ms")
386
+
387
+ logger.info("\n" + "="*60)
388
+
389
+
390
+ def main():
391
+ """Main entry point"""
392
+ parser = argparse.ArgumentParser(description="Helion Benchmark Runner")
393
+ parser.add_argument("--base-url", type=str, default="http://localhost:8000")
394
+ parser.add_argument("--output-dir", type=str, default="./benchmark_results")
395
+ parser.add_argument("--quick", action="store_true", help="Run quick benchmark")
396
+ parser.add_argument("--test", type=str, choices=['latency', 'throughput', 'context', 'quality', 'all'],
397
+ default='all', help="Specific test to run")
398
+
399
+ args = parser.parse_args()
400
+
401
+ runner = BenchmarkRunner(
402
+ base_url=args.base_url,
403
+ output_dir=args.output_dir
404
+ )
405
+
406
+ if args.test == 'all':
407
+ results = runner.run_all_benchmarks(quick_mode=args.quick)
408
+ elif args.test == 'latency':
409
+ results = runner.benchmark_latency(num_requests=20 if args.quick else 100)
410
+ elif args.test == 'throughput':
411
+ results = runner.benchmark_throughput(duration_seconds=30 if args.quick else 60)
412
+ elif args.test == 'context':
413
+ results = runner.benchmark_context_length(num_samples=5 if args.quick else 10)
414
+ elif args.test == 'quality':
415
+ results = runner.benchmark_generation_quality(num_samples=2 if args.quick else 5)
416
+
417
+ runner.save_results()
418
+ runner.print_summary()
419
+
420
+
421
+ if __name__ == "__main__":
422
+ main()