scheduler.py 51 KB

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