-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark_runner.py
More file actions
2590 lines (2145 loc) · 112 KB
/
benchmark_runner.py
File metadata and controls
2590 lines (2145 loc) · 112 KB
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
LLM Benchmark Runner for Vast.ai
Orchestrates vLLM deployment, AIPerf benchmarking, and result collection on Vast.ai instances.
Supports both single benchmarks and batch benchmark suites.
"""
import os
import sys
import time
import json
import logging
import argparse
import shutil
from datetime import datetime
from pathlib import Path
from typing import Dict, Any, Optional, List
import yaml
import requests
from dotenv import load_dotenv
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn
from rich.panel import Panel
from rich.table import Table
from vast_manager import VastManager
from result_uploader import ResultUploader
from utils import setup_logging, validate_config, format_duration
from power_analysis import generate_power_report, save_power_report, print_power_summary
console = Console()
# LoRA adapter configuration: maps adapter names to HuggingFace repo IDs
# These will be downloaded to /models/loras/<adapter-name> on the instance
# Repo IDs can be overridden via environment variables (see .env.example)
def get_lora_adapters():
return {
'customer-support-faq': os.getenv('LORA_CUSTOMER_SUPPORT_FAQ', 'holtmann/qwen3-8b-customer-support-faq-lora'),
'technical-docs': os.getenv('LORA_TECHNICAL_DOCS', 'holtmann/qwen3-8b-technical-docs-lora'),
'json-output': os.getenv('LORA_JSON_OUTPUT', 'holtmann/qwen3-8b-json-output-lora'),
}
LORA_BASE_PATH = '/models/loras'
class BenchmarkSuiteRunner:
"""Orchestrator for running benchmark suites on a single Vast.ai instance"""
def __init__(self, suite_config: Dict[str, Any], args: argparse.Namespace):
"""
Initialize the benchmark suite runner.
Args:
suite_config: Suite configuration from YAML
args: Command-line arguments
"""
self.suite_config = suite_config
self.args = args
self.logger = logging.getLogger(__name__)
# Extract instance and S3 config
self.instance_config = suite_config['instance']
self.s3_config = suite_config['s3']
self.benchmarks = suite_config['benchmarks']
# Build compatible config dict for VastManager and ResultUploader
self.config = self._build_legacy_config()
# Initialize managers
self.vast_manager = VastManager(self.config, self.logger)
self.result_uploader = ResultUploader(self.config, self.logger)
# Runtime state
self.instance_id: Optional[int] = None
self.instance_ip: Optional[str] = None
self.run_id = datetime.now().strftime("%Y%m%d_%H%M%S")
self.suite_name = suite_config.get('name', 'unnamed_suite')
self.results_base_dir = Path("results") / f"{self.run_id}_{self._sanitize_name(self.suite_name)}"
self.results_base_dir.mkdir(parents=True, exist_ok=True)
# Track current model for cleanup decisions
self.current_model: Optional[str] = None
# Track benchmark results
self.benchmark_results: List[Dict[str, Any]] = []
def _build_legacy_config(self) -> Dict[str, Any]:
"""Build config dict compatible with VastManager and ResultUploader"""
return {
'vast': {
'gpu_name': self.instance_config['gpu_type'],
'num_gpus': self.instance_config['gpu_count'],
'disk_space': self.instance_config['disk_space_gb'],
'image': self.instance_config.get('image', 'holtmann/llm-benchmark:latest'),
'max_bid_price': self.instance_config.get('max_bid_price', 1.0),
'ssh_timeout': self.instance_config.get('ssh_timeout', 900),
'prebuilt_image': True
},
'vllm': {
'port': 8000,
'host': '0.0.0.0',
'startup_timeout': 600
},
'aiperf': {},
's3': {
'upload_json': self.s3_config.get('upload_json', True),
'upload_csv': self.s3_config.get('upload_csv', True),
'upload_logs': self.s3_config.get('upload_logs', True),
'compress_logs': self.s3_config.get('compress_logs', True),
'timestamp_format': self.s3_config.get('timestamp_format', '%Y%m%d_%H%M%S')
}
}
def _sanitize_name(self, name: str) -> str:
"""Sanitize a name for use in file paths"""
return name.replace(' ', '_').replace('/', '_').replace(':', '_')
def run(self) -> bool:
"""
Execute the complete benchmark suite.
Returns:
bool: True if all benchmarks succeeded, False if any failed
"""
start_time = time.time()
try:
# Display suite header
self._display_suite_header()
# Step 1: Provision instance
if not self._provision_instance():
return False
# Step 2: Setup environment
if not self._setup_environment():
return False
# Step 3: Run all benchmarks
all_success = True
for i, benchmark in enumerate(self.benchmarks):
benchmark_name = benchmark.get('name', f'benchmark_{i+1}')
console.print(f"\n{'='*60}")
console.print(f"[bold cyan]Benchmark {i+1}/{len(self.benchmarks)}: {benchmark_name}[/bold cyan]")
console.print(f"{'='*60}")
success = self._run_single_benchmark(benchmark, i)
result = {
'name': benchmark_name,
'model': benchmark['model'],
'success': success,
'timestamp': datetime.now().isoformat()
}
self.benchmark_results.append(result)
if success:
console.print(f"[green]✓[/green] Benchmark '{benchmark_name}' completed successfully")
else:
console.print(f"[red]✗[/red] Benchmark '{benchmark_name}' failed")
all_success = False
# Check if we need to cleanup the model for the next benchmark
self._maybe_cleanup_model(benchmark, i)
# Step 4: Generate power analysis (only for performance benchmarks)
has_performance_benchmarks = any(b.get('type', 'performance') == 'performance' for b in self.benchmarks)
if has_performance_benchmarks:
self._generate_power_analysis()
# Step 5: Upload suite summary
self._upload_suite_summary()
# Final summary
elapsed = time.time() - start_time
self._display_final_summary(elapsed)
return all_success
except KeyboardInterrupt:
console.print("\n[bold red]✗ Benchmark suite interrupted by user[/bold red]")
return False
except Exception as e:
self.logger.error(f"Benchmark suite failed: {e}", exc_info=True)
console.print(f"\n[bold red]✗ Benchmark suite failed: {e}[/bold red]")
return False
finally:
self._cleanup()
def _display_suite_header(self):
"""Display suite information header"""
suite_name = self.suite_config.get('name', 'Unnamed Suite')
description = self.suite_config.get('description', '')
header_text = f"[bold cyan]Benchmark Suite: {suite_name}[/bold cyan]\n"
if description:
header_text += f"[dim]{description}[/dim]\n"
header_text += f"\nGPU: [green]{self.instance_config['gpu_type']} x{self.instance_config['gpu_count']}[/green]\n"
header_text += f"Benchmarks: [yellow]{len(self.benchmarks)}[/yellow]\n"
header_text += f"Run ID: [dim]{self.run_id}[/dim]"
console.print(Panel.fit(header_text, border_style="cyan"))
def _provision_instance(self) -> bool:
"""Provision a Vast.ai instance"""
console.print("\n[bold]Step 1: Provisioning Vast.ai instance[/bold]")
try:
# Check if using existing instance
if self.args.instance_id:
console.print(f"Using existing instance ID: {self.args.instance_id}")
instance_info = self.vast_manager.get_instance_info(self.args.instance_id)
if not instance_info:
console.print(f"[red]✗[/red] Could not find instance {self.args.instance_id}")
return False
self.instance_id = self.args.instance_id
# Get IP from instance info - try different possible field names
self.instance_ip = instance_info.get('public_ipaddr') or instance_info.get('ssh_host') or instance_info.get('ip')
if not self.instance_ip:
console.print(f"[yellow]Warning:[/yellow] Could not determine IP, using instance ID for SSH")
self.instance_ip = str(self.args.instance_id)
console.print(f"[green]✓[/green] Using existing instance: ID={self.instance_id}, IP={self.instance_ip}")
return True
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TimeElapsedColumn(),
console=console
) as progress:
task = progress.add_task("Searching for available instances...", total=None)
instance_id, instance_ip = self.vast_manager.create_instance(
gpu_name=self.instance_config['gpu_type'],
num_gpus=self.instance_config['gpu_count'],
disk_space=self.instance_config['disk_space_gb'],
image=self.instance_config.get('image', 'holtmann/llm-benchmark:latest'),
min_download_speed=self.instance_config.get('min_download_speed', 1000.0),
blacklist_machines=self.instance_config.get('blacklist_machines', [])
)
self.instance_id = instance_id
self.instance_ip = instance_ip
progress.update(task, description=f"Instance {instance_id} created at {instance_ip}")
console.print(f"[green]✓[/green] Instance provisioned: ID={instance_id}, IP={instance_ip}")
return True
except Exception as e:
self.logger.error(f"Failed to provision instance: {e}", exc_info=True)
console.print(f"[red]✗[/red] Failed to provision instance: {e}")
return False
def _setup_environment(self) -> bool:
"""Setup environment on the instance"""
console.print("\n[bold]Step 2: Setting up environment[/bold]")
try:
ssh_timeout = self.instance_config.get('ssh_timeout', 900)
console.print(f"Waiting for SSH connection (timeout: {ssh_timeout}s)...")
if not self.vast_manager.wait_for_ssh(self.instance_id, timeout=ssh_timeout):
console.print("[red]✗[/red] SSH connection timeout")
return False
# Using pre-built image - verify installations
console.print("Using pre-built Docker image - verifying installations...")
# Fix libcuda.so symlink
self.vast_manager.execute_command(
self.instance_id,
"ln -sf /usr/lib/x86_64-linux-gnu/libcuda.so.1 /usr/lib/x86_64-linux-gnu/libcuda.so 2>/dev/null || true"
)
# Setup HuggingFace token if available
hf_token = os.getenv('HF_TOKEN')
if hf_token:
console.print("Setting up HuggingFace token...")
self.vast_manager.execute_command(
self.instance_id,
f"export HF_TOKEN='{hf_token}' && huggingface-cli login --token $HF_TOKEN 2>/dev/null || true"
)
# Verify vLLM and aiperf
verify_commands = [
"python3 -m vllm.entrypoints.openai.api_server --help > /dev/null 2>&1",
"aiperf --help > /dev/null 2>&1"
]
for cmd in verify_commands:
success = self.vast_manager.execute_command(self.instance_id, cmd)
if not success:
console.print(f"[red]✗[/red] Verification failed: {cmd}")
return False
console.print("[green]✓[/green] Environment verified")
return True
except Exception as e:
self.logger.error(f"Environment setup failed: {e}", exc_info=True)
console.print(f"[red]✗[/red] Environment setup failed: {e}")
return False
def _run_single_benchmark(self, benchmark: Dict[str, Any], index: int) -> bool:
"""
Run a single benchmark from the suite.
Args:
benchmark: Benchmark configuration
index: Benchmark index in the suite
Returns:
bool: True if successful
"""
benchmark_name = benchmark.get('name', f'benchmark_{index+1}')
model = benchmark['model']
benchmark_type = benchmark.get('type', 'performance')
vllm_config = benchmark.get('vllm', {})
aiperf_config = benchmark.get('aiperf', {})
lm_eval_config = benchmark.get('lm_eval', {})
# Create results directory for this benchmark
results_dir = self.results_base_dir / f"{index+1:03d}_{self._sanitize_name(benchmark_name)}"
results_dir.mkdir(parents=True, exist_ok=True)
# Skip if benchmark already completed successfully (check all previous runs for this suite)
benchmark_dir_name = f"{index+1:03d}_{self._sanitize_name(benchmark_name)}"
suite_pattern = f"*_{self._sanitize_name(self.suite_name)}"
for prev_run_dir in Path("results").glob(suite_pattern):
prev_benchmark_dir = prev_run_dir / benchmark_dir_name
if (prev_benchmark_dir / 'profile_export_aiperf.json').exists():
console.print(f"[cyan]⏭[/cyan] Skipping '{benchmark_name}' - already completed in {prev_run_dir.name}")
return True
try:
# Save benchmark config
config_file = results_dir / 'benchmark_config.json'
config_file.write_text(json.dumps(benchmark, indent=2))
if benchmark_type == 'quality':
# Quality benchmark using lm_eval (lm_eval manages vLLM itself)
return self._run_quality_benchmark(benchmark_name, model, vllm_config, lm_eval_config, results_dir, benchmark)
else:
# Performance benchmark using AIPerf (requires vLLM server)
return self._run_performance_benchmark(benchmark_name, model, vllm_config, aiperf_config, results_dir, benchmark)
except Exception as e:
self.logger.error(f"Benchmark '{benchmark_name}' failed: {e}", exc_info=True)
self._save_error(results_dir, str(e))
self._collect_vllm_logs(results_dir)
self._stop_vllm()
self._upload_failed_benchmark(benchmark_name, model, results_dir, benchmark)
return False
def _run_performance_benchmark(self, benchmark_name: str, model: str, vllm_config: Dict[str, Any],
aiperf_config: Dict[str, Any], results_dir: Path, benchmark: Dict[str, Any]) -> bool:
"""Run a performance benchmark using AIPerf"""
try:
# Track if we used FP8 KV cache as fallback
used_fp8_kv_cache = False
# Step 1: Download model if needed
if model != self.current_model:
console.print(f"Downloading model: [yellow]{model}[/yellow]")
# Model will be downloaded when vLLM starts
# Step 2: Start vLLM server (pass concurrency to auto-set max-num-seqs)
concurrency = aiperf_config.get('concurrency')
vllm_ready = False
# First attempt with original config
if self._start_vllm(model, vllm_config, concurrency=concurrency):
if self._wait_for_vllm():
vllm_ready = True
else:
# Check if it was an OOM error
if self._check_vllm_oom():
console.print("\n[yellow]⚠ OOM detected - retrying with FP8 KV cache + gpu_memory_utilization=0.95[/yellow]")
self._stop_vllm()
# Retry with FP8 KV cache and higher GPU memory utilization
vllm_config_fp8 = vllm_config.copy()
vllm_config_fp8['kv_cache_dtype'] = 'fp8'
vllm_config_fp8['gpu_memory_utilization'] = 0.95
used_fp8_kv_cache = True
if self._start_vllm(model, vllm_config_fp8, concurrency=concurrency):
if self._wait_for_vllm():
vllm_ready = True
console.print("[green]✓ vLLM started with FP8 KV cache + gpu_memory_utilization=0.95[/green]")
else:
self._save_error(results_dir, "vLLM server did not become ready (even with FP8 KV cache)")
self._collect_vllm_logs(results_dir)
self._stop_vllm()
self._upload_failed_benchmark(benchmark_name, model, results_dir, benchmark)
return False
else:
self._save_error(results_dir, "vLLM server did not become ready")
self._collect_vllm_logs(results_dir)
self._stop_vllm()
self._upload_failed_benchmark(benchmark_name, model, results_dir, benchmark)
return False
else:
self._save_error(results_dir, "Failed to start vLLM server")
self._collect_vllm_logs(results_dir)
self._upload_failed_benchmark(benchmark_name, model, results_dir, benchmark)
return False
if not vllm_ready:
return False
self.current_model = model
# Store FP8 KV cache flag for metadata
benchmark['_used_fp8_kv_cache'] = used_fp8_kv_cache
# Extract LoRA adapter names for aiperf model switching
lora_adapters = None
if vllm_config.get('enable_lora') and vllm_config.get('lora_modules'):
lora_adapters = [m['name'] for m in vllm_config['lora_modules']]
# Step 4: Run aiperf benchmark
if not self._run_aiperf(model, aiperf_config, results_dir, lora_adapters=lora_adapters):
self._save_error(results_dir, "AIPerf benchmark failed")
self._collect_vllm_logs(results_dir)
self._stop_vllm()
self._upload_failed_benchmark(benchmark_name, model, results_dir, benchmark)
return False
# Step 5: Collect results
self._collect_results(results_dir)
# Step 6: Stop vLLM server
self._stop_vllm()
# Step 7: Upload results to S3
self._upload_benchmark_results(benchmark_name, model, results_dir, benchmark)
return True
except Exception as e:
self.logger.error(f"Performance benchmark '{benchmark_name}' failed: {e}", exc_info=True)
self._save_error(results_dir, str(e))
self._collect_vllm_logs(results_dir)
self._stop_vllm()
self._upload_failed_benchmark(benchmark_name, model, results_dir, benchmark)
return False
def _run_quality_benchmark(self, benchmark_name: str, model: str, vllm_config: Dict[str, Any],
lm_eval_config: Dict[str, Any], results_dir: Path, benchmark: Dict[str, Any]) -> bool:
"""Run a quality benchmark using lm_eval (lm_eval manages vLLM internally)"""
console.print(f"Running lm_eval quality benchmark: [yellow]{benchmark_name}[/yellow]")
console.print(f"Model: [cyan]{model}[/cyan]")
try:
num_gpus = self.instance_config['gpu_count']
# Build model_args for lm_eval vLLM backend
model_args = f"pretrained={model}"
model_args += f",tensor_parallel_size={num_gpus}"
# Add vllm config to model_args
if 'gpu_memory_utilization' in vllm_config:
model_args += f",gpu_memory_utilization={vllm_config['gpu_memory_utilization']}"
if 'max_model_len' in vllm_config:
model_args += f",max_model_len={vllm_config['max_model_len']}"
if 'dtype' in vllm_config:
model_args += f",dtype={vllm_config['dtype']}"
if 'max_num_seqs' in vllm_config:
model_args += f",max_num_seqs={vllm_config['max_num_seqs']}"
if 'enable_chunked_prefill' in vllm_config:
model_args += f",enable_chunked_prefill={vllm_config['enable_chunked_prefill']}"
if 'max_num_batched_tokens' in vllm_config:
model_args += f",max_num_batched_tokens={vllm_config['max_num_batched_tokens']}"
if 'enforce_eager' in vllm_config:
model_args += f",enforce_eager={vllm_config['enforce_eager']}"
# Add trust_remote_code for some models
if lm_eval_config.get('trust_remote_code', True):
model_args += ",trust_remote_code=True"
# Get lm_eval parameters
tasks = lm_eval_config.get('tasks', 'hellaswag')
num_fewshot = lm_eval_config.get('num_fewshot', 0)
batch_size = lm_eval_config.get('batch_size', 'auto')
limit = lm_eval_config.get('limit', None)
# Get timeout - default 3 hours for MMLU, 1 hour for others
default_timeout = 10800 if 'mmlu' in tasks.lower() else 3600
timeout = lm_eval_config.get('timeout', default_timeout)
console.print(f"Tasks: [yellow]{tasks}[/yellow]")
console.print(f"Few-shot: [yellow]{num_fewshot}[/yellow]")
console.print(f"Tensor Parallel: [yellow]{num_gpus}[/yellow]")
# HF token for gated models
hf_token = os.getenv('HF_TOKEN')
token_env = f"HF_TOKEN='{hf_token}' " if hf_token else ""
# Build lm_eval command
lm_eval_cmd = f"""{token_env}lm_eval --model vllm \\
--model_args "{model_args}" \\
--tasks {tasks} \\
--num_fewshot {num_fewshot} \\
--batch_size {batch_size} \\
--output_path /tmp/lm_eval_results \\
--log_samples"""
if limit:
lm_eval_cmd += f" \\\n --limit {limit}"
# Add any additional lm_eval parameters
for key, value in lm_eval_config.items():
if key not in ['tasks', 'num_fewshot', 'batch_size', 'limit', 'trust_remote_code', 'timeout']:
# Handle different value types
if isinstance(value, bool):
# Boolean flags: only add if True (e.g., --apply_chat_template)
if value:
lm_eval_cmd += f" \\\n --{key}"
elif isinstance(value, str) and any(c in value for c in ' :<>/'):
# Quote strings with spaces, colons, or shell special chars
lm_eval_cmd += f' \\\n --{key} "{value}"'
else:
lm_eval_cmd += f" \\\n --{key} {value}"
# Log the full command for debugging
console.print(f"\n[dim]lm_eval command:[/dim]")
console.print(f"[cyan]{lm_eval_cmd}[/cyan]\n")
# Write lm_eval command to a script file to avoid quoting issues
script_content = f"""#!/bin/bash
# Increase file descriptor limit to avoid "Too many open files" error
ulimit -n 65536 2>/dev/null || ulimit -n 4096 2>/dev/null || true
# Log the command being run
echo "=== LM_EVAL COMMAND ===" >> /tmp/lm_eval.log
echo '{lm_eval_cmd.replace("'", "'\"'\"'")}' >> /tmp/lm_eval.log
echo "=== END COMMAND ===" >> /tmp/lm_eval.log
{lm_eval_cmd} >> /tmp/lm_eval.log 2>&1
echo 'LMEVAL_SUCCESS' >> /tmp/lm_eval.log
"""
# Clear previous log, create script, and run in background
self.vast_manager.execute_command(self.instance_id, "rm -f /tmp/lm_eval.log && touch /tmp/lm_eval.log", quiet=True)
# Use heredoc to write script
write_script_cmd = f"""cat > /tmp/run_lm_eval.sh << 'SCRIPT_EOF'
{script_content}
SCRIPT_EOF
chmod +x /tmp/run_lm_eval.sh"""
self.vast_manager.execute_command(self.instance_id, write_script_cmd, quiet=True)
# Run the script in background
self.vast_manager.execute_command(self.instance_id, "nohup /tmp/run_lm_eval.sh > /dev/null 2>&1 &", quiet=True)
time.sleep(2) # Give the process time to start
# Stream logs while waiting for completion
success = self._wait_for_lm_eval(tasks, timeout=timeout)
if not success:
console.print("[red]✗[/red] lm_eval benchmark failed")
# Show last 50 lines of log
console.print("\nLast 50 lines of lm_eval.log:")
log_content = self.vast_manager.get_file_content(self.instance_id, "/tmp/lm_eval.log")
if log_content:
for line in log_content.strip().split('\n')[-50:]:
console.print(f" {line}")
self._save_error(results_dir, "lm_eval benchmark failed")
self._collect_lm_eval_logs(results_dir)
self._upload_failed_benchmark(benchmark_name, model, results_dir, benchmark, benchmark_type="quality")
return False
console.print("[green]✓[/green] lm_eval benchmark completed")
# Collect results
self._collect_lm_eval_results(results_dir)
# Upload results to S3
self._upload_benchmark_results(benchmark_name, model, results_dir, benchmark, benchmark_type="quality")
return True
except Exception as e:
self.logger.error(f"lm_eval benchmark failed: {e}", exc_info=True)
self._save_error(results_dir, str(e))
self._collect_lm_eval_logs(results_dir)
self._upload_failed_benchmark(benchmark_name, model, results_dir, benchmark, benchmark_type="quality")
return False
def _wait_for_lm_eval(self, tasks: str, timeout: int = 3600) -> bool:
"""Wait for lm_eval to complete while streaming logs"""
console.print("[dim]Streaming lm_eval output:[/dim]\n")
check_interval = 5
elapsed = 0
log_position = 0
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
TimeElapsedColumn(),
console=console,
transient=True
) as progress:
task = progress.add_task(f"Running lm_eval ({tasks})...", total=None)
while elapsed < timeout:
# Stream new log content
new_content, log_position = self.vast_manager.tail_file(
self.instance_id, "/tmp/lm_eval.log", log_position
)
if new_content:
progress.stop() # Temporarily stop progress for log output
for line in new_content.splitlines():
line = line.strip()
if line:
self._print_lm_eval_line(line)
progress.start()
# Check if lm_eval completed
if new_content and 'LMEVAL_SUCCESS' in new_content:
return True
# Check for obvious failures
if new_content and ('OutOfMemoryError' in new_content or 'CUDA out of memory' in new_content):
return False
time.sleep(check_interval)
elapsed += check_interval
console.print(f"\n[red]✗[/red] lm_eval did not complete within {timeout}s")
return False
def _print_lm_eval_line(self, line: str):
"""Print an lm_eval log line with color coding"""
if 'error' in line.lower() or 'exception' in line.lower() or 'traceback' in line.lower():
console.print(f" [red]{line}[/red]")
elif 'OutOfMemory' in line or 'CUDA out of memory' in line:
console.print(f" [red bold]{line}[/red bold]")
elif 'warning' in line.lower() or 'warn' in line.lower():
console.print(f" [yellow]{line}[/yellow]")
elif 'acc' in line.lower() or 'score' in line.lower() or 'result' in line.lower():
console.print(f" [green]{line}[/green]")
elif '%' in line: # Progress indicators
console.print(f" [magenta]{line}[/magenta]")
else:
console.print(f" [dim]{line}[/dim]")
def _collect_lm_eval_logs(self, results_dir: Path):
"""Collect lm_eval logs"""
console.print("Collecting lm_eval logs...")
log_files = {
'/tmp/lm_eval.log': 'lm_eval.log'
}
for remote_path, local_name in log_files.items():
content = self.vast_manager.get_file_content(self.instance_id, remote_path)
if content:
(results_dir / local_name).write_text(content)
def _collect_lm_eval_results(self, results_dir: Path):
"""Collect lm_eval results"""
console.print("Collecting lm_eval results...")
# Collect the log file first
log_content = self.vast_manager.get_file_content(self.instance_id, "/tmp/lm_eval.log")
if log_content:
(results_dir / 'lm_eval.log').write_text(log_content)
# lm_eval saves results in: /tmp/lm_eval_results/<model_name>/results_<timestamp>.json
# Find the actual results file
find_cmd = "find /tmp/lm_eval_results -name 'results_*.json' -type f 2>/dev/null | head -1"
results_path = self.vast_manager.execute_command_with_output(self.instance_id, find_cmd, quiet=True)
if results_path:
results_path = results_path.strip()
if results_path:
console.print(f" Found results at: {results_path}")
content = self.vast_manager.get_file_content(self.instance_id, results_path)
if content:
(results_dir / 'lm_eval_results.json').write_text(content)
console.print("[green]✓[/green] Collected lm_eval results")
return
console.print("[yellow]⚠[/yellow] Could not find lm_eval results file")
# Try to list what's in the results directory for debugging
ls_cmd = "find /tmp/lm_eval_results -type f 2>/dev/null"
files_output = self.vast_manager.execute_command_with_output(self.instance_id, ls_cmd, quiet=True)
if files_output:
console.print(f" Files in results dir: {files_output.strip()}")
def _download_lora_adapters(self, vllm_config: Dict[str, Any]) -> bool:
"""Download LoRA adapters from HuggingFace if needed"""
if not vllm_config.get('enable_lora'):
return True
lora_modules = vllm_config.get('lora_modules', [])
if not lora_modules:
return True
console.print("Downloading LoRA adapters from HuggingFace...")
# Get HF token for private repos
hf_token = os.getenv('HF_TOKEN')
token_arg = f"--token {hf_token}" if hf_token else ""
# Create base directory
mkdir_cmd = f"mkdir -p {LORA_BASE_PATH}"
self.vast_manager.execute_command(self.instance_id, mkdir_cmd, quiet=True)
for adapter in lora_modules:
adapter_name = adapter.get('name')
lora_adapters = get_lora_adapters()
if adapter_name not in lora_adapters:
console.print(f"[yellow]⚠[/yellow] Unknown LoRA adapter: {adapter_name}, skipping")
continue
repo_id = lora_adapters[adapter_name]
local_path = f"{LORA_BASE_PATH}/{adapter_name}"
console.print(f" Downloading {repo_id} -> {local_path}")
download_cmd = f"huggingface-cli download {repo_id} --local-dir {local_path} {token_arg}"
result = self.vast_manager.execute_command(self.instance_id, download_cmd)
if not result:
console.print(f"[red]✗[/red] Failed to download LoRA adapter: {adapter_name}")
return False
console.print(f" [green]✓[/green] Downloaded {adapter_name}")
return True
def _start_vllm(self, model: str, vllm_config: Dict[str, Any], concurrency: int = None) -> bool:
"""Start vLLM server with specified configuration (pass-through any vLLM args)
Args:
concurrency: If provided and max_num_seqs not in vllm_config, sets --max-num-seqs to this value
"""
# Download LoRA adapters if needed (before starting vLLM)
if vllm_config.get('enable_lora'):
if not self._download_lora_adapters(vllm_config):
return False
console.print("Starting vLLM server...")
try:
num_gpus = self.instance_config['gpu_count']
# HF token for gated models
hf_token = os.getenv('HF_TOKEN')
token_env = f"HF_TOKEN='{hf_token}' " if hf_token else ""
# Build vLLM arguments from config (pass-through any parameter)
vllm_args = []
for key, value in vllm_config.items():
# Convert underscores to hyphens for CLI args
arg_name = key.replace('_', '-')
# Handle lora_modules specially - needs name=path format with updated paths
if key == 'lora_modules':
lora_args = []
for adapter in value:
adapter_name = adapter.get('name')
# Use the standard download path instead of config path
local_path = f"{LORA_BASE_PATH}/{adapter_name}"
lora_args.append(f"{adapter_name}={local_path}")
vllm_args.append(f"--lora-modules {' '.join(lora_args)}")
elif isinstance(value, bool):
if value:
vllm_args.append(f"--{arg_name}")
elif isinstance(value, dict):
# Dicts become JSON strings (e.g., chat-template-kwargs)
import json
json_value = json.dumps(value).replace('"', '\\"')
vllm_args.append(f"--{arg_name} \"{json_value}\"")
elif isinstance(value, list):
# Lists become comma-separated
vllm_args.append(f"--{arg_name} {','.join(map(str, value))}")
elif value is not None:
vllm_args.append(f"--{arg_name} {value}")
# Add tensor-parallel-size if not specified
if 'tensor_parallel_size' not in vllm_config and 'tensor-parallel-size' not in vllm_config:
vllm_args.append(f"--tensor-parallel-size {num_gpus}")
# Auto-set max-num-seqs to match aiperf concurrency (avoids memory issues and request queuing)
if concurrency and 'max_num_seqs' not in vllm_config and 'max-num-seqs' not in vllm_config:
vllm_args.append(f"--max-num-seqs {concurrency}")
vllm_args_str = " \\\n ".join(vllm_args)
vllm_cmd = f"""
{token_env}python3 -m vllm.entrypoints.openai.api_server \\
--model {model} \\
--host 0.0.0.0 \\
--port 8000 \\
{vllm_args_str} \\
> /tmp/vllm.log 2>&1 &
"""
self.vast_manager.execute_command(self.instance_id, vllm_cmd, background=True)
# Display key config for user
display_config = {k: v for k, v in vllm_config.items() if k in ['max_model_len', 'gpu_memory_utilization', 'dtype', 'quantization', 'max_num_seqs']}
# Show auto-set max_num_seqs if not in config
if concurrency and 'max_num_seqs' not in vllm_config and 'max-num-seqs' not in vllm_config:
display_config['max_num_seqs'] = f"{concurrency} (from concurrency)"
console.print(f"[green]✓[/green] vLLM server started {display_config}")
return True
except Exception as e:
self.logger.error(f"Failed to start vLLM: {e}", exc_info=True)
return False
def _wait_for_vllm(self, timeout: int = 600) -> bool:
"""Wait for vLLM server to be ready while streaming logs"""
console.print("Waiting for vLLM server to be ready...")
console.print("[dim]Streaming vLLM logs:[/dim]\n")
check_interval = 5
elapsed = 0
log_position = 0
while elapsed < timeout:
# Stream new log content
new_content, log_position = self.vast_manager.tail_file(
self.instance_id, "/tmp/vllm.log", log_position
)
if new_content:
# Print each new line with formatting
for line in new_content.splitlines():
line = line.strip()
if line:
self._print_log_line(line)
# Check if vLLM is ready (quiet=True to suppress expected errors during startup)
check_cmd = "curl -f -s http://localhost:8000/v1/models -o /dev/null && echo 'SUCCESS'"
if self.vast_manager.execute_command(self.instance_id, check_cmd, quiet=True):
console.print(f"\n[green]✓[/green] vLLM server is ready! ({elapsed}s)")
return True
time.sleep(check_interval)
elapsed += check_interval
# Show progress every 30 seconds if no log activity
if elapsed % 30 == 0 and not new_content:
console.print(f" [dim]... waiting ({elapsed}/{timeout}s)[/dim]")
console.print(f"\n[red]✗[/red] vLLM server did not become ready within {timeout}s")
return False
def _print_log_line(self, line: str):
"""Print a log line with color coding based on content"""
if 'error' in line.lower() or 'exception' in line.lower() or 'traceback' in line.lower():
console.print(f" [red]{line}[/red]")
elif 'warning' in line.lower() or 'warn' in line.lower():
console.print(f" [yellow]{line}[/yellow]")
elif 'info' in line.lower() or 'starting' in line.lower() or 'loaded' in line.lower():
console.print(f" [cyan]{line}[/cyan]")
elif 'ready' in line.lower() or 'uvicorn' in line.lower() or 'application startup' in line.lower():
console.print(f" [green]{line}[/green]")
elif '%' in line: # Progress indicators (model loading)
console.print(f" [magenta]{line}[/magenta]")
else:
console.print(f" [dim]{line}[/dim]")
def _stop_vllm(self):
"""Stop the vLLM server"""
console.print("Stopping vLLM server...")
self.vast_manager.execute_command(
self.instance_id,
"pkill -f 'vllm.entrypoints' || true",
quiet=True
)
time.sleep(2) # Give it time to shutdown
def _check_vllm_oom(self) -> bool:
"""Check if vLLM failed due to out of memory error"""
try:
# execute_command returns bool (True if exit code 0, False otherwise)
# grep returns exit code 0 if matches found, 1 if no matches
return self.vast_manager.execute_command(
self.instance_id,
"grep -i -E 'out of memory|OOM|CUDA error|torch.cuda.OutOfMemoryError|cannot allocate|larger than the available KV cache memory' /tmp/vllm.log 2>/dev/null | head -5"
)
except Exception:
return False
def _run_aiperf(self, model: str, aiperf_config: Dict[str, Any], results_dir: Path, lora_adapters: list = None) -> bool:
"""Run AIPerf benchmark (pass-through any aiperf args)
Args:
lora_adapters: List of LoRA adapter names for model switching (e.g., ['customer-support-faq', 'technical-docs'])
"""
console.print("Running AIPerf benchmark...")
try:
# Build aiperf arguments from config (pass-through any parameter)
aiperf_args = []
# Set defaults for required args if not provided
defaults = {
'url': 'http://localhost:8000',
'output_artifact_dir': '/tmp/aiperf_results',
'random_seed': 42,
'request_timeout_seconds': 120
}
# Merge defaults with user config (user config takes precedence)
merged_config = {**defaults, **aiperf_config}
for key, value in merged_config.items():
# Convert underscores to hyphens for CLI args
arg_name = key.replace('_', '-')
if isinstance(value, bool):
if value:
aiperf_args.append(f"--{arg_name}")
elif isinstance(value, dict):
# Dicts become JSON strings (e.g., extra_inputs for chat_template_kwargs)
import json
json_value = json.dumps(value)
aiperf_args.append(f"--{arg_name} '{json_value}'")
elif isinstance(value, list):
# Lists become comma-separated (e.g., concurrency: [1, 4, 8])
aiperf_args.append(f"--{arg_name} {','.join(map(str, value))}")
elif value is not None:
aiperf_args.append(f"--{arg_name} {value}")
aiperf_args_str = " \\\n ".join(aiperf_args)
# Display key config for user
display_keys = ['concurrency', 'input_sequence_length', 'output_sequence_length', 'request_count']
for key in display_keys:
if key in aiperf_config:
console.print(f" {key}: [yellow]{aiperf_config[key]}[/yellow]")
# Start GPU monitoring using DCGM
console.print("Starting GPU telemetry collection...")
# Check if nv-hostengine is running, start if not (must background it), then start dcgmi dmon
gpu_cmd = "pgrep -x nv-hostengine >/dev/null || (nv-hostengine &); sleep 2; dcgmi dmon -e 150,155,156,203,204,240,241 -d 1000 > /tmp/gpu_metrics.log 2>&1 &"
self.vast_manager.execute_command(self.instance_id, gpu_cmd)
time.sleep(1)
# Build model arguments - include LoRA adapters if provided (comma-separated)
if lora_adapters:
# Multiple models: use --model-names with comma-separated list
# Also specify tokenizer since LoRA adapter names aren't HuggingFace models
# (they share the base model's tokenizer)
all_models = [model] + lora_adapters
model_args = f'--model-names "{",".join(all_models)}" --tokenizer "{model}"'
console.print(f" LoRA adapters for switching: [yellow]{', '.join(lora_adapters)}[/yellow]")
else:
# Single model: use --model (original behavior)
model_args = f'--model "{model}"'
# Build aiperf command - write to script file to avoid quoting issues with nohup
aiperf_script = f"""#!/bin/bash
cd /tmp
aiperf profile \\
{model_args} \\
{aiperf_args_str} \\
> /tmp/aiperf.log 2>&1
if [ $? -eq 0 ]; then
echo "AIPERF_SUCCESS" >> /tmp/aiperf.log
else
echo "AIPERF_FAILED" >> /tmp/aiperf.log
fi
"""
# Write script, make executable, and run with nohup
import base64
script_b64 = base64.b64encode(aiperf_script.encode()).decode()
setup_cmd = f"echo '{script_b64}' | base64 -d > /tmp/run_aiperf.sh && chmod +x /tmp/run_aiperf.sh"
self.vast_manager.execute_command(self.instance_id, setup_cmd, quiet=True)
# Start script in background with nohup
start_cmd = "nohup /tmp/run_aiperf.sh > /dev/null 2>&1 & echo $! > /tmp/aiperf.pid"
self.vast_manager.execute_command(self.instance_id, start_cmd, background=False)
time.sleep(3) # Give it time to start
# Verify aiperf started
pid_check = self.vast_manager.execute_command_with_output(
self.instance_id, "cat /tmp/aiperf.pid 2>/dev/null && ps -p $(cat /tmp/aiperf.pid) >/dev/null 2>&1 && echo 'STARTED' || echo 'NOT_STARTED'", quiet=True
)
if not pid_check or 'NOT_STARTED' in pid_check:
console.print("[red]✗[/red] AIPerf failed to start")