async_aphrodite.py 28 KB

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