scheduler.py 53 KB

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