async_aphrodite.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. import asyncio
  2. import time
  3. from functools import partial
  4. from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Type, Union
  5. from aphrodite.common.config import ModelConfig
  6. from aphrodite.engine.args_tools import AsyncEngineArgs
  7. from aphrodite.engine.aphrodite_engine import AphroditeEngine
  8. from aphrodite.engine.ray_tools import initialize_cluster, ray
  9. from aphrodite.common.logger import init_logger
  10. from aphrodite.common.outputs import RequestOutput
  11. from aphrodite.common.sampling_params import SamplingParams
  12. logger = init_logger(__name__)
  13. class AsyncEngineDeadError(RuntimeError):
  14. pass
  15. def _raise_exception_on_finish(task: asyncio.Task,
  16. request_tracker: "RequestTracker") -> None:
  17. msg = ("Task finished unexpectedly. This should never happen! "
  18. "Please open an issue on Github.")
  19. try:
  20. try:
  21. task.result()
  22. except asyncio.CancelledError:
  23. return
  24. except Exception as exc:
  25. raise AsyncEngineDeadError(
  26. msg + " See stack trace above for the actual cause.") from exc
  27. raise AsyncEngineDeadError(msg)
  28. except Exception as exc:
  29. request_tracker.propagate_exception(exc)
  30. raise exc
  31. class AsyncStream:
  32. """A stream of RequestOutputs for a request that can be
  33. iterated over asynchronously."""
  34. def __init__(self, request_id: str) -> None:
  35. self.request_id = request_id
  36. self._queue = asyncio.Queue()
  37. self._finished = False
  38. def put(self, item: RequestOutput) -> None:
  39. if self._finished:
  40. return
  41. self._queue.put_nowait(item)
  42. def finish(self) -> None:
  43. self._queue.put_nowait(StopIteration)
  44. self._finished = True
  45. @property
  46. def finished(self) -> bool:
  47. return self._finished
  48. def __aiter__(self):
  49. return self
  50. async def __anext__(self) -> RequestOutput:
  51. result = await self._queue.get()
  52. if result is StopIteration:
  53. raise StopAsyncIteration
  54. elif isinstance(result, Exception):
  55. raise result
  56. return result
  57. class RequestTracker:
  58. """Synchronous abstraction for tracking requests."""
  59. def __init__(self) -> None:
  60. self._request_streams: Dict[str, AsyncStream] = {}
  61. self._finished_requests: asyncio.Queue[str] = asyncio.Queue()
  62. self._new_requests: asyncio.Queue[Tuple[AsyncStream,
  63. dict]] = asyncio.Queue()
  64. self.new_requests_event = None
  65. def __contains__(self, item):
  66. return item in self._request_streams
  67. def init_event(self):
  68. self.new_requests_event = asyncio.Event()
  69. def propagate_exception(self,
  70. exc: Exception,
  71. request_id: Optional[str] = None) -> None:
  72. """Propagate an exception to request streams
  73. (all if request_id is None)."""
  74. if request_id is not None:
  75. self._request_streams[request_id].put(exc)
  76. else:
  77. for stream in self._request_streams.values():
  78. stream.put(exc)
  79. def process_request_output(self,
  80. request_output: RequestOutput,
  81. *,
  82. verbose: bool = False) -> None:
  83. """Process a request output from the engine."""
  84. request_id = request_output.request_id
  85. self._request_streams[request_id].put(request_output)
  86. if request_output.finished:
  87. if verbose:
  88. logger.info(f"Finished request {request_id}.")
  89. self.abort_request(request_id)
  90. def add_request(self, request_id: str,
  91. **engine_add_request_kwargs) -> AsyncStream:
  92. """Add a request to be sent to the engine on the next background
  93. loop iteration."""
  94. if request_id in self._request_streams:
  95. raise KeyError(f"Request {request_id} already exists.")
  96. stream = AsyncStream(request_id)
  97. self._new_requests.put_nowait((stream, {
  98. "request_id": request_id,
  99. **engine_add_request_kwargs
  100. }))
  101. self.new_requests_event.set()
  102. return stream
  103. def abort_request(self, request_id: str, *, verbose: bool = False) -> None:
  104. """Abort a request during next background loop iteration."""
  105. if verbose:
  106. logger.info(f"Aborted request {request_id}.")
  107. self._finished_requests.put_nowait(request_id)
  108. if request_id not in self._request_streams or self._request_streams[
  109. request_id].finished:
  110. # The request has already finished or been aborted.
  111. return
  112. self._request_streams[request_id].finish()
  113. def get_new_and_finished_requests(self) -> Tuple[List[Dict], Set[str]]:
  114. """Get the new requests and finished requests to be
  115. sent to the engine."""
  116. new_requests: List[Dict] = []
  117. finished_requests: Set[str] = set()
  118. while not self._finished_requests.empty():
  119. request_id = self._finished_requests.get_nowait()
  120. finished_requests.add(request_id)
  121. self._request_streams.pop(request_id, None)
  122. while not self._new_requests.empty():
  123. stream, new_request = self._new_requests.get_nowait()
  124. if stream.request_id in finished_requests:
  125. # The request has already been aborted.
  126. stream.finish()
  127. continue
  128. self._request_streams[stream.request_id] = stream
  129. new_requests.append(new_request)
  130. self.new_requests_event.clear()
  131. return new_requests, finished_requests
  132. async def wait_for_new_requests(self):
  133. await self.new_requests_event.wait()
  134. class _AsyncAphrodite(AphroditeEngine):
  135. """Extension of AphroditeEngine to add async methods."""
  136. async def step_async(self) -> List[RequestOutput]:
  137. """Performs one decoding iteration and returns newly generated results.
  138. The workers are ran asynchronously if possible.
  139. This function performs one decoding iteration of the engine. It first
  140. schedules the sequences to be executed in the next iteration and the
  141. token blocks to be swapped in/out/copy. Then, it executes the model
  142. and updates the scheduler with the model outputs. Finally, it decodes
  143. the sequences and returns the newly generated results.
  144. """
  145. seq_group_metadata_list, scheduler_outputs = self.scheduler.schedule()
  146. # Execute the model.
  147. output = (await self._run_workers_async(
  148. "execute_model",
  149. seq_group_metadata_list=seq_group_metadata_list,
  150. blocks_to_swap_in=scheduler_outputs.blocks_to_swap_in,
  151. blocks_to_swap_out=scheduler_outputs.blocks_to_swap_out,
  152. blocks_to_copy=scheduler_outputs.blocks_to_copy,
  153. )) if not scheduler_outputs.is_empty() else []
  154. return self._process_model_outputs(output, scheduler_outputs)
  155. async def _run_workers_async(
  156. self,
  157. method: str,
  158. *args,
  159. get_all_outputs: bool = False,
  160. **kwargs,
  161. ) -> Any:
  162. """Runs the given method on all workers."""
  163. all_outputs = []
  164. for worker in self.workers:
  165. if self.parallel_config.worker_use_ray:
  166. executor = partial(worker.execute_method.remote, method)
  167. else:
  168. executor = getattr(worker, method)
  169. output = executor(*args, **kwargs)
  170. all_outputs.append(output)
  171. if self.parallel_config.worker_use_ray:
  172. all_outputs = await asyncio.gather(*all_outputs)
  173. if get_all_outputs:
  174. return all_outputs
  175. # Make sure all workers have the same results.
  176. output = all_outputs[0]
  177. for other_output in all_outputs[1:]:
  178. assert output == other_output
  179. return output
  180. class AsyncAphrodite:
  181. """An asynchronous wrapper for AphroditeEngine.
  182. This class is used to wrap the AphroditeEngine class to make it
  183. asynchronous. It uses asyncio to create a background loop that
  184. keeps processing incoming requests. The AphroditeEngine is kicked
  185. by the generate method when there are requests in the waiting queue.
  186. The generate method yields the outputs from the AphroditeEngine to
  187. the caller.
  188. NOTE: For the comprehensive list of arguments, see `AphroditeEngine`.
  189. Args:
  190. worker_use_ray: Whether to use Ray for model workers. Required for
  191. distributed execution. Should be the same as
  192. `parallel_config.worker_use_ray`.
  193. engine_use_ray: Whether to make AphroditeEngine a Ray actor. If so, the
  194. async frontend will be executed in a separate process as the
  195. model workers.
  196. log_requests: Whether to log the requests.
  197. start_engine_loop: If True, the background task to run the engine
  198. will be automatically started in the generate call.
  199. *args, *kwargs: Arguments for AphroditeEngine.
  200. """
  201. _engine_class: Type[_AsyncAphrodite] = _AsyncAphrodite
  202. def __init__(self,
  203. worker_use_ray: bool,
  204. engine_use_ray: bool,
  205. *args,
  206. log_requests: bool = True,
  207. max_log_len: Optional[int] = None,
  208. start_engine_loop: bool = True,
  209. **kwargs) -> None:
  210. self.worker_use_ray = worker_use_ray
  211. self.engine_use_ray = engine_use_ray
  212. self.log_requests = log_requests
  213. self.max_log_len = max_log_len
  214. self.engine = self._init_engine(*args, **kwargs)
  215. self.background_loop = None
  216. # We need to keep a reference to unshielded
  217. # task as well to prevent it from being garbage
  218. # collected
  219. self._background_loop_unshielded = None
  220. self.start_engine_loop = start_engine_loop
  221. self._request_tracker = RequestTracker()
  222. @property
  223. def is_running(self) -> bool:
  224. return (self.background_loop is not None
  225. and not self.background_loop.done())
  226. def start_background_loop(self) -> None:
  227. """Start the background loop."""
  228. if self.is_running:
  229. raise RuntimeError("Background loop is already running.")
  230. self._request_tracker.init_event()
  231. self._background_loop_unshielded = asyncio.get_event_loop(
  232. ).create_task(self.run_engine_loop())
  233. self._background_loop_unshielded.add_done_callback(
  234. partial(_raise_exception_on_finish,
  235. request_tracker=self._request_tracker))
  236. self.background_loop = asyncio.shield(self._background_loop_unshielded)
  237. def _init_engine(self, *args,
  238. **kwargs) -> Union[_AsyncAphrodite, "ray.ObjectRef"]:
  239. if not self.engine_use_ray:
  240. engine_class = self._engine_class
  241. elif self.worker_use_ray:
  242. engine_class = ray.remote(num_cpus=0)(self._engine_class).remote
  243. else:
  244. # FIXME: This is a bit hacky. Be careful when changing the
  245. # order of the arguments.
  246. cache_config = args[1]
  247. parallel_config = args[2]
  248. if parallel_config.tensor_parallel_size == 1:
  249. num_gpus = cache_config.gpu_memory_utilization
  250. else:
  251. num_gpus = 1
  252. engine_class = ray.remote(num_gpus=num_gpus)(
  253. self._engine_class).remote
  254. return engine_class(*args, **kwargs)
  255. async def engine_step(self) -> bool:
  256. """Kick the engine to process the waiting requests.
  257. Returns True if there are in-progress requests."""
  258. new_requests, finished_requests = (
  259. self._request_tracker.get_new_and_finished_requests())
  260. for new_request in new_requests:
  261. # Add the request into the Aphrodite engine's waiting queue.
  262. # TODO: Maybe add add_request_batch to reduce Ray overhead
  263. if self.engine_use_ray:
  264. await self.engine.add_request.remote(**new_request)
  265. else:
  266. self.engine.add_request(**new_request)
  267. if finished_requests:
  268. await self._engine_abort(finished_requests)
  269. if self.engine_use_ray:
  270. request_outputs = await self.engine.step.remote()
  271. else:
  272. request_outputs = await self.engine.step_async()
  273. # Put the outputs into the corresponding streams.
  274. for request_output in request_outputs:
  275. self._request_tracker.process_request_output(
  276. request_output, verbose=self.log_requests)
  277. return len(request_outputs) > 0
  278. async def _engine_abort(self, request_ids: Iterable[str]):
  279. if self.engine_use_ray:
  280. await self.engine.abort_request.remote(request_ids)
  281. else:
  282. self.engine.abort_request(request_ids)
  283. async def run_engine_loop(self):
  284. # Initialize the RequestTracker here so it uses the right event loop.
  285. has_requests_in_progress = False
  286. while True:
  287. if not has_requests_in_progress:
  288. await self._request_tracker.wait_for_new_requests()
  289. has_requests_in_progress = await self.engine_step()
  290. await asyncio.sleep(0)
  291. async def add_request(
  292. self,
  293. request_id: str,
  294. prompt: Optional[str],
  295. sampling_params: SamplingParams,
  296. prompt_token_ids: Optional[List[int]] = None,
  297. arrival_time: Optional[float] = None,
  298. ) -> AsyncStream:
  299. if self.log_requests:
  300. shortened_prompt = prompt
  301. shortened_token_ids = prompt_token_ids
  302. if self.max_log_len is not None:
  303. if shortened_prompt is not None:
  304. shortened_prompt = shortened_prompt[:self.max_log_len]
  305. if shortened_token_ids is not None:
  306. shortened_token_ids = shortened_token_ids[:self.
  307. max_log_len]
  308. logger.info(f"Received request {request_id}: "
  309. f"prompt: {shortened_prompt!r}, "
  310. f"sampling params: {sampling_params}, "
  311. f"prompt token ids: {shortened_token_ids}.")
  312. if not self.is_running:
  313. if self.start_engine_loop:
  314. self.start_background_loop()
  315. else:
  316. raise AsyncEngineDeadError(
  317. "Background loop is not running. If it was running, "
  318. "inspect the output to find the stacktrace of the "
  319. "error that caused the background loop to stop "
  320. "(AsyncEngineDeadError).")
  321. stream = self._request_tracker.add_request(
  322. request_id,
  323. prompt=prompt,
  324. sampling_params=sampling_params,
  325. prompt_token_ids=prompt_token_ids,
  326. arrival_time=arrival_time)
  327. return stream
  328. async def generate(
  329. self,
  330. prompt: Optional[str],
  331. sampling_params: SamplingParams,
  332. request_id: str,
  333. prompt_token_ids: Optional[List[int]] = None) -> RequestOutput:
  334. """Generate outputs for a request.
  335. Generate outputs for a request. This method is a coroutine. It adds the
  336. request into the waiting queue of the AphroditeEngine and streams the
  337. outputs from the AphroditeEngine to the caller.
  338. Args:
  339. prompt: The prompt string. Can be None if prompt_token_ids is
  340. provided.
  341. sampling_params: The sampling parameters of the request.
  342. request_id: The unique id of the request.
  343. prompt_token_ids: The token IDs of the prompt. If None, we
  344. use the tokenizer to convert the prompts to token IDs.
  345. Yields:
  346. The output `RequestOutput` objects from the AphroditeEngine for the
  347. request.
  348. """
  349. # Preprocess the request.
  350. arrival_time = time.time()
  351. try:
  352. stream = await self.add_request(request_id,
  353. prompt,
  354. sampling_params,
  355. prompt_token_ids=prompt_token_ids,
  356. arrival_time=arrival_time)
  357. async for request_output in stream:
  358. yield request_output
  359. except (Exception, asyncio.CancelledError) as e:
  360. # If there is an exception or coroutine is cancelled, abort the
  361. # request.
  362. self._abort(request_id)
  363. raise e
  364. async def abort(self, request_id: str) -> None:
  365. """Abort a request.
  366. Abort a submitted request. If the request is finished or not found,
  367. this method will be a no-op.
  368. Args:
  369. request_id: The unique id of the request.
  370. """
  371. if not self.is_running:
  372. raise AsyncEngineDeadError(
  373. "Background loop is not running. If it was running, "
  374. "inspect the output to find the stacktrace of the "
  375. "error that caused the background loop to stop "
  376. "(AsyncEngineDeadError).")
  377. return self._abort(request_id)
  378. def _abort(self, request_id: str) -> None:
  379. """Abort a request.
  380. Abort a submitted request. If the request is finished or not found,
  381. this method will be a no-op.
  382. Args:
  383. request_id: The unique id of the request.
  384. """
  385. self._request_tracker.abort_request(request_id,
  386. verbose=self.log_requests)
  387. async def get_model_config(self) -> ModelConfig:
  388. """Get the model configuration of the Aphrodite engine."""
  389. if self.engine_use_ray:
  390. return await self.engine.get_model_config.remote()
  391. else:
  392. return self.engine.get_model_config()
  393. @classmethod
  394. def from_engine_args(cls,
  395. engine_args: AsyncEngineArgs,
  396. start_engine_loop: bool = True) -> "AsyncAphrodite":
  397. """Creates an async LLM engine from the engine arguments."""
  398. # Create the engine configs.
  399. engine_configs = engine_args.create_engine_configs()
  400. parallel_config = engine_configs[2]
  401. # Initialize the cluster.
  402. distributed_init_method, placement_group = initialize_cluster(
  403. parallel_config, engine_args.engine_use_ray)
  404. # Create the async LLM engine.
  405. engine = cls(parallel_config.worker_use_ray,
  406. engine_args.engine_use_ray,
  407. *engine_configs,
  408. distributed_init_method,
  409. placement_group,
  410. log_requests=not engine_args.disable_log_requests,
  411. log_stats=not engine_args.disable_log_stats,
  412. max_log_len=engine_args.max_log_len,
  413. start_engine_loop=start_engine_loop)
  414. return engine