async_aphrodite.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. import asyncio
  2. import os
  3. import time
  4. from functools import partial
  5. from typing import (Any, Dict, Iterable, List, Optional, Set, Tuple, Type,
  6. Union, AsyncIterator, Callable)
  7. from loguru import logger
  8. from aphrodite.lora.request import LoRARequest
  9. from aphrodite.common.config import ModelConfig
  10. from aphrodite.engine.args_tools import AsyncEngineArgs
  11. from aphrodite.engine.aphrodite_engine import AphroditeEngine
  12. from aphrodite.engine.ray_tools import initialize_cluster, ray
  13. from aphrodite.common.outputs import RequestOutput
  14. from aphrodite.common.sampling_params import SamplingParams
  15. ENGINE_ITERATION_TIMEOUT_S = int(
  16. os.environ.get("APHRODITE_ENGINE_ITERATION_TIMEOUT_S", 60))
  17. class AsyncEngineDeadError(RuntimeError):
  18. pass
  19. def _raise_exception_on_finish(
  20. task: asyncio.Task, error_callback: Callable[[Exception],
  21. None]) -> None:
  22. msg = ("Task finished unexpectedly. This should never happen! "
  23. "Please open an issue on Github.")
  24. exception = None
  25. try:
  26. task.result()
  27. # NOTE: This will be thrown if task exits normally (which it should not)
  28. raise AsyncEngineDeadError(msg)
  29. except Exception as e:
  30. exception = e
  31. logger.error("Engine background task failed", exc_info=e)
  32. error_callback(exception)
  33. raise AsyncEngineDeadError(
  34. msg + " See stack trace above for the actual cause.") from e
  35. class AsyncStream:
  36. """A stream of RequestOutputs for a request that can be
  37. iterated over asynchronously."""
  38. def __init__(self, request_id: str) -> None:
  39. self.request_id = request_id
  40. self._queue = asyncio.Queue()
  41. self._finished = False
  42. def put(self, item: Union[RequestOutput, Exception]) -> None:
  43. if self._finished:
  44. return
  45. self._queue.put_nowait(item)
  46. def finish(self) -> None:
  47. self._queue.put_nowait(StopAsyncIteration())
  48. self._finished = True
  49. @property
  50. def finished(self) -> bool:
  51. return self._finished
  52. def __aiter__(self):
  53. return self
  54. async def __anext__(self) -> RequestOutput:
  55. result = await self._queue.get()
  56. if isinstance(result, Exception):
  57. raise result
  58. return result
  59. class RequestTracker:
  60. """Synchronous abstraction for tracking requests."""
  61. def __init__(self) -> None:
  62. self._request_streams: Dict[str, AsyncStream] = {}
  63. self._finished_requests: asyncio.Queue[str] = asyncio.Queue()
  64. self._new_requests: asyncio.Queue[Tuple[AsyncStream,
  65. dict]] = asyncio.Queue()
  66. self.new_requests_event = asyncio.Event()
  67. def __contains__(self, item):
  68. return item in self._request_streams
  69. def __len__(self) -> int:
  70. return len(self._request_streams)
  71. def propagate_exception(self,
  72. exc: Exception,
  73. request_id: Optional[str] = None) -> None:
  74. """Propagate an exception to request streams
  75. (all if request_id is None)."""
  76. if request_id is not None:
  77. self._request_streams[request_id].put(exc)
  78. self.abort_request(request_id)
  79. else:
  80. for rid, stream in self._request_streams.items():
  81. stream.put(exc)
  82. self.abort_request(rid)
  83. def process_request_output(self,
  84. request_output: RequestOutput,
  85. *,
  86. verbose: bool = False) -> None:
  87. """Process a request output from the engine."""
  88. request_id = request_output.request_id
  89. self._request_streams[request_id].put(request_output)
  90. if request_output.finished:
  91. if verbose:
  92. logger.info(f"Finished request {request_id}.")
  93. self.abort_request(request_id)
  94. def process_exception(self,
  95. request_id: str,
  96. exception: Exception,
  97. *,
  98. verbose: bool = False) -> None:
  99. """Propagate an exception from the engine."""
  100. self._request_streams[request_id].put(exception)
  101. if verbose:
  102. logger.info(f"Finished request {request_id}.")
  103. self.abort_request(request_id)
  104. def add_request(self, request_id: str,
  105. **engine_add_request_kwargs) -> AsyncStream:
  106. """Add a request to be sent to the engine on the next background
  107. loop iteration."""
  108. if request_id in self._request_streams:
  109. raise KeyError(f"Request {request_id} already exists.")
  110. stream = AsyncStream(request_id)
  111. self._new_requests.put_nowait((stream, {
  112. "request_id": request_id,
  113. **engine_add_request_kwargs
  114. }))
  115. self.new_requests_event.set()
  116. return stream
  117. def abort_request(self, request_id: str, *, verbose: bool = False) -> None:
  118. """Abort a request during next background loop iteration."""
  119. if verbose:
  120. logger.info(f"Aborted request {request_id}.")
  121. self._finished_requests.put_nowait(request_id)
  122. if request_id not in self._request_streams or self._request_streams[
  123. request_id].finished:
  124. # The request has already finished or been aborted.
  125. return
  126. self._request_streams[request_id].finish()
  127. def get_new_and_finished_requests(self) -> Tuple[List[Dict], Set[str]]:
  128. """Get the new requests and finished requests to be
  129. sent to the engine."""
  130. new_requests: List[Dict] = []
  131. finished_requests: Set[str] = set()
  132. while not self._finished_requests.empty():
  133. request_id = self._finished_requests.get_nowait()
  134. finished_requests.add(request_id)
  135. self._request_streams.pop(request_id, None)
  136. while not self._new_requests.empty():
  137. stream, new_request = self._new_requests.get_nowait()
  138. if stream.request_id in finished_requests:
  139. # The request has already been aborted.
  140. stream.finish()
  141. continue
  142. self._request_streams[stream.request_id] = stream
  143. new_requests.append(new_request)
  144. return new_requests, finished_requests
  145. async def wait_for_new_requests(self):
  146. if not self.has_new_requests():
  147. await self.new_requests_event.wait()
  148. self.new_requests_event.clear()
  149. def has_new_requests(self):
  150. return not self._new_requests.empty()
  151. class _AsyncAphrodite(AphroditeEngine):
  152. """Extension of AphroditeEngine to add async methods."""
  153. async def step_async(self) -> List[RequestOutput]:
  154. """Performs one decoding iteration and returns newly generated results.
  155. The workers are ran asynchronously if possible.
  156. This function performs one decoding iteration of the engine. It first
  157. schedules the sequences to be executed in the next iteration and the
  158. token blocks to be swapped in/out/copy. Then, it executes the model
  159. and updates the scheduler with the model outputs. Finally, it decodes
  160. the sequences and returns the newly generated results.
  161. """
  162. seq_group_metadata_list, scheduler_outputs = self.scheduler.schedule()
  163. if not scheduler_outputs.is_empty():
  164. # Execute the model.
  165. all_outputs = await self._run_workers_async(
  166. "execute_model",
  167. driver_kwargs={
  168. "seq_group_metadata_list": seq_group_metadata_list,
  169. "blocks_to_swap_in": scheduler_outputs.blocks_to_swap_in,
  170. "blocks_to_swap_out": scheduler_outputs.blocks_to_swap_out,
  171. "blocks_to_copy": scheduler_outputs.blocks_to_copy,
  172. })
  173. # Only the driver worker returns the sampling results.
  174. output = all_outputs[0]
  175. else:
  176. output = []
  177. return self._process_model_outputs(output, scheduler_outputs)
  178. async def encode_request_async(
  179. self,
  180. request_id: str, # pylint: disable=unused-argument
  181. prompt: Optional[str],
  182. prompt_token_ids: Optional[List[int]] = None,
  183. lora_request: Optional[LoRARequest] = None,
  184. ):
  185. if prompt_token_ids is None:
  186. assert prompt is not None
  187. prompt_token_ids = await self.tokenizer.encode_async(
  188. request_id=request_id,
  189. prompt=prompt,
  190. lora_request=lora_request)
  191. return prompt_token_ids
  192. async def add_request_async(
  193. self,
  194. request_id: str,
  195. prompt: Optional[str],
  196. sampling_params: SamplingParams,
  197. prompt_token_ids: Optional[List[int]] = None,
  198. arrival_time: Optional[float] = None,
  199. lora_request: Optional[LoRARequest] = None,
  200. ) -> None:
  201. if lora_request is not None and not self.lora_config:
  202. raise ValueError(f"Got lora_request {lora_request} but LoRA is "
  203. "not enabled!")
  204. if arrival_time is None:
  205. arrival_time = time.time()
  206. prompt_token_ids = await self.encode_request_async(
  207. request_id=request_id,
  208. prompt=prompt,
  209. prompt_token_ids=prompt_token_ids,
  210. lora_request=lora_request)
  211. return self.add_request(
  212. request_id,
  213. prompt=prompt,
  214. prompt_token_ids=prompt_token_ids,
  215. sampling_params=sampling_params,
  216. arrival_time=arrival_time,
  217. lora_request=lora_request,
  218. )
  219. async def _run_workers_async(
  220. self,
  221. method: str,
  222. *args,
  223. driver_args: Optional[List[Any]] = None,
  224. driver_kwargs: Optional[Dict[str, Any]] = None,
  225. **kwargs,
  226. ) -> Any:
  227. """Runs the given method on all workers."""
  228. coros = []
  229. if driver_args is None:
  230. driver_args = args
  231. if driver_kwargs is None:
  232. driver_kwargs = kwargs
  233. # Run the driver worker asynchronously.
  234. driver_executor = getattr(self.driver_worker, method)
  235. coros.append(asyncio.get_event_loop().run_in_executor(
  236. None, partial(driver_executor, *driver_args, **driver_kwargs)))
  237. # Run the ray workers asynchronously.
  238. for worker in self.workers:
  239. coros.append(worker.execute_method.remote(method, *args, **kwargs))
  240. all_outputs = await asyncio.gather(*coros)
  241. return all_outputs
  242. async def check_health_async(self):
  243. """Raises an error if engine is unhealthy."""
  244. self._check_if_any_actor_is_dead()
  245. class AsyncAphrodite:
  246. """An asynchronous wrapper for AphroditeEngine.
  247. This class is used to wrap the AphroditeEngine class to make it
  248. asynchronous. It uses asyncio to create a background loop that keeps
  249. processing incoming requests. The AphroditeEngine is kicked by the
  250. generate method when there are requests in the waiting queue.
  251. The generate method yields the outputs from the AphroditeEngine
  252. to the caller.
  253. NOTE: For the comprehensive list of arguments, see `AphroditeEngine`.
  254. Args:
  255. worker_use_ray: Whether to use Ray for model workers. Required for
  256. distributed execution. Should be the same as
  257. `parallel_config.worker_use_ray`.
  258. engine_use_ray: Whether to make AphroditeEngine a Ray actor. If so, the
  259. async frontend will be executed in a separate process as the
  260. model workers.
  261. log_requests: Whether to log the requests.
  262. start_engine_loop: If True, the background task to run the engine
  263. will be automatically started in the generate call.
  264. *args: Arguments for AphroditeEngine.
  265. *kwargs: Arguments for AphroditeEngine.
  266. """
  267. _engine_class: Type[_AsyncAphrodite] = _AsyncAphrodite
  268. def __init__(self,
  269. worker_use_ray: bool,
  270. engine_use_ray: bool,
  271. *args,
  272. log_requests: bool = True,
  273. max_log_len: Optional[int] = None,
  274. start_engine_loop: bool = True,
  275. **kwargs) -> None:
  276. self.worker_use_ray = worker_use_ray
  277. self.engine_use_ray = engine_use_ray
  278. self.log_requests = log_requests
  279. self.max_log_len = max_log_len
  280. self.engine = self._init_engine(*args, **kwargs)
  281. self.background_loop = None
  282. # We need to keep a reference to unshielded
  283. # task as well to prevent it from being garbage
  284. # collected
  285. self._background_loop_unshielded = None
  286. self.start_engine_loop = start_engine_loop
  287. self._request_tracker: Optional[RequestTracker] = None
  288. self._errored_with: Optional[BaseException] = None
  289. @property
  290. def is_running(self) -> bool:
  291. return (self.background_loop is not None
  292. and not self._background_loop_unshielded.done())
  293. @property
  294. def is_stopped(self) -> bool:
  295. return self.errored or (self.background_loop is not None
  296. and self._background_loop_unshielded.done())
  297. @property
  298. def errored(self) -> bool:
  299. return self._errored_with is not None
  300. def set_errored(self, exc: Exception) -> None:
  301. self._errored_with = exc
  302. def _error_callback(self, exc: Exception) -> None:
  303. self.set_errored(exc)
  304. self._request_tracker.propagate_exception(exc)
  305. def get_tokenizer(self):
  306. return self.engine.tokenizer.tokenizer
  307. def start_background_loop(self) -> None:
  308. """Start the background loop."""
  309. if self.errored:
  310. raise AsyncEngineDeadError(
  311. "Background loop has errored already.") from self._errored_with
  312. if self.is_running:
  313. raise RuntimeError("Background loop is already running.")
  314. # Initialize the RequestTracker here so it uses the right event loop.
  315. self._request_tracker = RequestTracker()
  316. self._background_loop_unshielded = asyncio.get_event_loop(
  317. ).create_task(self.run_engine_loop())
  318. self._background_loop_unshielded.add_done_callback(
  319. partial(_raise_exception_on_finish,
  320. error_callback=self._error_callback))
  321. self.background_loop = asyncio.shield(self._background_loop_unshielded)
  322. def _init_engine(self, *args,
  323. **kwargs) -> Union[_AsyncAphrodite, "ray.ObjectRef"]:
  324. if not self.engine_use_ray:
  325. engine_class = self._engine_class
  326. elif self.worker_use_ray:
  327. engine_class = ray.remote(num_cpus=0)(self._engine_class).remote
  328. else:
  329. # FIXME: This is a bit hacky. Be careful when changing the
  330. # order of the arguments.
  331. cache_config = args[1]
  332. parallel_config = args[2]
  333. if parallel_config.tensor_parallel_size == 1:
  334. num_gpus = cache_config.gpu_memory_utilization
  335. else:
  336. num_gpus = 1
  337. engine_class = ray.remote(num_gpus=num_gpus)(
  338. self._engine_class).remote
  339. return engine_class(*args, **kwargs)
  340. async def engine_step(self) -> bool:
  341. """Kick the engine to process the waiting requests.
  342. Returns True if there are in-progress requests."""
  343. new_requests, finished_requests = (
  344. self._request_tracker.get_new_and_finished_requests())
  345. for new_request in new_requests:
  346. # Add the request into the Aphrodite engine's waiting queue.
  347. # TODO: Maybe add add_request_batch to reduce Ray overhead
  348. try:
  349. if self.engine_use_ray:
  350. await self.engine.add_request.remote(**new_request)
  351. else:
  352. await self.engine.add_request_async(**new_request)
  353. except ValueError as e:
  354. # TODO: use an Aphrodite specific error for failed validation
  355. self._request_tracker.process_exception(
  356. new_request["request_id"],
  357. e,
  358. verbose=self.log_requests,
  359. )
  360. if finished_requests:
  361. await self._engine_abort(finished_requests)
  362. if self.engine_use_ray:
  363. request_outputs = await self.engine.step.remote()
  364. else:
  365. request_outputs = await self.engine.step_async()
  366. # Put the outputs into the corresponding streams.
  367. for request_output in request_outputs:
  368. self._request_tracker.process_request_output(
  369. request_output, verbose=self.log_requests)
  370. return len(request_outputs) > 0
  371. async def _engine_abort(self, request_ids: Iterable[str]):
  372. if self.engine_use_ray:
  373. await self.engine.abort_request.remote(request_ids)
  374. else:
  375. self.engine.abort_request(request_ids)
  376. async def run_engine_loop(self):
  377. has_requests_in_progress = False
  378. while True:
  379. if not has_requests_in_progress:
  380. logger.debug("Waiting for new requests...")
  381. await self._request_tracker.wait_for_new_requests()
  382. logger.debug("Got new requests!")
  383. # Abort if iteration takes too long due to unrecoverable errors
  384. # (eg. NCCL timeouts).
  385. try:
  386. has_requests_in_progress = await asyncio.wait_for(
  387. self.engine_step(), ENGINE_ITERATION_TIMEOUT_S)
  388. except asyncio.TimeoutError as exc:
  389. logger.error(
  390. "Engine iteration timed out. This should never happen!")
  391. self.set_errored(exc)
  392. raise
  393. await asyncio.sleep(0)
  394. async def add_request(
  395. self,
  396. request_id: str,
  397. prompt: Optional[str],
  398. sampling_params: SamplingParams,
  399. prompt_token_ids: Optional[List[int]] = None,
  400. arrival_time: Optional[float] = None,
  401. lora_request: Optional[LoRARequest] = None,
  402. ) -> AsyncStream:
  403. if self.log_requests:
  404. shortened_prompt = prompt
  405. shortened_token_ids = prompt_token_ids
  406. if self.max_log_len is not None:
  407. if shortened_prompt is not None:
  408. shortened_prompt = shortened_prompt[:self.max_log_len]
  409. if shortened_token_ids is not None:
  410. shortened_token_ids = shortened_token_ids[:self.
  411. max_log_len]
  412. logger.info(f"Received request {request_id}: "
  413. f"prompt: {shortened_prompt!r}, "
  414. f"sampling params: {sampling_params}, "
  415. f"prompt token ids: {shortened_token_ids}, "
  416. f"lora_request: {lora_request}.")
  417. if not self.is_running:
  418. if self.start_engine_loop:
  419. self.start_background_loop()
  420. else:
  421. raise AsyncEngineDeadError(
  422. "Background loop is not running. If it was running, "
  423. "inspect the output to find the stacktrace of the "
  424. "error that caused the background loop to stop "
  425. "(AsyncEngineDeadError).")
  426. if arrival_time is None:
  427. arrival_time = time.time()
  428. if self.engine_use_ray:
  429. prompt_token_ids = await self.engine.encode_request_async.remote(
  430. request_id=request_id,
  431. prompt=prompt,
  432. prompt_token_ids=prompt_token_ids,
  433. lora_request=lora_request)
  434. else:
  435. prompt_token_ids = await self.engine.encode_request_async(
  436. request_id=request_id,
  437. prompt=prompt,
  438. prompt_token_ids=prompt_token_ids,
  439. lora_request=lora_request)
  440. stream = self._request_tracker.add_request(
  441. request_id,
  442. prompt=prompt,
  443. sampling_params=sampling_params,
  444. prompt_token_ids=prompt_token_ids,
  445. arrival_time=arrival_time,
  446. lora_request=lora_request)
  447. return stream
  448. async def generate(
  449. self,
  450. prompt: Optional[str],
  451. sampling_params: SamplingParams,
  452. request_id: str,
  453. prompt_token_ids: Optional[List[int]] = None,
  454. lora_request: Optional[LoRARequest] = None,
  455. ) -> AsyncIterator[RequestOutput]:
  456. """Generate outputs for a request.
  457. Generate outputs for a request. This method is a coroutine. It adds the
  458. request into the waiting queue of the AphroditeEngine and streams the
  459. outputs from the AphroditeEngine to the caller.
  460. Args:
  461. prompt: The prompt string. Can be None if prompt_token_ids is
  462. provided.
  463. sampling_params: The sampling parameters of the request.
  464. request_id: The unique id of the request.
  465. prompt_token_ids: The token IDs of the prompt. If None, we
  466. use the tokenizer to convert the prompts to token IDs.
  467. lora_request: LoRA request to use for generation, if any.
  468. Yields:
  469. The output `RequestOutput` objects from the AphroditeEngine for the
  470. request.
  471. Details:
  472. - If the engine is not running, start the background loop,
  473. which iteratively invokes
  474. # pylint: disable=line-too-long
  475. :meth:`~aphrodite.engine.async_llm_engine.AsyncAphrodite.engine_step`
  476. to process the waiting requests.
  477. - Add the request to the engine's `RequestTracker`.
  478. On the next background loop, this request will be sent to
  479. the underlying engine.
  480. Also, a corresponding `AsyncStream` will be created.
  481. - Wait for the request outputs from `AsyncStream` and yield them.
  482. Example:
  483. >>> # Please refer to entrypoints/api_server.py for
  484. >>> # the complete example.
  485. >>>
  486. >>> # initialize the engine and the example input
  487. >>> engine = AsyncAphrodite.from_engine_args(engine_args)
  488. >>> example_input = {
  489. >>> "prompt": "What is LLM?",
  490. >>> "stream": False, # assume the non-streaming case
  491. >>> "temperature": 0.0,
  492. >>> "request_id": 0,
  493. >>> }
  494. >>>
  495. >>> # start the generation
  496. >>> results_generator = engine.generate(
  497. >>> example_input["prompt"],
  498. >>> SamplingParams(temperature=example_input["temperature"]),
  499. >>> example_input["request_id"])
  500. >>>
  501. >>> # get the results
  502. >>> final_output = None
  503. >>> async for request_output in results_generator:
  504. >>> if await request.is_disconnected():
  505. >>> # Abort the request if the client disconnects.
  506. >>> await engine.abort(request_id)
  507. >>> # Return or raise an error
  508. >>> ...
  509. >>> final_output = request_output
  510. >>>
  511. >>> # Process and return the final output
  512. >>> ...
  513. """
  514. # Preprocess the request.
  515. # This should not be used for logging, as it is monotonic time.
  516. arrival_time = time.monotonic()
  517. try:
  518. stream = await self.add_request(request_id,
  519. prompt,
  520. sampling_params,
  521. prompt_token_ids=prompt_token_ids,
  522. arrival_time=arrival_time,
  523. lora_request=lora_request)
  524. async for request_output in stream:
  525. yield request_output
  526. except (Exception, asyncio.CancelledError) as e:
  527. # If there is an exception or coroutine is cancelled, abort the
  528. # request.
  529. self._abort(request_id)
  530. raise e
  531. async def abort(self, request_id: str) -> None:
  532. """Abort a request.
  533. Abort a submitted request. If the request is finished or not found,
  534. this method will be a no-op.
  535. Args:
  536. request_id: The unique id of the request.
  537. """
  538. if not self.is_running:
  539. raise AsyncEngineDeadError(
  540. "Background loop is not running. If it was running, "
  541. "inspect the output to find the stacktrace of the "
  542. "error that caused the background loop to stop "
  543. "(AsyncEngineDeadError).")
  544. return self._abort(request_id)
  545. def _abort(self, request_id: str) -> None:
  546. """Abort a request.
  547. Abort a submitted request. If the request is finished or not found,
  548. this method will be a no-op.
  549. Args:
  550. request_id: The unique id of the request.
  551. """
  552. self._request_tracker.abort_request(request_id,
  553. verbose=self.log_requests)
  554. async def get_model_config(self) -> ModelConfig:
  555. """Get the model configuration of the Aphrodite engine."""
  556. if self.engine_use_ray:
  557. return await self.engine.get_model_config.remote()
  558. else:
  559. return self.engine.get_model_config()
  560. @classmethod
  561. def from_engine_args(cls,
  562. engine_args: AsyncEngineArgs,
  563. start_engine_loop: bool = True) -> "AsyncAphrodite":
  564. """Creates an async LLM engine from the engine arguments."""
  565. # Create the engine configs.
  566. engine_configs = engine_args.create_engine_configs()
  567. parallel_config = engine_configs[2]
  568. # Initialize the cluster.
  569. placement_group = initialize_cluster(parallel_config,
  570. engine_args.engine_use_ray)
  571. # Create the async LLM engine.
  572. engine = cls(parallel_config.worker_use_ray,
  573. engine_args.engine_use_ray,
  574. *engine_configs,
  575. placement_group,
  576. log_requests=not engine_args.disable_log_requests,
  577. log_stats=not engine_args.disable_log_stats,
  578. max_log_len=engine_args.max_log_len,
  579. start_engine_loop=start_engine_loop)
  580. return engine
  581. async def do_log_stats(self) -> None:
  582. if self.engine_use_ray:
  583. await self.engine.do_log_stats.remote()
  584. else:
  585. self.engine.do_log_stats()
  586. async def check_health(self):
  587. """Raises an error if engine is unhealthy."""
  588. t = time.perf_counter()
  589. logger.debug("Starting health check...")
  590. if self.is_stopped:
  591. raise AsyncEngineDeadError("Background loop is stopped.")
  592. if self.engine_use_ray:
  593. try:
  594. await self.engine.check_health.remote()
  595. except ray.exceptions.RayActorError as e:
  596. raise RuntimeError("Engine is dead.") from e
  597. else:
  598. await self.engine.check_health_async()
  599. logger.debug(f"Health check took {time.perf_counter()-t}s")