async_aphrodite.py 42 KB

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