1
0

async_aphrodite.py 50 KB

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