async_aphrodite.py 39 KB

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