async_aphrodite.py 39 KB

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