async_aphrodite.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. import asyncio
  2. import os
  3. import time
  4. from functools import partial
  5. from typing import (AsyncIterator, Callable, Dict, Iterable, List, Optional,
  6. Set, Tuple, Type, Union)
  7. from loguru import logger
  8. from transformers import PreTrainedTokenizer
  9. from aphrodite.common.config import DecodingConfig, ModelConfig
  10. from aphrodite.inputs import LLMInputs, PromptInputs
  11. from aphrodite.common.outputs import EmbeddingRequestOutput, RequestOutput
  12. from aphrodite.common.pooling_params import PoolingParams
  13. from aphrodite.common.sampling_params import SamplingParams
  14. from aphrodite.common.sequence import ExecuteModelRequest, SamplerOutput
  15. from aphrodite.engine.aphrodite_engine import AphroditeEngine
  16. from aphrodite.engine.args_tools import AsyncEngineArgs
  17. from aphrodite.engine.async_timeout import asyncio_timeout
  18. from aphrodite.executor.ray_utils import initialize_ray_cluster, ray
  19. from aphrodite.lora.request import LoRARequest
  20. from aphrodite.processing.scheduler import SchedulerOutputs
  21. ENGINE_ITERATION_TIMEOUT_S = int(
  22. os.environ.get("APHRODITE_ENGINE_ITERATION_TIMEOUT_S", "60"))
  23. class AsyncEngineDeadError(RuntimeError):
  24. pass
  25. def _log_task_completion(task: asyncio.Task,
  26. error_callback: Callable[[Exception], None]) -> None:
  27. """This function is only intended for the `engine.run_engine_loop()` task.
  28. In particular, that task runs a `while True` loop that can only exit if
  29. there is an exception.
  30. """
  31. exception = None
  32. try:
  33. return_value = task.result()
  34. raise AssertionError(
  35. f"The engine background task should never finish without an "
  36. f"exception. {return_value}")
  37. except asyncio.exceptions.CancelledError:
  38. # We assume that if the task is cancelled, we are gracefully shutting
  39. # down. This should only happen on program exit.
  40. logger.info("Engine is gracefully shutting down.")
  41. except Exception as e:
  42. exception = e
  43. logger.error("Engine background task failed", exc_info=e)
  44. error_callback(exception)
  45. raise AsyncEngineDeadError(
  46. "Task finished unexpectedly. This should never happen! "
  47. "Please open an issue on Github. See stack trace above for the"
  48. "actual cause.") from e
  49. class AsyncStream:
  50. """A stream of RequestOutputs or EmbeddingRequestOutputs for a request
  51. that can be iterated over asynchronously."""
  52. def __init__(self, request_id: str) -> None:
  53. self.request_id = request_id
  54. self._queue: asyncio.Queue = asyncio.Queue()
  55. self._finished = False
  56. def put(self, item: Union[RequestOutput, EmbeddingRequestOutput,
  57. Exception]) -> None:
  58. if self._finished:
  59. return
  60. self._queue.put_nowait(item)
  61. def finish(self) -> None:
  62. self._queue.put_nowait(StopAsyncIteration())
  63. self._finished = True
  64. @property
  65. def finished(self) -> bool:
  66. return self._finished
  67. def __aiter__(self):
  68. return self
  69. async def __anext__(self) -> Union[RequestOutput, EmbeddingRequestOutput]:
  70. result = await self._queue.get()
  71. if isinstance(result, Exception):
  72. raise result
  73. return result
  74. class RequestTracker:
  75. """Synchronous abstraction for tracking requests."""
  76. def __init__(self) -> None:
  77. self._request_streams: Dict[str, AsyncStream] = {}
  78. self._finished_requests: asyncio.Queue[str] = asyncio.Queue()
  79. self._new_requests: asyncio.Queue[Tuple[AsyncStream,
  80. dict]] = asyncio.Queue()
  81. self.new_requests_event = asyncio.Event()
  82. def __contains__(self, item):
  83. return item in self._request_streams
  84. def __len__(self) -> int:
  85. return len(self._request_streams)
  86. def propagate_exception(self,
  87. exc: Exception,
  88. request_id: Optional[str] = None) -> None:
  89. """Propagate an exception to request streams
  90. (all if request_id is None)."""
  91. if request_id is not None:
  92. self._request_streams[request_id].put(exc)
  93. self.abort_request(request_id)
  94. else:
  95. for rid, stream in self._request_streams.items():
  96. stream.put(exc)
  97. self.abort_request(rid)
  98. def process_request_output(self,
  99. request_output: Union[RequestOutput,
  100. EmbeddingRequestOutput],
  101. *,
  102. verbose: bool = False) -> None:
  103. """Process a request output from the engine."""
  104. request_id = request_output.request_id
  105. self._request_streams[request_id].put(request_output)
  106. if request_output.finished:
  107. if verbose:
  108. logger.info(f"Finished request {request_id}.")
  109. self.abort_request(request_id)
  110. def process_exception(self,
  111. request_id: str,
  112. exception: Exception,
  113. *,
  114. verbose: bool = False) -> None:
  115. """Propagate an exception from the engine."""
  116. self._request_streams[request_id].put(exception)
  117. if verbose:
  118. logger.info(f"Finished request {request_id}.")
  119. self.abort_request(request_id)
  120. def add_request(self, request_id: str,
  121. **engine_add_request_kwargs) -> AsyncStream:
  122. """Add a request to be sent to the engine on the next background
  123. loop iteration."""
  124. if request_id in self._request_streams:
  125. raise KeyError(f"Request {request_id} already exists.")
  126. stream = AsyncStream(request_id)
  127. self._new_requests.put_nowait((stream, {
  128. "request_id": request_id,
  129. **engine_add_request_kwargs
  130. }))
  131. self.new_requests_event.set()
  132. return stream
  133. def abort_request(self, request_id: str, *, verbose: bool = False) -> None:
  134. """Abort a request during next background loop iteration."""
  135. if verbose:
  136. logger.info(f"Aborted request {request_id}.")
  137. self._finished_requests.put_nowait(request_id)
  138. if request_id not in self._request_streams or self._request_streams[
  139. request_id].finished:
  140. # The request has already finished or been aborted.
  141. return
  142. self._request_streams[request_id].finish()
  143. def get_new_and_finished_requests(self) -> Tuple[List[Dict], Set[str]]:
  144. """Get the new requests and finished requests to be
  145. sent to the engine."""
  146. new_requests: List[Dict] = []
  147. finished_requests: Set[str] = set()
  148. while not self._finished_requests.empty():
  149. request_id = self._finished_requests.get_nowait()
  150. finished_requests.add(request_id)
  151. self._request_streams.pop(request_id, None)
  152. while not self._new_requests.empty():
  153. stream, new_request = self._new_requests.get_nowait()
  154. if stream.request_id in finished_requests:
  155. # The request has already been aborted.
  156. stream.finish()
  157. continue
  158. self._request_streams[stream.request_id] = stream
  159. new_requests.append(new_request)
  160. return new_requests, finished_requests
  161. async def wait_for_new_requests(self):
  162. if not self.has_new_requests():
  163. await self.new_requests_event.wait()
  164. self.new_requests_event.clear()
  165. def has_new_requests(self):
  166. return not self._new_requests.empty()
  167. class _AsyncAphrodite(AphroditeEngine):
  168. """Extension of AphroditeEngine to add async methods."""
  169. async def step_async(
  170. self, virtual_engine: int
  171. ) -> List[Union[RequestOutput, EmbeddingRequestOutput]]:
  172. """Performs one decoding iteration and returns newly generated results.
  173. The workers are ran asynchronously if possible.
  174. This function performs one decoding iteration of the engine. It first
  175. schedules the sequences to be executed in the next iteration and the
  176. token blocks to be swapped in/out/copy. Then, it executes the model
  177. and updates the scheduler with the model outputs. Finally, it decodes
  178. the sequences and returns the newly generated results.
  179. """
  180. seq_group_metadata_list, scheduler_outputs = self.scheduler[
  181. virtual_engine].schedule()
  182. finished_requests_ids = self.scheduler[
  183. virtual_engine].get_and_reset_finished_requests_ids()
  184. if not scheduler_outputs.is_empty():
  185. # Execute the model.
  186. execute_model_req = ExecuteModelRequest(
  187. seq_group_metadata_list=seq_group_metadata_list,
  188. blocks_to_swap_in=scheduler_outputs.blocks_to_swap_in,
  189. blocks_to_swap_out=scheduler_outputs.blocks_to_swap_out,
  190. blocks_to_copy=scheduler_outputs.blocks_to_copy,
  191. virtual_engine=virtual_engine,
  192. num_lookahead_slots=scheduler_outputs.num_lookahead_slots,
  193. running_queue_size=scheduler_outputs.running_queue_size,
  194. finished_requests_ids=finished_requests_ids,
  195. )
  196. output = await self.model_executor.execute_model_async(
  197. execute_model_req)
  198. else:
  199. output = []
  200. request_outputs = self._process_model_outputs(
  201. output, scheduler_outputs.scheduled_seq_groups,
  202. scheduler_outputs.ignored_seq_groups, seq_group_metadata_list)
  203. # Log stats.
  204. self.do_log_stats(scheduler_outputs, output)
  205. return request_outputs
  206. async def stop_remote_worker_execution_loop_async(self) -> None:
  207. """Stop the remote worker execution loop."""
  208. await self.model_executor.stop_remote_worker_execution_loop_async()
  209. async def process_model_inputs_async(
  210. self,
  211. request_id: str,
  212. inputs: PromptInputs,
  213. lora_request: Optional[LoRARequest] = None,
  214. ) -> LLMInputs:
  215. if isinstance(inputs, str):
  216. inputs = {"prompt": inputs}
  217. if "prompt_token_ids" not in inputs:
  218. tokenizer = self.get_tokenizer_group("prompts must be None if "
  219. "skip_tokenizer_init is True")
  220. prompt_token_ids = await tokenizer.encode_async(
  221. request_id=request_id,
  222. prompt=inputs["prompt"],
  223. lora_request=lora_request)
  224. else:
  225. prompt_token_ids = inputs["prompt_token_ids"]
  226. llm_inputs = LLMInputs(prompt_token_ids=prompt_token_ids,
  227. prompt=inputs.get("prompt"),
  228. multi_modal_data=inputs.get("multi_modal_data"))
  229. return self.input_processor(llm_inputs)
  230. async def add_request_async(
  231. self,
  232. request_id: str,
  233. inputs: PromptInputs,
  234. params: Union[SamplingParams, PoolingParams],
  235. arrival_time: Optional[float] = None,
  236. lora_request: Optional[LoRARequest] = None,
  237. ) -> None:
  238. if lora_request is not None and not self.lora_config:
  239. raise ValueError(f"Got lora_request {lora_request} but LoRA is "
  240. "not enabled!")
  241. if arrival_time is None:
  242. arrival_time = time.time()
  243. processed_inputs = await self.process_model_inputs_async(
  244. request_id=request_id, inputs=inputs, lora_request=lora_request)
  245. self._add_processed_request(
  246. request_id=request_id,
  247. processed_inputs=processed_inputs,
  248. params=params,
  249. arrival_time=arrival_time,
  250. lora_request=lora_request,
  251. )
  252. async def check_health_async(self) -> None:
  253. if self.tokenizer:
  254. self.tokenizer.check_health()
  255. self.model_executor.check_health()
  256. class AsyncAphrodite:
  257. """An asynchronous wrapper for AphroditeEngine.
  258. This class is used to wrap the AphroditeEngine class to make it
  259. asynchronous. It uses asyncio to create a background loop that keeps
  260. processing incoming requests. The AphroditeEngine is kicked by the
  261. generate method when there are requests in the waiting queue.
  262. The generate method yields the outputs from the AphroditeEngine
  263. to the caller.
  264. NOTE: For the comprehensive list of arguments, see `AphroditeEngine`.
  265. Args:
  266. worker_use_ray: Whether to use Ray for model workers. Required for
  267. distributed execution. Should be the same as
  268. `parallel_config.worker_use_ray`.
  269. engine_use_ray: Whether to make AphroditeEngine a Ray actor. If so, the
  270. async frontend will be executed in a separate process as the
  271. model workers.
  272. log_requests: Whether to log the requests.
  273. max_log_len: Maximum number of prompt characters or prompt ID numbers
  274. being printed in log.
  275. start_engine_loop: If True, the background task to run the engine
  276. will be automatically started in the generate call.
  277. *args: Arguments for AphroditeEngine.
  278. *kwargs: Arguments for AphroditeEngine.
  279. """
  280. _engine_class: Type[_AsyncAphrodite] = _AsyncAphrodite
  281. def __init__(self,
  282. worker_use_ray: bool,
  283. engine_use_ray: bool,
  284. *args,
  285. log_requests: bool = True,
  286. max_log_len: int = 0,
  287. start_engine_loop: bool = True,
  288. **kwargs) -> None:
  289. self.worker_use_ray = worker_use_ray
  290. self.engine_use_ray = engine_use_ray
  291. self.log_requests = log_requests
  292. self.max_log_len = max_log_len
  293. self.engine = self._init_engine(*args, **kwargs)
  294. self.background_loop: Optional[asyncio.Future] = None
  295. # We need to keep a reference to unshielded
  296. # task as well to prevent it from being garbage
  297. # collected
  298. self._background_loop_unshielded: Optional[asyncio.Task] = None
  299. self.start_engine_loop = start_engine_loop
  300. self._errored_with: Optional[BaseException] = None
  301. # Lazy initialized fields
  302. self._request_tracker: RequestTracker
  303. @classmethod
  304. def from_engine_args(
  305. cls,
  306. engine_args: AsyncEngineArgs,
  307. start_engine_loop: bool = True,
  308. ) -> "AsyncAphrodite":
  309. """Creates an async LLM engine from the engine arguments."""
  310. # Create the engine configs.
  311. engine_config = engine_args.create_engine_config()
  312. if engine_args.engine_use_ray:
  313. from aphrodite.executor import ray_utils
  314. ray_utils.assert_ray_available()
  315. distributed_executor_backend = (
  316. engine_config.parallel_config.distributed_executor_backend)
  317. if engine_config.device_config.device_type == "neuron":
  318. from aphrodite.executor.neuron_executor import NeuronExecutorAsync
  319. executor_class = NeuronExecutorAsync
  320. elif engine_config.device_config.device_type == "tpu":
  321. from aphrodite.executor.tpu_executor import TPUExecutorAsync
  322. executor_class = TPUExecutorAsync
  323. elif engine_config.device_config.device_type == "cpu":
  324. from aphrodite.executor.cpu_executor import CPUExecutorAsync
  325. assert distributed_executor_backend is None, (
  326. "Distributed execution is not supported with the CPU backend.")
  327. executor_class = CPUExecutorAsync
  328. elif engine_config.device_config.device_type == "openvino":
  329. assert distributed_executor_backend is None, (
  330. "Distributed execution is not supported with the OpenVINO "
  331. "backend.")
  332. from aphrodite.executor.openvino_executor import \
  333. OpenVINOExecutorAsync
  334. executor_class = OpenVINOExecutorAsync
  335. elif engine_config.device_config.device_type == "xpu":
  336. if distributed_executor_backend is None:
  337. from aphrodite.executor.xpu_executor import XPUExecutorAsync
  338. executor_class = XPUExecutorAsync
  339. elif distributed_executor_backend == "ray":
  340. initialize_ray_cluster(engine_config.parallel_config)
  341. from aphrodite.executor.ray_xpu_executor import \
  342. RayXPUExecutorAsync
  343. executor_class = RayXPUExecutorAsync
  344. else:
  345. raise RuntimeError(
  346. "Unsupported distributed executor backend for XPU.")
  347. elif distributed_executor_backend == "ray":
  348. initialize_ray_cluster(engine_config.parallel_config)
  349. from aphrodite.executor.ray_gpu_executor import RayGPUExecutorAsync
  350. executor_class = RayGPUExecutorAsync
  351. elif distributed_executor_backend == "mp":
  352. from aphrodite.executor.multiproc_gpu_executor import \
  353. MultiprocessingGPUExecutorAsync
  354. executor_class = MultiprocessingGPUExecutorAsync
  355. else:
  356. from aphrodite.executor.gpu_executor import GPUExecutorAsync
  357. executor_class = GPUExecutorAsync
  358. # Create the async LLM engine.
  359. engine = cls(
  360. distributed_executor_backend == "ray",
  361. engine_args.engine_use_ray,
  362. **engine_config.to_dict(),
  363. executor_class=executor_class,
  364. log_requests=not engine_args.disable_log_requests,
  365. log_stats=not engine_args.disable_log_stats,
  366. max_log_len=engine_args.max_log_len,
  367. start_engine_loop=start_engine_loop,
  368. )
  369. return engine
  370. @property
  371. def is_running(self) -> bool:
  372. return (self.background_loop is not None
  373. and self._background_loop_unshielded is not None
  374. and not self._background_loop_unshielded.done())
  375. @property
  376. def is_stopped(self) -> bool:
  377. return self.errored or (self.background_loop is not None and
  378. self._background_loop_unshielded is not None
  379. and self._background_loop_unshielded.done())
  380. @property
  381. def errored(self) -> bool:
  382. return self._errored_with is not None
  383. def set_errored(self, exc: Exception) -> None:
  384. self._errored_with = exc
  385. def _error_callback(self, exc: Exception) -> None:
  386. self.set_errored(exc)
  387. self._request_tracker.propagate_exception(exc)
  388. async def get_tokenizer(self) -> "PreTrainedTokenizer":
  389. if self.engine_use_ray:
  390. return await self.engine.get_tokenizer.remote() # type: ignore
  391. else:
  392. return self.engine.get_tokenizer()
  393. def start_background_loop(self) -> None:
  394. """Start the background loop."""
  395. if self.errored:
  396. raise AsyncEngineDeadError(
  397. "Background loop has errored already.") from self._errored_with
  398. if self.is_running:
  399. raise RuntimeError("Background loop is already running.")
  400. # Initialize the RequestTracker here so it uses the right event loop.
  401. self._request_tracker = RequestTracker()
  402. self._background_loop_unshielded = asyncio.get_event_loop(
  403. ).create_task(self.run_engine_loop())
  404. self._background_loop_unshielded.add_done_callback(
  405. partial(_log_task_completion, error_callback=self._error_callback))
  406. self.background_loop = asyncio.shield(self._background_loop_unshielded)
  407. def _init_engine(self, *args,
  408. **kwargs) -> Union[_AsyncAphrodite, "ray.ObjectRef"]:
  409. if not self.engine_use_ray:
  410. engine_class = self._engine_class
  411. elif self.worker_use_ray:
  412. engine_class = ray.remote(num_cpus=0)(self._engine_class).remote
  413. else:
  414. # FIXME: This is a bit hacky. Be careful when changing the
  415. # order of the arguments.
  416. cache_config = kwargs["cache_config"]
  417. parallel_config = kwargs["parallel_config"]
  418. if (parallel_config.tensor_parallel_size == 1
  419. and parallel_config.pipeline_parallel_size == 1):
  420. num_gpus = cache_config.gpu_memory_utilization
  421. else:
  422. num_gpus = 1
  423. engine_class = ray.remote(num_gpus=num_gpus)(
  424. self._engine_class).remote
  425. return engine_class(*args, **kwargs)
  426. async def engine_step(self, virtual_engine: int) -> bool:
  427. """Kick the engine to process the waiting requests.
  428. Returns True if there are in-progress requests."""
  429. new_requests, finished_requests = (
  430. self._request_tracker.get_new_and_finished_requests())
  431. for new_request in new_requests:
  432. # Add the request into the Aphrodite engine's waiting queue.
  433. # TODO: Maybe add add_request_batch to reduce Ray overhead
  434. try:
  435. if self.engine_use_ray:
  436. await self.engine.add_request.remote( # type: ignore
  437. **new_request)
  438. else:
  439. await self.engine.add_request_async(**new_request)
  440. except ValueError as e:
  441. # TODO: use an Aphrodite specific error for failed validation
  442. self._request_tracker.process_exception(
  443. new_request["request_id"],
  444. e,
  445. verbose=self.log_requests,
  446. )
  447. if finished_requests:
  448. await self._engine_abort(finished_requests)
  449. if self.engine_use_ray:
  450. request_outputs = await self.engine.step.remote() # type: ignore
  451. else:
  452. request_outputs = await self.engine.step_async(virtual_engine)
  453. # Put the outputs into the corresponding streams.
  454. for request_output in request_outputs:
  455. self._request_tracker.process_request_output(
  456. request_output, verbose=self.log_requests)
  457. return len(request_outputs) > 0
  458. async def _engine_abort(self, request_ids: Iterable[str]):
  459. if self.engine_use_ray:
  460. await self.engine.abort_request.remote(request_ids) # type: ignore
  461. else:
  462. self.engine.abort_request(request_ids)
  463. async def run_engine_loop(self):
  464. if self.engine_use_ray:
  465. pipeline_parallel_size = 1 # type: ignore
  466. else:
  467. pipeline_parallel_size = \
  468. self.engine.parallel_config.pipeline_parallel_size
  469. has_requests_in_progress = [False] * pipeline_parallel_size
  470. while True:
  471. if not any(has_requests_in_progress):
  472. logger.debug("Waiting for new requests...")
  473. # Stop the execute model loop in parallel workers until there
  474. # are more requests to process. This avoids waiting
  475. # indefinitely in torch.distributed ops which may otherwise
  476. # timeout, and unblocks the RPC thread in the workers so that
  477. # they can process any other queued control plane messages,
  478. # such as add/remove lora adapters.
  479. if self.engine_use_ray:
  480. await (self.engine.stop_remote_worker_execution_loop.
  481. remote() # type: ignore
  482. )
  483. else:
  484. await self.engine.stop_remote_worker_execution_loop_async()
  485. await self._request_tracker.wait_for_new_requests()
  486. logger.debug("Got new requests!")
  487. requests_in_progress = [
  488. asyncio.create_task(self.engine_step(ve))
  489. for ve in range(pipeline_parallel_size)
  490. ]
  491. has_requests_in_progress = [True] * pipeline_parallel_size
  492. # Abort if iteration takes too long due to unrecoverable errors
  493. # (eg. NCCL timeouts).
  494. try:
  495. async with asyncio_timeout(ENGINE_ITERATION_TIMEOUT_S):
  496. done, _ = await asyncio.wait(
  497. requests_in_progress,
  498. return_when=asyncio.FIRST_COMPLETED)
  499. for _ in range(pipeline_parallel_size):
  500. await asyncio.sleep(0)
  501. for task in done:
  502. result = task.result()
  503. virtual_engine = requests_in_progress.index(task)
  504. if self.engine_use_ray:
  505. has_unfinished_requests = (
  506. await (self.engine.
  507. has_unfinished_requests_for_virtual_engine.
  508. remote( # type: ignore
  509. virtual_engine)))
  510. else:
  511. has_unfinished_requests = (
  512. self.engine.
  513. has_unfinished_requests_for_virtual_engine(
  514. virtual_engine))
  515. if result or has_unfinished_requests:
  516. requests_in_progress[virtual_engine] = (
  517. asyncio.create_task(
  518. self.engine_step(virtual_engine)))
  519. has_requests_in_progress[virtual_engine] = True
  520. else:
  521. has_requests_in_progress[virtual_engine] = False
  522. except asyncio.TimeoutError as exc:
  523. logger.error(
  524. "Engine iteration timed out. This should never happen!")
  525. self.set_errored(exc)
  526. raise
  527. await asyncio.sleep(0)
  528. async def add_request(
  529. self,
  530. request_id: str,
  531. inputs: PromptInputs,
  532. params: Union[SamplingParams, PoolingParams],
  533. arrival_time: Optional[float] = None,
  534. lora_request: Optional[LoRARequest] = None,
  535. ) -> AsyncStream:
  536. if self.log_requests:
  537. if isinstance(inputs, str):
  538. shortened_prompt = inputs
  539. shortened_token_ids = None
  540. else:
  541. shortened_prompt = inputs.get("prompt")
  542. shortened_token_ids = inputs.get("prompt_token_ids")
  543. max_log_len = self.max_log_len
  544. if max_log_len is not None:
  545. if shortened_prompt is not None:
  546. shortened_prompt = shortened_prompt[:max_log_len]
  547. if shortened_token_ids is not None:
  548. shortened_token_ids = shortened_token_ids[:max_log_len]
  549. logger.info(f"Received request {request_id}: "
  550. f"prompt: {shortened_prompt!r}, "
  551. f"params: {params}, "
  552. f"prompt_token_ids: {shortened_token_ids}, "
  553. f"lora_request: {lora_request}.")
  554. if not self.is_running:
  555. if self.start_engine_loop:
  556. self.start_background_loop()
  557. else:
  558. raise AsyncEngineDeadError(
  559. "Background loop is not running. If it was running, "
  560. "inspect the output to find the stacktrace of the "
  561. "error that caused the background loop to stop "
  562. "(AsyncEngineDeadError).")
  563. if arrival_time is None:
  564. arrival_time = time.time()
  565. stream = self._request_tracker.add_request(
  566. request_id,
  567. inputs=inputs,
  568. params=params,
  569. arrival_time=arrival_time,
  570. lora_request=lora_request,
  571. )
  572. return stream
  573. async def generate(
  574. self,
  575. inputs: PromptInputs,
  576. sampling_params: SamplingParams,
  577. request_id: str,
  578. lora_request: Optional[LoRARequest] = None,
  579. ) -> AsyncIterator[RequestOutput]:
  580. """Generate outputs for a request.
  581. Generate outputs for a request. This method is a coroutine. It adds the
  582. request into the waiting queue of the AphroditeEngine and streams the
  583. outputs from the AphroditeEngine to the caller.
  584. Args:
  585. prompt: The prompt string. Can be None if prompt_token_ids is
  586. provided.
  587. sampling_params: The sampling parameters of the request.
  588. request_id: The unique id of the request.
  589. prompt_token_ids: The token IDs of the prompt. If None, we
  590. use the tokenizer to convert the prompts to token IDs.
  591. lora_request: LoRA request to use for generation, if any.
  592. multi_modal_data: Multi modal data per request.
  593. Yields:
  594. The output `RequestOutput` objects from the LLMEngine
  595. for the request.
  596. Details:
  597. - If the engine is not running, start the background loop,
  598. which iteratively invokes
  599. # pylint: disable=line-too-long
  600. :meth:`~aphrodite.engine.async_aphrodite.AsyncAphrodite.engine_step`
  601. to process the waiting requests.
  602. - Add the request to the engine's `RequestTracker`.
  603. On the next background loop, this request will be sent to
  604. the underlying engine.
  605. Also, a corresponding `AsyncStream` will be created.
  606. - Wait for the request outputs from `AsyncStream` and yield them.
  607. Example:
  608. >>> # Please refer to entrypoints/api_server.py for
  609. >>> # the complete example.
  610. >>>
  611. >>> # initialize the engine and the example input
  612. >>> engine = AsyncAphrodite.from_engine_args(engine_args)
  613. >>> example_input = {
  614. >>> "prompt": "What is LLM?",
  615. >>> "stream": False, # assume the non-streaming case
  616. >>> "temperature": 0.0,
  617. >>> "request_id": 0,
  618. >>> }
  619. >>>
  620. >>> # start the generation
  621. >>> results_generator = engine.generate(
  622. >>> example_input["prompt"],
  623. >>> SamplingParams(temperature=example_input["temperature"]),
  624. >>> example_input["request_id"])
  625. >>>
  626. >>> # get the results
  627. >>> final_output = None
  628. >>> async for request_output in results_generator:
  629. >>> if await request.is_disconnected():
  630. >>> # Abort the request if the client disconnects.
  631. >>> await engine.abort(request_id)
  632. >>> # Return or raise an error
  633. >>> ...
  634. >>> final_output = request_output
  635. >>>
  636. >>> # Process and return the final output
  637. >>> ...
  638. """
  639. async for output in self._process_request(
  640. request_id,
  641. inputs,
  642. sampling_params,
  643. lora_request=lora_request,
  644. ):
  645. yield AphroditeEngine.validate_output(output, RequestOutput)
  646. async def encode(
  647. self,
  648. inputs: PromptInputs,
  649. pooling_params: PoolingParams,
  650. request_id: str,
  651. lora_request: Optional[LoRARequest] = None,
  652. ) -> AsyncIterator[EmbeddingRequestOutput]:
  653. """Generate outputs for a request from an embedding model.
  654. Generate outputs for a request. This method is a coroutine. It adds the
  655. request into the waiting queue of the LLMEngine and streams the outputs
  656. from the LLMEngine to the caller.
  657. Args:
  658. prompt: The prompt string. Can be None if prompt_token_ids is
  659. provided.
  660. pooling_params: The pooling parameters of the request.
  661. request_id: The unique id of the request.
  662. prompt_token_ids: The token IDs of the prompt. If None, we
  663. use the tokenizer to convert the prompts to token IDs.
  664. lora_request: LoRA request to use for generation, if any.
  665. multi_modal_data: Multi modal data per request.
  666. Yields:
  667. The output `EmbeddingRequestOutput` objects from the LLMEngine
  668. for the request.
  669. Details:
  670. - If the engine is not running, start the background loop,
  671. which iteratively invokes
  672. :meth:`~aphrodite.engine.async_aphrodite.AsyncAphrodite.engine_step`
  673. to process the waiting requests.
  674. - Add the request to the engine's `RequestTracker`.
  675. On the next background loop, this request will be sent to
  676. the underlying engine.
  677. Also, a corresponding `AsyncStream` will be created.
  678. - Wait for the request outputs from `AsyncStream` and yield them.
  679. Example:
  680. >>> # initialize the engine and the example input
  681. >>> engine = AsyncAphrodite.from_engine_args(engine_args)
  682. >>> example_input = {
  683. >>> "input": "What is LLM?",
  684. >>> "request_id": 0,
  685. >>> }
  686. >>>
  687. >>> # start the generation
  688. >>> results_generator = engine.encode(
  689. >>> example_input["input"],
  690. >>> PoolingParams(),
  691. >>> example_input["request_id"])
  692. >>>
  693. >>> # get the results
  694. >>> final_output = None
  695. >>> async for request_output in results_generator:
  696. >>> if await request.is_disconnected():
  697. >>> # Abort the request if the client disconnects.
  698. >>> await engine.abort(request_id)
  699. >>> # Return or raise an error
  700. >>> ...
  701. >>> final_output = request_output
  702. >>>
  703. >>> # Process and return the final output
  704. >>> ...
  705. """
  706. async for output in self._process_request(
  707. request_id,
  708. inputs,
  709. pooling_params,
  710. lora_request=lora_request,
  711. ):
  712. yield AphroditeEngine.validate_output(output,
  713. EmbeddingRequestOutput)
  714. async def _process_request(
  715. self,
  716. request_id: str,
  717. inputs: PromptInputs,
  718. params: Union[SamplingParams, PoolingParams],
  719. *,
  720. lora_request: Optional[LoRARequest] = None,
  721. ) -> AsyncIterator[Union[RequestOutput, EmbeddingRequestOutput]]:
  722. """Common logic to process requests with SamplingParams or
  723. PoolingParams."""
  724. arrival_time = time.time()
  725. stream = await self.add_request(
  726. request_id,
  727. inputs,
  728. params,
  729. arrival_time=arrival_time,
  730. lora_request=lora_request,
  731. )
  732. try:
  733. async for request_output in stream:
  734. yield request_output
  735. except (Exception, asyncio.CancelledError) as e:
  736. self._abort(request_id)
  737. raise e
  738. async def abort(self, request_id: str) -> None:
  739. """Abort a request.
  740. Abort a submitted request. If the request is finished or not found,
  741. this method will be a no-op.
  742. Args:
  743. request_id: The unique id of the request.
  744. """
  745. if not self.is_running:
  746. raise AsyncEngineDeadError(
  747. "Background loop is not running. If it was running, "
  748. "inspect the output to find the stacktrace of the "
  749. "error that caused the background loop to stop "
  750. "(AsyncEngineDeadError).")
  751. return self._abort(request_id)
  752. def _abort(self, request_id: str) -> None:
  753. """Abort a request.
  754. Abort a submitted request. If the request is finished or not found,
  755. this method will be a no-op.
  756. Args:
  757. request_id: The unique id of the request.
  758. """
  759. self._request_tracker.abort_request(request_id,
  760. verbose=self.log_requests)
  761. async def get_model_config(self) -> ModelConfig:
  762. """Get the model configuration of the Aphrodite engine."""
  763. if self.engine_use_ray:
  764. return await self.engine.get_model_config.remote() # type: ignore
  765. else:
  766. return self.engine.get_model_config()
  767. async def get_decoding_config(self) -> DecodingConfig:
  768. """Get the decoding configuration of the Aphrodite engine."""
  769. if self.engine_use_ray:
  770. return await self.engine.get_decoding_config.remote( # type: ignore
  771. )
  772. else:
  773. return self.engine.get_decoding_config()
  774. async def do_log_stats(
  775. self,
  776. scheduler_outputs: Optional[SchedulerOutputs] = None,
  777. model_output: Optional[List[SamplerOutput]] = None) -> None:
  778. if self.engine_use_ray:
  779. await self.engine.do_log_stats.remote( # type: ignore
  780. scheduler_outputs, model_output)
  781. else:
  782. self.engine.do_log_stats()
  783. async def check_health(self) -> None:
  784. """Raises an error if engine is unhealthy."""
  785. t = time.perf_counter()
  786. logger.debug("Starting health check...")
  787. if self.is_stopped:
  788. raise AsyncEngineDeadError("Background loop is stopped.")
  789. if self.engine_use_ray:
  790. try:
  791. await self.engine.check_health.remote() # type: ignore
  792. except ray.exceptions.RayActorError as e:
  793. raise RuntimeError("Engine is dead.") from e
  794. else:
  795. await self.engine.check_health_async()
  796. logger.debug(f"Health check took {time.perf_counter()-t}s")