async_aphrodite.py 52 KB

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