async_aphrodite.py 39 KB

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