async_aphrodite.py 27 KB

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