-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrun-bench.py
More file actions
1596 lines (1329 loc) · 74 KB
/
run-bench.py
File metadata and controls
1596 lines (1329 loc) · 74 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
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: Apache-2.0
# SPDX-License-Identifier: Apache-2.0
#!/usr/bin/env python3
import yaml
import os
import subprocess
import time
import uuid
from pathlib import Path
from typing import Dict, Any, Union, Optional
import sys
GLOBAL_ARGS = None # MIGHT be set in parse_args()
# Global variables passed between stages in the pipeline
MODEL_URL = None # MUST be set in setup_baseline()
HF_TOKEN = None # MUST be set in setup_baseline()
KEY = None # MUST be set in run_workload()
CURRENT_SERVING_INDEX = None # Track which serving baseline we're currently running
CURRENT_SERVING_CONFIG = None # Track the current serving configuration
CURRENT_SPEC_CONFIG = None # Track the current spec configuration
CURRENT_SPEC_FILE_PATH = None # Track the current spec file path
LMBENCH_SESSION_ID = None # MUST be set in main() - unique identifier for this benchmarking session
def read_run_bench_config() -> Dict[str, Any]:
"""Read and parse the run-bench.yaml file."""
with open('run-bench.yaml', 'r') as f:
config = yaml.safe_load(f)
if '0-bench-specs' not in config:
raise ValueError("0-bench-specs field is missing in run-bench.yaml")
spec_files = config['0-bench-specs']
if not isinstance(spec_files, list):
raise ValueError("0-bench-specs must be a list of spec files")
if len(spec_files) == 0:
raise ValueError("At least one spec file must be specified in 0-bench-specs")
# Validate infrastructure configuration
if '1-infrastructure' not in config:
raise ValueError("1-infrastructure field is missing in run-bench.yaml")
infrastructure_config = config['1-infrastructure']
if not isinstance(infrastructure_config, dict):
raise ValueError("1-infrastructure must be a dictionary")
location = infrastructure_config.get('Location')
if not location:
raise ValueError("Location must be specified in 1-infrastructure")
if location not in ['NoBench', 'LocalMinikube', 'LMCacheGKE', 'Local-Flat']:
raise ValueError(f"Unsupported infrastructure location: {location}")
if location == 'LMCacheGKE':
if 'numClusterGPUs' not in infrastructure_config:
raise ValueError("numClusterGPUs must be specified for LMCacheGKE")
if not isinstance(infrastructure_config['numClusterGPUs'], int):
raise ValueError("numClusterGPUs must be an integer")
print(f"Validated run-bench.yaml with infrastructure location: {location}")
return config
def substitute_hf_token_in_config(config: Dict[str, Any]) -> Dict[str, Any]:
"""Recursively substitute <YOUR_HF_TOKEN> with the HF_TOKEN environment variable."""
hf_token = os.environ.get('HF_TOKEN')
if not hf_token:
print("Warning: HF_TOKEN environment variable must be set!")
sys.exit(1)
def recursive_substitute(obj: Any) -> Any:
if isinstance(obj, dict):
return {k: recursive_substitute(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [recursive_substitute(item) for item in obj]
elif isinstance(obj, str) and obj == '<YOUR_HF_TOKEN>':
return hf_token
else:
return obj
return recursive_substitute(config)
def read_and_process_spec_file(spec_file_path: str) -> Dict[str, Any]:
"""Read a single spec file and process HF_TOKEN substitution."""
full_path = Path('0-bench-specs') / spec_file_path
if not full_path.exists():
raise FileNotFoundError(f"Spec file not found: {full_path}")
with open(full_path, 'r') as f:
config = yaml.safe_load(f)
# Substitute HF_TOKEN
config = substitute_hf_token_in_config(config)
# Validate the config using the existing validation logic
return validate_single_spec_config(config, str(full_path))
def validate_single_spec_config(config: Dict[str, Any], file_path: str) -> Dict[str, Any]:
"""Validate a single spec configuration using the existing validation logic."""
# Validate Name field
if 'Name' not in config:
raise ValueError(f"Name field is missing in {file_path}")
# Validate that Serving is a list of baselines
if 'Serving' not in config:
raise ValueError(f"Serving configuration is missing in {file_path}")
serving_configs = config['Serving']
if not isinstance(serving_configs, list):
raise ValueError(f"Serving configuration must be a list of baseline configurations in {file_path}")
if len(serving_configs) == 0:
raise ValueError(f"At least one serving baseline must be specified in {file_path}")
# Validate each serving baseline configuration
for i, serving_config in enumerate(serving_configs):
if not isinstance(serving_config, dict) or len(serving_config) != 1:
raise ValueError(f"Serving baseline {i} must be a dict with exactly one key (the baseline type) in {file_path}")
baseline_type = list(serving_config.keys())[0]
baseline_config = serving_config[baseline_type]
print(f"Validating serving baseline {i}: {baseline_type} in {file_path}")
if baseline_type == 'SGLang':
script_name = baseline_config.get('scriptName')
model_url = baseline_config.get('modelURL')
api_type = baseline_config.get('apiType', 'completions') # Default to completions for backward compatibility
if not script_name:
raise ValueError(f"scriptName must be specified for SGLang baseline {i} in {file_path}")
if not model_url:
raise ValueError(f"modelURL must be specified for SGLang baseline {i} in {file_path}")
if api_type not in ['completions', 'chat']:
raise ValueError(f"apiType must be 'completions' or 'chat' for SGLang baseline {i} in {file_path}, got: {api_type}")
elif baseline_type == 'RayServe':
script_name = baseline_config.get('scriptName')
accelerator_type = baseline_config.get('acceleratorType')
model_url = baseline_config.get('modelURL')
api_type = baseline_config.get('apiType', 'completions') # Default to completions for backward compatibility
if not script_name:
raise ValueError(f"scriptName must be specified for RayServe baseline {i} in {file_path}")
if not accelerator_type:
raise ValueError(f"acceleratorType must be specified for RayServe baseline {i} in {file_path}")
if not model_url:
raise ValueError(f"modelURL must be specified for RayServe baseline {i} in {file_path}")
if api_type not in ['completions', 'chat']:
raise ValueError(f"apiType must be 'completions' or 'chat' for RayServe baseline {i} in {file_path}, got: {api_type}")
elif baseline_type == 'Helm-ProductionStack':
helm_config = baseline_config.get('helmConfigSelection', '')
hf_token = baseline_config.get('hf_token')
model_url = baseline_config.get('modelURL')
api_type = baseline_config.get('apiType', 'completions') # Default to completions for backward compatibility
if not helm_config:
raise ValueError(f"helmConfigSelection must be specified for Helm-ProductionStack baseline {i} in {file_path}")
if not hf_token:
raise ValueError(f"hf_token must be specified for Helm-ProductionStack baseline {i} in {file_path}")
if not model_url:
raise ValueError(f"modelURL must be specified for Helm-ProductionStack baseline {i} in {file_path}")
if api_type not in ['completions', 'chat']:
raise ValueError(f"apiType must be 'completions' or 'chat' for Helm-ProductionStack baseline {i} in {file_path}, got: {api_type}")
elif baseline_type == 'Direct-ProductionStack':
model_url = baseline_config.get('modelURL')
hf_token = baseline_config.get('hf_token')
api_type = baseline_config.get('apiType', 'completions') # Default to completions for backward compatibility
if not model_url:
raise ValueError(f"modelURL must be specified for Direct-ProductionStack baseline {i} in {file_path}")
if not hf_token:
raise ValueError(f"hf_token must be specified for Direct-ProductionStack baseline {i} in {file_path}")
if api_type not in ['completions', 'chat']:
raise ValueError(f"apiType must be 'completions' or 'chat' for Direct-ProductionStack baseline {i} in {file_path}, got: {api_type}")
elif baseline_type == 'LLM-D':
config_selection = baseline_config.get('configSelection')
model_url = baseline_config.get('modelURL')
hf_token = baseline_config.get('hf_token')
api_type = baseline_config.get('apiType', 'completions') # Default to completions for backward compatibility
if not config_selection:
raise ValueError(f"configSelection must be specified for LLM-D baseline {i} in {file_path}")
if not model_url:
raise ValueError(f"modelURL must be specified for LLM-D baseline {i} in {file_path}")
if not hf_token:
raise ValueError(f"hf_token must be specified for LLM-D baseline {i} in {file_path}")
if api_type not in ['completions', 'chat']:
raise ValueError(f"apiType must be 'completions' or 'chat' for LLM-D baseline {i} in {file_path}, got: {api_type}")
elif baseline_type == 'Dynamo':
config_selection = baseline_config.get('configSelection')
model_url = baseline_config.get('modelURL')
api_type = baseline_config.get('apiType', 'completions') # Default to completions for backward compatibility
if not config_selection:
raise ValueError(f"configSelection must be specified for Dynamo baseline {i} in {file_path}")
if not model_url:
raise ValueError(f"modelURL must be specified for Dynamo baseline {i} in {file_path}")
if api_type not in ['completions', 'chat']:
raise ValueError(f"apiType must be 'completions' or 'chat' for Dynamo baseline {i} in {file_path}, got: {api_type}")
elif baseline_type == 'Flat':
config_selection = baseline_config.get('configSelection')
model_url = baseline_config.get('modelURL')
api_type = baseline_config.get('apiType', 'completions') # Default to completions for backward compatibility
if not config_selection:
raise ValueError(f"configSelection must be specified for Flat baseline {i} in {file_path}")
if not model_url:
raise ValueError(f"modelURL must be specified for Flat baseline {i} in {file_path}")
if api_type not in ['completions', 'chat']:
raise ValueError(f"apiType must be 'completions' or 'chat' for Flat baseline {i} in {file_path}, got: {api_type}")
else:
raise ValueError(f"Unsupported baseline type: {baseline_type} in baseline {i} in {file_path}")
# Validate workload configuration
if 'Workload' in config:
workload_cfg = config['Workload']
supported_workloads = ['ShareGPT', 'LMCacheSynthetic', 'Agentic', 'TraceReplayer', 'Random', 'VLLMBenchmark', 'StrictSynthetic']
for workload in workload_cfg:
if workload not in supported_workloads:
raise ValueError(f"Unsupported workload type: {workload} in {file_path}")
# Note: Infrastructure validation is now handled at the run-bench.yaml level
# Individual spec files no longer need to specify infrastructure
print(f"Validated all serving baselines and workloads in {file_path}")
return config
# 1. Infrastructure Setup
def setup_infrastructure(config: Dict[str, Any]) -> None:
"""Set up the infrastructure based on the configuration."""
if 'Infrastructure' not in config:
raise ValueError("Infrastructure configuration is missing in bench-spec.yaml")
location = config['Infrastructure'].get('Location')
if not location:
raise ValueError("Infrastructure Location is not specified in bench-spec.yaml")
if location == 'NoBench':
print("Not running any benchmarks!")
sys.exit(0)
elif location == 'LocalMinikube':
minikube_installation(config)
elif location == 'LMCacheGKE':
start_gke_cluster(config)
else:
raise ValueError(f"Unsupported infrastructure location: {location}")
def minikube_installation(config: Dict[str, Any]) -> None:
script_path = Path(__file__).parent / '1-infrastructure' / 'local-minikube' / 'install-local-minikube.sh'
if not script_path.exists():
raise FileNotFoundError(f"Installation script not found at {script_path}")
# Make the script executable if it isn't already
os.chmod(script_path, 0o755)
# Execute the installation script
print("Setting up local minikube environment...")
# This is blocking
result = subprocess.run([str(script_path)], check=True)
if result.returncode == 0:
print("Local minikube environment setup completed successfully")
else:
raise RuntimeError("Failed to set up local minikube environment")
def start_gke_cluster(config: Dict[str, Any]) -> None:
script_path = Path(__file__).parent / '1-infrastructure' / 'lmcache-gke' / 'run-gke.sh'
if not script_path.exists():
raise FileNotFoundError(f"GKE cluster setup script not found at {script_path}")
# add execution permission
os.chmod(script_path, 0o755)
# Execute the script
num_gpus = config['Infrastructure'].get('numClusterGPUs')
a100_vram = config['Infrastructure'].get('A100_VRAM', "40")
if not num_gpus:
raise ValueError("numClusterGPUs must be specified in bench-spec.yaml for GKE cluster setup")
result = subprocess.run([str(script_path), str(num_gpus), str(a100_vram)], check=True)
if result.returncode == 0:
print("GKE cluster setup completed successfully")
else:
raise RuntimeError("Failed to set up GKE cluster")
def setup_infrastructure_from_run_bench_config(infrastructure_config: Dict[str, Any]) -> None:
"""Set up the infrastructure based on the run-bench.yaml configuration."""
location = infrastructure_config.get('Location')
if not location:
raise ValueError("Infrastructure Location is not specified in run-bench.yaml")
if location == 'NoBench':
print("Not running any benchmarks!")
sys.exit(0)
elif location == 'LocalMinikube':
minikube_installation_from_infrastructure_config(infrastructure_config)
elif location == 'LMCacheGKE':
start_gke_cluster_from_infrastructure_config(infrastructure_config)
elif location == 'Local-Flat':
print("Using Local-Flat infrastructure - no setup required")
else:
raise ValueError(f"Unsupported infrastructure location: {location}")
def minikube_installation_from_infrastructure_config(infrastructure_config: Dict[str, Any]) -> None:
"""Set up minikube using infrastructure config from run-bench.yaml."""
script_path = Path(__file__).parent / '1-infrastructure' / 'local-minikube' / 'install-local-minikube.sh'
if not script_path.exists():
raise FileNotFoundError(f"Installation script not found at {script_path}")
# Make the script executable if it isn't already
os.chmod(script_path, 0o755)
# Execute the installation script
print("Setting up local minikube environment...")
# This is blocking
result = subprocess.run([str(script_path)], check=True)
if result.returncode == 0:
print("Local minikube environment setup completed successfully")
else:
raise RuntimeError("Failed to set up local minikube environment")
def start_gke_cluster_from_infrastructure_config(infrastructure_config: Dict[str, Any]) -> None:
"""Set up GKE cluster using infrastructure config from run-bench.yaml."""
script_path = Path(__file__).parent / '1-infrastructure' / 'lmcache-gke' / 'run-gke.sh'
if not script_path.exists():
raise FileNotFoundError(f"GKE cluster setup script not found at {script_path}")
# add execution permission
os.chmod(script_path, 0o755)
# Execute the script
num_gpus = infrastructure_config.get('numClusterGPUs')
a100_vram = infrastructure_config.get('A100_VRAM', "40")
if not num_gpus:
raise ValueError("numClusterGPUs must be specified in run-bench.yaml for GKE cluster setup")
result = subprocess.run([str(script_path), str(num_gpus), str(a100_vram)], check=True)
if result.returncode == 0:
print("GKE cluster setup completed successfully")
else:
raise RuntimeError("Failed to set up GKE cluster")
# 2. Baseline Setup
def generate_baseline_key(serving_config: Dict[str, Any]) -> str:
"""Generate a baseline key based on the serving configuration."""
baseline_type = list(serving_config.keys())[0]
baseline_config = serving_config[baseline_type]
if baseline_type == 'SGLang':
script_name = baseline_config.get('scriptName', '')
return f"sglang_{script_name.replace('.sh', '').replace('-', '_')}"
elif baseline_type == 'RayServe':
script_name = baseline_config.get('scriptName', '')
accelerator_type = baseline_config.get('acceleratorType', '')
return f"rayserve_{script_name.replace('.py', '').replace('-', '_')}_{accelerator_type.lower()}"
elif baseline_type == 'Helm-ProductionStack':
# helm_{config_name} based on helmConfigSelection
helm_config = baseline_config.get('helmConfigSelection', '')
return f"helm_{helm_config.replace('/', '_').replace('.yaml', '')}"
elif baseline_type == 'Direct-ProductionStack':
# Convert kubernetesConfigSelection filepath where "/" becomes "_"
k8s_config = baseline_config.get('kubernetesConfigSelection', '')
return k8s_config.replace('/', '_').replace('.yaml', '')
elif baseline_type == 'LLM-D':
# llmd_{config_name} based on configSelection
config_selection = baseline_config.get('configSelection', '')
return f"llmd_{config_selection.replace('/', '_').replace('.yaml', '')}"
elif baseline_type == 'Dynamo':
# dynamo_{config_name} based on configSelection
config_selection = baseline_config.get('configSelection', '')
return f"dynamo_{config_selection.replace('/', '_').replace('.yaml', '')}"
elif baseline_type == 'Flat':
# flat_{config_name} based on configSelection
config_selection = baseline_config.get('configSelection', '')
return f"flat_{config_selection.replace('/', '_').replace('-', '_').replace('.sh', '')}"
else:
raise ValueError(f"Unsupported baseline type: {baseline_type}")
def setup_single_baseline(serving_config: Dict[str, Any], global_config: Dict[str, Any], serving_index: int) -> None:
"""Set up a single baseline (cluster of serving engines) based on the configuration."""
global MODEL_URL, HF_TOKEN, KEY, CURRENT_SERVING_INDEX, CURRENT_SERVING_CONFIG, CURRENT_SPEC_CONFIG, CURRENT_SPEC_FILE_PATH
# Store current serving info for later use
CURRENT_SERVING_INDEX = serving_index
CURRENT_SERVING_CONFIG = serving_config
baseline_type = list(serving_config.keys())[0]
baseline_config = serving_config[baseline_type]
# Generate the proper KEY
KEY = generate_baseline_key(serving_config)
print(f"\n=== Setting up serving baseline {serving_index}: {baseline_type} (key: {KEY}) ===")
if baseline_type == 'SGLang':
model_url = baseline_config.get('modelURL')
if not model_url:
raise ValueError(f"modelURL must be specified for SGLang baseline {serving_index}")
MODEL_URL = model_url
# HF_TOKEN is read directly from environment variable by the script
HF_TOKEN = os.environ.get('HF_TOKEN')
if not HF_TOKEN:
raise ValueError("HF_TOKEN environment variable is not set")
sglang_installation(baseline_config)
elif baseline_type == 'RayServe':
model_url = baseline_config.get('modelURL')
if not model_url:
raise ValueError(f"modelURL must be specified for RayServe baseline {serving_index}")
MODEL_URL = model_url
# HF_TOKEN is read directly from environment variable by the script
HF_TOKEN = os.environ.get('HF_TOKEN')
if not HF_TOKEN:
raise ValueError("HF_TOKEN environment variable is not set")
rayserve_installation(baseline_config)
elif baseline_type == 'Helm-ProductionStack':
model_url = baseline_config.get('modelURL')
hf_token = baseline_config.get('hf_token')
if not model_url:
raise ValueError(f"modelURL must be specified for Helm-ProductionStack baseline {serving_index}")
if not hf_token:
raise ValueError(f"hf_token must be specified for Helm-ProductionStack baseline {serving_index}")
MODEL_URL = model_url
HF_TOKEN = hf_token
helm_installation_with_config(baseline_config, global_config)
elif baseline_type == 'Direct-ProductionStack':
model_url = baseline_config.get('modelURL')
hf_token = baseline_config.get('hf_token')
if not model_url:
raise ValueError(f"modelURL must be specified for Direct-ProductionStack baseline {serving_index}")
if not hf_token:
raise ValueError(f"hf_token must be specified for Direct-ProductionStack baseline {serving_index}")
MODEL_URL = model_url
HF_TOKEN = hf_token
kubernetes_application(baseline_config, global_config)
elif baseline_type == 'LLM-D':
model_url = baseline_config.get('modelURL')
hf_token = baseline_config.get('hf_token')
if not model_url:
raise ValueError(f"modelURL must be specified for LLM-D baseline {serving_index}")
if not hf_token:
raise ValueError(f"hf_token must be specified for LLM-D baseline {serving_index}")
MODEL_URL = model_url
HF_TOKEN = hf_token
llmd_installation(baseline_config)
elif baseline_type == 'Dynamo':
config_selection = baseline_config.get('configSelection')
model_url = baseline_config.get('modelURL')
api_type = baseline_config.get('apiType', 'completions') # Default to completions for backward compatibility
if not config_selection:
raise ValueError(f"configSelection must be specified for Dynamo baseline {serving_index}")
if not model_url:
raise ValueError(f"modelURL must be specified for Dynamo baseline {serving_index}")
if api_type not in ['completions', 'chat']:
raise ValueError(f"apiType must be 'completions' or 'chat' for Dynamo baseline {serving_index}, got: {api_type}")
MODEL_URL = model_url
# HF_TOKEN is read directly from environment variable by the script
HF_TOKEN = os.environ.get('HF_TOKEN')
if not HF_TOKEN:
raise ValueError("HF_TOKEN environment variable is not set")
dynamo_installation(baseline_config)
elif baseline_type == 'Flat':
# Validate that Flat baseline is only used with Local-Flat infrastructure
infrastructure_location = global_config.get('Infrastructure', {}).get('Location')
if infrastructure_location != 'Local-Flat':
raise ValueError(f"Flat baseline requires Local-Flat infrastructure, but got {infrastructure_location}")
config_selection = baseline_config.get('configSelection')
model_url = baseline_config.get('modelURL')
api_type = baseline_config.get('apiType', 'completions') # Default to completions for backward compatibility
if not config_selection:
raise ValueError(f"configSelection must be specified for Flat baseline {serving_index}")
if not model_url:
raise ValueError(f"modelURL must be specified for Flat baseline {serving_index}")
if api_type not in ['completions', 'chat']:
raise ValueError(f"apiType must be 'completions' or 'chat' for Flat baseline {serving_index}, got: {api_type}")
MODEL_URL = model_url
# HF_TOKEN is read directly from environment variable by the script
HF_TOKEN = os.environ.get('HF_TOKEN')
if not HF_TOKEN:
raise ValueError("HF_TOKEN environment variable is not set")
flat_installation(baseline_config)
else:
raise ValueError(f"Unsupported baseline type: {baseline_type}")
def setup_baseline(config: Dict[str, Any]) -> None:
"""Legacy function - now redirects to setup_single_baseline for backward compatibility."""
# This function is kept for backward compatibility but should not be used in the new pipeline
raise RuntimeError("setup_baseline() should not be called in the new multi-baseline pipeline")
def sglang_installation(sglang_config: Dict[str, Any]) -> None:
"""
Deploy SGLang using the unified choose-and-deploy.sh entrypoint
"""
script_name = sglang_config.get('scriptName')
if not script_name:
raise ValueError("scriptName must be specified for SGLang")
# Script reads HF_TOKEN directly from environment variable
if not os.environ.get('HF_TOKEN'):
raise ValueError("HF_TOKEN environment variable is not set")
# Use choose-and-deploy.sh as the single entrypoint (includes setup + deployment + wait)
script_path = Path(__file__).parent / '2-serving-engines' / 'sglang' / 'choose-and-deploy.sh'
if not script_path.exists():
raise FileNotFoundError(f"SGLang choose-and-deploy script not found: {script_path}")
os.chmod(script_path, 0o755)
print(f"Running SGLang choose-and-deploy script with {script_name} (includes setup + deployment + wait)")
# CRITICAL: Block until service ready (choose-and-deploy.sh handles this internally)
subprocess.run([str(script_path), script_name], check=True)
print("SGLang deployment completed successfully")
def rayserve_installation(rayserve_config: Dict[str, Any]) -> None:
"""
Deploy RayServe using the unified choose-and-deploy.sh entrypoint
"""
script_name = rayserve_config.get('scriptName')
accelerator_type = rayserve_config.get('acceleratorType')
if not script_name:
raise ValueError("scriptName must be specified for RayServe")
if not accelerator_type:
raise ValueError("acceleratorType must be specified for RayServe")
# Script reads HF_TOKEN directly from environment variable
if not os.environ.get('HF_TOKEN'):
raise ValueError("HF_TOKEN environment variable is not set")
# Use choose-and-deploy.sh as the single entrypoint (includes setup + deployment + wait)
script_path = Path(__file__).parent / '2-serving-engines' / 'rayserve' / 'choose-and-deploy.sh'
if not script_path.exists():
raise FileNotFoundError(f"RayServe choose-and-deploy script not found: {script_path}")
os.chmod(script_path, 0o755)
print(f"Running RayServe choose-and-deploy script with {script_name} and {accelerator_type} (includes setup + deployment + wait)")
# CRITICAL: Block until service ready (choose-and-deploy.sh handles this internally)
subprocess.run([str(script_path), script_name, accelerator_type], check=True)
print("RayServe deployment completed successfully")
def llmd_installation(llmd_config: Dict[str, Any]) -> None:
"""
Deploy LLM-D using the configured script for LocalMinikube deployment
"""
config_selection = llmd_config.get('configSelection')
if not config_selection:
raise ValueError("configSelection must be specified for LLM-D")
# Ensure HF_TOKEN environment variable is set for the script
global HF_TOKEN
if not HF_TOKEN:
raise ValueError("HF_TOKEN is not set when trying to deploy LLM-D baseline")
os.environ['HF_TOKEN'] = HF_TOKEN
# Run the LLM-D choose-and-deploy script with config selection
# NOTE: choose-and-deploy.sh already calls setup.sh internally, so no need to call setup.sh separately
script_path = Path(__file__).parent / '2-serving-engines' / 'llm-d' / 'choose-and-deploy.sh'
if not script_path.exists():
raise FileNotFoundError(f"LLM-D script not found: {script_path}")
os.chmod(script_path, 0o755)
print(f"Running LLM-D script with config: {config_selection} (includes comprehensive cleanup)")
# CRITICAL: Block until service ready
print("Deploying LLM-D and waiting for service readiness...")
subprocess.run([str(script_path), config_selection], check=True)
# The choose-and-deploy.sh script already includes wait.sh, so service should be ready
# Additional verification that the service is accessible
import time
time.sleep(5) # Give the service a moment after deployment completion
timeout = 60 # Short timeout since choose-and-deploy.sh already waited
start_time = time.time()
while time.time() - start_time < timeout:
try:
import requests
response = requests.get('http://localhost:30080/v1/models', timeout=5)
if response.status_code == 200:
print("LLM-D service is ready and accessible")
return
except:
pass
time.sleep(5)
raise RuntimeError("LLM-D service failed to become accessible within timeout")
def dynamo_installation(dynamo_config: Dict[str, Any]) -> None:
"""
Deploy Dynamo using the unified choose-and-deploy.sh entrypoint
"""
config_selection = dynamo_config.get('configSelection')
if not config_selection:
raise ValueError("configSelection must be specified for Dynamo")
# Script reads HF_TOKEN directly from environment variable
if not os.environ.get('HF_TOKEN'):
raise ValueError("HF_TOKEN environment variable is not set")
# Use choose-and-deploy.sh as the single entrypoint (includes setup + deployment + wait)
script_path = Path(__file__).parent / '2-serving-engines' / 'dynamo' / 'choose-and-deploy.sh'
if not script_path.exists():
raise FileNotFoundError(f"Dynamo choose-and-deploy script not found: {script_path}")
os.chmod(script_path, 0o755)
print("Running Dynamo choose-and-deploy script (includes setup + deployment + wait)")
# CRITICAL: Block until service ready (choose-and-deploy.sh handles this internally)
subprocess.run([str(script_path), config_selection], check=True)
print("Dynamo deployment completed successfully")
def flat_installation(flat_config: Dict[str, Any]) -> None:
"""
Deploy Flat baseline using the unified choose-and-deploy.sh entrypoint
"""
config_selection = flat_config.get('configSelection')
if not config_selection:
raise ValueError("configSelection must be specified for Flat")
# Script reads HF_TOKEN directly from environment variable
if not os.environ.get('HF_TOKEN'):
raise ValueError("HF_TOKEN environment variable is not set")
# Use choose-and-deploy.sh as the single entrypoint (includes setup + deployment + wait)
script_path = Path(__file__).parent / '2-serving-engines' / 'flat' / 'choose-and-deploy.sh'
if not script_path.exists():
raise FileNotFoundError(f"Flat choose-and-deploy script not found: {script_path}")
os.chmod(script_path, 0o755)
print(f"Running Flat choose-and-deploy script with configuration: {config_selection}")
# CRITICAL: Block until service ready (choose-and-deploy.sh handles this internally)
subprocess.run([str(script_path), config_selection], check=True)
print("Flat deployment completed successfully")
# Note: The old complex SGLang YAML overriding function has been removed
# as we now use simple script-based deployment for Local-Flat infrastructure
def helm_installation_with_config(prodstack_config: Dict[str, Any], global_config: Dict[str, Any]) -> None:
"""
Deploy the router and serving engines through production stack helm installation using config file selection
"""
# Get the helm config file name
helm_config_filename = prodstack_config.get('helmConfigSelection')
if not helm_config_filename:
raise ValueError("helmConfigSelection must be specified in bench-spec.yaml for Helm-ProductionStack baseline")
# Ensure HF_TOKEN environment variable is set for the script
global HF_TOKEN, CURRENT_SPEC_CONFIG, LMBENCH_SESSION_ID
if not HF_TOKEN:
raise ValueError("HF_TOKEN is not set when trying to deploy Helm-ProductionStack baseline")
os.environ['HF_TOKEN'] = HF_TOKEN
# Set environment variables for log collection
benchmark_name = CURRENT_SPEC_CONFIG.get('Name', 'unknown') if CURRENT_SPEC_CONFIG else 'unknown'
os.environ['LMBENCH_BENCHMARK_NAME'] = benchmark_name
os.environ['LMBENCH_SESSION_ID'] = LMBENCH_SESSION_ID or 'unknown'
# Execute the choose-and-deploy script
deploy_script_path = Path(__file__).parent / '2-serving-engines' / 'helm-production-stack' / 'choose-and-deploy.sh'
os.chmod(deploy_script_path, 0o755)
# Determine if we should skip node affinity based on Infrastructure.Location or command-line flag
skip_node_affinity = (GLOBAL_ARGS and GLOBAL_ARGS.skip_node_affinity) or (global_config.get('Infrastructure', {}).get('Location') != 'LMCacheGKE')
cmd = [str(deploy_script_path), str(helm_config_filename)]
if skip_node_affinity:
cmd.append("--skip-node-affinity")
result = subprocess.run(cmd, check=True)
if result.returncode == 0:
print("Helm deployment completed successfully")
else:
raise RuntimeError("Failed to deploy Helm")
def kubernetes_application(direct_production_stack_config: Dict[str, Any], global_config: Dict[str, Any]) -> None:
"""
Apply pre-made kubernetes configurations from direct-production-stack
"""
# Get the kubernetes config file name
k8s_config_filename = direct_production_stack_config.get('kubernetesConfigSelection')
if not k8s_config_filename:
raise ValueError("kubernetesConfigSelection must be specified in bench-spec.yaml for Direct-ProductionStack baseline")
# Ensure HF_TOKEN environment variable is set for the script
global HF_TOKEN, CURRENT_SPEC_CONFIG, LMBENCH_SESSION_ID
if not HF_TOKEN:
raise ValueError("HF_TOKEN is not set when trying to deploy Direct-ProductionStack baseline")
os.environ['HF_TOKEN'] = HF_TOKEN
# Set environment variables for log collection
benchmark_name = CURRENT_SPEC_CONFIG.get('Name', 'unknown') if CURRENT_SPEC_CONFIG else 'unknown'
os.environ['LMBENCH_BENCHMARK_NAME'] = benchmark_name
os.environ['LMBENCH_SESSION_ID'] = LMBENCH_SESSION_ID or 'unknown'
# Execute the choose-and-deploy script
deploy_script_path = Path(__file__).parent / '2-serving-engines' / 'direct-production-stack' / 'choose-and-deploy.sh'
os.chmod(deploy_script_path, 0o755)
# Determine if we should skip node affinity based on Infrastructure.Location or command-line flag
skip_node_affinity = (GLOBAL_ARGS and GLOBAL_ARGS.skip_node_affinity) or (global_config.get('Infrastructure', {}).get('Location') != 'LMCacheGKE')
cmd = [str(deploy_script_path), str(k8s_config_filename)]
if skip_node_affinity:
cmd.append("--skip-node-affinity")
result = subprocess.run(cmd, check=True)
if result.returncode == 0:
print("Kubernetes deployment completed successfully")
else:
raise RuntimeError("Failed to deploy Kubernetes")
# The patching of deployments to the appropriate node pools is now handled directly
# in the choose-and-deploy.sh script before waiting for pods to be ready
# 3. Run the specified workload
def run_workload(config: Dict[str, Any]) -> None:
"""Run the specified workload based on the configuration."""
if 'Workload' not in config:
raise ValueError("Workload configuration is missing in bench-spec.yaml")
global MODEL_URL
if not MODEL_URL:
raise ValueError("MODEL_URL is not set when trying to run the workload. It should have been set up regardless of what baseline was used!")
global HF_TOKEN
if not HF_TOKEN:
raise ValueError("HF_TOKEN is not set when trying to run the workload. It should have been set up regardless of what baseline was used!")
global KEY
if not KEY:
raise ValueError("KEY is not set when trying to run the workload. It should have been set up regardless of what baseline was used!")
# export HF_TOKEN
os.environ['HF_TOKEN'] = HF_TOKEN
workload_cfg = config['Workload']
supported_workloads = ['ShareGPT', 'LMCacheSynthetic', 'Agentic', 'TraceReplayer', 'Random', 'VLLMBenchmark', 'StrictSynthetic']
for workload in workload_cfg:
if workload not in supported_workloads:
raise ValueError(f"Unsupported workload type: {workload}")
# Multiple workloads can be run
if 'ShareGPT' in workload_cfg:
sharegpt_config = workload_cfg['ShareGPT']
if isinstance(sharegpt_config, list):
for config in sharegpt_config:
run_sharegpt(config)
else:
run_sharegpt(sharegpt_config)
if 'LMCacheSynthetic' in workload_cfg:
lmcache_synthetic_config = workload_cfg['LMCacheSynthetic']
if isinstance(lmcache_synthetic_config, list):
for config in lmcache_synthetic_config:
run_synthetic(config)
else:
run_synthetic(lmcache_synthetic_config)
if 'TraceReplayer' in workload_cfg:
trace_replayer_config = workload_cfg['TraceReplayer']
if isinstance(trace_replayer_config, list):
for config in trace_replayer_config:
run_trace_replayer(config)
else:
run_trace_replayer(trace_replayer_config)
if 'Agentic' in workload_cfg:
agentic_config = workload_cfg['Agentic']
if isinstance(agentic_config, list):
for config in agentic_config:
run_agentic(config)
else:
run_agentic(agentic_config)
if 'Random' in workload_cfg:
random_config = workload_cfg['Random']
if isinstance(random_config, list):
for config in random_config:
run_random(config)
else:
run_random(random_config)
if 'VLLMBenchmark' in workload_cfg:
vllm_benchmark_config = workload_cfg['VLLMBenchmark']
if isinstance(vllm_benchmark_config, list):
for config in vllm_benchmark_config:
run_vllm_benchmark(config)
else:
run_vllm_benchmark(vllm_benchmark_config)
if 'StrictSynthetic' in workload_cfg:
strict_synthetic_config = workload_cfg['StrictSynthetic']
if isinstance(strict_synthetic_config, list):
for config in strict_synthetic_config:
run_strict_synthetic(config)
else:
run_strict_synthetic(strict_synthetic_config)
def run_sharegpt(sharegpt_config: Dict[str, Any]) -> None:
"""Run the ShareGPT workload with the specified configuration."""
sharegpt_data_generation(sharegpt_config)
sharegpt_run_workload(sharegpt_config)
def sharegpt_data_generation(sharegpt_config: Dict[str, Any]) -> None:
# Function level attribute to ensure we only generate data once
if not hasattr(sharegpt_data_generation, 'data_generated'):
sharegpt_data_generation.data_generated = False
if sharegpt_data_generation.data_generated:
print("ShareGPT data already generated, skipping...")
return
# Get ShareGPT specific parameters with defaults
limit = sharegpt_config.get('LIMIT')
min_rounds = sharegpt_config.get('MIN_ROUNDS')
start_round = sharegpt_config.get('START_ROUND')
# Construct the command with parameters
data_gen_script_path = Path(__file__).parent / '3-workloads' / 'sharegpt' / 'data_generation' / 'prepare_sharegpt_data.sh'
if not data_gen_script_path.exists():
raise FileNotFoundError(f"ShareGPT script not found at {data_gen_script_path}")
# Make the script executable
os.chmod(data_gen_script_path, 0o755)
global MODEL_URL
cmd = [str(data_gen_script_path)]
if limit is not None:
cmd.extend(['-l', str(limit)])
if min_rounds is not None:
cmd.extend(['-m', str(min_rounds)])
if start_round is not None:
cmd.extend(['-s', str(start_round)])
cmd.extend(['--model-url', str(MODEL_URL)])
# Execute data generation script
print(f"Generating and processing ShareGPT data with parameters: {' '.join(cmd)}")
result = subprocess.run(cmd, check=True)
if result.returncode == 0:
print("ShareGPT data generation completed successfully into 4-latest-results/sharegpt-data.json")
sharegpt_data_generation.data_generated = True
else:
raise RuntimeError("Failed to generate ShareGPT data")
def sharegpt_run_workload(sharegpt_config: Dict[str, Any]) -> None:
workload_exec_script_path = Path(__file__).parent / '3-workloads' / 'sharegpt' / 'workload_execution' / 'run-sharegpt.sh'
if not workload_exec_script_path.exists():
raise FileNotFoundError(f"ShareGPT script not found at {workload_exec_script_path}")
os.chmod(workload_exec_script_path, 0o755)
global MODEL_URL, CURRENT_SERVING_INDEX, CURRENT_SPEC_CONFIG, CURRENT_SPEC_FILE_PATH, LMBENCH_SESSION_ID, KEY
# Validate required globals
if not KEY:
raise ValueError("KEY is not set for ShareGPT workload")
if not MODEL_URL:
raise ValueError("MODEL_URL is not set for ShareGPT workload")
# Read the benchmark name from the current spec config
benchmark_name = CURRENT_SPEC_CONFIG.get('Name', 'unknown') if CURRENT_SPEC_CONFIG else 'unknown'
cmd = [str(workload_exec_script_path)]
cmd.extend([str(MODEL_URL)])
cmd.extend(["http://localhost:30080"]) # the base URL when serving with production stack
cmd.extend([KEY]) # the key that will be embedded in the filenames of the results
limit = sharegpt_config.get('LIMIT')
min_rounds = sharegpt_config.get('MIN_ROUNDS')
start_round = sharegpt_config.get('START_ROUND')
qps_values = sharegpt_config.get('QPS')
if not qps_values:
raise ValueError("QPS values are required for ShareGPT workload")
cmd.extend([str(limit)])
cmd.extend([str(min_rounds)])
cmd.extend([str(start_round)])
cmd.extend([str(benchmark_name)])
cmd.extend([str(CURRENT_SERVING_INDEX)])
cmd.extend([str(CURRENT_SPEC_FILE_PATH)]) # Pass the spec file path
cmd.extend([str(LMBENCH_SESSION_ID)]) # Pass the session ID
cmd.extend([str(qps) for qps in qps_values])
# Execute the workload
print(f"Running ShareGPT workload with parameters: {' '.join(cmd)}")
result = subprocess.run(cmd, check=True)
if result.returncode == 0:
print("ShareGPT workloads completed successfully")
else:
raise RuntimeError("Failed to run ShareGPT workload")
def synthetic_sharegpt_data_generation() -> None:
"""Generate ShareGPT data for synthetic workload."""
print("Generating ShareGPT data for synthetic workload...")
data_gen_script_path = Path(__file__).parent / '3-workloads' / 'synthetic' / 'prepare_synthetic_sharegpt.sh'
os.chmod(data_gen_script_path, 0o755)
global MODEL_URL
result = subprocess.run([str(data_gen_script_path), str(MODEL_URL)], check=True)
if result.returncode == 0:
print("ShareGPT data generation completed successfully into 4-latest-results/sharegpt-data.json")
else:
raise RuntimeError("Failed to generate ShareGPT data")
def run_synthetic(synthetic_config: Dict[str, Any]) -> None:
"""Run the synthetic workload with the specified configuration."""
# function level attribute of share_gpt_generated so we only generate data once
if not hasattr(run_synthetic, 'share_gpt_generated'):
run_synthetic.share_gpt_generated = False
global MODEL_URL, CURRENT_SERVING_INDEX, CURRENT_SPEC_CONFIG, CURRENT_SPEC_FILE_PATH, LMBENCH_SESSION_ID, CURRENT_SERVING_CONFIG
# Read the benchmark name from the current spec config
benchmark_name = CURRENT_SPEC_CONFIG.get('Name', 'unknown') if CURRENT_SPEC_CONFIG else 'unknown'
# Get apiType from the current serving configuration
api_type = 'completions' # Default value
if CURRENT_SERVING_CONFIG:
baseline_type = list(CURRENT_SERVING_CONFIG.keys())[0]
baseline_config = CURRENT_SERVING_CONFIG[baseline_type]
api_type = baseline_config.get('apiType', 'completions') # Default to completions for backward compatibility
qps_values = synthetic_config.get('QPS')
NUM_USERS_WARMUP = synthetic_config.get('NUM_USERS_WARMUP')
NUM_USERS = synthetic_config.get('NUM_USERS')
NUM_ROUNDS = synthetic_config.get('NUM_ROUNDS')
SYSTEM_PROMPT = synthetic_config.get('SYSTEM_PROMPT')
CHAT_HISTORY = synthetic_config.get('CHAT_HISTORY')
ANSWER_LEN = synthetic_config.get('ANSWER_LEN')
USE_SHAREGPT = synthetic_config.get('USE_SHAREGPT', False)
if USE_SHAREGPT and (not run_synthetic.share_gpt_generated):
synthetic_sharegpt_data_generation()
run_synthetic.share_gpt_generated = True
workload_exec_script_path = Path(__file__).parent / '3-workloads' / 'synthetic' / 'run_synthetic.sh'
if not workload_exec_script_path.exists():
raise FileNotFoundError(f"Synthetic script not found at {workload_exec_script_path}")
os.chmod(workload_exec_script_path, 0o755)
cmd = [str(workload_exec_script_path)]
cmd.extend([str(MODEL_URL)])
cmd.extend(["http://localhost:30080"]) # the base URL when serving with production stack
cmd.extend([KEY]) # the key that will be embedded in the filenames of the results
"""
Updated script signature:
MODEL=$1
BASE_URL=$2
KEY=$3
NUM_USERS_WARMUP=$4
NUM_USERS=$5
NUM_ROUNDS=$6
SYSTEM_PROMPT=$7
CHAT_HISTORY=$8
ANSWER_LEN=$9
USE_SHAREGPT=${10}
NAME=${11}
SERVING_INDEX=${12}
SPEC_FILE_PATH=${13}
LMBENCH_SESSION_ID=${14}
API_TYPE=${15}
[qps_values...]
"""
cmd.extend([str(NUM_USERS_WARMUP)])
cmd.extend([str(NUM_USERS)])
cmd.extend([str(NUM_ROUNDS)])
cmd.extend([str(SYSTEM_PROMPT)])
cmd.extend([str(CHAT_HISTORY)])
cmd.extend([str(ANSWER_LEN)])
cmd.extend([str(USE_SHAREGPT)])
cmd.extend([str(benchmark_name)])
cmd.extend([str(CURRENT_SERVING_INDEX)])
cmd.extend([str(CURRENT_SPEC_FILE_PATH)]) # Pass the spec file path
cmd.extend([str(LMBENCH_SESSION_ID)]) # Pass the session ID
cmd.extend([str(api_type)]) # Pass the API type
cmd.extend([str(qps) for qps in qps_values])
# Execute the workload
print(f"Running synthetic workload with parameters: {' '.join(cmd)}")