async_aphrodite.py 38 KB

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