scheduler.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. import enum
  2. import os
  3. import random
  4. import time
  5. from collections import deque
  6. from dataclasses import dataclass, field
  7. from typing import Deque, Dict, Iterable, List, Optional, Set, Tuple, Union
  8. from loguru import logger
  9. from aphrodite.common.config import CacheConfig, LoRAConfig, SchedulerConfig
  10. from aphrodite.common.sequence import (Sequence, SequenceData, SequenceGroup,
  11. SequenceGroupMetadata, SequenceStatus)
  12. from aphrodite.lora.request import LoRARequest
  13. from aphrodite.processing.interfaces import AllocStatus, BlockSpaceManager
  14. from aphrodite.processing.policy import Policy, PolicyFactory
  15. # Test-only. If configured, decode is preempted with
  16. # ARTIFICIAL_PREEMPTION_PROB% probability.
  17. ENABLE_ARTIFICIAL_PREEMPT = bool(
  18. os.getenv("APHRODITE_TEST_ENABLE_ARTIFICIAL_PREEMPT", False)) # noqa
  19. ARTIFICIAL_PREEMPTION_PROB = 0.5
  20. ARTIFICIAL_PREEMPTION_MAX_CNT = 500
  21. class PreemptionMode(enum.Enum):
  22. """Preemption modes.
  23. 1. Swapping: Swap out the blocks of the preempted sequences to CPU memory
  24. and swap them back in when the sequences are resumed.
  25. 2. Recomputation: Discard the blocks of the preempted sequences and
  26. recompute them when the sequences are resumed, treating the sequences as
  27. new prompts.
  28. """
  29. SWAP = enum.auto()
  30. RECOMPUTE = enum.auto()
  31. @dataclass
  32. class SchedulingBudget:
  33. """The available slots for scheduling.
  34. TODO: Right now, the budget is request_id-aware meaning it can ignore
  35. budget update from the same request_id. It is because in normal scheduling
  36. path, we update RUNNING num_seqs ahead of time, meaning it could be
  37. updated more than once when scheduling RUNNING requests. Since this won't
  38. happen if we only have chunked prefill scheduling, we can remove this
  39. feature from the API when chunked prefill is enabled by default.
  40. """
  41. token_budget: int
  42. max_num_seqs: int
  43. _request_ids_num_batched_tokens: Set[str] = field(default_factory=set)
  44. _request_ids_num_curr_seqs: Set[str] = field(default_factory=set)
  45. _num_batched_tokens: int = 0
  46. _num_curr_seqs: int = 0
  47. def can_schedule(self, *, num_new_tokens: int, num_new_seqs: int):
  48. assert num_new_tokens != 0
  49. assert num_new_seqs != 0
  50. return (self.num_batched_tokens + num_new_tokens <= self.token_budget
  51. and self.num_curr_seqs + num_new_seqs <= self.max_num_seqs)
  52. def remaining_token_budget(self):
  53. return self.token_budget - self.num_batched_tokens
  54. def add_num_batched_tokens(self, req_id: str, num_batched_tokens: int):
  55. if req_id in self._request_ids_num_batched_tokens:
  56. return
  57. self._request_ids_num_batched_tokens.add(req_id)
  58. self._num_batched_tokens += num_batched_tokens
  59. def subtract_num_batched_tokens(self, req_id: str,
  60. num_batched_tokens: int):
  61. if req_id in self._request_ids_num_batched_tokens:
  62. self._request_ids_num_batched_tokens.remove(req_id)
  63. self._num_batched_tokens -= num_batched_tokens
  64. def add_num_seqs(self, req_id: str, num_curr_seqs: int):
  65. if req_id in self._request_ids_num_curr_seqs:
  66. return
  67. self._request_ids_num_curr_seqs.add(req_id)
  68. self._num_curr_seqs += num_curr_seqs
  69. def subtract_num_seqs(self, req_id: str, num_curr_seqs: int):
  70. if req_id in self._request_ids_num_curr_seqs:
  71. self._request_ids_num_curr_seqs.remove(req_id)
  72. self._num_curr_seqs -= num_curr_seqs
  73. @property
  74. def num_batched_tokens(self):
  75. return self._num_batched_tokens
  76. @property
  77. def num_curr_seqs(self):
  78. return self._num_curr_seqs
  79. @dataclass
  80. class ScheduledSequenceGroup:
  81. # A sequence group that's scheduled.
  82. seq_group: SequenceGroup
  83. # The total chunk size (number of tokens) to process for next iteration.
  84. # 1 for decoding. Same as prompt tokens for prefill, but if prefill is
  85. # chunked, it can be smaller than that.
  86. token_chunk_size: int
  87. @dataclass
  88. class SchedulerOutputs:
  89. """The scheduling decision made from a scheduler."""
  90. # Scheduled sequence groups.
  91. scheduled_seq_groups: Iterable[ScheduledSequenceGroup]
  92. # Number of prefill groups scheduled.
  93. num_prefill_groups: int
  94. # Total number of batched tokens.
  95. num_batched_tokens: int
  96. # Blocks to swap in. List of CPU -> GPU block number.
  97. blocks_to_swap_in: List[Tuple[int, int]]
  98. # Blocks to swap out. List of GPU -> CPU block number.
  99. blocks_to_swap_out: List[Tuple[int, int]]
  100. # Blocks to copy. Source to dest block.
  101. blocks_to_copy: List[Tuple[int, int]]
  102. # Sequence groups that are going to be ignored.
  103. ignored_seq_groups: List[SequenceGroup]
  104. # The number of slots for lookahead decoding.
  105. num_lookahead_slots: int
  106. # The number of requests in the running queue
  107. running_queue_size: int
  108. preempted: int
  109. def __post_init__(self):
  110. # Swap in and swap out should never happen at the same time.
  111. assert not (self.blocks_to_swap_in and self.blocks_to_swap_out)
  112. self.num_loras: int = len(self.lora_requests)
  113. if self.num_loras > 0:
  114. self._sort_by_lora_ids()
  115. def is_empty(self) -> bool:
  116. # NOTE: We do not consider the ignored sequence groups.
  117. return (not self.scheduled_seq_groups and not self.blocks_to_swap_in
  118. and not self.blocks_to_swap_out and not self.blocks_to_copy)
  119. def _sort_by_lora_ids(self):
  120. self.scheduled_seq_groups = sorted(
  121. self.scheduled_seq_groups,
  122. key=lambda g: (g.seq_group.lora_int_id, g.seq_group.request_id))
  123. @property
  124. def lora_requests(self) -> Set[LoRARequest]:
  125. return {
  126. g.seq_group.lora_request
  127. for g in self.scheduled_seq_groups
  128. if g.seq_group.lora_request is not None
  129. }
  130. @dataclass
  131. class SchedulerRunningOutputs:
  132. """The requests that are scheduled from a running queue.
  133. Could contain prefill (prefill that's chunked) or decodes. If there's not
  134. enough memory, it can be preempted (for recompute) or swapped out.
  135. """
  136. # Selected sequences that are running and in a decoding phase.
  137. decode_seq_groups: List[SequenceGroup]
  138. # Selected sequences that are running and in a prefill phase.
  139. # I.e., it means the prefill has been chunked.
  140. prefill_seq_groups: List[SequenceGroup]
  141. # The preempted sequences.
  142. preempted: List[SequenceGroup]
  143. # Sequences that are swapped out.
  144. swapped_out: List[SequenceGroup]
  145. # The blocks to swap out.
  146. blocks_to_swap_out: List[Tuple[int, int]]
  147. # The blocks to copy.
  148. blocks_to_copy: List[Tuple[int, int]]
  149. # The number of slots for lookahead decoding.
  150. num_lookahead_slots: int
  151. @classmethod
  152. def create_empty(cls) -> "SchedulerRunningOutputs":
  153. return SchedulerRunningOutputs(
  154. decode_seq_groups=[],
  155. prefill_seq_groups=[],
  156. preempted=[],
  157. swapped_out=[],
  158. blocks_to_swap_out=[],
  159. blocks_to_copy=[],
  160. num_lookahead_slots=0,
  161. )
  162. @dataclass
  163. class SchedulerSwappedInOutputs:
  164. """The requests that are scheduled from a swap queue.
  165. Could contain prefill (prefill that's chunked) or decodes.
  166. """
  167. # Selected sequences that are going to be swapped in and is in a
  168. # decoding phase.
  169. decode_seq_groups: List[SequenceGroup]
  170. # Selected sequences that are going to be swapped in and in a prefill
  171. # phase. I.e., it means the prefill has been chunked.
  172. prefill_seq_groups: List[SequenceGroup]
  173. # The blocks to swap in.
  174. blocks_to_swap_in: List[Tuple[int, int]]
  175. # The blocks to copy.
  176. blocks_to_copy: List[Tuple[int, int]]
  177. # The number of slots for lookahead decoding.
  178. num_lookahead_slots: int
  179. # Infeasible sequence groups.
  180. infeasible_seq_groups: List[SequenceGroup]
  181. @classmethod
  182. def create_empty(cls) -> "SchedulerSwappedInOutputs":
  183. return SchedulerSwappedInOutputs(
  184. decode_seq_groups=[],
  185. prefill_seq_groups=[],
  186. blocks_to_swap_in=[],
  187. blocks_to_copy=[],
  188. num_lookahead_slots=0,
  189. infeasible_seq_groups=[],
  190. )
  191. @dataclass
  192. class SchedulerPrefillOutputs:
  193. """The requests that are scheduled from a waiting queue.
  194. Could contain a fresh prefill requests or preempted requests that need
  195. to be recomputed from scratch.
  196. """
  197. # Selected sequences for prefill.
  198. seq_groups: List[SequenceGroup]
  199. # Ignored sequence groups.
  200. ignored_seq_groups: List[SequenceGroup]
  201. num_lookahead_slots: int
  202. @classmethod
  203. def create_empty(cls) -> "SchedulerPrefillOutputs":
  204. return SchedulerPrefillOutputs(
  205. seq_groups=[],
  206. ignored_seq_groups=[],
  207. num_lookahead_slots=0,
  208. )
  209. class Scheduler:
  210. def __init__(
  211. self,
  212. scheduler_config: SchedulerConfig,
  213. cache_config: CacheConfig,
  214. lora_config: Optional[LoRAConfig],
  215. ) -> None:
  216. self.scheduler_config = scheduler_config
  217. self.cache_config = cache_config
  218. # Note for LoRA scheduling: the current policy is extremely
  219. # simple and NOT fair. It can lead to starvation of some
  220. # LoRAs. This should be improved in the future.
  221. self.lora_config = lora_config
  222. version = "v1"
  223. if self.scheduler_config.use_v2_block_manager:
  224. version = "v2"
  225. if self.scheduler_config.embedding_mode:
  226. version = "embedding"
  227. BlockSpaceManagerImpl = BlockSpaceManager.get_block_space_manager_class(
  228. version)
  229. # Create the block space manager.
  230. self.block_manager = BlockSpaceManagerImpl(
  231. block_size=self.cache_config.block_size,
  232. num_gpu_blocks=self.cache_config.num_gpu_blocks,
  233. num_cpu_blocks=self.cache_config.num_cpu_blocks,
  234. sliding_window=self.cache_config.sliding_window,
  235. enable_caching=self.cache_config.enable_prefix_caching)
  236. # Sequence groups in the WAITING state.
  237. # Contain new prefill or preempted requests.
  238. self.waiting: Deque[SequenceGroup] = deque()
  239. # Sequence groups in the RUNNING state.
  240. # Contain decode requests.
  241. self.running: Deque[SequenceGroup] = deque()
  242. # Sequence groups in the SWAPPED state.
  243. # Contain decode requests that are swapped out.
  244. self.swapped: Deque[SequenceGroup] = deque()
  245. # Time at previous scheduling step
  246. self.prev_time = 0.0
  247. # Did we schedule a prompt at previous step?
  248. self.prev_prompt = False
  249. # Latency of the last prompt step
  250. self.last_prompt_latency = 0.0
  251. # preemption mode, RECOMPUTE or SWAP
  252. self.user_specified_preemption_mode = scheduler_config.preemption_mode
  253. # The following field is test-only. It is used to inject artificial
  254. # preemption.
  255. self.enable_artificial_preemption = ENABLE_ARTIFICIAL_PREEMPT
  256. self.artificial_preempt_cnt = (ARTIFICIAL_PREEMPTION_MAX_CNT
  257. if self.enable_artificial_preemption
  258. else 0)
  259. self.num_cumulative_preemption: int = 0
  260. @property
  261. def lora_enabled(self) -> bool:
  262. return bool(self.lora_config)
  263. @property
  264. def num_decoding_tokens_per_seq(self) -> int:
  265. """The number of new tokens."""
  266. return 1
  267. def add_seq_group(self, seq_group: SequenceGroup) -> None:
  268. # Add sequence groups to the waiting queue.
  269. self.waiting.append(seq_group)
  270. def abort_seq_group(self, request_id: Union[str, Iterable[str]]) -> None:
  271. """Aborts a sequence group with the given ID.
  272. Check if the sequence group with the given ID
  273. is present in any of the state queue.
  274. If present, remove the sequence group from the state queue.
  275. Also, if any of the sequences in the sequence group is not finished,
  276. free the sequence with status `FINISHED_ABORTED`.
  277. Otherwise, do nothing.
  278. Args:
  279. request_id: The ID(s) of the sequence group to abort.
  280. """
  281. if isinstance(request_id, str):
  282. request_id = (request_id, )
  283. request_ids = set(request_id)
  284. for state_queue in [self.waiting, self.running, self.swapped]:
  285. aborted_groups: List[SequenceGroup] = []
  286. for seq_group in state_queue:
  287. if not request_ids:
  288. # Using 'break' here may add two extra iterations,
  289. # but is acceptable to reduce complexity.
  290. break
  291. if seq_group.request_id in request_ids:
  292. # Appending aborted group into pending list.
  293. aborted_groups.append(seq_group)
  294. request_ids.remove(seq_group.request_id)
  295. for aborted_group in aborted_groups:
  296. # Remove the sequence group from the state queue.
  297. state_queue.remove(aborted_group)
  298. for seq in aborted_group.get_seqs():
  299. if seq.is_finished():
  300. continue
  301. seq.status = SequenceStatus.FINISHED_ABORTED
  302. self.free_seq(seq)
  303. def has_unfinished_seqs(self) -> bool:
  304. return len(self.waiting) != 0 or len(self.running) != 0 or len(
  305. self.swapped) != 0
  306. def get_num_unfinished_seq_groups(self) -> int:
  307. return len(self.waiting) + len(self.running) + len(self.swapped)
  308. def _schedule_running(
  309. self,
  310. running_queue: deque,
  311. budget: SchedulingBudget,
  312. curr_loras: Optional[Set[int]],
  313. policy: Policy,
  314. enable_chunking: bool = False,
  315. ) -> Tuple[deque, SchedulerRunningOutputs]:
  316. """Schedule sequence groups that are running.
  317. Running queue should include decode and chunked prefill requests.
  318. Args:
  319. running_queue: The queue that contains running requests (i.e.,
  320. decodes). The given arguments are NOT in-place modified.
  321. budget: The scheduling budget. The argument is in-place updated
  322. when any decodes are preempted.
  323. curr_loras: Currently batched lora request ids. The argument is
  324. in-place updated when any decodes are preempted.
  325. policy: The sorting policy to sort running_queue.
  326. enable_chunking: If True, seq group can be chunked and only a
  327. chunked number of tokens are scheduled if
  328. `budget.num_batched_tokens` has not enough capacity to schedule
  329. all tokens.
  330. Returns:
  331. A tuple of remaining running queue (should be always 0) after
  332. scheduling and SchedulerRunningOutputs.
  333. """
  334. # Blocks that need to be swapped or copied before model execution.
  335. blocks_to_swap_out: List[Tuple[int, int]] = []
  336. blocks_to_copy: List[Tuple[int, int]] = []
  337. decode_seq_groups: List[ScheduledSequenceGroup] = []
  338. prefill_seq_groups: List[ScheduledSequenceGroup] = []
  339. preempted: List[SequenceGroup] = []
  340. swapped_out: List[SequenceGroup] = []
  341. # NOTE(woosuk): Preemption happens only when there is no available slot
  342. # to keep all the sequence groups in the RUNNING state.
  343. # In this case, the policy is responsible for deciding which sequence
  344. # groups to preempt.
  345. now = time.time()
  346. running_queue = policy.sort_by_priority(now, running_queue)
  347. while running_queue:
  348. seq_group = running_queue[0]
  349. num_running_tokens = self._get_num_new_tokens(
  350. seq_group, SequenceStatus.RUNNING, enable_chunking, budget)
  351. if num_running_tokens == 0:
  352. break
  353. running_queue.popleft()
  354. while not self._can_append_slots(seq_group):
  355. budget.subtract_num_batched_tokens(seq_group.request_id,
  356. num_running_tokens)
  357. num_running_seqs = seq_group.get_max_num_running_seqs()
  358. budget.subtract_num_seqs(seq_group.request_id,
  359. num_running_seqs)
  360. if (curr_loras is not None and seq_group.lora_int_id > 0
  361. and seq_group.lora_int_id in curr_loras):
  362. curr_loras.remove(seq_group.lora_int_id)
  363. if running_queue:
  364. # Preempt the lowest-priority sequence groups.
  365. victim_seq_group = running_queue.pop()
  366. preempted_mode = self._preempt(victim_seq_group,
  367. blocks_to_swap_out)
  368. if preempted_mode == PreemptionMode.RECOMPUTE:
  369. preempted.append(victim_seq_group)
  370. else:
  371. swapped_out.append(victim_seq_group)
  372. else:
  373. # No other sequence groups can be preempted.
  374. # Preempt the current sequence group.
  375. preempted_mode = self._preempt(seq_group,
  376. blocks_to_swap_out)
  377. if preempted_mode == PreemptionMode.RECOMPUTE:
  378. preempted.append(seq_group)
  379. else:
  380. swapped_out.append(seq_group)
  381. break
  382. else:
  383. self._append_slots(seq_group, blocks_to_copy)
  384. is_prefill = seq_group.is_prefill()
  385. if is_prefill:
  386. prefill_seq_groups.append(
  387. ScheduledSequenceGroup(
  388. seq_group=seq_group,
  389. token_chunk_size=num_running_tokens))
  390. else:
  391. decode_seq_groups.append(
  392. ScheduledSequenceGroup(seq_group=seq_group,
  393. token_chunk_size=1))
  394. budget.add_num_batched_tokens(seq_group.request_id,
  395. num_running_tokens)
  396. # OPTIMIZATION: Note that get_max_num_running_seqs is
  397. # expensive. For the default scheduling chase where
  398. # enable_chunking is False, num_seqs are updated before running
  399. # this method, so we don't have to update it again here.
  400. if enable_chunking:
  401. num_running_seqs = seq_group.get_max_num_running_seqs()
  402. budget.add_num_seqs(seq_group.request_id, num_running_seqs)
  403. if curr_loras is not None and seq_group.lora_int_id > 0:
  404. curr_loras.add(seq_group.lora_int_id)
  405. return running_queue, SchedulerRunningOutputs(
  406. decode_seq_groups=decode_seq_groups,
  407. prefill_seq_groups=prefill_seq_groups,
  408. preempted=preempted,
  409. swapped_out=swapped_out,
  410. blocks_to_swap_out=blocks_to_swap_out,
  411. blocks_to_copy=blocks_to_copy,
  412. num_lookahead_slots=self._get_num_lookahead_slots(
  413. is_prefill=False))
  414. def _schedule_swapped(
  415. self,
  416. swapped_queue: deque,
  417. budget: SchedulingBudget,
  418. curr_loras: Optional[Set[int]],
  419. policy: Policy,
  420. enable_chunking: bool = False,
  421. ) -> Tuple[deque, SchedulerSwappedInOutputs]:
  422. """Schedule sequence groups that are swapped out.
  423. It schedules swapped requests as long as it fits `budget` and
  424. curr_loras <= max_lora from the scheduling config. The input arguments
  425. `budget` and `curr_loras` are updated based on scheduled seq_groups.
  426. Args:
  427. swapped_queue: The queue that contains swapped out requests.
  428. The given arguments are NOT in-place modified.
  429. budget: The scheduling budget. The argument is in-place updated
  430. when any requests are swapped in.
  431. curr_loras: Currently batched lora request ids. The argument is
  432. in-place updated when any requests are swapped in.
  433. policy: The sorting policy to sort swapped_queue.
  434. enable_chunking: If True, seq group can be chunked and only a
  435. chunked number of tokens are scheduled if
  436. `budget.num_batched_tokens` has not enough capacity to schedule
  437. all tokens.
  438. Returns:
  439. A tuple of remaining swapped_queue after scheduling and
  440. SchedulerSwappedInOutputs.
  441. """
  442. # Blocks that need to be swapped or copied before model execution.
  443. blocks_to_swap_in: List[Tuple[int, int]] = []
  444. blocks_to_copy: List[Tuple[int, int]] = []
  445. decode_seq_groups: List[ScheduledSequenceGroup] = []
  446. prefill_seq_groups: List[ScheduledSequenceGroup] = []
  447. now = time.time()
  448. swapped_queue = policy.sort_by_priority(now, swapped_queue)
  449. infeasible_seq_groups: List[SequenceGroup] = []
  450. leftover_swapped: Deque[SequenceGroup] = deque()
  451. while swapped_queue:
  452. seq_group = swapped_queue[0]
  453. # If the sequence group cannot be swapped in, stop.
  454. is_prefill = seq_group.is_prefill()
  455. alloc_status = self.block_manager.can_swap_in(
  456. seq_group, self._get_num_lookahead_slots(is_prefill))
  457. if alloc_status == AllocStatus.LATER:
  458. break
  459. elif alloc_status == AllocStatus.NEVER:
  460. logger.warning(f"Failing the request {seq_group.request_id} "
  461. "because there's not enough kv cache blocks to "
  462. "run the entire sequence.")
  463. for seq in seq_group.get_seqs():
  464. seq.status = SequenceStatus.FINISHED_IGNORED
  465. infeasible_seq_groups.append(seq_group)
  466. swapped_queue.popleft()
  467. continue
  468. lora_int_id = 0
  469. if self.lora_enabled:
  470. lora_int_id = seq_group.lora_int_id
  471. assert curr_loras is not None
  472. assert self.lora_config is not None
  473. if (lora_int_id > 0 and (lora_int_id not in curr_loras)
  474. and len(curr_loras) >= self.lora_config.max_loras):
  475. # We don't have a space for another LoRA, so
  476. # we ignore this request for now.
  477. leftover_swapped.appendleft(seq_group)
  478. swapped_queue.popleft()
  479. continue
  480. # The total number of sequences in the RUNNING state should not
  481. # exceed the maximum number of sequences.
  482. num_new_seqs = seq_group.get_max_num_running_seqs()
  483. num_new_tokens = self._get_num_new_tokens(seq_group,
  484. SequenceStatus.SWAPPED,
  485. enable_chunking, budget)
  486. if (num_new_tokens == 0
  487. or not budget.can_schedule(num_new_tokens=num_new_tokens,
  488. num_new_seqs=num_new_seqs)):
  489. break
  490. if lora_int_id > 0 and curr_loras is not None:
  491. curr_loras.add(lora_int_id)
  492. swapped_queue.popleft()
  493. self._swap_in(seq_group, blocks_to_swap_in)
  494. self._append_slots(seq_group, blocks_to_copy)
  495. is_prefill = seq_group.is_prefill()
  496. if is_prefill:
  497. prefill_seq_groups.append(
  498. ScheduledSequenceGroup(seq_group,
  499. token_chunk_size=num_new_tokens))
  500. else:
  501. decode_seq_groups.append(
  502. ScheduledSequenceGroup(seq_group, token_chunk_size=1))
  503. budget.add_num_batched_tokens(seq_group.request_id, num_new_tokens)
  504. budget.add_num_seqs(seq_group.request_id, num_new_seqs)
  505. swapped_queue.extendleft(leftover_swapped)
  506. return swapped_queue, SchedulerSwappedInOutputs(
  507. decode_seq_groups=decode_seq_groups,
  508. prefill_seq_groups=prefill_seq_groups,
  509. blocks_to_swap_in=blocks_to_swap_in,
  510. blocks_to_copy=blocks_to_copy,
  511. num_lookahead_slots=self._get_num_lookahead_slots(
  512. is_prefill=False),
  513. infeasible_seq_groups=infeasible_seq_groups,
  514. )
  515. def _get_prompt_limit(self, seq_group: SequenceGroup) -> int:
  516. if self.scheduler_config.chunked_prefill_enabled:
  517. prompt_limit = self.scheduler_config.max_model_len
  518. else:
  519. prompt_limit = min(self.scheduler_config.max_model_len,
  520. self.scheduler_config.max_num_batched_tokens)
  521. # Model is fine tuned with long context. Return the fine tuned max_len.
  522. if (seq_group.lora_request
  523. and seq_group.lora_request.long_lora_max_len):
  524. assert prompt_limit <= seq_group.lora_request.long_lora_max_len
  525. return seq_group.lora_request.long_lora_max_len
  526. else:
  527. return prompt_limit
  528. def _schedule_prefills(
  529. self,
  530. waiting_queue: deque,
  531. budget: SchedulingBudget,
  532. curr_loras: Optional[Set[int]],
  533. enable_chunking: bool = False,
  534. ) -> Tuple[deque, SchedulerPrefillOutputs]:
  535. """Schedule sequence groups that are in prefill stage.
  536. Note that the current scheduler treats PREEMPTED_FOR_RECOMPUTE
  537. as a new prefill (that starts from beginning -> most recently generated
  538. tokens).
  539. It schedules waiting requests as long as it fits `budget` and
  540. curr_loras <= max_lora from the scheduling config. The input arguments
  541. `budget` and `curr_loras` are updated based on scheduled seq_groups.
  542. Args:
  543. waiting_queue: The queue that contains prefill requests.
  544. The given arguments are NOT in-place modified.
  545. budget: The scheduling budget. The argument is in-place updated
  546. when any requests are scheduled.
  547. curr_loras: Currently batched lora request ids. The argument is
  548. in-place updated when any requests are scheduled.
  549. enable_chunking: If True, seq group can be chunked and only a
  550. chunked number of tokens are scheduled if
  551. `budget.num_batched_tokens` has not enough capacity to schedule
  552. all tokens.
  553. Returns:
  554. A tuple of remaining waiting_queue after scheduling and
  555. SchedulerSwappedInOutputs.
  556. """
  557. ignored_seq_groups: List[SequenceGroup] = []
  558. seq_groups: List[SequenceGroup] = []
  559. # We don't sort waiting queue because we assume it is sorted.
  560. # Copy the queue so that the input queue is not modified.
  561. waiting_queue = deque([s for s in waiting_queue])
  562. leftover_waiting_sequences: Deque[SequenceGroup] = deque()
  563. while self._passed_delay(time.time()) and waiting_queue:
  564. seq_group = waiting_queue[0]
  565. waiting_seqs = seq_group.get_seqs(status=SequenceStatus.WAITING)
  566. assert len(waiting_seqs) == 1, (
  567. "Waiting sequence group should have only one prompt "
  568. "sequence.")
  569. num_new_tokens = self._get_num_new_tokens(seq_group,
  570. SequenceStatus.WAITING,
  571. enable_chunking, budget)
  572. if not enable_chunking:
  573. num_prompt_tokens = waiting_seqs[0].get_len()
  574. assert num_new_tokens == num_prompt_tokens
  575. prompt_limit = self._get_prompt_limit(seq_group)
  576. if num_new_tokens > prompt_limit:
  577. logger.warning(
  578. f"Input prompt ({num_new_tokens}) tokens) is too long"
  579. f" and exceeds limit of {prompt_limit}")
  580. for seq in waiting_seqs:
  581. seq.status = SequenceStatus.FINISHED_IGNORED
  582. ignored_seq_groups.append(seq_group)
  583. waiting_queue.popleft()
  584. continue
  585. # If the sequence group cannot be allocated, stop.
  586. can_allocate = self.block_manager.can_allocate(seq_group)
  587. if can_allocate == AllocStatus.LATER:
  588. break
  589. elif can_allocate == AllocStatus.NEVER:
  590. logger.warning(
  591. f"Input prompt ({num_new_tokens} tokens) is too long"
  592. f" and exceeds the capacity of block_manager")
  593. for seq in waiting_seqs:
  594. seq.status = SequenceStatus.FINISHED_IGNORED
  595. ignored_seq_groups.append(seq_group)
  596. waiting_queue.popleft()
  597. continue
  598. lora_int_id = 0
  599. if self.lora_enabled:
  600. lora_int_id = seq_group.lora_int_id
  601. assert curr_loras is not None
  602. assert self.lora_config is not None
  603. if (self.lora_enabled and lora_int_id > 0
  604. and lora_int_id not in curr_loras
  605. and len(curr_loras) >= self.lora_config.max_loras):
  606. # We don't have a space for another LoRA, so
  607. # we ignore this request for now.
  608. leftover_waiting_sequences.appendleft(seq_group)
  609. waiting_queue.popleft()
  610. continue
  611. num_new_seqs = seq_group.get_max_num_running_seqs()
  612. if (num_new_tokens == 0
  613. or not budget.can_schedule(num_new_tokens=num_new_tokens,
  614. num_new_seqs=num_new_seqs)):
  615. break
  616. # Can schedule this request.
  617. if curr_loras is not None and lora_int_id > 0:
  618. curr_loras.add(lora_int_id)
  619. waiting_queue.popleft()
  620. self._allocate_and_set_running(seq_group)
  621. seq_groups.append(
  622. ScheduledSequenceGroup(seq_group=seq_group,
  623. token_chunk_size=num_new_tokens))
  624. budget.add_num_batched_tokens(seq_group.request_id, num_new_tokens)
  625. budget.add_num_seqs(seq_group.request_id, num_new_seqs)
  626. # Queue requests that couldn't be scheduled.
  627. waiting_queue.extendleft(leftover_waiting_sequences)
  628. if len(seq_groups) > 0:
  629. self.prev_prompt = True
  630. return waiting_queue, SchedulerPrefillOutputs(
  631. seq_groups=seq_groups,
  632. ignored_seq_groups=ignored_seq_groups,
  633. num_lookahead_slots=self._get_num_lookahead_slots(is_prefill=True))
  634. def _schedule_default(self) -> SchedulerOutputs:
  635. """Schedule queued requests.
  636. The current policy is designed to optimize the throughput. First,
  637. it batches as many prefill requests as possible. And it schedules
  638. decodes. If there's a pressure on GPU memory, decode requests can
  639. be swapped or preempted.
  640. """
  641. # Include running requests to the budget.
  642. budget = SchedulingBudget(
  643. token_budget=self.scheduler_config.max_num_batched_tokens,
  644. max_num_seqs=self.scheduler_config.max_num_seqs,
  645. )
  646. # Make sure we include num running seqs before scheduling prefill,
  647. # so that we don't schedule beyond max_num_seqs for prefill.
  648. for seq_group in self.running:
  649. budget.add_num_seqs(seq_group.request_id,
  650. seq_group.get_max_num_running_seqs())
  651. curr_loras = set(
  652. seq_group.lora_int_id for seq_group in self.running
  653. if seq_group.lora_int_id > 0) if self.lora_enabled else None
  654. remaining_waiting, prefills = (self.waiting,
  655. SchedulerPrefillOutputs.create_empty())
  656. remaining_running, running_scheduled = (
  657. self.running, SchedulerRunningOutputs.create_empty())
  658. remaining_swapped, swapped_in = (
  659. self.swapped, SchedulerSwappedInOutputs.create_empty())
  660. # If any requests are swapped, prioritized swapped requests.
  661. if not self.swapped:
  662. remaining_waiting, prefills = self._schedule_prefills(
  663. self.waiting, budget, curr_loras, enable_chunking=False)
  664. fcfs_policy = PolicyFactory.get_policy(policy_name="fcfs")
  665. # Don't schedule decodes if prefills are scheduled.
  666. # NOTE: If `_schedule_prefills` doesn't enable chunking, self.running
  667. # only contains decode requests, not chunked prefills.
  668. if len(prefills.seq_groups) == 0:
  669. remaining_running, running_scheduled = self._schedule_running(
  670. self.running,
  671. budget,
  672. curr_loras,
  673. fcfs_policy,
  674. enable_chunking=False)
  675. # If any sequence group is preempted, do not swap in any sequence
  676. # group. because it means there's no slot for new running requests.
  677. if len(running_scheduled.preempted) + len(
  678. running_scheduled.swapped_out) == 0:
  679. remaining_swapped, swapped_in = self._schedule_swapped(
  680. self.swapped, budget, curr_loras, fcfs_policy)
  681. assert (budget.num_batched_tokens <=
  682. self.scheduler_config.max_num_batched_tokens)
  683. assert budget.num_curr_seqs <= self.scheduler_config.max_num_seqs
  684. # Update waiting requests.
  685. self.waiting = remaining_waiting
  686. self.waiting.extendleft(running_scheduled.preempted)
  687. # Update new running requests.
  688. self.running = remaining_running
  689. self.running.extend([s.seq_group for s in prefills.seq_groups])
  690. self.running.extend(
  691. [s.seq_group for s in running_scheduled.decode_seq_groups])
  692. self.running.extend(
  693. [s.seq_group for s in swapped_in.decode_seq_groups])
  694. # Update swapped requests.
  695. # Update swapped requests.
  696. self.swapped = remaining_swapped
  697. self.swapped.extend(running_scheduled.swapped_out)
  698. preempted = (len(running_scheduled.preempted) +
  699. len(running_scheduled.swapped_out))
  700. # There should be no prefill from running queue because this policy
  701. # doesn't allow chunked prefills.
  702. assert len(running_scheduled.prefill_seq_groups) == 0
  703. assert len(swapped_in.prefill_seq_groups) == 0
  704. return SchedulerOutputs(
  705. scheduled_seq_groups=(prefills.seq_groups +
  706. running_scheduled.decode_seq_groups +
  707. swapped_in.decode_seq_groups),
  708. num_prefill_groups=len(prefills.seq_groups),
  709. num_batched_tokens=budget.num_batched_tokens,
  710. blocks_to_swap_in=swapped_in.blocks_to_swap_in,
  711. blocks_to_swap_out=running_scheduled.blocks_to_swap_out,
  712. blocks_to_copy=running_scheduled.blocks_to_copy +
  713. swapped_in.blocks_to_copy,
  714. ignored_seq_groups=prefills.ignored_seq_groups +
  715. swapped_in.infeasible_seq_groups,
  716. num_lookahead_slots=running_scheduled.num_lookahead_slots,
  717. running_queue_size=len(self.running),
  718. preempted=preempted,
  719. )
  720. def _schedule_chunked_prefill(self):
  721. """Schedule queued requests.
  722. Chunked prefill allows to chunk prefill requests, batch them together
  723. with decode requests. This policy 1. schedule as many decoding requests
  724. as possible. 2. schedule chunked prefill requests that are not
  725. finished. 3. schedule swapped request. 4. schedule new prefill
  726. requests.
  727. The policy can sustain the high GPU utilization because it can put
  728. prefill and decodes requests to the same batch, while it improves
  729. inter token latency because decodes requests don't need to blocked
  730. by prefill requests.
  731. """
  732. budget = SchedulingBudget(
  733. token_budget=self.scheduler_config.max_num_batched_tokens,
  734. max_num_seqs=self.scheduler_config.max_num_seqs,
  735. )
  736. curr_loras: Set[int] = set()
  737. remaining_waiting, prefills = (self.waiting,
  738. SchedulerPrefillOutputs.create_empty())
  739. remaining_running, running_scheduled = (
  740. self.running, SchedulerRunningOutputs.create_empty())
  741. remaining_swapped, swapped_in = (
  742. self.swapped, SchedulerSwappedInOutputs.create_empty())
  743. # Decoding should be always scheduled first by fcfs.
  744. fcfs_policy = PolicyFactory.get_policy(policy_name="fcfs")
  745. remaining_running, running_scheduled = self._schedule_running(
  746. self.running,
  747. budget,
  748. curr_loras,
  749. fcfs_policy,
  750. enable_chunking=True)
  751. # Schedule swapped out requests.
  752. # If preemption happens, it means we don't have space for swap-in.
  753. if len(running_scheduled.preempted) + len(
  754. running_scheduled.swapped_out) == 0:
  755. remaining_swapped, swapped_in = self._schedule_swapped(
  756. self.swapped, budget, curr_loras, fcfs_policy)
  757. # Schedule new prefills.
  758. remaining_waiting, prefills = self._schedule_prefills(
  759. self.waiting, budget, curr_loras, enable_chunking=True)
  760. assert (budget.num_batched_tokens <=
  761. self.scheduler_config.max_num_batched_tokens)
  762. assert budget.num_curr_seqs <= self.scheduler_config.max_num_seqs
  763. # Update waiting requests.
  764. self.waiting = remaining_waiting
  765. self.waiting.extendleft(running_scheduled.preempted)
  766. # Update new running requests.
  767. self.running = remaining_running
  768. self.running.extend([s.seq_group for s in prefills.seq_groups])
  769. self.running.extend(
  770. [s.seq_group for s in running_scheduled.decode_seq_groups])
  771. self.running.extend(
  772. [s.seq_group for s in running_scheduled.prefill_seq_groups])
  773. self.running.extend(
  774. [s.seq_group for s in swapped_in.decode_seq_groups])
  775. self.running.extend(
  776. [s.seq_group for s in swapped_in.prefill_seq_groups])
  777. # Update swapped requests.
  778. self.swapped = remaining_swapped
  779. self.swapped.extend(running_scheduled.swapped_out)
  780. return SchedulerOutputs(
  781. scheduled_seq_groups=(prefills.seq_groups +
  782. running_scheduled.prefill_seq_groups +
  783. swapped_in.prefill_seq_groups +
  784. running_scheduled.decode_seq_groups +
  785. swapped_in.decode_seq_groups),
  786. num_prefill_groups=(len(prefills.seq_groups) +
  787. len(swapped_in.prefill_seq_groups) +
  788. len(running_scheduled.prefill_seq_groups)),
  789. num_batched_tokens=budget.num_batched_tokens,
  790. blocks_to_swap_in=swapped_in.blocks_to_swap_in,
  791. blocks_to_swap_out=running_scheduled.blocks_to_swap_out,
  792. blocks_to_copy=running_scheduled.blocks_to_copy +
  793. swapped_in.blocks_to_copy,
  794. ignored_seq_groups=prefills.ignored_seq_groups +
  795. swapped_in.infeasible_seq_groups,
  796. num_lookahead_slots=running_scheduled.num_lookahead_slots,
  797. running_queue_size=len(self.running),
  798. preempted=(len(running_scheduled.preempted) +
  799. len(running_scheduled.swapped_out)),
  800. )
  801. def _schedule(self) -> SchedulerOutputs:
  802. """Schedule queued requests."""
  803. if self.scheduler_config.chunked_prefill_enabled:
  804. return self._schedule_chunked_prefill()
  805. else:
  806. return self._schedule_default()
  807. def _can_append_slots(self, seq_group: SequenceGroup) -> bool:
  808. """Determine whether or not we have enough space in the KV cache to
  809. continue generation of the sequence group.
  810. """
  811. # It is True only for testing case to trigger artificial preemption.
  812. if (self.enable_artificial_preemption
  813. and random.uniform(0, 1) < ARTIFICIAL_PREEMPTION_PROB
  814. and self.artificial_preempt_cnt > 0):
  815. self.artificial_preempt_cnt -= 1
  816. return False
  817. # Appending slots only occurs in decoding.
  818. is_prefill = False
  819. return self.block_manager.can_append_slots(
  820. seq_group=seq_group,
  821. num_lookahead_slots=self._get_num_lookahead_slots(is_prefill),
  822. )
  823. def schedule(self) -> Tuple[List[SequenceGroupMetadata], SchedulerOutputs]:
  824. # Schedule sequence groups.
  825. # This function call changes the internal states of the scheduler
  826. # such as self.running, self.swapped, and self.waiting.
  827. scheduler_outputs = self._schedule()
  828. now = time.time()
  829. # Create input data structures.
  830. seq_group_metadata_list: List[SequenceGroupMetadata] = []
  831. for i, scheduled_seq_group in enumerate(
  832. scheduler_outputs.scheduled_seq_groups):
  833. seq_group = scheduled_seq_group.seq_group
  834. token_chunk_size = scheduled_seq_group.token_chunk_size
  835. seq_group.maybe_set_first_scheduled_time(now)
  836. # seq_id -> SequenceData
  837. seq_data: Dict[int, SequenceData] = {}
  838. # seq_id -> physical block numbers
  839. block_tables: Dict[int, List[int]] = {}
  840. for seq in seq_group.get_seqs(status=SequenceStatus.RUNNING):
  841. seq_id = seq.seq_id
  842. seq_data[seq_id] = seq.data
  843. block_tables[seq_id] = self.block_manager.get_block_table(seq)
  844. self.block_manager.access_all_blocks_in_seq(seq, now)
  845. common_computed_block_nums = (
  846. self.block_manager.get_common_computed_block_ids(
  847. seq_group.get_seqs(status=SequenceStatus.RUNNING)))
  848. do_sample = True
  849. if seq_group.is_prefill():
  850. seqs = seq_group.get_seqs()
  851. # Prefill has only 1 sequence.
  852. assert len(seqs) == 1
  853. # In the next iteration, all prompt tokens are not computed.
  854. # It means the prefill is chunked, and we don't need sampling.
  855. # NOTE: We use get_len instead of get_prompt_len because when
  856. # a sequence is preempted, prefill includes previous generated
  857. # output tokens.
  858. if (token_chunk_size + seqs[0].data.get_num_computed_tokens() <
  859. seqs[0].data.get_len()):
  860. do_sample = False
  861. # It assumes the scheduled_seq_groups is ordered by
  862. # prefill < decoding.
  863. is_prompt = seq_group.is_prefill()
  864. seq_group_metadata = SequenceGroupMetadata(
  865. request_id=seq_group.request_id,
  866. is_prompt=is_prompt,
  867. seq_data=seq_data,
  868. sampling_params=seq_group.sampling_params,
  869. block_tables=block_tables,
  870. do_sample=do_sample,
  871. pooling_params=seq_group.pooling_params,
  872. token_chunk_size=token_chunk_size,
  873. lora_request=seq_group.lora_request,
  874. computed_block_nums=common_computed_block_nums,
  875. state=seq_group.state,
  876. # `multi_modal_data` will only be present for the 1st comm
  877. # between engine and worker.
  878. # the subsequent comms can still use delta, but
  879. # `multi_modal_data` will be None.
  880. multi_modal_data=seq_group.multi_modal_data
  881. if scheduler_outputs.num_prefill_groups > 0 else None,
  882. )
  883. seq_group_metadata_list.append(seq_group_metadata)
  884. # Now that the batch has been created, we can assume all blocks in the
  885. # batch will have been computed before the next scheduling invocation.
  886. # This is because the engine assumes that a failure in model execution
  887. # will crash the Aphrodite instance / will not retry.
  888. for scheduled_seq_group in scheduler_outputs.scheduled_seq_groups:
  889. self.block_manager.mark_blocks_as_computed(
  890. scheduled_seq_group.seq_group)
  891. return seq_group_metadata_list, scheduler_outputs
  892. def fork_seq(self, parent_seq: Sequence, child_seq: Sequence) -> None:
  893. self.block_manager.fork(parent_seq, child_seq)
  894. def free_seq(self, seq: Sequence) -> None:
  895. """Free a sequence from a block table."""
  896. self.block_manager.free(seq)
  897. def free_finished_seq_groups(self) -> None:
  898. self.running = deque(seq_group for seq_group in self.running
  899. if not seq_group.is_finished())
  900. def _allocate_and_set_running(self, seq_group: SequenceGroup) -> None:
  901. self.block_manager.allocate(seq_group)
  902. for seq in seq_group.get_seqs(status=SequenceStatus.WAITING):
  903. seq.status = SequenceStatus.RUNNING
  904. def _append_slots(
  905. self,
  906. seq_group: SequenceGroup,
  907. blocks_to_copy: List[Tuple[int, int]],
  908. ) -> None:
  909. """Appends new slots to the sequences in the given sequence group.
  910. Args:
  911. seq_group (SequenceGroup): The sequence group containing the
  912. sequences to append slots to.
  913. blocks_to_copy (List[Tuple[int, int]]): A list of tuple of two
  914. ints, the first int is the source block index, and the second
  915. int is the destination block index. This list is updated with
  916. the new source and destination block indices for the appended
  917. slots.
  918. """
  919. num_lookahead_slots = self._get_num_lookahead_slots(is_prefill=False)
  920. for seq in seq_group.get_seqs(status=SequenceStatus.RUNNING):
  921. cows = self.block_manager.append_slots(seq, num_lookahead_slots)
  922. blocks_to_copy.extend(cows)
  923. def _preempt(
  924. self,
  925. seq_group: SequenceGroup,
  926. blocks_to_swap_out: List[Tuple[int, int]],
  927. preemption_mode: Optional[PreemptionMode] = None,
  928. ) -> PreemptionMode:
  929. # If preemption mode is not specified, we determine the mode as follows:
  930. # We use recomputation by default since it incurs lower overhead than
  931. # swapping. However, when the sequence group has multiple sequences
  932. # (e.g., beam search), recomputation is not currently supported. In
  933. # such a case, we use swapping instead.
  934. # FIXME: This makes our scheduling policy a bit bizarre.
  935. # As swapped sequences are prioritized over waiting sequences,
  936. # sequence groups with multiple sequences are implicitly prioritized
  937. # over sequence groups with a single sequence.
  938. # TODO: Support recomputation for sequence groups with multiple
  939. # sequences. This may require a more sophisticated CUDA kernel.
  940. if self.user_specified_preemption_mode is None:
  941. if seq_group.get_max_num_running_seqs() == 1:
  942. preemption_mode = PreemptionMode.RECOMPUTE
  943. else:
  944. preemption_mode = PreemptionMode.SWAP
  945. elif self.user_specified_preemption_mode == "swap":
  946. preemption_mode = PreemptionMode.SWAP
  947. else:
  948. preemption_mode = PreemptionMode.RECOMPUTE
  949. if self.num_cumulative_preemption % 50 == 0:
  950. logger.warning(
  951. f"Sequence group {seq_group.request_id} is preempted by "
  952. f"{preemption_mode} mode because there is "
  953. "not enough KV cache space. This can affect the end-to-end "
  954. "performance. Increase gpu_memory_utilization or "
  955. "tensor_parallel_size to provide more KV cache memory. "
  956. "total_num_cumulative_preemption="
  957. f"{self.num_cumulative_preemption + 1}")
  958. self.num_cumulative_preemption += 1
  959. if preemption_mode == PreemptionMode.RECOMPUTE:
  960. self._preempt_by_recompute(seq_group)
  961. elif preemption_mode == PreemptionMode.SWAP:
  962. self._preempt_by_swap(seq_group, blocks_to_swap_out)
  963. else:
  964. raise AssertionError("Invalid preemption mode.")
  965. return preemption_mode
  966. def _preempt_by_recompute(
  967. self,
  968. seq_group: SequenceGroup,
  969. ) -> None:
  970. seqs = seq_group.get_seqs(status=SequenceStatus.RUNNING)
  971. assert len(seqs) == 1
  972. for seq in seqs:
  973. seq.status = SequenceStatus.WAITING
  974. self.free_seq(seq)
  975. seq.reset_state_for_recompute()
  976. def _preempt_by_swap(
  977. self,
  978. seq_group: SequenceGroup,
  979. blocks_to_swap_out: List[Tuple[int, int]],
  980. ) -> None:
  981. self._swap_out(seq_group, blocks_to_swap_out)
  982. def _swap_in(
  983. self,
  984. seq_group: SequenceGroup,
  985. blocks_to_swap_in: List[Tuple[int, int]],
  986. ) -> None:
  987. mapping = self.block_manager.swap_in(seq_group)
  988. blocks_to_swap_in.extend(mapping)
  989. for seq in seq_group.get_seqs(status=SequenceStatus.SWAPPED):
  990. seq.status = SequenceStatus.RUNNING
  991. def _swap_out(
  992. self,
  993. seq_group: SequenceGroup,
  994. blocks_to_swap_out: List[Tuple[int, int]],
  995. ) -> None:
  996. if not self.block_manager.can_swap_out(seq_group):
  997. # FIXME: Abort the sequence group instead of aborting the
  998. # entire engine.
  999. raise RuntimeError(
  1000. "Aborted due to the lack of CPU swap space. Please increase "
  1001. "the swap space to avoid this error.")
  1002. mapping = self.block_manager.swap_out(seq_group)
  1003. blocks_to_swap_out.extend(mapping)
  1004. for seq in seq_group.get_seqs(status=SequenceStatus.RUNNING):
  1005. seq.status = SequenceStatus.SWAPPED
  1006. def _passed_delay(self, now: float) -> bool:
  1007. if self.prev_prompt:
  1008. self.last_prompt_latency = now - self.prev_time
  1009. self.prev_time, self.prev_prompt = now, False
  1010. # Delay scheduling prompts to let waiting queue fill up
  1011. if self.scheduler_config.delay_factor > 0 and self.waiting:
  1012. earliest_arrival_time = min(
  1013. [e.metrics.arrival_time for e in self.waiting])
  1014. passed_delay = (
  1015. (now - earliest_arrival_time) >
  1016. (self.scheduler_config.delay_factor * self.last_prompt_latency)
  1017. or not self.running)
  1018. else:
  1019. passed_delay = True
  1020. return passed_delay
  1021. def _get_num_lookahead_slots(self, is_prefill: bool) -> int:
  1022. """The number of slots to allocate per sequence per step, beyond known
  1023. token ids. Speculative decoding uses these slots to store KV activations
  1024. of tokens which may or may not be accepted.
  1025. Speculative decoding does not yet support prefill, so we do not perform
  1026. lookahead allocation for prefill.
  1027. """
  1028. if is_prefill:
  1029. return 0
  1030. return self.scheduler_config.num_lookahead_slots
  1031. def _get_num_new_tokens(self, seq_group: SequenceGroup,
  1032. status: SequenceStatus, enable_chunking: bool,
  1033. budget: SchedulingBudget) -> int:
  1034. """Get the next new tokens to compute for a given sequence group
  1035. that's in a given `status`.
  1036. The API could chunk the number of tokens to compute based on `budget`
  1037. if `enable_chunking` is True. If a sequence group has multiple
  1038. sequences (e.g., running beam search), it means it is in decoding
  1039. phase, so chunking doesn't happen.
  1040. Returns 0 if the new token cannot be computed due to token budget.
  1041. """
  1042. num_new_tokens = 0
  1043. seqs = seq_group.get_seqs(status=status)
  1044. for seq in seqs:
  1045. num_new_tokens += seq.get_num_new_tokens()
  1046. assert num_new_tokens > 0
  1047. # Chunk if a running request cannot fit in.
  1048. # If number of seq > 1, it means it is doing beam search in a
  1049. # decode phase. Do not chunk in that case.
  1050. if enable_chunking and len(seqs) == 1:
  1051. num_new_tokens = min(num_new_tokens,
  1052. budget.remaining_token_budget())
  1053. return num_new_tokens