async_aphrodite.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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. scheduler_outputs.num_lookahead_slots)
  177. else:
  178. output = []
  179. request_outputs = self._process_model_outputs(
  180. output, scheduler_outputs.scheduled_seq_groups,
  181. scheduler_outputs.ignored_seq_groups)
  182. # Log stats.
  183. if self.log_stats:
  184. self.stat_logger.log(self._get_stats(scheduler_outputs))
  185. return request_outputs
  186. async def encode_request_async(
  187. self,
  188. request_id: str, # pylint: disable=unused-argument
  189. prompt: Optional[str],
  190. prompt_token_ids: Optional[List[int]] = None,
  191. lora_request: Optional[LoRARequest] = None,
  192. ):
  193. if prompt_token_ids is None:
  194. assert prompt is not None
  195. prompt_token_ids = await self.tokenizer.encode_async(
  196. request_id=request_id,
  197. prompt=prompt,
  198. lora_request=lora_request)
  199. return prompt_token_ids
  200. async def add_request_async(
  201. self,
  202. request_id: str,
  203. prompt: Optional[str],
  204. sampling_params: SamplingParams,
  205. prompt_token_ids: Optional[List[int]] = None,
  206. arrival_time: Optional[float] = None,
  207. lora_request: Optional[LoRARequest] = None,
  208. multi_modal_data: Optional[MultiModalData] = None,
  209. ) -> None:
  210. if lora_request is not None and not self.lora_config:
  211. raise ValueError(f"Got lora_request {lora_request} but LoRA is "
  212. "not enabled!")
  213. if arrival_time is None:
  214. arrival_time = time.time()
  215. prompt_token_ids = await self.encode_request_async(
  216. request_id=request_id,
  217. prompt=prompt,
  218. prompt_token_ids=prompt_token_ids,
  219. lora_request=lora_request)
  220. return self.add_request(request_id,
  221. prompt=prompt,
  222. prompt_token_ids=prompt_token_ids,
  223. sampling_params=sampling_params,
  224. arrival_time=arrival_time,
  225. lora_request=lora_request,
  226. multi_modal_data=multi_modal_data)
  227. async def check_health_async(self) -> None:
  228. self.model_executor.check_health()
  229. class AsyncAphrodite:
  230. """An asynchronous wrapper for AphroditeEngine.
  231. This class is used to wrap the AphroditeEngine class to make it
  232. asynchronous. It uses asyncio to create a background loop that keeps
  233. processing incoming requests. The AphroditeEngine is kicked by the
  234. generate method when there are requests in the waiting queue.
  235. The generate method yields the outputs from the AphroditeEngine
  236. to the caller.
  237. NOTE: For the comprehensive list of arguments, see `AphroditeEngine`.
  238. Args:
  239. worker_use_ray: Whether to use Ray for model workers. Required for
  240. distributed execution. Should be the same as
  241. `parallel_config.worker_use_ray`.
  242. engine_use_ray: Whether to make AphroditeEngine a Ray actor. If so, the
  243. async frontend will be executed in a separate process as the
  244. model workers.
  245. log_requests: Whether to log the requests.
  246. max_log_len: Maximum number of prompt characters or prompt ID numbers
  247. being printed in log.
  248. start_engine_loop: If True, the background task to run the engine
  249. will be automatically started in the generate call.
  250. *args: Arguments for AphroditeEngine.
  251. *kwargs: Arguments for AphroditeEngine.
  252. """
  253. _engine_class: Type[_AsyncAphrodite] = _AsyncAphrodite
  254. def __init__(self,
  255. worker_use_ray: bool,
  256. engine_use_ray: bool,
  257. *args,
  258. log_requests: bool = True,
  259. max_log_len: int = 0,
  260. start_engine_loop: bool = True,
  261. **kwargs) -> None:
  262. self.worker_use_ray = worker_use_ray
  263. self.engine_use_ray = engine_use_ray
  264. self.log_requests = log_requests
  265. self.max_log_len = max_log_len
  266. self.engine = self._init_engine(*args, **kwargs)
  267. self.background_loop = None
  268. # We need to keep a reference to unshielded
  269. # task as well to prevent it from being garbage
  270. # collected
  271. self._background_loop_unshielded = None
  272. self.start_engine_loop = start_engine_loop
  273. self._request_tracker: Optional[RequestTracker] = None
  274. self._errored_with: Optional[BaseException] = None
  275. @classmethod
  276. def from_engine_args(cls,
  277. engine_args: AsyncEngineArgs,
  278. start_engine_loop: bool = True) -> "AsyncAphrodite":
  279. """Creates an async LLM engine from the engine arguments."""
  280. # Create the engine configs.
  281. engine_config = engine_args.create_engine_config()
  282. if engine_config.device_config.device_type == "neuron":
  283. raise NotImplementedError("Neuron is not supported for "
  284. "async engine yet.")
  285. elif engine_config.device_config.device_type == "cpu":
  286. from aphrodite.executor.cpu_executor import CPUExecutor
  287. executor_class = CPUExecutor
  288. elif engine_config.parallel_config.worker_use_ray:
  289. initialize_ray_cluster(engine_config.parallel_config)
  290. from aphrodite.executor.ray_gpu_executor import RayGPUExecutorAsync
  291. executor_class = RayGPUExecutorAsync
  292. else:
  293. assert engine_config.parallel_config.world_size == 1, (
  294. "Ray is required if parallel_config.world_size > 1.")
  295. from aphrodite.executor.gpu_executor import GPUExecutorAsync
  296. executor_class = GPUExecutorAsync
  297. # Create the async LLM engine.
  298. engine = cls(engine_config.parallel_config.worker_use_ray,
  299. engine_args.engine_use_ray,
  300. **engine_config.to_dict(),
  301. executor_class=executor_class,
  302. log_requests=not engine_args.disable_log_requests,
  303. log_stats=not engine_args.disable_log_stats,
  304. max_log_len=engine_args.max_log_len,
  305. start_engine_loop=start_engine_loop)
  306. return engine
  307. @property
  308. def is_running(self) -> bool:
  309. return (self.background_loop is not None
  310. and not self._background_loop_unshielded.done())
  311. @property
  312. def is_stopped(self) -> bool:
  313. return self.errored or (self.background_loop is not None
  314. and self._background_loop_unshielded.done())
  315. @property
  316. def errored(self) -> bool:
  317. return self._errored_with is not None
  318. def set_errored(self, exc: Exception) -> None:
  319. self._errored_with = exc
  320. def _error_callback(self, exc: Exception) -> None:
  321. self.set_errored(exc)
  322. self._request_tracker.propagate_exception(exc)
  323. async def get_tokenizer(self) -> "PreTrainedTokenizer":
  324. if self.engine_use_ray:
  325. return await self.engine.get_tokenizer.remote()
  326. else:
  327. return self.engine.get_tokenizer()
  328. def start_background_loop(self) -> None:
  329. """Start the background loop."""
  330. if self.errored:
  331. raise AsyncEngineDeadError(
  332. "Background loop has errored already.") from self._errored_with
  333. if self.is_running:
  334. raise RuntimeError("Background loop is already running.")
  335. # Initialize the RequestTracker here so it uses the right event loop.
  336. self._request_tracker = RequestTracker()
  337. self._background_loop_unshielded = asyncio.get_event_loop(
  338. ).create_task(self.run_engine_loop())
  339. self._background_loop_unshielded.add_done_callback(
  340. partial(_raise_exception_on_finish,
  341. error_callback=self._error_callback))
  342. self.background_loop = asyncio.shield(self._background_loop_unshielded)
  343. def _init_engine(self, *args,
  344. **kwargs) -> Union[_AsyncAphrodite, "ray.ObjectRef"]:
  345. if not self.engine_use_ray:
  346. engine_class = self._engine_class
  347. elif self.worker_use_ray:
  348. engine_class = ray.remote(num_cpus=0)(self._engine_class).remote
  349. else:
  350. # FIXME: This is a bit hacky. Be careful when changing the
  351. # order of the arguments.
  352. cache_config = kwargs["cache_config"]
  353. parallel_config = kwargs["parallel_config"]
  354. if parallel_config.tensor_parallel_size == 1:
  355. num_gpus = cache_config.gpu_memory_utilization
  356. else:
  357. num_gpus = 1
  358. engine_class = ray.remote(num_gpus=num_gpus)(
  359. self._engine_class).remote
  360. return engine_class(*args, **kwargs)
  361. async def engine_step(self) -> bool:
  362. """Kick the engine to process the waiting requests.
  363. Returns True if there are in-progress requests."""
  364. new_requests, finished_requests = (
  365. self._request_tracker.get_new_and_finished_requests())
  366. for new_request in new_requests:
  367. # Add the request into the Aphrodite engine's waiting queue.
  368. # TODO: Maybe add add_request_batch to reduce Ray overhead
  369. try:
  370. if self.engine_use_ray:
  371. await self.engine.add_request.remote(**new_request)
  372. else:
  373. await self.engine.add_request_async(**new_request)
  374. except ValueError as e:
  375. # TODO: use an Aphrodite specific error for failed validation
  376. self._request_tracker.process_exception(
  377. new_request["request_id"],
  378. e,
  379. verbose=self.log_requests,
  380. )
  381. if finished_requests:
  382. await self._engine_abort(finished_requests)
  383. if self.engine_use_ray:
  384. request_outputs = await self.engine.step.remote()
  385. else:
  386. request_outputs = await self.engine.step_async()
  387. # Put the outputs into the corresponding streams.
  388. for request_output in request_outputs:
  389. self._request_tracker.process_request_output(
  390. request_output, verbose=self.log_requests)
  391. return len(request_outputs) > 0
  392. async def _engine_abort(self, request_ids: Iterable[str]):
  393. if self.engine_use_ray:
  394. await self.engine.abort_request.remote(request_ids)
  395. else:
  396. self.engine.abort_request(request_ids)
  397. async def run_engine_loop(self):
  398. has_requests_in_progress = False
  399. try:
  400. while True:
  401. if not has_requests_in_progress:
  402. logger.debug("Waiting for new requests...")
  403. await self._request_tracker.wait_for_new_requests()
  404. logger.debug("Got new requests!")
  405. # Abort if iteration takes too long due to unrecoverable errors
  406. # (eg. NCCL timeouts).
  407. try:
  408. has_requests_in_progress = await asyncio.wait_for(
  409. self.engine_step(), ENGINE_ITERATION_TIMEOUT_S)
  410. except asyncio.TimeoutError as exc:
  411. logger.error(
  412. "Engine iteration timed out. This should never happen!"
  413. )
  414. self.set_errored(exc)
  415. raise
  416. await asyncio.sleep(0)
  417. except KeyboardInterrupt:
  418. logger.info("Engine loop interrupted. Exiting gracefully.")
  419. async def add_request(
  420. self,
  421. request_id: str,
  422. prompt: Optional[str],
  423. sampling_params: SamplingParams,
  424. prompt_token_ids: Optional[List[int]] = None,
  425. arrival_time: Optional[float] = None,
  426. lora_request: Optional[LoRARequest] = None,
  427. ) -> AsyncStream:
  428. if self.log_requests:
  429. shortened_prompt = prompt
  430. shortened_token_ids = prompt_token_ids
  431. if self.max_log_len is not None:
  432. if shortened_prompt is not None:
  433. shortened_prompt = shortened_prompt[:self.max_log_len]
  434. if shortened_token_ids is not None:
  435. shortened_token_ids = shortened_token_ids[:self.
  436. max_log_len]
  437. logger.info(f"Received request {request_id}: "
  438. f"prompt: {shortened_prompt!r}, "
  439. f"sampling_params: {sampling_params}, "
  440. f"lora_request: {lora_request}.")
  441. if not self.is_running:
  442. if self.start_engine_loop:
  443. self.start_background_loop()
  444. else:
  445. raise AsyncEngineDeadError(
  446. "Background loop is not running. If it was running, "
  447. "inspect the output to find the stacktrace of the "
  448. "error that caused the background loop to stop "
  449. "(AsyncEngineDeadError).")
  450. if arrival_time is None:
  451. arrival_time = time.time()
  452. if self.engine_use_ray:
  453. prompt_token_ids = await self.engine.encode_request_async.remote(
  454. request_id=request_id,
  455. prompt=prompt,
  456. prompt_token_ids=prompt_token_ids,
  457. lora_request=lora_request)
  458. else:
  459. prompt_token_ids = await self.engine.encode_request_async(
  460. request_id=request_id,
  461. prompt=prompt,
  462. prompt_token_ids=prompt_token_ids,
  463. lora_request=lora_request)
  464. stream = self._request_tracker.add_request(
  465. request_id,
  466. prompt=prompt,
  467. sampling_params=sampling_params,
  468. prompt_token_ids=prompt_token_ids,
  469. arrival_time=arrival_time,
  470. lora_request=lora_request)
  471. return stream
  472. async def generate(
  473. self,
  474. prompt: Optional[str],
  475. sampling_params: SamplingParams,
  476. request_id: str,
  477. prompt_token_ids: Optional[List[int]] = None,
  478. lora_request: Optional[LoRARequest] = None,
  479. ) -> AsyncIterator[RequestOutput]:
  480. """Generate outputs for a request.
  481. Generate outputs for a request. This method is a coroutine. It adds the
  482. request into the waiting queue of the AphroditeEngine and streams the
  483. outputs from the AphroditeEngine to the caller.
  484. Args:
  485. prompt: The prompt string. Can be None if prompt_token_ids is
  486. provided.
  487. sampling_params: The sampling parameters of the request.
  488. request_id: The unique id of the request.
  489. prompt_token_ids: The token IDs of the prompt. If None, we
  490. use the tokenizer to convert the prompts to token IDs.
  491. lora_request: LoRA request to use for generation, if any.
  492. Yields:
  493. The output `RequestOutput` objects from the AphroditeEngine for the
  494. request.
  495. Details:
  496. - If the engine is not running, start the background loop,
  497. which iteratively invokes
  498. # pylint: disable=line-too-long
  499. :meth:`~aphrodite.engine.async_aphrodite.AsyncAphrodite.engine_step`
  500. to process the waiting requests.
  501. - Add the request to the engine's `RequestTracker`.
  502. On the next background loop, this request will be sent to
  503. the underlying engine.
  504. Also, a corresponding `AsyncStream` will be created.
  505. - Wait for the request outputs from `AsyncStream` and yield them.
  506. Example:
  507. >>> # Please refer to entrypoints/api_server.py for
  508. >>> # the complete example.
  509. >>>
  510. >>> # initialize the engine and the example input
  511. >>> engine = AsyncAphrodite.from_engine_args(engine_args)
  512. >>> example_input = {
  513. >>> "prompt": "What is LLM?",
  514. >>> "stream": False, # assume the non-streaming case
  515. >>> "temperature": 0.0,
  516. >>> "request_id": 0,
  517. >>> }
  518. >>>
  519. >>> # start the generation
  520. >>> results_generator = engine.generate(
  521. >>> example_input["prompt"],
  522. >>> SamplingParams(temperature=example_input["temperature"]),
  523. >>> example_input["request_id"])
  524. >>>
  525. >>> # get the results
  526. >>> final_output = None
  527. >>> async for request_output in results_generator:
  528. >>> if await request.is_disconnected():
  529. >>> # Abort the request if the client disconnects.
  530. >>> await engine.abort(request_id)
  531. >>> # Return or raise an error
  532. >>> ...
  533. >>> final_output = request_output
  534. >>>
  535. >>> # Process and return the final output
  536. >>> ...
  537. """
  538. # Preprocess the request.
  539. # This should not be used for logging, as it is monotonic time.
  540. arrival_time = time.monotonic()
  541. try:
  542. stream = await self.add_request(
  543. request_id,
  544. prompt,
  545. sampling_params,
  546. prompt_token_ids=prompt_token_ids,
  547. arrival_time=arrival_time,
  548. lora_request=lora_request,
  549. )
  550. async for request_output in stream:
  551. yield request_output
  552. except asyncio.exceptions.CancelledError:
  553. logger.info(f"Request {request_id} cancelled.")
  554. self._abort(request_id)
  555. raise
  556. except (Exception, asyncio.CancelledError) as e:
  557. # If there is an exception or coroutine is cancelled, abort the
  558. # request.
  559. self._abort(request_id)
  560. raise e
  561. async def abort(self, request_id: str) -> None:
  562. """Abort a request.
  563. Abort a submitted request. If the request is finished or not found,
  564. this method will be a no-op.
  565. Args:
  566. request_id: The unique id of the request.
  567. """
  568. if not self.is_running:
  569. raise AsyncEngineDeadError(
  570. "Background loop is not running. If it was running, "
  571. "inspect the output to find the stacktrace of the "
  572. "error that caused the background loop to stop "
  573. "(AsyncEngineDeadError).")
  574. return self._abort(request_id)
  575. def _abort(self, request_id: str) -> None:
  576. """Abort a request.
  577. Abort a submitted request. If the request is finished or not found,
  578. this method will be a no-op.
  579. Args:
  580. request_id: The unique id of the request.
  581. """
  582. self._request_tracker.abort_request(request_id,
  583. verbose=self.log_requests)
  584. async def get_model_config(self) -> ModelConfig:
  585. """Get the model configuration of the Aphrodite engine."""
  586. if self.engine_use_ray:
  587. return await self.engine.get_model_config.remote()
  588. else:
  589. return self.engine.get_model_config()
  590. async def do_log_stats(self) -> None:
  591. if self.engine_use_ray:
  592. await self.engine.do_log_stats.remote()
  593. else:
  594. self.engine.do_log_stats()
  595. async def check_health(self) -> None:
  596. """Raises an error if engine is unhealthy."""
  597. t = time.perf_counter()
  598. logger.debug("Starting health check...")
  599. if self.is_stopped:
  600. raise AsyncEngineDeadError("Background loop is stopped.")
  601. if self.engine_use_ray:
  602. try:
  603. await self.engine.check_health.remote()
  604. except ray.exceptions.RayActorError as e:
  605. raise RuntimeError("Engine is dead.") from e
  606. else:
  607. await self.engine.check_health_async()
  608. logger.debug(f"Health check took {time.perf_counter()-t}s")