async_aphrodite.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  1. import asyncio
  2. import os
  3. import time
  4. from dataclasses import dataclass
  5. from functools import partial
  6. from typing import (Any, AsyncGenerator, Callable, Dict, Iterable, List,
  7. Optional, Set, Tuple, Type, Union)
  8. import torch
  9. from loguru import logger
  10. from transformers import PreTrainedTokenizer
  11. from typing_extensions import assert_never
  12. from aphrodite.common.config import (DecodingConfig, EngineConfig, LoRAConfig,
  13. ModelConfig, ParallelConfig,
  14. SchedulerConfig)
  15. from aphrodite.common.outputs import EmbeddingRequestOutput, RequestOutput
  16. from aphrodite.common.pooling_params import PoolingParams
  17. from aphrodite.common.sampling_params import SamplingParams
  18. from aphrodite.common.sequence import (ExecuteModelRequest, SamplerOutput,
  19. SequenceGroupMetadata)
  20. from aphrodite.engine.aphrodite_engine import (AphroditeEngine,
  21. DecoderPromptComponents,
  22. PromptComponents)
  23. from aphrodite.engine.args_tools import AsyncEngineArgs
  24. from aphrodite.engine.async_timeout import asyncio_timeout
  25. from aphrodite.engine.metrics_types import StatLoggerBase
  26. from aphrodite.executor.executor_base import ExecutorAsyncBase
  27. from aphrodite.executor.ray_utils import initialize_ray_cluster, ray
  28. from aphrodite.inputs import (EncoderDecoderLLMInputs, LLMInputs, PromptInputs,
  29. SingletonPromptInputs)
  30. from aphrodite.inputs.parse import is_explicit_encoder_decoder_prompt
  31. from aphrodite.lora.request import LoRARequest
  32. from aphrodite.processing.scheduler import SchedulerOutputs
  33. from aphrodite.prompt_adapter.request import PromptAdapterRequest
  34. ENGINE_ITERATION_TIMEOUT_S = int(
  35. os.environ.get("APHRODITE_ENGINE_ITERATION_TIMEOUT_S", "60"))
  36. class AsyncEngineDeadError(RuntimeError):
  37. pass
  38. def _log_task_completion(task: asyncio.Task,
  39. error_callback: Callable[[Exception], None]) -> None:
  40. """This function is only intended for the `engine.run_engine_loop()` task.
  41. In particular, that task runs a `while True` loop that can only exit if
  42. there is an exception.
  43. """
  44. exception = None
  45. try:
  46. return_value = task.result()
  47. raise AssertionError(
  48. f"The engine background task should never finish without an "
  49. f"exception. {return_value}")
  50. except asyncio.exceptions.CancelledError:
  51. # We assume that if the task is cancelled, we are gracefully shutting
  52. # down. This should only happen on program exit.
  53. logger.info("Engine is gracefully shutting down.")
  54. except Exception as e:
  55. exception = e
  56. logger.error("Engine background task failed", exc_info=e)
  57. error_callback(exception)
  58. raise AsyncEngineDeadError(
  59. "Task finished unexpectedly. This should never happen! "
  60. "Please open an issue on Github. See stack trace above for the "
  61. "actual cause.") from e
  62. STOP_ITERATION = Exception() # Sentinel
  63. class AsyncStream:
  64. """A stream of RequestOutputs or EmbeddingRequestOutputs for a request
  65. that can be iterated over asynchronously via an async generator."""
  66. def __init__(self, request_id: str, cancel: Callable[[str], None]) -> None:
  67. self.request_id = request_id
  68. self._cancel = cancel
  69. self._queue: asyncio.Queue = asyncio.Queue()
  70. self._finished = False
  71. def put(self, item: Union[RequestOutput, EmbeddingRequestOutput,
  72. Exception]) -> None:
  73. if not self._finished:
  74. self._queue.put_nowait(item)
  75. def finish(
  76. self,
  77. exception: Optional[Union[BaseException, Type[BaseException]]] = None,
  78. ) -> None:
  79. if not self._finished:
  80. self._finished = True
  81. self._queue.put_nowait(
  82. exception if self._is_raisable(exception) else STOP_ITERATION)
  83. @property
  84. def finished(self) -> bool:
  85. return self._finished
  86. async def generator(
  87. self
  88. ) -> AsyncGenerator[Union[RequestOutput, EmbeddingRequestOutput], None]:
  89. try:
  90. while True:
  91. result = await self._queue.get()
  92. if self._is_raisable(result):
  93. if result == STOP_ITERATION:
  94. return
  95. raise result
  96. yield result
  97. except GeneratorExit:
  98. self._cancel(self.request_id)
  99. raise asyncio.CancelledError from None
  100. @staticmethod
  101. def _is_raisable(value: Any):
  102. return isinstance(value, BaseException) or \
  103. (isinstance(value, type) and \
  104. issubclass(value, BaseException))
  105. class RequestTracker:
  106. """Synchronous abstraction for tracking requests."""
  107. def __init__(self) -> None:
  108. self._request_streams: Dict[str, AsyncStream] = {}
  109. self._aborted_requests: asyncio.Queue[str] = asyncio.Queue()
  110. self._new_requests: asyncio.Queue[Tuple[AsyncStream,
  111. dict]] = asyncio.Queue()
  112. self.new_requests_event = asyncio.Event()
  113. def __contains__(self, item):
  114. return item in self._request_streams
  115. def __len__(self) -> int:
  116. return len(self._request_streams)
  117. def propagate_exception(self,
  118. exc: Exception,
  119. request_id: Optional[str] = None) -> None:
  120. """Propagate an exception to request streams
  121. (all if request_id is None)."""
  122. if request_id is not None:
  123. self.abort_request(request_id, exception=exc)
  124. else:
  125. # NB: tuple() used here because self.abort_request pops the stream
  126. # out of self._request_streams, so we can't iterate on it directly
  127. for rid in tuple(self._request_streams.keys()):
  128. self.abort_request(rid, exception=exc)
  129. def process_request_output(self,
  130. request_output: Union[RequestOutput,
  131. EmbeddingRequestOutput],
  132. *,
  133. verbose: bool = False) -> None:
  134. """Process a request output from the engine."""
  135. request_id = request_output.request_id
  136. finished = request_output.finished
  137. if finished:
  138. stream = self._request_streams.pop(request_id, None)
  139. else:
  140. stream = self._request_streams.get(request_id)
  141. # Guard against a KeyError which can occur if the request was aborted
  142. # while the output was generated
  143. if stream is not None:
  144. stream.put(request_output)
  145. if finished:
  146. stream.finish()
  147. if verbose and finished:
  148. logger.info(f"Finished request {request_id}.")
  149. def process_exception(self,
  150. request_id: str,
  151. exception: BaseException,
  152. *,
  153. verbose: bool = False) -> None:
  154. """Propagate an exception from the engine."""
  155. if verbose:
  156. logger.info(f"Finished request {request_id}.")
  157. self.abort_request(request_id, exception=exception)
  158. def add_request(self,
  159. request_id: str,
  160. *,
  161. verbose: bool = False,
  162. **engine_add_request_kwargs) -> AsyncStream:
  163. """Add a request to be sent to the engine on the next background
  164. loop iteration."""
  165. if request_id in self._request_streams:
  166. raise KeyError(f"Request {request_id} already exists.")
  167. abort_request = partial(self.abort_request, verbose=verbose)
  168. stream = AsyncStream(request_id, abort_request)
  169. self._new_requests.put_nowait((stream, {
  170. "request_id": request_id,
  171. **engine_add_request_kwargs
  172. }))
  173. self.new_requests_event.set()
  174. if verbose:
  175. logger.info(f"Added request {request_id}.")
  176. return stream
  177. def abort_request(self,
  178. request_id: str,
  179. *,
  180. exception: Optional[Union[BaseException,
  181. Type[BaseException]]] = None,
  182. verbose: bool = False) -> None:
  183. """Abort a request during next background loop iteration."""
  184. if verbose:
  185. logger.info(f"Aborted request {request_id}.")
  186. self._aborted_requests.put_nowait(request_id)
  187. stream = self._request_streams.pop(request_id, None)
  188. if stream is not None:
  189. stream.finish(exception=exception)
  190. def get_new_and_aborted_requests(self) -> Tuple[List[Dict], Set[str]]:
  191. """Get the new requests and finished requests to be
  192. sent to the engine."""
  193. new_requests: List[Dict] = []
  194. finished_requests: Set[str] = set()
  195. while not self._aborted_requests.empty():
  196. request_id = self._aborted_requests.get_nowait()
  197. finished_requests.add(request_id)
  198. while not self._new_requests.empty():
  199. stream, new_request = self._new_requests.get_nowait()
  200. request_id = stream.request_id
  201. if request_id in finished_requests:
  202. # The request has already been aborted.
  203. stream.finish(asyncio.CancelledError)
  204. finished_requests.discard(request_id)
  205. else:
  206. self._request_streams[request_id] = stream
  207. new_requests.append(new_request)
  208. return new_requests, finished_requests
  209. async def wait_for_new_requests(self):
  210. if not self.has_new_requests():
  211. await self.new_requests_event.wait()
  212. self.new_requests_event.clear()
  213. def has_new_requests(self):
  214. return not self._new_requests.empty()
  215. @dataclass
  216. class SchedulerOutputState:
  217. """Caches the scheduler outputs for a virtual engine. Used for Multi-Step"""
  218. last_output: Optional[SamplerOutput] = None
  219. seq_group_metadata_list: Optional[List[SequenceGroupMetadata]] = None
  220. scheduler_outputs: Optional[SchedulerOutputs] = None
  221. class _AsyncAphrodite(AphroditeEngine):
  222. """Extension of AphroditeEngine to add async methods."""
  223. def __init__(self, *args, **kwargs):
  224. super().__init__(*args, **kwargs)
  225. pipeline_parallel_size = \
  226. self.parallel_config.pipeline_parallel_size
  227. self.cached_scheduler_outputs = [
  228. SchedulerOutputState() for _ in range(pipeline_parallel_size)
  229. ]
  230. async def step_async(
  231. self, virtual_engine: int
  232. ) -> List[Union[RequestOutput, EmbeddingRequestOutput]]:
  233. """Performs one decoding iteration and returns newly generated results.
  234. The workers are ran asynchronously if possible.
  235. This function performs one decoding iteration of the engine. It first
  236. schedules the sequences to be executed in the next iteration and the
  237. token blocks to be swapped in/out/copy. Then, it executes the model
  238. and updates the scheduler with the model outputs. Finally, it decodes
  239. the sequences and returns the newly generated results.
  240. """
  241. # these are cached outputs from previous iterations. None if on first
  242. # iteration
  243. cached_outputs = self.cached_scheduler_outputs[virtual_engine]
  244. seq_group_metadata_list = cached_outputs.seq_group_metadata_list
  245. scheduler_outputs = cached_outputs.scheduler_outputs
  246. # skip the scheduler if there are any remaining steps in the seq groups.
  247. # This ensures that the scheduler is only called again when the current
  248. # batch has completed.
  249. if not self._has_remaining_steps(seq_group_metadata_list):
  250. seq_group_metadata_list, scheduler_outputs = self.scheduler[
  251. virtual_engine].schedule()
  252. if (self.scheduler_config.is_multi_step
  253. and scheduler_outputs.num_lookahead_slots > 0):
  254. # cache the scheduler outputs for the next iteration if we have
  255. # lookahead slots
  256. self._cache_scheduler_outputs_for_multi_step(
  257. virtual_engine, seq_group_metadata_list, scheduler_outputs)
  258. assert seq_group_metadata_list is not None
  259. assert scheduler_outputs is not None
  260. if not scheduler_outputs.is_empty():
  261. finished_requests_ids = self.scheduler[
  262. virtual_engine].get_and_reset_finished_requests_ids()
  263. # Check if we have a cached last_output from the previous iteration.
  264. # For supporting PP this is probably the best way to pass the
  265. # sampled_token_ids, as a separate broadcast over all the PP stages
  266. # will cause one virtual engine's microbatch to block the pipeline.
  267. last_sampled_token_ids = \
  268. self._get_last_sampled_token_ids(virtual_engine)
  269. execute_model_req = ExecuteModelRequest(
  270. seq_group_metadata_list=seq_group_metadata_list,
  271. blocks_to_swap_in=scheduler_outputs.blocks_to_swap_in,
  272. blocks_to_swap_out=scheduler_outputs.blocks_to_swap_out,
  273. blocks_to_copy=scheduler_outputs.blocks_to_copy,
  274. virtual_engine=virtual_engine,
  275. num_lookahead_slots=scheduler_outputs.num_lookahead_slots,
  276. running_queue_size=scheduler_outputs.running_queue_size,
  277. finished_requests_ids=finished_requests_ids,
  278. # We use ExecuteModelRequest to pass the last sampled_token_ids
  279. # to each of the non-last PP stages for in-place prepare_input.
  280. last_sampled_token_ids=last_sampled_token_ids)
  281. # Execute the model.
  282. output = await self.model_executor.execute_model_async(
  283. execute_model_req)
  284. # we need to do this here so that last step's sampled_token_ids can
  285. # be passed to the next iteration for PP.
  286. if self.scheduler_config.is_multi_step:
  287. self._update_cached_scheduler_output(virtual_engine, output)
  288. else:
  289. output = []
  290. # Finish the current step for all the sequence groups.
  291. if self.scheduler_config.is_multi_step:
  292. for seq_group in seq_group_metadata_list:
  293. seq_group.finish_step()
  294. if not self._has_remaining_steps(seq_group_metadata_list):
  295. # clear the cache if we have finished all the steps
  296. if self.scheduler_config.is_multi_step:
  297. self.cached_scheduler_outputs[
  298. virtual_engine] = SchedulerOutputState()
  299. request_outputs = self._process_model_outputs(
  300. output, scheduler_outputs.scheduled_seq_groups,
  301. scheduler_outputs.ignored_seq_groups, seq_group_metadata_list)
  302. else:
  303. request_outputs = []
  304. # Log stats.
  305. self.do_log_stats(scheduler_outputs, output)
  306. return request_outputs
  307. def _has_remaining_steps(
  308. self, seq_group_metadata_list: Optional[List[SequenceGroupMetadata]]
  309. ) -> bool:
  310. if (not self.scheduler_config.is_multi_step
  311. or not seq_group_metadata_list):
  312. return False
  313. # TODO: this is a sanity check for now to make sure that all the
  314. # seqs are on the same steps. Eventually we will want to do some sort of
  315. # dynamic scheduling when doing multi-step decoding.
  316. ref_remaining_steps = seq_group_metadata_list[0].state.remaining_steps
  317. if any([
  318. seq_group.state.remaining_steps != ref_remaining_steps
  319. for seq_group in seq_group_metadata_list[1:]
  320. ]):
  321. raise AssertionError(("All running sequence groups should "
  322. "have the same remaining steps."))
  323. return ref_remaining_steps > 0
  324. def _cache_scheduler_outputs_for_multi_step(
  325. self, virtual_engine: int,
  326. seq_group_metadata_list: Optional[List[SequenceGroupMetadata]],
  327. scheduler_outputs: SchedulerOutputs) -> None:
  328. self.cached_scheduler_outputs[
  329. virtual_engine].seq_group_metadata_list = seq_group_metadata_list
  330. self.cached_scheduler_outputs[virtual_engine].scheduler_outputs = \
  331. scheduler_outputs
  332. self.cached_scheduler_outputs[virtual_engine].last_output = None
  333. def _get_last_sampled_token_ids(
  334. self, virtual_engine: int) -> Optional[torch.Tensor]:
  335. cached_last_output = self.cached_scheduler_outputs[
  336. virtual_engine].last_output
  337. if (self.scheduler_config.is_multi_step
  338. and self.parallel_config.pipeline_parallel_size > 1
  339. and cached_last_output is not None
  340. and cached_last_output.sampled_token_ids_cpu is not None):
  341. return cached_last_output.sampled_token_ids_cpu
  342. return None
  343. def _update_cached_scheduler_output(
  344. self, virtual_engine: int,
  345. output: List[Optional[SamplerOutput]]) -> None:
  346. if (self.parallel_config.pipeline_parallel_size > 1 and len(output) > 0
  347. and output[0] is not None):
  348. last_output = output[-1]
  349. assert last_output is not None
  350. assert last_output.sampled_token_ids_cpu is not None
  351. assert last_output.sampled_token_ids is None
  352. assert last_output.sampled_token_probs is None
  353. self.cached_scheduler_outputs[
  354. virtual_engine].last_output = last_output
  355. async def stop_remote_worker_execution_loop_async(self) -> None:
  356. """Stop the remote worker execution loop."""
  357. await self.model_executor.stop_remote_worker_execution_loop_async()
  358. async def _tokenize_prompt_async(
  359. self,
  360. prompt: str,
  361. request_id: str,
  362. lora_request: Optional[LoRARequest],
  363. ) -> List[int]:
  364. """Async version of :meth:`_tokenize_prompt`."""
  365. tokenizer = self.get_tokenizer_group("prompts must be None if "
  366. "skip_tokenizer_init is True")
  367. return await tokenizer.encode_async(request_id=request_id,
  368. prompt=prompt,
  369. lora_request=lora_request)
  370. async def _extract_prompt_components_async(
  371. self,
  372. inputs: SingletonPromptInputs,
  373. request_id: str,
  374. lora_request: Optional[LoRARequest] = None,
  375. ) -> PromptComponents:
  376. """Async version of :meth:`_extract_prompt_components`."""
  377. if isinstance(inputs, str):
  378. prompt = inputs
  379. prompt_token_ids = await self._tokenize_prompt_async(
  380. prompt,
  381. request_id=request_id,
  382. lora_request=lora_request,
  383. )
  384. multi_modal_data = None
  385. elif isinstance(inputs, dict):
  386. if "prompt_token_ids" in inputs:
  387. prompt = None
  388. prompt_token_ids = inputs["prompt_token_ids"]
  389. else:
  390. # NOTE: This extra assignment is required to pass mypy
  391. prompt = parsed_prompt = inputs["prompt"]
  392. prompt_token_ids = await self._tokenize_prompt_async(
  393. parsed_prompt,
  394. request_id=request_id,
  395. lora_request=lora_request,
  396. )
  397. multi_modal_data = inputs.get("multi_modal_data")
  398. else:
  399. assert_never(inputs)
  400. return prompt, prompt_token_ids, multi_modal_data
  401. async def _process_encoder_decoder_prompt_async(
  402. self,
  403. inputs: PromptInputs,
  404. request_id: str,
  405. ) -> EncoderDecoderLLMInputs:
  406. """Async version of :meth:`_process_encoder_decoder_prompt`."""
  407. encoder_comps: PromptComponents
  408. decoder_comps: DecoderPromptComponents
  409. if is_explicit_encoder_decoder_prompt(inputs):
  410. encoder_task = self._extract_prompt_components_async(
  411. inputs["encoder_prompt"],
  412. request_id=request_id,
  413. )
  414. if (decoder_input := inputs["decoder_prompt"]) is None:
  415. encoder_comps = await encoder_task
  416. decoder_comps = None, None, None
  417. else:
  418. decoder_task = self._extract_prompt_components_async(
  419. decoder_input,
  420. request_id=request_id,
  421. )
  422. encoder_comps, decoder_comps = await asyncio.gather(
  423. encoder_task, decoder_task)
  424. else:
  425. encoder_comps = await self._extract_prompt_components_async(
  426. inputs,
  427. request_id=request_id,
  428. )
  429. decoder_comps = None, None, None
  430. return self._build_enc_dec_llm_inputs(encoder_comps, decoder_comps)
  431. async def _process_decoder_only_prompt_async(
  432. self,
  433. inputs: SingletonPromptInputs,
  434. request_id: str,
  435. lora_request: Optional[LoRARequest] = None,
  436. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  437. ) -> LLMInputs:
  438. """Async version of :meth:`_process_decoder_only_prompt`."""
  439. prompt_comps = await self._extract_prompt_components_async(
  440. inputs,
  441. request_id=request_id,
  442. lora_request=lora_request,
  443. )
  444. return self._build_decoder_only_llm_inputs(
  445. prompt_comps,
  446. prompt_adapter_request=prompt_adapter_request,
  447. )
  448. async def process_model_inputs_async(
  449. self,
  450. inputs: PromptInputs,
  451. request_id: str,
  452. lora_request: Optional[LoRARequest] = None,
  453. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  454. ) -> Union[LLMInputs, EncoderDecoderLLMInputs]:
  455. """Async version of :meth:`process_model_inputs`."""
  456. if self.is_encoder_decoder_model():
  457. # Encoder-decoder model requires special mapping of
  458. # input prompts to encoder & decoder
  459. model_inputs = await self._process_encoder_decoder_prompt_async(
  460. inputs,
  461. request_id=request_id,
  462. )
  463. else:
  464. if is_explicit_encoder_decoder_prompt(inputs):
  465. raise ValueError("Cannot pass encoder-decoder prompt "
  466. "to decoder-only models")
  467. # Decoder-only operation
  468. model_inputs = await self._process_decoder_only_prompt_async(
  469. inputs,
  470. request_id=request_id,
  471. lora_request=lora_request,
  472. prompt_adapter_request=prompt_adapter_request,
  473. )
  474. return self.input_processor(model_inputs)
  475. async def add_request_async(
  476. self,
  477. request_id: str,
  478. inputs: PromptInputs,
  479. params: Union[SamplingParams, PoolingParams],
  480. arrival_time: Optional[float] = None,
  481. lora_request: Optional[LoRARequest] = None,
  482. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  483. ) -> None:
  484. """Async version of :meth:`add_request`."""
  485. if lora_request is not None and not self.lora_config:
  486. raise ValueError(f"Got lora_request {lora_request} but LoRA is "
  487. "not enabled!")
  488. if arrival_time is None:
  489. arrival_time = time.time()
  490. processed_inputs = await self.process_model_inputs_async(
  491. inputs,
  492. request_id=request_id,
  493. lora_request=lora_request,
  494. prompt_adapter_request=prompt_adapter_request,
  495. )
  496. self._add_processed_request(
  497. request_id=request_id,
  498. processed_inputs=processed_inputs,
  499. params=params,
  500. arrival_time=arrival_time,
  501. lora_request=lora_request,
  502. prompt_adapter_request=prompt_adapter_request,
  503. )
  504. async def check_health_async(self) -> None:
  505. if self.tokenizer:
  506. self.tokenizer.check_health()
  507. self.model_executor.check_health()
  508. class AsyncAphrodite:
  509. """An asynchronous wrapper for AphroditeEngine.
  510. This class is used to wrap the AphroditeEngine class to make it
  511. asynchronous. It uses asyncio to create a background loop that keeps
  512. processing incoming requests. The AphroditeEngine is kicked by the
  513. generate method when there are requests in the waiting queue.
  514. The generate method yields the outputs from the AphroditeEngine
  515. to the caller.
  516. NOTE: For the comprehensive list of arguments, see `AphroditeEngine`.
  517. Args:
  518. worker_use_ray: Whether to use Ray for model workers. Required for
  519. distributed execution. Should be the same as
  520. `parallel_config.worker_use_ray`.
  521. engine_use_ray: Whether to make AphroditeEngine a Ray actor. If so, the
  522. async frontend will be executed in a separate process as the
  523. model workers.
  524. log_requests: Whether to log the requests.
  525. start_engine_loop: If True, the background task to run the engine
  526. will be automatically started in the generate call.
  527. *args: Arguments for AphroditeEngine.
  528. *kwargs: Arguments for AphroditeEngine.
  529. """
  530. _engine_class: Type[_AsyncAphrodite] = _AsyncAphrodite
  531. def __init__(self,
  532. worker_use_ray: bool,
  533. engine_use_ray: bool,
  534. *args,
  535. log_requests: bool = True,
  536. start_engine_loop: bool = True,
  537. **kwargs) -> None:
  538. self.worker_use_ray = worker_use_ray
  539. self.engine_use_ray = engine_use_ray
  540. self.log_requests = log_requests
  541. self.engine = self._init_engine(*args, **kwargs)
  542. self.background_loop: Optional[asyncio.Future] = None
  543. # We need to keep a reference to unshielded
  544. # task as well to prevent it from being garbage
  545. # collected
  546. self._background_loop_unshielded: Optional[asyncio.Task] = None
  547. self.start_engine_loop = start_engine_loop
  548. self._errored_with: Optional[BaseException] = None
  549. # Lazy initialized fields
  550. self._request_tracker: RequestTracker
  551. @classmethod
  552. def _get_executor_cls(
  553. cls, engine_config: EngineConfig) -> Type[ExecutorAsyncBase]:
  554. distributed_executor_backend = (
  555. engine_config.parallel_config.distributed_executor_backend)
  556. if isinstance(distributed_executor_backend, type):
  557. if not issubclass(distributed_executor_backend, ExecutorAsyncBase):
  558. raise TypeError(
  559. "distributed_executor_backend must be a subclass of "
  560. f"ExecutorAsyncBase. Got {distributed_executor_backend}.")
  561. if distributed_executor_backend.uses_ray: # type: ignore
  562. initialize_ray_cluster(engine_config.parallel_config)
  563. executor_class = distributed_executor_backend
  564. elif engine_config.device_config.device_type == "neuron":
  565. from aphrodite.executor.neuron_executor import NeuronExecutorAsync
  566. executor_class = NeuronExecutorAsync
  567. elif engine_config.device_config.device_type == "tpu":
  568. if distributed_executor_backend == "ray":
  569. initialize_ray_cluster(engine_config.parallel_config)
  570. from aphrodite.executor.ray_tpu_executor import (
  571. RayTPUExecutorAsync)
  572. executor_class = RayTPUExecutorAsync
  573. else:
  574. assert distributed_executor_backend is None
  575. from aphrodite.executor.tpu_executor import TPUExecutorAsync
  576. executor_class = TPUExecutorAsync
  577. elif engine_config.device_config.device_type == "cpu":
  578. from aphrodite.executor.cpu_executor import CPUExecutorAsync
  579. executor_class = CPUExecutorAsync
  580. elif engine_config.device_config.device_type == "openvino":
  581. assert distributed_executor_backend is None, (
  582. "Distributed execution is not supported with the OpenVINO "
  583. "backend.")
  584. from aphrodite.executor.openvino_executor import (
  585. OpenVINOExecutorAsync)
  586. executor_class = OpenVINOExecutorAsync
  587. elif engine_config.device_config.device_type == "xpu":
  588. if distributed_executor_backend is None:
  589. from aphrodite.executor.xpu_executor import XPUExecutorAsync
  590. executor_class = XPUExecutorAsync
  591. elif distributed_executor_backend == "ray":
  592. initialize_ray_cluster(engine_config.parallel_config)
  593. from aphrodite.executor.ray_xpu_executor import (
  594. RayXPUExecutorAsync)
  595. executor_class = RayXPUExecutorAsync
  596. else:
  597. raise RuntimeError(
  598. "Unsupported distributed executor backend for XPU.")
  599. elif distributed_executor_backend == "ray":
  600. initialize_ray_cluster(engine_config.parallel_config)
  601. from aphrodite.executor.ray_gpu_executor import RayGPUExecutorAsync
  602. executor_class = RayGPUExecutorAsync
  603. elif distributed_executor_backend == "mp":
  604. from aphrodite.executor.multiproc_gpu_executor import (
  605. MultiprocessingGPUExecutorAsync)
  606. executor_class = MultiprocessingGPUExecutorAsync
  607. else:
  608. from aphrodite.executor.gpu_executor import GPUExecutorAsync
  609. executor_class = GPUExecutorAsync
  610. return executor_class
  611. @classmethod
  612. def from_engine_args(
  613. cls,
  614. engine_args: AsyncEngineArgs,
  615. start_engine_loop: bool = True,
  616. stat_loggers: Optional[Dict[str, StatLoggerBase]] = None,
  617. ) -> "AsyncAphrodite":
  618. """Creates an async LLM engine from the engine arguments."""
  619. # Create the engine configs.
  620. engine_config = engine_args.create_engine_config()
  621. if engine_args.engine_use_ray:
  622. from aphrodite.executor import ray_utils
  623. ray_utils.assert_ray_available()
  624. executor_class = cls._get_executor_cls(engine_config)
  625. # Create the async LLM engine.
  626. engine = cls(
  627. executor_class.uses_ray,
  628. engine_args.engine_use_ray,
  629. **engine_config.to_dict(),
  630. executor_class=executor_class,
  631. log_requests=not engine_args.disable_log_requests,
  632. log_stats=not engine_args.disable_log_stats,
  633. start_engine_loop=start_engine_loop,
  634. stat_loggers=stat_loggers,
  635. )
  636. return engine
  637. @property
  638. def is_running(self) -> bool:
  639. return (self.background_loop is not None
  640. and self._background_loop_unshielded is not None
  641. and not self._background_loop_unshielded.done())
  642. @property
  643. def is_stopped(self) -> bool:
  644. return self.errored or (self.background_loop is not None and
  645. self._background_loop_unshielded is not None
  646. and self._background_loop_unshielded.done())
  647. @property
  648. def errored(self) -> bool:
  649. return self._errored_with is not None
  650. def set_errored(self, exc: Exception) -> None:
  651. self._errored_with = exc
  652. def _error_callback(self, exc: Exception) -> None:
  653. self.set_errored(exc)
  654. self._request_tracker.propagate_exception(exc)
  655. async def get_tokenizer(
  656. self,
  657. lora_request: Optional[LoRARequest] = None,
  658. ) -> "PreTrainedTokenizer":
  659. if self.engine_use_ray:
  660. return await self.engine.get_tokenizer.remote( # type: ignore
  661. lora_request)
  662. return await (self.engine.get_tokenizer_group().
  663. get_lora_tokenizer_async(lora_request))
  664. def start_background_loop(self) -> None:
  665. """Start the background loop."""
  666. if self.errored:
  667. raise AsyncEngineDeadError(
  668. "Background loop has errored already.") from self._errored_with
  669. if self.is_running:
  670. raise RuntimeError("Background loop is already running.")
  671. # Initialize the RequestTracker here so it uses the right event loop.
  672. self._request_tracker = RequestTracker()
  673. self._background_loop_unshielded = asyncio.get_event_loop(
  674. ).create_task(self.run_engine_loop())
  675. self._background_loop_unshielded.add_done_callback(
  676. partial(_log_task_completion, error_callback=self._error_callback))
  677. self.background_loop = asyncio.shield(self._background_loop_unshielded)
  678. def shutdown_background_loop(self) -> None:
  679. """
  680. Shut down the background loop.
  681. This method needs to be called during cleanup to remove
  682. references to `self` and properly GC the resources held
  683. by the async LLM engine (e.g., the executors as well as
  684. their resources).
  685. """
  686. if self._background_loop_unshielded is not None:
  687. self._background_loop_unshielded.cancel()
  688. self._background_loop_unshielded = None
  689. self.background_loop = None
  690. def _init_engine(self, *args,
  691. **kwargs) -> Union[_AsyncAphrodite, "ray.ObjectRef"]:
  692. if not self.engine_use_ray:
  693. engine_class = self._engine_class
  694. elif self.worker_use_ray:
  695. engine_class = ray.remote(num_cpus=0)(self._engine_class).remote
  696. else:
  697. # FIXME: This is a bit hacky. Be careful when changing the
  698. # order of the arguments.
  699. cache_config = kwargs["cache_config"]
  700. parallel_config = kwargs["parallel_config"]
  701. if (parallel_config.tensor_parallel_size == 1
  702. and parallel_config.pipeline_parallel_size == 1):
  703. num_gpus = cache_config.gpu_memory_utilization
  704. else:
  705. num_gpus = 1
  706. engine_class = ray.remote(num_gpus=num_gpus)(
  707. self._engine_class).remote
  708. return engine_class(*args, **kwargs)
  709. async def engine_step(self, virtual_engine: int) -> bool:
  710. """Kick the engine to process the waiting requests.
  711. Returns True if there are in-progress requests."""
  712. new_requests, aborted_requests = (
  713. self._request_tracker.get_new_and_aborted_requests())
  714. for new_request in new_requests:
  715. # Add the request into the Aphrodite engine's waiting queue.
  716. # TODO: Maybe add add_request_batch to reduce Ray overhead
  717. try:
  718. if self.engine_use_ray:
  719. await self.engine.add_request.remote( # type: ignore
  720. **new_request)
  721. else:
  722. await self.engine.add_request_async(**new_request)
  723. except ValueError as e:
  724. # TODO: use an Aphrodite specific error for failed validation
  725. self._request_tracker.process_exception(
  726. new_request["request_id"],
  727. e,
  728. verbose=self.log_requests,
  729. )
  730. if aborted_requests:
  731. await self._engine_abort(aborted_requests)
  732. if self.engine_use_ray:
  733. request_outputs = await self.engine.step.remote() # type: ignore
  734. else:
  735. request_outputs = await self.engine.step_async(virtual_engine)
  736. # Put the outputs into the corresponding streams.
  737. finished = True
  738. for request_output in request_outputs:
  739. self._request_tracker.process_request_output(
  740. request_output, verbose=self.log_requests)
  741. finished = finished and request_output.finished
  742. return not finished
  743. async def _engine_abort(self, request_ids: Iterable[str]):
  744. if self.engine_use_ray:
  745. await self.engine.abort_request.remote(request_ids) # type: ignore
  746. else:
  747. self.engine.abort_request(request_ids)
  748. async def run_engine_loop(self):
  749. if self.engine_use_ray:
  750. pipeline_parallel_size = 1 # type: ignore
  751. else:
  752. pipeline_parallel_size = \
  753. self.engine.parallel_config.pipeline_parallel_size
  754. has_requests_in_progress = [False] * pipeline_parallel_size
  755. while True:
  756. if not any(has_requests_in_progress):
  757. logger.debug("Waiting for new requests...")
  758. # Stop the execute model loop in parallel workers until there
  759. # are more requests to process. This avoids waiting
  760. # indefinitely in torch.distributed ops which may otherwise
  761. # timeout, and unblocks the RPC thread in the workers so that
  762. # they can process any other queued control plane messages,
  763. # such as add/remove lora adapters.
  764. if self.engine_use_ray:
  765. await (self.engine.stop_remote_worker_execution_loop.
  766. remote() # type: ignore
  767. )
  768. else:
  769. await self.engine.stop_remote_worker_execution_loop_async()
  770. await self._request_tracker.wait_for_new_requests()
  771. logger.debug("Got new requests!")
  772. requests_in_progress = [
  773. asyncio.create_task(self.engine_step(ve))
  774. for ve in range(pipeline_parallel_size)
  775. ]
  776. has_requests_in_progress = [True] * pipeline_parallel_size
  777. # Abort if iteration takes too long due to unrecoverable errors
  778. # (eg. NCCL timeouts).
  779. try:
  780. async with asyncio_timeout(ENGINE_ITERATION_TIMEOUT_S):
  781. done, _ = await asyncio.wait(
  782. requests_in_progress,
  783. return_when=asyncio.FIRST_COMPLETED)
  784. for _ in range(pipeline_parallel_size):
  785. await asyncio.sleep(0)
  786. for task in done:
  787. result = task.result()
  788. virtual_engine = requests_in_progress.index(task)
  789. if self.engine_use_ray:
  790. has_unfinished_requests = (
  791. await (self.engine.
  792. has_unfinished_requests_for_virtual_engine.
  793. remote( # type: ignore
  794. virtual_engine)))
  795. else:
  796. has_unfinished_requests = (
  797. self.engine.
  798. has_unfinished_requests_for_virtual_engine(
  799. virtual_engine))
  800. if result or has_unfinished_requests:
  801. requests_in_progress[virtual_engine] = (
  802. asyncio.create_task(
  803. self.engine_step(virtual_engine)))
  804. has_requests_in_progress[virtual_engine] = True
  805. else:
  806. has_requests_in_progress[virtual_engine] = False
  807. except asyncio.TimeoutError as exc:
  808. logger.error(
  809. "Engine iteration timed out. This should never happen!")
  810. self.set_errored(exc)
  811. raise
  812. await asyncio.sleep(0)
  813. # This method does not need to be async, but kept that way
  814. # for backwards compatibility.
  815. async def add_request(
  816. self,
  817. request_id: str,
  818. inputs: PromptInputs,
  819. params: Union[SamplingParams, PoolingParams],
  820. arrival_time: Optional[float] = None,
  821. lora_request: Optional[LoRARequest] = None,
  822. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  823. ) -> AsyncGenerator[Union[RequestOutput, EmbeddingRequestOutput], None]:
  824. if not self.is_running:
  825. if self.start_engine_loop:
  826. self.start_background_loop()
  827. else:
  828. raise AsyncEngineDeadError(
  829. "Background loop is not running. If it was running, "
  830. "inspect the output to find the stacktrace of the "
  831. "error that caused the background loop to stop "
  832. "(AsyncEngineDeadError).")
  833. stream = self._request_tracker.add_request(
  834. request_id,
  835. verbose=self.log_requests,
  836. inputs=inputs,
  837. params=params,
  838. arrival_time=arrival_time or time.time(),
  839. lora_request=lora_request,
  840. prompt_adapter_request=prompt_adapter_request)
  841. return stream.generator()
  842. async def generate(
  843. self,
  844. inputs: PromptInputs,
  845. sampling_params: SamplingParams,
  846. request_id: str,
  847. lora_request: Optional[LoRARequest] = None,
  848. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  849. ) -> AsyncGenerator[RequestOutput, None]:
  850. """Generate outputs for a request.
  851. Generate outputs for a request. This method is a coroutine. It adds the
  852. request into the waiting queue of the AphroditeEngine and streams the
  853. outputs from the AphroditeEngine to the caller.
  854. Args:
  855. prompt: The prompt string. Can be None if prompt_token_ids is
  856. provided.
  857. sampling_params: The sampling parameters of the request.
  858. request_id: The unique id of the request.
  859. prompt_token_ids: The token IDs of the prompt. If None, we
  860. use the tokenizer to convert the prompts to token IDs.
  861. lora_request: LoRA request to use for generation, if any.
  862. prompt_adapter_request: Prompt Adapter request to use
  863. for generation, if any.
  864. Yields:
  865. The output `RequestOutput` objects from the AphroditeEngine
  866. for the request.
  867. Details:
  868. - If the engine is not running, start the background loop,
  869. which iteratively invokes
  870. # pylint: disable=line-too-long
  871. :meth:`~aphrodite.engine.async_aphrodite.AsyncAphrodite.engine_step`
  872. to process the waiting requests.
  873. - Add the request to the engine's `RequestTracker`.
  874. On the next background loop, this request will be sent to
  875. the underlying engine.
  876. Also, a corresponding `AsyncStream` will be created.
  877. - Wait for the request outputs from `AsyncStream` and yield them.
  878. Example:
  879. >>> # Please refer to entrypoints/api_server.py for
  880. >>> # the complete example.
  881. >>>
  882. >>> # initialize the engine and the example input
  883. >>> engine = AsyncAphrodite.from_engine_args(engine_args)
  884. >>> example_input = {
  885. >>> "prompt": "What is LLM?",
  886. >>> "stream": False, # assume the non-streaming case
  887. >>> "temperature": 0.0,
  888. >>> "request_id": 0,
  889. >>> }
  890. >>>
  891. >>> # start the generation
  892. >>> results_generator = engine.generate(
  893. >>> example_input["prompt"],
  894. >>> SamplingParams(temperature=example_input["temperature"]),
  895. >>> example_input["request_id"])
  896. >>>
  897. >>> # get the results
  898. >>> final_output = None
  899. >>> async for request_output in results_generator:
  900. >>> if await request.is_disconnected():
  901. >>> # Abort the request if the client disconnects.
  902. >>> await engine.abort(request_id)
  903. >>> # Return or raise an error
  904. >>> ...
  905. >>> final_output = request_output
  906. >>>
  907. >>> # Process and return the final output
  908. >>> ...
  909. """
  910. async for output in await self.add_request(
  911. request_id,
  912. inputs,
  913. sampling_params,
  914. lora_request=lora_request,
  915. prompt_adapter_request=prompt_adapter_request,
  916. ):
  917. yield AphroditeEngine.validate_output(output, RequestOutput)
  918. async def encode(
  919. self,
  920. inputs: PromptInputs,
  921. pooling_params: PoolingParams,
  922. request_id: str,
  923. lora_request: Optional[LoRARequest] = None,
  924. ) -> AsyncGenerator[EmbeddingRequestOutput, None]:
  925. """Generate outputs for a request from an embedding model.
  926. Generate outputs for a request. This method is a coroutine. It adds the
  927. request into the waiting queue of the AphroditeEngine and streams the
  928. outputs from the AphroditeEngine to the caller.
  929. Args:
  930. prompt: The prompt string. Can be None if prompt_token_ids is
  931. provided.
  932. pooling_params: The pooling parameters of the request.
  933. request_id: The unique id of the request.
  934. prompt_token_ids: The token IDs of the prompt. If None, we
  935. use the tokenizer to convert the prompts to token IDs.
  936. lora_request: LoRA request to use for generation, if any.
  937. multi_modal_data: Multi modal data per request.
  938. Yields:
  939. The output `EmbeddingRequestOutput` objects from the
  940. AphroditeEngine for the request.
  941. Details:
  942. - If the engine is not running, start the background loop,
  943. which iteratively invokes
  944. :meth:`~aphrodite.engine.async_aphrodite.AsyncAphrodite.engine_step`
  945. to process the waiting requests.
  946. - Add the request to the engine's `RequestTracker`.
  947. On the next background loop, this request will be sent to
  948. the underlying engine.
  949. Also, a corresponding `AsyncStream` will be created.
  950. - Wait for the request outputs from `AsyncStream` and yield them.
  951. Example:
  952. >>> # initialize the engine and the example input
  953. >>> engine = AsyncAphrodite.from_engine_args(engine_args)
  954. >>> example_input = {
  955. >>> "input": "What is LLM?",
  956. >>> "request_id": 0,
  957. >>> }
  958. >>>
  959. >>> # start the generation
  960. >>> results_generator = engine.encode(
  961. >>> example_input["input"],
  962. >>> PoolingParams(),
  963. >>> example_input["request_id"])
  964. >>>
  965. >>> # get the results
  966. >>> final_output = None
  967. >>> async for request_output in results_generator:
  968. >>> if await request.is_disconnected():
  969. >>> # Abort the request if the client disconnects.
  970. >>> await engine.abort(request_id)
  971. >>> # Return or raise an error
  972. >>> ...
  973. >>> final_output = request_output
  974. >>>
  975. >>> # Process and return the final output
  976. >>> ...
  977. """
  978. async for output in await self.add_request(
  979. request_id,
  980. inputs,
  981. pooling_params,
  982. lora_request=lora_request,
  983. ):
  984. yield AphroditeEngine.validate_output(output,
  985. EmbeddingRequestOutput)
  986. async def abort(self, request_id: str) -> None:
  987. """Abort a request.
  988. Abort a submitted request. If the request is finished or not found,
  989. this method will be a no-op.
  990. Args:
  991. request_id: The unique id of the request.
  992. """
  993. if not self.is_running:
  994. raise AsyncEngineDeadError(
  995. "Background loop is not running. If it was running, "
  996. "inspect the output to find the stacktrace of the "
  997. "error that caused the background loop to stop "
  998. "(AsyncEngineDeadError).")
  999. return self._abort(request_id)
  1000. def _abort(self, request_id: str) -> None:
  1001. """Abort a request.
  1002. Abort a submitted request. If the request is finished or not found,
  1003. this method will be a no-op.
  1004. Args:
  1005. request_id: The unique id of the request.
  1006. """
  1007. self._request_tracker.abort_request(request_id,
  1008. exception=asyncio.CancelledError,
  1009. verbose=self.log_requests)
  1010. async def get_model_config(self) -> ModelConfig:
  1011. """Get the model configuration of the Aphrodite engine."""
  1012. if self.engine_use_ray:
  1013. return await self.engine.get_model_config.remote() # type: ignore
  1014. else:
  1015. return self.engine.get_model_config()
  1016. async def get_parallel_config(self) -> ParallelConfig:
  1017. """Get the parallel configuration of the Aphrodite engine."""
  1018. if self.engine_use_ray:
  1019. return await self.engine.get_parallel_config.remote( # type: ignore
  1020. )
  1021. else:
  1022. return self.engine.get_parallel_config()
  1023. async def get_decoding_config(self) -> DecodingConfig:
  1024. """Get the decoding configuration of the Aphrodite engine."""
  1025. if self.engine_use_ray:
  1026. return await self.engine.get_decoding_config.remote( # type: ignore
  1027. )
  1028. else:
  1029. return self.engine.get_decoding_config()
  1030. async def get_scheduler_config(self) -> SchedulerConfig:
  1031. """Get the scheduling configuration of the Aphrodite engine."""
  1032. if self.engine_use_ray:
  1033. return await self.engine.get_scheduler_config.remote( # type: ignore
  1034. )
  1035. else:
  1036. return self.engine.get_scheduler_config()
  1037. async def get_lora_config(self) -> LoRAConfig:
  1038. """Get the lora configuration of the Aphrodite engine."""
  1039. if self.engine_use_ray:
  1040. return await self.engine.get_lora_config.remote( # type: ignore
  1041. )
  1042. else:
  1043. return self.engine.get_lora_config()
  1044. async def do_log_stats(
  1045. self,
  1046. scheduler_outputs: Optional[SchedulerOutputs] = None,
  1047. model_output: Optional[List[SamplerOutput]] = None) -> None:
  1048. if self.engine_use_ray:
  1049. await self.engine.do_log_stats.remote( # type: ignore
  1050. scheduler_outputs, model_output)
  1051. else:
  1052. self.engine.do_log_stats()
  1053. async def check_health(self) -> None:
  1054. """Raises an error if engine is unhealthy."""
  1055. t = time.perf_counter()
  1056. logger.debug("Starting health check...")
  1057. if self.is_stopped:
  1058. raise AsyncEngineDeadError("Background loop is stopped.")
  1059. if self.engine_use_ray:
  1060. try:
  1061. await self.engine.check_health.remote() # type: ignore
  1062. except ray.exceptions.RayActorError as e:
  1063. raise RuntimeError("Engine is dead.") from e
  1064. else:
  1065. await self.engine.check_health_async()
  1066. logger.debug(f"Health check took {time.perf_counter()-t}s")