async_aphrodite.py 44 KB

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