1
0

async_aphrodite.py 47 KB

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