-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschedule_multi_model.py
More file actions
4220 lines (2372 loc) · 135 KB
/
Copy pathschedule_multi_model.py
File metadata and controls
4220 lines (2372 loc) · 135 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
"""
This file contains functions to schedule multiple models together on a given set of GPUs on the same machine.
"""
from concurrent.futures import ProcessPoolExecutor, wait
import asyncio
from multiprocessing import Array, Event
from vllm.core.multimodel_scheduler import SHARED_CONTECT, LLM_COMMUNICATOR, MyManager
from vllm.sampling_params import SamplingParams
import benchmark_throughput
import time
import numpy as np
from typing import List, Optional, Tuple, Dict, Union
import itertools
from search_exec_plans import MyExecPlan, MyExecPlanGroupSeq, MyModelInfor, get_best_model_schedule, get_dependent_exec_plans_for_each_plan
import output_length_sampler
from collections import defaultdict
import traceback
import argparse
class MyExecPlanState:
"""Record the state of an exec plan"""
def __init__(self,
exec_plan: MyExecPlan,
launched: bool,
stage_i: int,
last_exec_plan_for_the_model: bool,
need_prepare_infer_env: bool,
) -> None:
self.exec_plan = exec_plan
self.stage_i = stage_i
self.last_exec_plan_for_the_model = last_exec_plan_for_the_model
self.need_prepare_infer_env = need_prepare_infer_env
self.comp_gpus: List[int] = list()
self.launched = launched
def set_comp_gpus(self, comp_gpus: List[int]):
self.comp_gpus = list(comp_gpus)
def get_comp_gpus(self):
return self.comp_gpus
def __str__(self) ->str:
return f'{str(self.exec_plan)}, launched:{self.launched}, stage_i:{self.stage_i}, model_id: {self.exec_plan.model.model_id}, comp_gpus: {self.comp_gpus}'
class InferenceArgs:
"""Arguments for vLLM single model inference."""
def __init__(self,
model:str="huggyllama/llama-7b",
num_prompts: int = 1000,
dataset: str = "ShareGPT_V3_unfiltered_cleaned_split.json",
ignore_eos: bool = False,
fixed_output_len: int = None,
) -> None:
self.backend: str = "vllm"
self.dataset: str = dataset
self.input_len: int = None
self.output_len: int = fixed_output_len
self.model: str = model
self.tokenizer: str = None
self.quantization = None
self.tensor_parallel_size: int = 1
self.n: int = 1
self.use_beam_search: bool = False
self.num_prompts: int = num_prompts
self.seed: int = 0
self.hf_max_batch_size: int = None
self.trust_remote_code: bool = True
self.max_model_len: int = None
self.dtype: str = 'auto'
self.enforce_eager: bool = True
self.kv_cache_dtype: str = "auto"
self.device: str = "cuda"
self.weight_load_degree: str = '16'
self.gpu_use_ratio: float = 0.9
self.temperature: float = 1.0
self.ignore_eos: bool = ignore_eos
if self.tokenizer is None:
self.tokenizer = self.model
if self.dataset is None:
assert self.input_len is not None
assert self.output_len is not None
else:
assert self.input_len is None
if self.backend == "vllm":
if self.hf_max_batch_size is not None:
raise ValueError("HF max batch size is only for HF backend.")
elif self.backend == "hf":
if self.hf_max_batch_size is None:
raise ValueError("HF max batch size is required for HF backend.")
if self.quantization is not None:
raise ValueError("Quantization is only for vLLM backend.")
elif self.backend == "mii":
if self.dtype != "auto":
raise ValueError("dtype must be auto for MII backend.")
if self.n != 1:
raise ValueError("n must be 1 for MII backend.")
if self.use_beam_search:
raise ValueError("Beam search is not supported for MII backend.")
if self.quantization is not None:
raise ValueError("Quantization is only for vLLM backend.")
if self.hf_max_batch_size is not None:
raise ValueError("HF max batch size is only for HF backend.")
if self.tokenizer != self.model:
raise ValueError("Tokenizer must be the same as the model for MII "
"backend.")
def start_a_model_inference_child_process(
communicator: LLM_COMMUNICATOR, use_vllm: bool, gpus: str, shared_id: int, model: str = "huggyllama/llama-7b",
return_str=True, req_num=None):
try:
print(f"in running start_a_model_inference_child_process")
import os
os.environ['CUDA_VISIBLE_DEVICES'] = gpus
os.environ['USE_VLLM']='False'
os.environ['DYNAMIC_INCREASE_ONCARD_WEIGHTS'] = 'True'
if use_vllm:
os.environ['USE_VLLM']='True'
os.environ['DYNAMIC_INCREASE_ONCARD_WEIGHTS'] = 'False'
from huggingface_hub import snapshot_download
local_model_path = snapshot_download(model)
args = InferenceArgs(local_model_path, req_num)
SHARED_CONTECT.shared_id = shared_id
SHARED_CONTECT.communicator = communicator
SHARED_CONTECT.return_str = return_str
SHARED_CONTECT.tot_req_num_remained = req_num
print(f"SHARED_CONTECT.shared_id: {SHARED_CONTECT.shared_id}")
print(f"SHARED_CONTECT.tot_req_num_remained: {SHARED_CONTECT.tot_req_num_remained}")
benchmark_throughput.main(args)
print(f"MODEL PROCESS ENDS: shared_id: {SHARED_CONTECT.shared_id}", flush=True)
except Exception as e:
print(f"Exception in running benchmark_throughput.main(): {e}")
print(traceback.format_exc())
def start_a_model_inference(
communicator: LLM_COMMUNICATOR, use_vllm: bool, gpus: str, model_id: int, model: str = "huggyllama/llama-7b",
return_str=True, req_num=None):
print(f"in running start_a_model_inference")
with ProcessPoolExecutor(max_workers=1) as executor:
try:
print(f"in running start_a_model_inference 1")
executor.submit(start_a_model_inference_child_process, communicator, use_vllm, gpus, model_id,
model, return_str, req_num)
except Exception as e:
print(f"Exception in running start_a_model_inference: {e}")
print(traceback.format_exc())
def get_exec_settings_from_exec_plans(
exec_plan: MyExecPlan, available_gpus: List[int], tot_gpu_num: int, gpu_order_we_set: List[int]):
"""
Get the exec setting to store in the SHARED_CONTECT later, based on the given exec_plan.
"""
tp, gpu_ratio, wldeg, cache_gpu_num, dp_size = exec_plan.get_key()
gpu_list = available_gpus + [i for i in range(tot_gpu_num) if i not in available_gpus]
if max(gpu_list) > tot_gpu_num-1:
print(f"available_gpus:{available_gpus}, tot_gpu_num: {tot_gpu_num}, [i for i in range(tot_gpu_num) if i not in available_gpus]: {[i for i in range(tot_gpu_num) if i not in available_gpus]}")
assert False
print(f"gpu_order_we_set: {gpu_order_we_set}, gpu_list: {gpu_list}")
gpu_list = [gpu_order_we_set[i] for i in gpu_list]
print(f"gpu_list to set: {gpu_list}", flush=True)
new_setting = [tp, int(gpu_ratio*10), wldeg, dp_size] + gpu_list
return new_setting
def get_model_path_list() -> List[str]:
model_paths = [
'lmsys/vicuna-13b-v1.5',
'OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5',
'chavinlo/alpaca-13b',
'project-baize/baize-v2-13b',
'TheBloke/koala-13B-HF',
'databricks/dolly-v2-12b',
'mosaicml/mpt-7b-chat',
]
return model_paths
def query_use_vllm(model_path: str) -> bool:
return True
setting_dict = {
'NousResearch/Llama-2-7b-hf': False,
'NousResearch/Llama-2-7b-chat-hf': False,
'NousResearch/Llama-2-13b-hf': False,
'NousResearch/Llama-2-70b-hf': False,
'THUDM/chatglm3-6b': True,
'EleutherAI/gpt-j-6b': True,
'EleutherAI/gpt-neox-20b': True,
'baichuan-inc/Baichuan2-13B-Chat': True,
'baichuan-inc/Baichuan-7B': True,
'mistralai/Mixtral-8x7B-v0.1': True,
'lmsys/vicuna-13b-v1.5': True,
'OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5': True,
'chavinlo/alpaca-13b': True,
'project-baize/baize-v2-13b': True,
'TheBloke/koala-13B-HF': True,
'databricks/dolly-v2-12b': True,
'mosaicml/mpt-7b-chat': True,
'meta-llama/Llama-2-70b-chat-hf': True,
'mistralai/Mixtral-8x7B-Instruct-v0.1': True,
'WizardLMTeam/WizardLM-13B-V1.2': True,
'meta-llama/CodeLlama-34b-Instruct-hf': True,
'mistralai/Mistral-7B-Instruct-v0.2': True,
}
return setting_dict[model_path]
def prepare_exec_plan_states(
plan_group_seq: MyExecPlanGroupSeq
)->List[List[MyExecPlanState]]:
'''
Prepare the corresponding MyExecPlanState object for each exec plan.
Set the ``last_exec_plan_for_the_model`` and ``need_prepare_infer_env`` attributes for each exec plan.
Output:
List of exec plan state objects for each stage.
'''
plan_group_list = plan_group_seq.plan_group_seq
plan_state_group_list: List[List[MyExecPlanState]] = [[] for i in range(len(plan_group_list))]
checked_model_ids: List[int] = list()
for stage_i in range(len(plan_group_list)-1, -1, -1):
plan_group = plan_group_list[stage_i]
plan_state_group: List[MyExecPlanState] = plan_state_group_list[stage_i]
if stage_i == 0:
for exec_plan in plan_group.exec_plans:
last_exec_plan_for_the_model = False
if exec_plan.model.model_id not in checked_model_ids:
last_exec_plan_for_the_model = True
checked_model_ids.append(exec_plan.model.model_id)
plan_state_group.append(MyExecPlanState(
exec_plan, launched=False, stage_i=stage_i,
last_exec_plan_for_the_model=last_exec_plan_for_the_model,
need_prepare_infer_env=False))
else:
last_stage_exec_plans = plan_group_seq.plan_group_seq[stage_i-1].exec_plans
last_stage_exec_plans_info = [
(exec_plan.model.model_id, exec_plan.get_key()) for exec_plan in last_stage_exec_plans
]
for exec_plan in plan_group.exec_plans:
need_prepare_infer_env = True
if (exec_plan.model.model_id, exec_plan.get_key()) in last_stage_exec_plans_info:
need_prepare_infer_env = False
last_exec_plan_for_the_model = False
if exec_plan.model.model_id not in checked_model_ids:
last_exec_plan_for_the_model = True
checked_model_ids.append(exec_plan.model.model_id)
plan_state_group.append(MyExecPlanState(
exec_plan, launched=False, stage_i=stage_i,
last_exec_plan_for_the_model=last_exec_plan_for_the_model,
need_prepare_infer_env=need_prepare_infer_env))
return plan_state_group_list
def _get_model_sys_structure_from_selected_plan_group_seq(
plan_state_group_list: List[List[MyExecPlanState]],
in_edge_dict_with_dummy_inp_nodes: Dict[int, List[int]],
out_edge_dict: Dict[int, List[int]],
) -> Tuple[Dict[int, int], Dict[int, MyModelInfor], Dict[int, List[int]], Dict[int, List[int]]]:
"""
Input:
1. in_edge_dict_with_dummy_inp_nodes: the in edge dict of the initial model system with dummy inp nodes.
2. out_edge_dict: the out edge dict of the initial model system without dummy inp nodes.
"""
print(f"in_edge_dict_with_dummy_inp_nodes: {in_edge_dict_with_dummy_inp_nodes}")
print(f"out_edge_dict: {out_edge_dict}")
model_id_shared_id_mapping: Dict[int, int] = dict()
shared_id: int = 0
model_dict: Dict[int, MyModelInfor] = dict()
for plan_state_group in plan_state_group_list:
for plan_state in plan_state_group:
model_id = plan_state.exec_plan.model.model_id
model_dict[model_id] = plan_state.exec_plan.model
if model_id not in model_id_shared_id_mapping:
model_id_shared_id_mapping[model_id] = shared_id
shared_id += 1
node_mapping: Dict[int, int] = dict()
for model_id, model in model_dict.items():
for ori in model.get_base_model_ids():
node_mapping[ori] = model_id
dummy_model_ids = np.concatenate(list(in_edge_dict_with_dummy_inp_nodes.values()))
dummy_model_ids = dummy_model_ids[dummy_model_ids<0]
for model_id in dummy_model_ids:
node_mapping[model_id] = model_id
new_in_edge_dict_with_dummy_inp_nodes = defaultdict(list)
for k, vs in in_edge_dict_with_dummy_inp_nodes.items():
new_in_edge_dict_with_dummy_inp_nodes[node_mapping[k]].extend([node_mapping[v] for v in vs])
new_out_edge_dict = defaultdict(list)
for k, vs in out_edge_dict.items():
new_out_edge_dict[node_mapping[k]].extend([node_mapping[v] for v in vs])
return model_id_shared_id_mapping, model_dict, new_in_edge_dict_with_dummy_inp_nodes, new_out_edge_dict
def search_best_scheduling(
test_cases:List[str], versions: List[str], max_token_nums: List[str], specify_outlens: List[bool],
gen_execplans_baseline:str,
search_method_baseline:str,
model_paths: List[str],
out_edge_dict: Dict[int, List[int]],
check_gap: int, sort_input: bool,
num_prompts: int,
inp_seq_ids_dict,
out_req_id_mapping: Dict[int, Dict[int, Tuple[int, int]]],
inp_req_ids: Dict[int, Dict[int, List[int]]],
inp_req_from_which_model_which_out_reqs: Dict[int, Dict[int, Dict[int, int]]],
independent_srcs: Dict[int, bool],
prompt_templates_lens: Dict[int, int],
gpu_name='A100-80G',
byte_per_gpu=80*(1024**3),
tot_gpu_num: int = 4,
max_group_seq_num: int = 100,
top_k: int=100,
similar_threshold: float=0.1,
fully_connected_gpu_unit: int=4,
machine_name:str='machine1',
)->List[List[MyExecPlanState]]:
print(f"test_cases, versions, max_token_nums, specify_outlens: {test_cases, versions, max_token_nums, specify_outlens}")
funcs = [_get_req_len_funcs(
test_case=test_case, version=version, max_token_num=max_token_num, specify_outlen=specify_outlen) \
for test_case, version, max_token_num, specify_outlen in zip(test_cases, versions, max_token_nums, specify_outlens)]
inp_generators = [_[0] for _ in funcs]
inp_mergers = [_[1] for _ in funcs]
outlen_generators = [_[2] for _ in funcs]
best_group_seq = get_best_model_schedule(
search_method_baseline,
gen_execplans_baseline,
check_gap,
sort_input,
model_paths,
num_prompts,
inp_seq_ids_dict,
out_req_id_mapping,
inp_req_ids,
inp_req_from_which_model_which_out_reqs,
independent_srcs,
inp_generators,
inp_mergers,
outlen_generators,
prompt_templates_lens,
out_edge_dict,
sample_config=(1, 1, -1, 0),
trust_remote_code=True, revision=None,
gpu_name=gpu_name, tot_gpu_num = tot_gpu_num, byte_per_gpu=byte_per_gpu,
data_byte=2,
max_group_seq_num=max_group_seq_num,
top_k=top_k,
similar_threshold=similar_threshold,
fully_connected_gpu_unit=fully_connected_gpu_unit,
machine_name=machine_name,
)
plan_state_group_list = prepare_exec_plan_states(best_group_seq)
return plan_state_group_list
def initialize_SHARED_CONTECT_not_support_fused_models(
tot_gpu_num: int,
model_paths: List[str],
check_gap: int,
plan_state_group_list:List[List[MyExecPlanState]],
model_driver_worker_gpu_i: Dict[int,int],
gpu_order_we_set: List[int],
) -> Tuple[List[MyExecPlanState], int, List[MyExecPlanState]]:
'''
Update: (1) SHARED_CONTECT events, shared_finish_status, shared_setting
(2) call SHARED_CONTECT.start_specific_models()
Output: (1) launched_exec_plan_states; (2) new target stage i; (3) candidate_exec_plan_states
NOTE:
1. this version does not support the case where there are fused models in the model system.
'''
import ctypes
SHARED_CONTECT.set_execution_plan_size(tot_gpu_num)
counter = Array('i', [0 for i in range(len(model_paths)*SHARED_CONTECT.execution_plan_size)])
SHARED_CONTECT.events = [Event() for _ in range(2+len(model_paths))]
SHARED_CONTECT.started_status = [Event() for _ in range(len(model_paths))]
SHARED_CONTECT.shared_setting = counter
SHARED_CONTECT.shared_finish_status = Array(ctypes.c_bool, [False for i in range(len(model_paths))])
check_out_gaps = Array('i', [int(1e9)]*len(model_paths))
SHARED_CONTECT.check_out_gaps = check_out_gaps
SHARED_CONTECT.check_in_gap = check_gap
available_gpus: List[int] = list(range(tot_gpu_num))
launched_exec_plan_states: List[MyExecPlanState] = plan_state_group_list[0]
for exec_plan_state in launched_exec_plan_states:
exec_plan = exec_plan_state.exec_plan
exec_plan_state.set_comp_gpus(available_gpus[:exec_plan.num_worker*exec_plan.dp_size])
setting = get_exec_settings_from_exec_plans(
exec_plan=exec_plan, available_gpus=available_gpus, tot_gpu_num=tot_gpu_num, gpu_order_we_set=gpu_order_we_set)
SHARED_CONTECT.set_execution_plan(setting, model_ids=[exec_plan.model.model_id])
if exec_plan.model.model_id not in model_driver_worker_gpu_i:
model_driver_worker_gpu_i[exec_plan.model.model_id] = available_gpus[0]
available_gpus = available_gpus[exec_plan.num_worker*exec_plan.dp_size:]
exec_plan_state.launched = True
new_target_stage_i: int = 1
candidate_exec_plan_states: List[MyExecPlanState] = []
if len(plan_state_group_list)>1:
candidate_exec_plan_states = plan_state_group_list[1]
return launched_exec_plan_states, new_target_stage_i, candidate_exec_plan_states
def initialize_SHARED_CONTECT(
tot_gpu_num: int,
check_gap: int,
plan_state_group_list:List[List[MyExecPlanState]],
model_driver_worker_gpu_i: Dict[int,int],
gpu_order_we_set: List[int],
model_id_shared_id_mapping: Dict[int, int],
new_out_edge_dict: Dict[int, List[int]],
sampling_args_dict: Dict[int, Tuple[bool, int, int]],
seq_outlen_dict: Dict[int, Dict[int,int]],
fully_connected_gpu_unit: int,
) -> Tuple[List[MyExecPlanState], int, List[MyExecPlanState]]:
'''
Update: (1) SHARED_CONTECT events, shared_finish_status, shared_setting
(2) call SHARED_CONTECT.start_specific_models()
Output: (1) launched_exec_plan_states; (2) new target stage i; (3) candidate_exec_plan_states
'''
import ctypes
new_model_num = len(model_id_shared_id_mapping)
SHARED_CONTECT.set_execution_plan_size(tot_gpu_num)
counter = Array('i', [0 for i in range(new_model_num*SHARED_CONTECT.execution_plan_size)])
SHARED_CONTECT.events = [Event() for _ in range(2+new_model_num)]
SHARED_CONTECT.started_status = [Event() for _ in range(new_model_num)]
SHARED_CONTECT.shared_setting = counter
SHARED_CONTECT.shared_finish_status = Array(ctypes.c_bool, [False for i in range(new_model_num)])
check_out_gaps = Array('i', [int(1e9)]*new_model_num)
SHARED_CONTECT.check_out_gaps = check_out_gaps
SHARED_CONTECT.check_in_gap = check_gap
SHARED_CONTECT.sampling_args_dict = sampling_args_dict
SHARED_CONTECT.seq_outlen_dict = seq_outlen_dict
available_gpus: List[int] = list(range(tot_gpu_num))
launched_exec_plan_states: List[MyExecPlanState] = plan_state_group_list[0]
launched_exec_plan_states = sorted(launched_exec_plan_states, key=lambda plan_state: (plan_state.exec_plan.num_worker, (plan_state.exec_plan.num_worker*plan_state.exec_plan.dp_size)%fully_connected_gpu_unit == 0, plan_state.exec_plan.dp_size), reverse=True)
for exec_plan_state in launched_exec_plan_states:
exec_plan = exec_plan_state.exec_plan
exec_plan_state.set_comp_gpus(available_gpus[:exec_plan.num_worker*exec_plan.dp_size])
setting = get_exec_settings_from_exec_plans(
exec_plan=exec_plan, available_gpus=available_gpus, tot_gpu_num=tot_gpu_num, gpu_order_we_set=gpu_order_we_set)
SHARED_CONTECT.set_execution_plan(setting, shared_ids=[model_id_shared_id_mapping[exec_plan.model.model_id]])
if exec_plan.model.model_id not in model_driver_worker_gpu_i:
model_driver_worker_gpu_i[exec_plan.model.model_id] = available_gpus[0]
available_gpus = available_gpus[exec_plan.num_worker*exec_plan.dp_size:]
exec_plan_state.launched = True
new_target_stage_i: int = 1
candidate_exec_plan_states: List[MyExecPlanState] = []
if len(plan_state_group_list)>1:
candidate_exec_plan_states = plan_state_group_list[1]
set_check_in_out_gap(
curr_stage_plan_states=launched_exec_plan_states, check_gap=check_gap, new_out_edge_dict=new_out_edge_dict,
model_id_shared_id_mapping=model_id_shared_id_mapping)
return launched_exec_plan_states, new_target_stage_i, candidate_exec_plan_states
def get_the_next_round_exec_plan_schedule_deprecated(
launched_exec_plan_states: List[MyExecPlanState], candidate_exec_plan_states: List[MyExecPlanState],
target_stage_i: int,
tot_gpu_num: int,
plan_state_group_list:List[List[MyExecPlanState]],
model_driver_worker_gpu_i: Dict[int,int],
)->Tuple[List[MyExecPlanState], List[MyExecPlanState], List[int], List[MyExecPlanState], int]:
'''
Output:
(1) the updated launched_exec_plan_states (i.e., running exec plan states);
(2) the updated candidate_exec_plan_states;
(3) the models to stop;
(4) the new exec plans to launch;
(5) the new target stage i;
'''
to_launch: List[MyExecPlanState] = list()
to_launch_model_ids: List[int] = list()
cand_to_launch_list: List[List[MyExecPlanState]] = [list(), list()]
for plan_state in launched_exec_plan_states:
if SHARED_CONTECT.query_finish_status(plan_state.exec_plan.model.model_id):
continue
if plan_state.stage_i < target_stage_i:
if plan_state.last_exec_plan_for_the_model:
to_launch.append(plan_state)
to_launch_model_ids.append(plan_state.exec_plan.model.model_id)
print(f"to_launch add 0: {str(plan_state)}")
else:
cand_to_launch_list[0].append(plan_state)
else:
to_launch.append(plan_state)
to_launch_model_ids.append(plan_state.exec_plan.model.model_id)
print(f"to_launch add 1: {str(plan_state)}")
for plan_state in candidate_exec_plan_states:
if SHARED_CONTECT.query_finish_status(plan_state.exec_plan.model.model_id):
plan_state.launched = True
continue
if not plan_state.need_prepare_infer_env:
to_launch.append(plan_state)
to_launch_model_ids.append(plan_state.exec_plan.model.model_id)
print(f"to_launch add 2: {str(plan_state)}")
else:
cand_to_launch_list[1].append(plan_state)
print(f"to_launch 1: {[str(i) for i in to_launch]}")
print(f"cand_to_launch_list 1: {[[str(i) for i in cand_to_launch] for cand_to_launch in cand_to_launch_list]}")
occupied_gpus: List[int] = list()
for plan_state in to_launch:
occupied_gpus.extend(SHARED_CONTECT.get_comp_gpus(plan_state.exec_plan.model.model_id))
available_gpus = [i for i in range(tot_gpu_num) if i not in occupied_gpus]
cand_to_launch = sorted(cand_to_launch, key=lambda i: (i.stage_i, i.exec_plan.num_worker), reverse=True)
new_launch: List[MyExecPlanState] = list()
model_ids_to_stop: List[int] = list()
new_candidate_exec_plan_states: List[MyExecPlanState] = list()
for plan_state in cand_to_launch:
if plan_state.exec_plan.model.model_id in to_launch_model_ids:
continue
tp_size = plan_state.exec_plan.num_worker
if tp_size <= len(available_gpus):
to_launch.append(plan_state)
print(f"to_launch add 3: {str(plan_state)}")
if plan_state.launched:
comp_gpus = SHARED_CONTECT.get_comp_gpus(plan_state.exec_plan.model.model_id)
available_gpus = [i for i in available_gpus if i not in comp_gpus]
else:
plan_state.launched = True
if plan_state.exec_plan.model.model_id not in model_driver_worker_gpu_i:
plan_state.set_comp_gpus(available_gpus[:tp_size])
model_driver_worker_gpu_i[plan_state.exec_plan.model.model_id] = available_gpus[0]
available_gpus = available_gpus[tp_size:]
else:
driver_gpu_i = model_driver_worker_gpu_i[plan_state.exec_plan.model.model_id]
assert driver_gpu_i in available_gpus, f"The driver gpu is not available: {driver_gpu_i, available_gpus}"
available_gpus = [i for i in available_gpus if i != driver_gpu_i]
comp_gpus = [driver_gpu_i]+available_gpus[:tp_size-1]
plan_state.set_comp_gpus(comp_gpus)
available_gpus = available_gpus[tp_size-1:]
new_launch.append(plan_state)
else:
print(f"cannot run")
if plan_state.launched:
print(f"plan launced: {str(plan_state)}")
model_ids_to_stop.append(plan_state.exec_plan.model.model_id)
else:
print(f"add to new candidate: {str(plan_state)}")
new_candidate_exec_plan_states.append(plan_state)
new_target_stage_i = target_stage_i
if len(new_candidate_exec_plan_states) == 0:
new_target_stage_i = target_stage_i + 1
if new_target_stage_i < len(plan_state_group_list):
new_candidate_exec_plan_states = plan_state_group_list[new_target_stage_i]
return to_launch, new_candidate_exec_plan_states, model_ids_to_stop, new_launch, new_target_stage_i
def _get_the_first_plan_state_when_sorted_by_gpu_num_and_topology(
plan_state_list: List[MyExecPlanState]
)->List[MyExecPlanState]:
"""
Sort the given list of plan states by the topology order and their gpu numbers.
Policy:
if a plan state A depends on plan state B, then A must be checked later than B.
Output:
1. the first plan state to consider
2. the remaining plan states to be considered
"""
model_ids = [plan_state.exec_plan.model.model_id for plan_state in plan_state_list]
roots = [plan_state for plan_state in plan_state_list if len(set(plan_state.exec_plan.model.input_model_ids).intersection(model_ids)) == 0]
roots = sorted(roots, key=lambda plan_state: (plan_state.exec_plan.num_worker*plan_state.exec_plan.dp_size) , reverse=True)
remaining_plan_states = [plan_state for plan_state in plan_state_list if plan_state != roots[0]]
return roots[0], remaining_plan_states
def _try_to_load_exec_plans(
cands_to_launch: List[MyExecPlanState],
to_launch: List[MyExecPlanState],
new_candidate_exec_plan_states: List[MyExecPlanState],
model_driver_worker_gpu_i: Dict[int,int],
available_gpus: List[int],
to_launch_model_ids: List[int]
) -> List[int]:
'''
Get the exec plans to launch from the given candidates.
Update: to_launch, to_launch_model_ids, model_driver_worker_gpu_i;
new_launch,
model_ids_to_stop, new_candidate_exec_plan_states;
set the comp gpus of the to-launch plans;
Output: available_gpus
NOTE:
since we support model-level pipeline: we do not simply sort the plan states by their gpu number, but also consider their dependency,
therefore, we call ``_get_the_first_plan_state_when_sorted_by_gpu_num_and_topology`` to get the next plan state to consider every time.
'''
while len(cands_to_launch) > 0:
plan_state, cands_to_launch = _get_the_first_plan_state_when_sorted_by_gpu_num_and_topology(cands_to_launch)
model_id = plan_state.exec_plan.model.model_id
if model_id in to_launch_model_ids:
continue
gpu_num = plan_state.exec_plan.num_worker * plan_state.exec_plan.dp_size
if gpu_num <= len(available_gpus):
to_launch.append(plan_state)
to_launch_model_ids.append(model_id)
print(f"to_launch add 3: {str(plan_state)}")
if plan_state.launched:
comp_gpus = plan_state.get_comp_gpus()
available_gpus = [i for i in available_gpus if i not in comp_gpus]
else:
plan_state.launched = True
plan_state.set_comp_gpus(available_gpus[:gpu_num])
model_driver_worker_gpu_i[plan_state.exec_plan.model.model_id] = available_gpus[0]
available_gpus = available_gpus[gpu_num:]
else:
print(f"cannot run")
if plan_state.launched:
print(f"plan launced: {str(plan_state)}")
else:
print(f"add to new candidate: {str(plan_state)}")
new_candidate_exec_plan_states.append(plan_state)
return available_gpus
def _has_model_finished(
plan_state_group_list:List[List[MyExecPlanState]],
stage_i: int,
model_id_shared_id_mapping: Dict[int, int],
)-> bool:
finished = [i for i in plan_state_group_list[stage_i] \
if SHARED_CONTECT.query_finish_status(model_id_shared_id_mapping[i.exec_plan.model.model_id])]
return len(finished) > 0
def _get_the_next_round_exec_plan_schedule(
launched_exec_plan_states: List[MyExecPlanState], candidate_exec_plan_states: List[MyExecPlanState],
target_stage_i: int,
tot_gpu_num: int,
plan_state_group_list:List[List[MyExecPlanState]],
model_driver_worker_gpu_i: Dict[int,int],
model_id_shared_id_mapping: Dict[int, int],
)->Tuple[List[MyExecPlanState], List[MyExecPlanState], int]:
'''
Output:
(1) the updated launched_exec_plan_states (i.e., running exec plan states);
(2) the updated candidate_exec_plan_states;
(3) the models to stop;
(4) the new exec plans to launch;
(5) the new target stage i;
'''
to_launch: List[MyExecPlanState] = list()
to_launch_model_ids: List[int] = list()
launched_plan_gpus = {(i.exec_plan.model.model_id, tuple(i.exec_plan.get_key())):i.get_comp_gpus() for i in launched_exec_plan_states}
cand_to_launch_list: List[List[MyExecPlanState]] = [list(), list()]
for plan_state in launched_exec_plan_states:
if SHARED_CONTECT.query_finish_status(model_id_shared_id_mapping[plan_state.exec_plan.model.model_id]):
continue
if plan_state.stage_i < target_stage_i:
if plan_state.last_exec_plan_for_the_model:
to_launch.append(plan_state)
to_launch_model_ids.append(plan_state.exec_plan.model.model_id)
print(f"to_launch add 0: {str(plan_state)}")
else:
cand_to_launch_list[0].append(plan_state)
else:
to_launch.append(plan_state)
to_launch_model_ids.append(plan_state.exec_plan.model.model_id)
print(f"to_launch add 1: {str(plan_state)}")
for plan_state in candidate_exec_plan_states:
if SHARED_CONTECT.query_finish_status(model_id_shared_id_mapping[plan_state.exec_plan.model.model_id]):
plan_state.launched = True
continue
if not plan_state.need_prepare_infer_env:
plan_state.launched = True
to_launch.append(plan_state)
to_launch_model_ids.append(plan_state.exec_plan.model.model_id)
plan_state.set_comp_gpus(launched_plan_gpus[(plan_state.exec_plan.model.model_id, tuple(plan_state.exec_plan.get_key()))])
print(f"to_launch add 2: {str(plan_state)}")
else:
cand_to_launch_list[1].append(plan_state)
print(f"to_launch 1: {[str(i) for i in to_launch]}")
print(f"cand_to_launch_list 1: {[[str(i) for i in cand_to_launch] for cand_to_launch in cand_to_launch_list]}")
occupied_gpus: List[int] = list()
for plan_state in to_launch: