scheduler.py 56 KB

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