-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglobal_scheduler.patch
1662 lines (1553 loc) · 61.5 KB
/
global_scheduler.patch
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
diff --git a/sarathi/benchmark/benchmark_runner.py b/sarathi/benchmark/benchmark_runner.py
index 083dcb3..36bf343 100644
--- a/sarathi/benchmark/benchmark_runner.py
+++ b/sarathi/benchmark/benchmark_runner.py
@@ -2,6 +2,9 @@ import logging
import os
import time
+from typing import Optional, List
+from queue import Queue
+
import ray
import wandb
from tqdm import tqdm
@@ -11,30 +14,23 @@ from sarathi.benchmark.config import BenchmarkConfig
from sarathi.benchmark.entities import Request
from sarathi.benchmark.request_generator import RequestGeneratorRegistry
from sarathi.benchmark.utils.random import set_seeds
-from sarathi.config import ReplicaConfig
+from sarathi.config import ReplicaConfig, BaseGlobalSchedulerTypeConfig
from sarathi.metrics.metrics_store import MetricsStore
from sarathi.types import ReplicaResourceMapping, ResourceMapping
from sarathi.utils import get_ip
+from sarathi.core.datatypes.sequence import SamplerOutputs, Sequence
+from sarathi.utils import Counter
+from sarathi.engine.multi_replica_llm_engine import MultiReplicaLLMEngine
logger = logging.getLogger(__name__)
-class BenchmarkRunner:
+class BenchmarkRunnerLauncher:
- def __init__(
- self,
- replica_id: int,
- config: BenchmarkConfig,
- resource_mapping: ResourceMapping,
- ) -> None:
- self.replica_id = replica_id
+ def __init__(self, config: BenchmarkConfig) -> None:
self.config = config
- replica_config = ReplicaConfig(
- replica_id,
- self.config.output_dir,
- resource_mapping,
- )
+ replica_config = ReplicaConfig(0, self.config.output_dir)
os.makedirs(replica_config.output_dir, exist_ok=True)
set_seeds(self.config.seed)
@@ -44,19 +40,12 @@ class BenchmarkRunner:
)
self.requests = request_generator.generate()
- # select every nth request for this replica
- # e.g. if there are 4 replicas, and this is the 2nd replica, then
- # we will select the 2nd, 6th, 10th, ... requests
- # round robin scheduling
- self.requests = self.requests[self.replica_id :: self.config.num_replicas]
+ self.config.metrics_config.wandb_project = None
- if self.config.num_replicas > 1:
- # disable per-replica wandb logging for multi-replica runs
- # so that we can aggregate metrics across all replicas
- self.config.metrics_config.wandb_project = None
+ self.system_config = self.config.create_system_config(replica_config)
+ self.system_config.num_replicas = self.config.num_replicas
- system_config = self.config.create_system_config(replica_config)
- self.llm_engine = LLMEngine.from_system_config(system_config)
+ self.llm_engine = MultiReplicaLLMEngine(self.system_config)
if wandb.run is not None:
wandb.config.update(self.config.to_dict())
@@ -95,9 +84,10 @@ class BenchmarkRunner:
num_processed_requests = 0
num_steps = 0
+
pbar = tqdm(
total=len(self.requests),
- desc=f"Replica {self.replica_id} processed requests",
+ desc=f"Total processed requests",
)
start_time = time.monotonic()
@@ -119,7 +109,11 @@ class BenchmarkRunner:
pbar.close()
logger.info(
- f"Replica {self.replica_id} exiting after processing {len(self.requests)} ({num_steps} iterations), Total time taken: {end_time - start_time:.2f} seconds"
+ f"{num_processed_requests} requests processed and exited before completing all requests"
+ )
+
+ logger.info(
+ f"Exiting after processing {len(self.requests)} ({num_steps} iterations), Total time taken: {end_time - start_time:.2f} seconds"
)
if self.config.enable_profiling:
@@ -130,150 +124,23 @@ class BenchmarkRunner:
first_request_time = time.monotonic()
while index < len(self.requests):
request = self.requests[index]
+
self.llm_engine.add_request(
**self._get_input_params(request, first_request_time)
)
index += 1
- def run(self) -> None:
+ def run_benchmark(self) -> None:
self.llm_engine.reset_metrics()
self._add_requests()
+ self.llm_engine.start_engine_execution()
self._run()
self.llm_engine.pull_worker_metrics()
metric_store = self.llm_engine.get_metric_store()
return metric_store
-
-class BenchmarkRunnerLauncher:
-
- def __init__(self, config: BenchmarkConfig) -> None:
- self.config = config
- self.is_multi_replica = self.config.num_replicas > 1
-
- ray.init(ignore_reinit_error=True)
-
- self._validate_cluster_resources()
- self.runners = self._create_runners()
-
- if self.is_multi_replica:
- self.aggregate_metric_store = self._create_aggregate_metric_store()
-
- def _validate_cluster_resources(self):
- num_replicas = self.config.num_replicas
- num_gpus_required = num_replicas * self.config.parallel_config.world_size
-
- available_resources = ray.available_resources()
-
- assert (
- available_resources["GPU"] >= num_gpus_required
- ), f"Insufficient GPUs. Required: {num_gpus_required}, Available: {available_resources['GPU']}"
-
- def _get_replica_resource_mapping(self) -> ReplicaResourceMapping:
- if self.config.replica_resource_mapping:
- assert len(self.config.replica_resource_mapping) == self.config.num_replicas
- logger.info(
- f"Replica resource mapping: {self.config.replica_resource_mapping}"
- )
- return self.config.replica_resource_mapping
-
- cluster_resources_keys = list(ray.available_resources().keys())
- num_gpus = ray.available_resources()["GPU"]
- ip_addresses = [
- x
- for x in cluster_resources_keys
- if x.startswith("node:") and x != "node:__internal_head__"
- ]
-
- runner_ip = f"node:{get_ip()}"
-
- ip_addresses.remove(runner_ip)
- ip_addresses.insert(0, runner_ip)
-
- num_nodes = len(ip_addresses)
- assert num_nodes > 0, "No nodes found in the cluster"
- assert num_gpus > 0, "No GPUs found in the cluster"
- assert (
- num_gpus % num_nodes == 0
- ), f"Number of GPUs ({num_gpus}) is not a multiple of number of nodes ({num_nodes})"
- num_gpus_per_node = int(num_gpus // num_nodes)
- num_replicas = self.config.num_replicas
- num_gpus_per_replica = self.config.parallel_config.world_size
-
- assert (
- num_gpus >= num_replicas * num_gpus_per_replica
- ), f"Insufficient GPUs. Required: {num_replicas * num_gpus_per_replica}, Available: {num_gpus}"
-
- replica_resource_mapping = []
-
- available_gpus = []
- for ip_address in ip_addresses:
- for gpu_id in reversed(range(num_gpus_per_node)):
- available_gpus.append((ip_address, gpu_id))
-
- for _ in range(num_replicas):
- resource_mapping = []
- for _ in range(num_gpus_per_replica):
- resource_mapping.append(available_gpus.pop(0))
- replica_resource_mapping.append(resource_mapping)
-
- logger.info(f"Replica resource mapping: {replica_resource_mapping}")
-
- return replica_resource_mapping
-
- def _create_runners(self):
- replica_resource_mapping = self._get_replica_resource_mapping()
-
- if not self.is_multi_replica:
- return [BenchmarkRunner(0, self.config, replica_resource_mapping[0])]
-
- runner_class = ray.remote(num_cpus=1)(BenchmarkRunner)
-
- runners = []
-
- for replica_id in range(self.config.num_replicas):
- runners.append(
- runner_class.options(
- resources={
- replica_resource_mapping[replica_id][0][0]: 0.01,
- },
- ).remote(replica_id, self.config, replica_resource_mapping[replica_id])
- )
-
- return runners
-
- def _create_aggregate_metric_store(self):
- replica_config = ReplicaConfig(
- replica_id=0, # dummy replica id
- output_dir=self.config.output_dir,
- )
- metrics_store = MetricsStore.get_instance(
- replica_config,
- self.config.model_config,
- self.config.metrics_config,
- )
-
- if wandb.run is not None:
- wandb.config.update(self.config.to_dict())
-
- metrics_store.mark_initial_memory_profiling_done()
-
- return metrics_store
-
def run(self):
- if self.is_multi_replica:
- ray.get([runner.warmup.remote() for runner in self.runners])
-
- runner_metrics = ray.get([runner.run.remote() for runner in self.runners])
-
- for runner_metric in runner_metrics:
- self.aggregate_metric_store.merge(runner_metric)
-
- if wandb.run is not None:
- wandb.config.update(self.config.__dict__)
-
- self.aggregate_metric_store.plot()
- else:
- metric_store = self.runners[0].run()
- metric_store.plot()
-
- wandb.finish()
+ metric_store = self.run_benchmark()
+ metric_store.plot()
+ if wandb.run is not None:
+ wandb.finish()
diff --git a/sarathi/benchmark/config.py b/sarathi/benchmark/config.py
index bbc5d10..4780e24 100644
--- a/sarathi/benchmark/config.py
+++ b/sarathi/benchmark/config.py
@@ -2,7 +2,7 @@ import datetime
from dataclasses import dataclass, field
from typing import Optional
-from sarathi.config import BaseEndpointConfig
+from sarathi.config import BaseEndpointConfig, BaseGlobalSchedulerTypeConfig
from sarathi.config.base_poly_config import BasePolyConfig
from sarathi.config.flat_dataclass import create_flat_dataclass
from sarathi.logger import init_logger
diff --git a/sarathi/config/config.py b/sarathi/config/config.py
index a36d583..63e3605 100644
--- a/sarathi/config/config.py
+++ b/sarathi/config/config.py
@@ -7,7 +7,7 @@ from sarathi.config.base_poly_config import BasePolyConfig
from sarathi.config.flat_dataclass import create_flat_dataclass
from sarathi.logger import init_logger
from sarathi.transformers_utils.config import get_config
-from sarathi.types import AttentionBackend, ResourceMapping, SchedulerType
+from sarathi.types import AttentionBackend, ResourceMapping, SchedulerType, GlobalSchedulerType
from sarathi.utils.hf_utils import get_and_verify_dtype, get_and_verify_max_len
logger = init_logger(__name__)
@@ -221,7 +221,6 @@ class SimpleChunkingSchedulerConfig(BaseSchedulerConfig):
@dataclass
class OrcaSchedulerConfig(BaseSchedulerConfig):
-
def get_max_num_batched_tokens(self, max_model_len: int):
return self.max_num_seqs * max_model_len
@@ -232,7 +231,6 @@ class OrcaSchedulerConfig(BaseSchedulerConfig):
@dataclass
class FasterTransformerSchedulerConfig(BaseSchedulerConfig):
-
def get_max_num_batched_tokens(self, max_model_len: int):
return self.max_num_seqs * max_model_len
@@ -356,6 +354,28 @@ class WorkerConfig:
)
+@dataclass
+class BaseGlobalSchedulerTypeConfig(BasePolyConfig):
+ scheduler_type: str = field(
+ default="pull",
+ metadata={"help": "Replica level scheduler type either pull or RR"},
+ )
+
+
+@dataclass
+class PullGlobalSchedulerConfig(BaseGlobalSchedulerTypeConfig):
+ @staticmethod
+ def get_type():
+ return GlobalSchedulerType.PULL
+
+
+@dataclass
+class RoundRobinGlobalSchedulerConfig(BaseGlobalSchedulerTypeConfig):
+ @staticmethod
+ def get_type():
+ return GlobalSchedulerType.ROUND_ROBIN
+
+
@dataclass
class SystemConfig:
replica_config: ReplicaConfig = field(default_factory=ReplicaConfig)
@@ -367,6 +387,10 @@ class SystemConfig:
default_factory=SarathiSchedulerConfig
)
metrics_config: MetricsConfig = field(default_factory=MetricsConfig)
+ num_replicas: int = field(default=1, metadata={"help": "Number of replicas."})
+ global_scheduler_config : BaseGlobalSchedulerTypeConfig = field(
+ default_factory=BaseGlobalSchedulerTypeConfig
+ )
@dataclass
diff --git a/sarathi/core/datatypes/sequence.py b/sarathi/core/datatypes/sequence.py
index 07dbf1b..7b61e90 100644
--- a/sarathi/core/datatypes/sequence.py
+++ b/sarathi/core/datatypes/sequence.py
@@ -1,6 +1,8 @@
"""Sequence and its related classes."""
-from typing import List, Optional
+from typing import List, Optional,Any
+from dataclasses import dataclass, field
+import random
from sarathi.core.datatypes.block import LogicalTokenBlock
from sarathi.core.datatypes.sampling_params import SamplingParams
@@ -8,6 +10,11 @@ from sarathi.core.datatypes.sequence_state import SequenceState
from sarathi.core.datatypes.sequence_status import SequenceStatus
+@dataclass(order=True)
+class SequenceWithPriority:
+ priority : float
+ seq : Any=field(compare=False)
+
class Sequence:
"""Stores the data, status, and block information of a sequence.
@@ -216,6 +223,9 @@ class Sequence:
f"prompt_stage_processing_finished={self.prompt_stage_processing_finished})"
)
+ @property
+ def arrived_at(self) -> float:
+ return self.arrival_time
class SequenceScheduleMetadata:
"""Metadata generated by the scheduler for sequence that has been scheduled.
diff --git a/sarathi/core/scheduler/base_scheduler.py b/sarathi/core/scheduler/base_scheduler.py
index 6c73d59..d69dc9f 100644
--- a/sarathi/core/scheduler/base_scheduler.py
+++ b/sarathi/core/scheduler/base_scheduler.py
@@ -1,15 +1,19 @@
from abc import ABC, abstractmethod
from typing import List
+from queue import PriorityQueue
from sarathi.config import BaseSchedulerConfig, CacheConfig, ModelConfig, ParallelConfig
from sarathi.core.block_space_manager.block_space_manager_registry import (
BlockSpaceManagerRegistry,
)
from sarathi.core.datatypes.scheduler_output import SchedulerOutputs
-from sarathi.core.datatypes.sequence import Sequence, SequenceStatus
+from sarathi.core.datatypes.sequence import Sequence, SequenceStatus, SequenceWithPriority
+from sarathi.core.sequence_manager.engine_sequence_manager import EngineSequenceManager
from sarathi.core.policy import PolicyFactory
from sarathi.logger import init_logger
from sarathi.metrics.metrics_store import MetricsStore
+from sarathi.utils.threading_utils import synchronized
+
logger = init_logger(__name__)
@@ -22,6 +26,9 @@ class BaseScheduler(ABC):
scheduler_config: BaseSchedulerConfig,
cache_config: CacheConfig,
parallel_config: ParallelConfig,
+ waiting_queue : PriorityQueue,
+ replica_seq_manager : EngineSequenceManager,
+ metric_store : MetricsStore,
) -> None:
self.metrics_store = MetricsStore.get_instance()
self.model_config = model_config
@@ -42,13 +49,18 @@ class BaseScheduler(ABC):
model_config.max_model_len,
)
self.prompt_limit = model_config.max_model_len
+ self.replica_seq_manager = replica_seq_manager
+ self.new_seqs: List[Sequence] = []
+ self.metrics_store = metric_store
+ self.seq_seen = set()
# number of running batches should be less than or equal to the number of pipeline stages
self.num_running_batches = 0
# TODO(zhuohan): Use deque instead of list for better performance.
# Sequence groups in the WAITING state.
- self.waiting: List[Sequence] = []
+ # self.waiting : PriorityQueue = PriorityQueue()
+ self.waiting : PriorityQueue = waiting_queue
# Sequence groups in the RUNNING state.
self.running: List[Sequence] = []
@@ -56,19 +68,37 @@ class BaseScheduler(ABC):
self._iteration_id = -1
def add_seq(self, seq: Sequence) -> None:
- # Add sequence groups to the waiting queue.
- self.waiting.append(seq)
+ # Add sequence groups to the waiting queue.
+ wrapped_seq = SequenceWithPriority(seq.arrived_at, seq)
+
+ self.waiting.put(wrapped_seq)
def has_unfinished_seqs(self) -> bool:
- return self.waiting or self.running
+ return self.waiting.qsize() > 0 or self.running
def get_num_unfinished_seqs(self) -> int:
- return len(self.waiting) + len(self.running)
+ return self.waiting.qsize() + len(self.running)
@abstractmethod
def _schedule(self) -> SchedulerOutputs:
pass
+ @synchronized
+ def add_to_new_seqs(self, seq: Sequence) -> None:
+ self.new_seqs.append(seq)
+
+ @synchronized
+ def get_new_seqs(
+ self,
+ ) -> List[Sequence]:
+ new_seqs = self.new_seqs
+ self.new_seqs = []
+ return new_seqs
+
+ @synchronized
+ def add_seq_to_seq_manager(self, seq: Sequence) -> None:
+ self.replica_seq_manager.add_seq(seq)
+
def schedule(self) -> SchedulerOutputs:
# Schedule sequence groups.
# This function call changes the internal states of the scheduler
@@ -82,7 +112,7 @@ class BaseScheduler(ABC):
preempted_seq_ids=[],
scheduled_seq_metadata_list=[],
)
-
+
scheduler_outputs = self._schedule()
if not scheduler_outputs.is_empty():
@@ -119,7 +149,10 @@ class BaseScheduler(ABC):
) -> None:
assert seq.is_executing()
self._free_seq(seq)
- self.waiting.insert(0, seq)
+
+ wrapped_seq = SequenceWithPriority(seq.arrived_at, seq)
+
+ self.waiting.put(wrapped_seq)
def _check_request_prompt_length(self, seq: Sequence) -> bool:
if seq.get_len() > self.prompt_limit:
@@ -128,7 +161,7 @@ class BaseScheduler(ABC):
f" and exceeds limit of {self.prompt_limit}"
)
seq.set_status(SequenceStatus.FINISHED_IGNORED)
- self.waiting.pop(0)
+ self.waiting.get(block=False)
return False
- return True
+ return True
\ No newline at end of file
diff --git a/sarathi/core/scheduler/faster_transformer_scheduler.py b/sarathi/core/scheduler/faster_transformer_scheduler.py
index b103630..8ae05d3 100644
--- a/sarathi/core/scheduler/faster_transformer_scheduler.py
+++ b/sarathi/core/scheduler/faster_transformer_scheduler.py
@@ -1,5 +1,6 @@
import time
from typing import List
+from queue import PriorityQueue
from sarathi.config import (
CacheConfig,
@@ -12,8 +13,11 @@ from sarathi.core.block_space_manager.faster_transformer_block_space_manager imp
)
from sarathi.core.datatypes.scheduler_output import SchedulerOutputs
from sarathi.core.datatypes.sequence import SequenceScheduleMetadata
+from sarathi.core.sequence_manager.engine_sequence_manager import EngineSequenceManager
from sarathi.core.scheduler.base_scheduler import BaseScheduler
from sarathi.logger import init_logger
+from sarathi.metrics.metrics_store import MetricsStore
+
logger = init_logger(__name__)
@@ -26,8 +30,11 @@ class FasterTransformerScheduler(BaseScheduler):
scheduler_config: FasterTransformerSchedulerConfig,
cache_config: CacheConfig,
parallel_config: ParallelConfig,
+ waiting_queue : PriorityQueue,
+ replica_seq_manager : EngineSequenceManager,
+ metric_store : MetricsStore,
) -> None:
- super().__init__(model_config, scheduler_config, cache_config, parallel_config)
+ super().__init__(model_config, scheduler_config, cache_config, parallel_config, waiting_queue, replica_seq_manager, metric_store)
def get_block_space_manager_class(self):
return FasterTransformerBlockSpaceManager
@@ -58,9 +65,9 @@ class FasterTransformerScheduler(BaseScheduler):
# Optimization: We do not sort the waiting queue since the preempted
# sequences are added to the front and the new sequences
# are added to the back.
- while self.waiting:
- seq = self.waiting[0]
-
+ while self.waiting.qsize() > 0:
+ seq_wrapped = self.waiting.queue[0]
+ seq = seq_wrapped.seq
# This is required to handle benchmarking where
# we set request arrival time ahead of time
if seq.arrival_time > now:
@@ -77,7 +84,8 @@ class FasterTransformerScheduler(BaseScheduler):
if len(self.running) + 1 > self.scheduler_config.max_num_seqs:
break
- seq = self.waiting.pop(0)
+ seq_wrapped = self.waiting.get()
+ seq = seq_wrapped.seq
self._allocate(seq)
self.running.append(seq)
scheduled_seq_metadata_list.append(
diff --git a/sarathi/core/scheduler/global_scheduler.py b/sarathi/core/scheduler/global_scheduler.py
new file mode 100644
index 0000000..dde1064
--- /dev/null
+++ b/sarathi/core/scheduler/global_scheduler.py
@@ -0,0 +1,172 @@
+import random
+import time
+
+from typing import List, Optional, Dict
+from threading import Thread
+from queue import PriorityQueue
+
+from sarathi.core.datatypes.sampling_params import SamplingParams
+from sarathi.logger import init_logger
+from sarathi.core.sequence_manager.engine_sequence_manager import EngineSequenceManager
+from sarathi.core.datatypes.sequence import SamplerOutputs, Sequence, SequenceWithPriority
+from sarathi.utils.threading_utils import synchronized
+
+logger = init_logger(__name__)
+
+
+class GlobalScheduler:
+ def __init__(self, config, num_replicas, sequence_counter, ):
+ logger.info(
+ f"GlobalScheduler initialized with {num_replicas} replicas"
+ )
+
+ self.config = config
+ self.num_replicas = num_replicas
+ self.replica_llm_engine_mapping = {}
+ self.seq_counter = sequence_counter
+ self.seq_map = None
+ self.new_seq_list = None
+
+ def init_queue(self):
+ pass
+
+ def get_replica_queue(self, replica_id):
+ pass
+
+ def get_replica_queue_mapping(self):
+ pass
+
+ def get_seq_map(self):
+ return self.seq_map
+
+ def get_new_seq_list(self):
+ return self.new_seq_list
+
+ def set_replica_llm_engine(self, replica_id, replica_llm_engine):
+ self.replica_llm_engine_mapping[replica_id] = replica_llm_engine
+
+ def _assign_queue(self, seq: Sequence, replica_id : int):
+ pass
+
+ @synchronized
+ def assign_seq_replica(self, seq : Sequence) -> None:
+ pass
+
+ def assign_replica(
+ self,
+ prompt: Optional[str],
+ sampling_params: SamplingParams,
+ prompt_token_ids: Optional[List[int]] = None,
+ arrival_time: Optional[float] = None,
+ seq_id: Optional[str] = None,
+ ):
+ pass
+
+ def get_num_unfinished_requests(self):
+ pass
+
+ def has_unfinished_requests(self):
+ pass
+
+ def get_replica_id(self):
+ pass
+
+
+class PullScheduler(GlobalScheduler):
+ """
+ PullScheduler is a global scheduler that assigns requests to a global request queue and the replicas pull requests from the queue.
+ """
+
+ def __init__(self, config, num_replicas, sequence_counter):
+ super().__init__(config, num_replicas, sequence_counter)
+ logger.info(f"PullScheduler initialized with {num_replicas} replicas")
+
+ def init_queue(self):
+ self.replica_queue_mapping = {"global": PriorityQueue()}
+ self.seq_map: Dict[str, Sequence] = None
+ self.new_seq_list = None
+
+ def get_replica_queue_mapping(self):
+ return self.replica_queue_mapping
+
+ def get_replica_queue(self, replica_id):
+ return self.replica_queue_mapping["global"]
+
+ def assign_replica(
+ self,
+ prompt: Optional[str],
+ sampling_params: SamplingParams,
+ prompt_token_ids: Optional[List[int]] = None,
+ arrival_time: Optional[float] = None,
+ seq_id: Optional[str] = None,
+ ):
+ pass
+
+ def _assign_queue(self, seq, replica_id):
+ wrapped_seq = SequenceWithPriority(seq.arrived_at, seq)
+ self.replica_queue_mapping["global"].put(wrapped_seq)
+
+ @synchronized
+ def assign_seq_replica(self, seq : Sequence) -> None:
+ self._assign_queue(seq, None)
+
+ def get_num_unfinished_requests(self):
+ return self.replica_queue_mapping["global"].qsize()
+
+ def has_unfinished_requests(self):
+ return not self.replica_queue_mapping["global"].empty()
+
+
+class RoundRobinScheduler(GlobalScheduler):
+ """
+ RoundRobinScheduler is a global scheduler that assigns requests to replicas in a round-robin manner.
+ """
+
+ def __init__(self, config, num_replicas, sequence_counter):
+ super().__init__(config, num_replicas, sequence_counter)
+ self.current_replica_id = 0
+ logger.info(f"RoundRobinScheduler initialized with {num_replicas} replicas")
+
+ def init_queue(self):
+ self.replica_queue_mapping = {
+ replica_id: PriorityQueue() for replica_id in range(self.num_replicas)
+ }
+
+ def get_replica_queue_mapping(self):
+ return self.replica_queue_mapping
+
+ def get_replica_queue(self, replica_id):
+ return self.replica_queue_mapping[replica_id]
+
+ def _assign_queue(self, seq, replica_id):
+ logger.info(f"[ROUND ROBIN SCHED] Assigning request to replica {replica_id}")
+ wrapped_seq = SequenceWithPriority(seq.arrived_at, seq)
+ self.replica_queue_mapping[replica_id].put(wrapped_seq)
+
+ @synchronized
+ def assign_seq_replica(self, seq: Sequence) -> None:
+ replica_id = self.current_replica_id
+ self._assign_queue(seq, replica_id)
+ self.current_replica_id = (self.current_replica_id + 1) % self.num_replicas
+
+ def assign_replica(
+ self,
+ prompt: Optional[str],
+ sampling_params: SamplingParams,
+ prompt_token_ids: Optional[List[int]] = None,
+ arrival_time: Optional[float] = None,
+ seq_id: Optional[str] = None,
+ ):
+ pass
+
+ def get_num_unfinished_requests(self):
+ num_unfinished_requests = 0
+ for replica_id in range(self.num_replicas):
+ num_unfinished_requests += self.replica_queue_mapping[replica_id].qsize
+ return num_unfinished_requests
+
+ def has_unfinished_requests(self):
+ for replica_id in range(self.num_replicas):
+ if not self.replica_queue_mapping[replica_id].empty():
+ return True
+ return False
diff --git a/sarathi/core/scheduler/orca_scheduler.py b/sarathi/core/scheduler/orca_scheduler.py
index c80ad04..daae28d 100644
--- a/sarathi/core/scheduler/orca_scheduler.py
+++ b/sarathi/core/scheduler/orca_scheduler.py
@@ -1,5 +1,6 @@
import time
from typing import List
+from queue import PriorityQueue
from sarathi.config import CacheConfig, ModelConfig, OrcaSchedulerConfig, ParallelConfig
from sarathi.core.block_space_manager.orca_block_space_manager import (
@@ -7,8 +8,10 @@ from sarathi.core.block_space_manager.orca_block_space_manager import (
)
from sarathi.core.datatypes.scheduler_output import SchedulerOutputs
from sarathi.core.datatypes.sequence import SequenceScheduleMetadata
+from sarathi.core.sequence_manager.engine_sequence_manager import EngineSequenceManager
from sarathi.core.scheduler.base_scheduler import BaseScheduler
from sarathi.logger import init_logger
+from sarathi.metrics.metrics_store import MetricsStore
logger = init_logger(__name__)
@@ -21,8 +24,11 @@ class OrcaScheduler(BaseScheduler):
scheduler_config: OrcaSchedulerConfig,
cache_config: CacheConfig,
parallel_config: ParallelConfig,
+ waiting_queue : PriorityQueue,
+ replica_seq_manager : EngineSequenceManager,
+ metric_store : MetricsStore,
) -> None:
- super().__init__(model_config, scheduler_config, cache_config, parallel_config)
+ super().__init__(model_config, scheduler_config, cache_config, parallel_config,waiting_queue, replica_seq_manager, metric_store)
def get_block_space_manager_class(self):
return OrcaBlockSpaceManager
@@ -48,8 +54,9 @@ class OrcaScheduler(BaseScheduler):
# Optimization: We do not sort the waiting queue since the preempted
# sequences are added to the front and the new sequences
# are added to the back.
- while self.waiting:
- seq = self.waiting[0]
+ while self.waiting.qsize() > 0:
+ seq_wrapped = self.waiting.queue[0]
+ seq = seq_wrapped.seq
# This is required to handle benchmarking where we set request arrival time ahead of time
if seq.arrival_time > now:
@@ -66,7 +73,8 @@ class OrcaScheduler(BaseScheduler):
if len(self.running) + 1 > self.scheduler_config.max_num_seqs:
break
- seq = self.waiting.pop(0)
+ seq_wrapped = self.waiting.get()
+ seq = seq_wrapped.seq
self._allocate(seq)
self.running.append(seq)
scheduled_seq_metadata_list.append(
diff --git a/sarathi/core/scheduler/sarathi_scheduler.py b/sarathi/core/scheduler/sarathi_scheduler.py
index bd47563..49d33b2 100644
--- a/sarathi/core/scheduler/sarathi_scheduler.py
+++ b/sarathi/core/scheduler/sarathi_scheduler.py
@@ -1,5 +1,7 @@
+import copy
import time
from typing import List
+from queue import PriorityQueue
import numpy as np
@@ -13,9 +15,11 @@ from sarathi.core.block_space_manager.sarathi_block_space_manager import (
SarathiBlockSpaceManager,
)
from sarathi.core.datatypes.scheduler_output import SchedulerOutputs
-from sarathi.core.datatypes.sequence import Sequence, SequenceScheduleMetadata
+from sarathi.core.datatypes.sequence import Sequence, SequenceScheduleMetadata, SequenceWithPriority
+from sarathi.core.sequence_manager.engine_sequence_manager import EngineSequenceManager
from sarathi.core.scheduler.base_scheduler import BaseScheduler
from sarathi.logger import init_logger
+from sarathi.metrics.metrics_store import MetricsStore
logger = init_logger(__name__)
@@ -28,8 +32,11 @@ class SarathiScheduler(BaseScheduler):
scheduler_config: SarathiSchedulerConfig,
cache_config: CacheConfig,
parallel_config: ParallelConfig,
+ waiting_queue : PriorityQueue,
+ replica_seq_manager : EngineSequenceManager,
+ metric_store : MetricsStore,
) -> None:
- super().__init__(model_config, scheduler_config, cache_config, parallel_config)
+ super().__init__(model_config, scheduler_config, cache_config, parallel_config, waiting_queue, replica_seq_manager, metric_store)
self.chunk_size = self.scheduler_config.chunk_size
self.enable_dynamic_chunking_schedule = (
@@ -193,8 +200,9 @@ class SarathiScheduler(BaseScheduler):
# Optimization: We do not sort the waiting queue since the preempted
# sequence groups are added to the front and the new sequence groups
# are added to the back.
- while self.waiting:
- seq = self.waiting[0]
+ while self.waiting.qsize() > 0:
+ seq_wrapped = self.waiting.queue[0]
+ seq = seq_wrapped.seq
# This is required to handle benchmarking where we set request arrival time ahead of time
if seq.arrival_time > now:
@@ -223,8 +231,9 @@ class SarathiScheduler(BaseScheduler):
if next_num_prefill_tokens == 0:
break
-
- seq = self.waiting.pop(0)
+
+ seq_wrapped = self.waiting.get()
+ seq = seq_wrapped.seq
self._allocate(seq)
num_batched_tokens += next_num_prefill_tokens
scheduled_seq_metadata_list.append(
@@ -232,6 +241,13 @@ class SarathiScheduler(BaseScheduler):
seq, prompt_chunk_len=next_num_prefill_tokens
)
)
+
+ if seq.seq_id not in self.seq_seen:
+ self.add_seq_to_seq_manager(seq)
+ self.add_to_new_seqs(copy.deepcopy(seq))
+ self.seq_seen.add(seq.seq_id)
+ self.metrics_store.on_request_arrival(seq)
+
running.append(seq)
# make sure that prefills are at the start of the batch, so that we don't violate assumptions
@@ -243,4 +259,4 @@ class SarathiScheduler(BaseScheduler):
ignored_seq_ids=ignored_seq_ids,
preempted_seq_ids=preempted_seq_ids,
scheduled_seq_metadata_list=scheduled_seq_metadata_list,
- )
+ )
\ No newline at end of file
diff --git a/sarathi/core/scheduler/simple_chunking_scheduler.py b/sarathi/core/scheduler/simple_chunking_scheduler.py
index 95b4329..7d6e43c 100644
--- a/sarathi/core/scheduler/simple_chunking_scheduler.py
+++ b/sarathi/core/scheduler/simple_chunking_scheduler.py
@@ -1,6 +1,7 @@
import time
from enum import Enum, auto
from typing import List
+from queue import PriorityQueue
from sarathi.config import (
CacheConfig,
@@ -14,8 +15,10 @@ from sarathi.core.block_space_manager.vllm_block_space_manager import (
from sarathi.core.datatypes.scheduler_output import SchedulerOutputs
from sarathi.core.datatypes.sequence import Sequence, SequenceScheduleMetadata
from sarathi.core.datatypes.sequence_status import SequenceStatus
+from sarathi.core.sequence_manager.engine_sequence_manager import EngineSequenceManager
from sarathi.core.scheduler.base_scheduler import BaseScheduler
from sarathi.logger import init_logger
+from sarathi.metrics.metrics_store import MetricsStore
logger = init_logger(__name__)
@@ -33,8 +36,11 @@ class SimpleChunkingScheduler(BaseScheduler):
scheduler_config: SimpleChunkingSchedulerConfig,
cache_config: CacheConfig,
parallel_config: ParallelConfig,
+ waiting_queue : PriorityQueue,
+ replica_seq_manager : EngineSequenceManager,
+ metric_store : MetricsStore,
) -> None:
- super().__init__(model_config, scheduler_config, cache_config, parallel_config)
+ super().__init__(model_config, scheduler_config, cache_config, parallel_config, waiting_queue, replica_seq_manager, metric_store)
self.chunk_size = self.scheduler_config.chunk_size
self.whose_turn = Turn.PREFILL
@@ -115,8 +121,9 @@ class SimpleChunkingScheduler(BaseScheduler):
scheduled_seq_metadata_list=scheduled_seq_metadata_list,
)
- while self.waiting and self.whose_turn == Turn.PREFILL:
- seq = self.waiting[0]
+ while self.waiting.qsize() > 0 and self.whose_turn == Turn.PREFILL:
+ seq_wrapped = self.waiting.queue[0]
+ seq = seq_wrapped.seq
# This is required to handle benchmarking where
# we set request arrival time ahead of time
if seq.arrival_time > now:
@@ -141,7 +148,8 @@ class SimpleChunkingScheduler(BaseScheduler):
# not enough space to allocate the sequence
break
- self.waiting.pop(0)
+ seq_wrapped = self.waiting.get()
+ seq = seq_wrapped.seq
self._allocate(seq)
self.running.append(seq)
num_batched_tokens += next_num_prefill_tokens
diff --git a/sarathi/core/scheduler/vllm_scheduler.py b/sarathi/core/scheduler/vllm_scheduler.py
index 84cb3b1..e4bcfca 100644
--- a/sarathi/core/scheduler/vllm_scheduler.py
+++ b/sarathi/core/scheduler/vllm_scheduler.py
@@ -1,14 +1,17 @@
import time
from typing import List
+from queue import PriorityQueue
from sarathi.config import CacheConfig, ModelConfig, ParallelConfig, VllmSchedulerConfig
from sarathi.core.block_space_manager.vllm_block_space_manager import (
VLLMBlockSpaceManager,
)
from sarathi.core.datatypes.scheduler_output import SchedulerOutputs
-from sarathi.core.datatypes.sequence import Sequence, SequenceScheduleMetadata
+from sarathi.core.datatypes.sequence import Sequence, SequenceScheduleMetadata, SequenceWithPriority
+from sarathi.core.sequence_manager.engine_sequence_manager import EngineSequenceManager
from sarathi.core.scheduler.base_scheduler import BaseScheduler
from sarathi.logger import init_logger
+from sarathi.metrics.metrics_store import MetricsStore
logger = init_logger(__name__)
@@ -21,8 +24,12 @@ class VLLMScheduler(BaseScheduler):
scheduler_config: VllmSchedulerConfig,
cache_config: CacheConfig,
parallel_config: ParallelConfig,
+ waiting_queue : PriorityQueue,
+ replica_seq_manager : EngineSequenceManager,
+ metric_store : MetricsStore,
+
) -> None:
- super().__init__(model_config, scheduler_config, cache_config, parallel_config)
+ super().__init__(model_config, scheduler_config, cache_config, parallel_config, waiting_queue, replica_seq_manager, metric_store)
self.max_num_batched_tokens = self.scheduler_config.get_max_num_batched_tokens(
self.model_config.max_model_len
@@ -46,8 +53,10 @@ class VLLMScheduler(BaseScheduler):
# Optimization: We do not sort the waiting queue since the preempted
# sequence groups are added to the front and the new sequence groups
# are added to the back.
- while self.waiting:
- seq = self.waiting[0]
+ while self.waiting.qsize() > 0:
+ seq_wrapped = self.waiting.queue[0]
+ seq = seq_wrapped.seq
+
# This is required to handle benchmarking where
# we set request arrival time ahead of time
if seq.arrival_time > now:
@@ -68,8 +77,9 @@ class VLLMScheduler(BaseScheduler):
if len(self.running) + 1 > self.scheduler_config.max_num_seqs:
break
-
- seq = self.waiting.pop(0)
+
+ seq_wrapped = self.waiting.get()
+ seq = seq_wrapped.seq