async_aphrodite.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. import asyncio
  2. import time
  3. from functools import partial
  4. from typing import (Any, Dict, Iterable, List, Optional, Set, Tuple, Type,
  5. Union, AsyncIterator)
  6. from aphrodite.lora.request import LoRARequest
  7. from aphrodite.common.config import ModelConfig
  8. from aphrodite.engine.args_tools import AsyncEngineArgs
  9. from aphrodite.engine.aphrodite_engine import AphroditeEngine
  10. from aphrodite.engine.ray_tools import initialize_cluster, ray
  11. from aphrodite.common.logger import init_logger
  12. from aphrodite.common.outputs import RequestOutput
  13. from aphrodite.common.sampling_params import SamplingParams
  14. logger = init_logger(__name__)
  15. class AsyncEngineDeadError(RuntimeError):
  16. pass
  17. def _raise_exception_on_finish(task: asyncio.Task,
  18. request_tracker: "RequestTracker") -> None:
  19. msg = ("Task finished unexpectedly. This should never happen! "
  20. "Please open an issue on Github.")
  21. try:
  22. try:
  23. task.result()
  24. except asyncio.CancelledError:
  25. return
  26. except Exception as exc:
  27. raise AsyncEngineDeadError(
  28. msg + " See stack trace above for the actual cause.") from exc
  29. raise AsyncEngineDeadError(msg)
  30. except Exception as exc:
  31. request_tracker.propagate_exception(exc)
  32. raise exc
  33. class AsyncStream:
  34. """A stream of RequestOutputs for a request that can be
  35. iterated over asynchronously."""
  36. def __init__(self, request_id: str) -> None:
  37. self.request_id = request_id
  38. self._queue = asyncio.Queue()
  39. self._finished = False
  40. def put(self, item: RequestOutput) -> None:
  41. if self._finished:
  42. return
  43. self._queue.put_nowait(item)
  44. def finish(self) -> None:
  45. self._queue.put_nowait(StopAsyncIteration())
  46. self._finished = True
  47. @property
  48. def finished(self) -> bool:
  49. return self._finished
  50. def __aiter__(self):
  51. return self
  52. async def __anext__(self) -> RequestOutput:
  53. result = await self._queue.get()
  54. if 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. if not scheduler_outputs.is_empty():
  147. # Execute the model.
  148. all_outputs = await self._run_workers_async(
  149. "execute_model",
  150. driver_kwargs={
  151. "seq_group_metadata_list": seq_group_metadata_list,
  152. "blocks_to_swap_in": scheduler_outputs.blocks_to_swap_in,
  153. "blocks_to_swap_out": scheduler_outputs.blocks_to_swap_out,
  154. "blocks_to_copy": scheduler_outputs.blocks_to_copy,
  155. })
  156. # Only the driver worker returns the sampling results.
  157. output = all_outputs[0]
  158. else:
  159. output = []
  160. return self._process_model_outputs(output, scheduler_outputs)
  161. async def encode_request_async(
  162. self,
  163. request_id: str, # pylint: disable=unused-argument
  164. prompt: Optional[str],
  165. prompt_token_ids: Optional[List[int]] = None,
  166. lora_request: Optional[LoRARequest] = None,
  167. ):
  168. if prompt_token_ids is None:
  169. assert prompt is not None
  170. prompt_token_ids = await self.tokenizer.encode_async(
  171. request_id=request_id,
  172. prompt=prompt,
  173. lora_request=lora_request)
  174. return prompt_token_ids
  175. async def add_request_async(
  176. self,
  177. request_id: str,
  178. prompt: Optional[str],
  179. sampling_params: SamplingParams,
  180. prompt_token_ids: Optional[List[int]] = None,
  181. arrival_time: Optional[float] = None,
  182. lora_request: Optional[LoRARequest] = None,
  183. prefix_pos: Optional[int] = None,
  184. ) -> None:
  185. if lora_request is not None and not self.lora_config:
  186. raise ValueError(f"Got lora_request {lora_request} but LoRA is "
  187. "not enabled!")
  188. if arrival_time is None:
  189. arrival_time = time.time()
  190. prompt_token_ids = await self.encode_request_async(
  191. request_id=request_id,
  192. prompt=prompt,
  193. prompt_token_ids=prompt_token_ids,
  194. lora_request=lora_request)
  195. return self.add_request(
  196. request_id,
  197. prompt=prompt,
  198. prompt_token_ids=prompt_token_ids,
  199. sampling_params=sampling_params,
  200. arrival_time=arrival_time,
  201. lora_request=lora_request,
  202. prefix_pos=prefix_pos,
  203. )
  204. async def _run_workers_async(
  205. self,
  206. method: str,
  207. *args,
  208. driver_args: Optional[List[Any]] = None,
  209. driver_kwargs: Optional[Dict[str, Any]] = None,
  210. **kwargs,
  211. ) -> Any:
  212. """Runs the given method on all workers."""
  213. coros = []
  214. if driver_args is None:
  215. driver_args = args
  216. if driver_kwargs is None:
  217. driver_kwargs = kwargs
  218. # Run the driver worker asynchronously.
  219. driver_executor = getattr(self.driver_worker, method)
  220. coros.append(asyncio.get_event_loop().run_in_executor(
  221. None, partial(driver_executor, *driver_args, **driver_kwargs)))
  222. # Run the ray workers asynchronously.
  223. for worker in self.workers:
  224. coros.append(worker.execute_method.remote(method, *args, **kwargs))
  225. all_outputs = await asyncio.gather(*coros)
  226. return all_outputs
  227. class AsyncAphrodite:
  228. """An asynchronous wrapper for AphroditeEngine.
  229. This class is used to wrap the AphroditeEngine class to make it
  230. asynchronous. It uses asyncio to create a background loop that keeps
  231. processing incoming requests. The AphroditeEngine is kicked by the
  232. generate method when there are requests in the waiting queue.
  233. The generate method yields the outputs from the AphroditeEngine
  234. to the caller.
  235. NOTE: For the comprehensive list of arguments, see `AphroditeEngine`.
  236. Args:
  237. worker_use_ray: Whether to use Ray for model workers. Required for
  238. distributed execution. Should be the same as
  239. `parallel_config.worker_use_ray`.
  240. engine_use_ray: Whether to make AphroditeEngine a Ray actor. If so, the
  241. async frontend will be executed in a separate process as the
  242. model workers.
  243. log_requests: Whether to log the requests.
  244. start_engine_loop: If True, the background task to run the engine
  245. will be automatically started in the generate call.
  246. *args: Arguments for AphroditeEngine.
  247. *kwargs: Arguments for AphroditeEngine.
  248. """
  249. _engine_class: Type[_AsyncAphrodite] = _AsyncAphrodite
  250. def __init__(self,
  251. worker_use_ray: bool,
  252. engine_use_ray: bool,
  253. *args,
  254. log_requests: bool = True,
  255. max_log_len: Optional[int] = None,
  256. start_engine_loop: bool = True,
  257. **kwargs) -> None:
  258. self.worker_use_ray = worker_use_ray
  259. self.engine_use_ray = engine_use_ray
  260. self.log_requests = log_requests
  261. self.max_log_len = max_log_len
  262. self.engine = self._init_engine(*args, **kwargs)
  263. self.background_loop = None
  264. # We need to keep a reference to unshielded
  265. # task as well to prevent it from being garbage
  266. # collected
  267. self._background_loop_unshielded = None
  268. self.start_engine_loop = start_engine_loop
  269. self._request_tracker = RequestTracker()
  270. @property
  271. def is_running(self) -> bool:
  272. return (self.background_loop is not None
  273. and not self.background_loop.done())
  274. def start_background_loop(self) -> None:
  275. """Start the background loop."""
  276. if self.is_running:
  277. raise RuntimeError("Background loop is already running.")
  278. self._request_tracker.init_event()
  279. self._background_loop_unshielded = asyncio.get_event_loop(
  280. ).create_task(self.run_engine_loop())
  281. self._background_loop_unshielded.add_done_callback(
  282. partial(_raise_exception_on_finish,
  283. request_tracker=self._request_tracker))
  284. self.background_loop = asyncio.shield(self._background_loop_unshielded)
  285. def _init_engine(self, *args,
  286. **kwargs) -> Union[_AsyncAphrodite, "ray.ObjectRef"]:
  287. if not self.engine_use_ray:
  288. engine_class = self._engine_class
  289. elif self.worker_use_ray:
  290. engine_class = ray.remote(num_cpus=0)(self._engine_class).remote
  291. else:
  292. # FIXME: This is a bit hacky. Be careful when changing the
  293. # order of the arguments.
  294. cache_config = args[1]
  295. parallel_config = args[2]
  296. if parallel_config.tensor_parallel_size == 1:
  297. num_gpus = cache_config.gpu_memory_utilization
  298. else:
  299. num_gpus = 1
  300. engine_class = ray.remote(num_gpus=num_gpus)(
  301. self._engine_class).remote
  302. return engine_class(*args, **kwargs)
  303. async def engine_step(self) -> bool:
  304. """Kick the engine to process the waiting requests.
  305. Returns True if there are in-progress requests."""
  306. new_requests, finished_requests = (
  307. self._request_tracker.get_new_and_finished_requests())
  308. for new_request in new_requests:
  309. # Add the request into the Aphrodite engine's waiting queue.
  310. # TODO: Maybe add add_request_batch to reduce Ray overhead
  311. if self.engine_use_ray:
  312. await self.engine.add_request.remote(**new_request)
  313. else:
  314. await self.engine.add_request_async(**new_request)
  315. if finished_requests:
  316. await self._engine_abort(finished_requests)
  317. if self.engine_use_ray:
  318. request_outputs = await self.engine.step.remote()
  319. else:
  320. request_outputs = await self.engine.step_async()
  321. # Put the outputs into the corresponding streams.
  322. for request_output in request_outputs:
  323. self._request_tracker.process_request_output(
  324. request_output, verbose=self.log_requests)
  325. return len(request_outputs) > 0
  326. async def _engine_abort(self, request_ids: Iterable[str]):
  327. if self.engine_use_ray:
  328. await self.engine.abort_request.remote(request_ids)
  329. else:
  330. self.engine.abort_request(request_ids)
  331. async def run_engine_loop(self):
  332. # Initialize the RequestTracker here so it uses the right event loop.
  333. has_requests_in_progress = False
  334. while True:
  335. if not has_requests_in_progress:
  336. await self._request_tracker.wait_for_new_requests()
  337. has_requests_in_progress = await self.engine_step()
  338. await asyncio.sleep(0)
  339. async def add_request(
  340. self,
  341. request_id: str,
  342. prompt: Optional[str],
  343. sampling_params: SamplingParams,
  344. prompt_token_ids: Optional[List[int]] = None,
  345. arrival_time: Optional[float] = None,
  346. lora_request: Optional[LoRARequest] = None,
  347. prefix_pos: Optional[int] = None,
  348. ) -> AsyncStream:
  349. if self.log_requests:
  350. shortened_prompt = prompt
  351. shortened_token_ids = prompt_token_ids
  352. if self.max_log_len is not None:
  353. if shortened_prompt is not None:
  354. shortened_prompt = shortened_prompt[:self.max_log_len]
  355. if shortened_token_ids is not None:
  356. shortened_token_ids = shortened_token_ids[:self.
  357. max_log_len]
  358. logger.info(f"Received request {request_id}: "
  359. f"prompt: {shortened_prompt!r}, "
  360. f"prefix_pos: {prefix_pos},"
  361. f"sampling params: {sampling_params}, "
  362. f"prompt token ids: {shortened_token_ids}, "
  363. f"lora_request: {lora_request}.")
  364. if not self.is_running:
  365. if self.start_engine_loop:
  366. self.start_background_loop()
  367. else:
  368. raise AsyncEngineDeadError(
  369. "Background loop is not running. If it was running, "
  370. "inspect the output to find the stacktrace of the "
  371. "error that caused the background loop to stop "
  372. "(AsyncEngineDeadError).")
  373. if arrival_time is None:
  374. arrival_time = time.time()
  375. prompt_token_ids = await self.engine.encode_request_async(
  376. request_id=request_id,
  377. prompt=prompt,
  378. prompt_token_ids=prompt_token_ids,
  379. lora_request=lora_request)
  380. stream = self._request_tracker.add_request(
  381. request_id,
  382. prompt=prompt,
  383. sampling_params=sampling_params,
  384. prompt_token_ids=prompt_token_ids,
  385. arrival_time=arrival_time,
  386. lora_request=lora_request,
  387. prefix_pos=prefix_pos,
  388. )
  389. return stream
  390. async def generate(
  391. self,
  392. prompt: Optional[str],
  393. sampling_params: SamplingParams,
  394. request_id: str,
  395. prompt_token_ids: Optional[List[int]] = None,
  396. lora_request: Optional[LoRARequest] = None,
  397. prefix_pos: Optional[int] = None,
  398. ) -> AsyncIterator[RequestOutput]:
  399. """Generate outputs for a request.
  400. Generate outputs for a request. This method is a coroutine. It adds the
  401. request into the waiting queue of the AphroditeEngine and streams the
  402. outputs from the AphroditeEngine to the caller.
  403. Args:
  404. prompt: The prompt string. Can be None if prompt_token_ids is
  405. provided.
  406. sampling_params: The sampling parameters of the request.
  407. request_id: The unique id of the request.
  408. prompt_token_ids: The token IDs of the prompt. If None, we
  409. use the tokenizer to convert the prompts to token IDs.
  410. lora_request: LoRA request to use for generation, if any.
  411. prefix_pos: If not None, we use the given position as the prefix
  412. position for each prompt. We will cache the prefix's KV
  413. cache and reuse it for the next request with the same prefix.
  414. This is an experimental feature, and may be replaced with
  415. automatic prefix caching in the future.
  416. Yields:
  417. The output `RequestOutput` objects from the AphroditeEngine for the
  418. request.
  419. Details:
  420. - If the engine is not running, start the background loop,
  421. which iteratively invokes
  422. # pylint: disable=line-too-long
  423. :meth:`~aphrodite.engine.async_llm_engine.AsyncAphrodite.engine_step`
  424. to process the waiting requests.
  425. - Add the request to the engine's `RequestTracker`.
  426. On the next background loop, this request will be sent to
  427. the underlying engine.
  428. Also, a corresponding `AsyncStream` will be created.
  429. - Wait for the request outputs from `AsyncStream` and yield them.
  430. Example:
  431. >>> # Please refer to entrypoints/api_server.py for
  432. >>> # the complete example.
  433. >>>
  434. >>> # initialize the engine and the example input
  435. >>> engine = AsyncAphrodite.from_engine_args(engine_args)
  436. >>> example_input = {
  437. >>> "prompt": "What is LLM?",
  438. >>> "stream": False, # assume the non-streaming case
  439. >>> "temperature": 0.0,
  440. >>> "request_id": 0,
  441. >>> }
  442. >>>
  443. >>> # start the generation
  444. >>> results_generator = engine.generate(
  445. >>> example_input["prompt"],
  446. >>> SamplingParams(temperature=example_input["temperature"]),
  447. >>> example_input["request_id"])
  448. >>>
  449. >>> # get the results
  450. >>> final_output = None
  451. >>> async for request_output in results_generator:
  452. >>> if await request.is_disconnected():
  453. >>> # Abort the request if the client disconnects.
  454. >>> await engine.abort(request_id)
  455. >>> # Return or raise an error
  456. >>> ...
  457. >>> final_output = request_output
  458. >>>
  459. >>> # Process and return the final output
  460. >>> ...
  461. """
  462. # Preprocess the request.
  463. # This should not be used for logging, as it is monotonic time.
  464. arrival_time = time.monotonic()
  465. try:
  466. stream = await self.add_request(
  467. request_id,
  468. prompt,
  469. sampling_params,
  470. prompt_token_ids=prompt_token_ids,
  471. arrival_time=arrival_time,
  472. lora_request=lora_request,
  473. prefix_pos=prefix_pos,
  474. )
  475. async for request_output in stream:
  476. yield request_output
  477. except (Exception, asyncio.CancelledError) as e:
  478. # If there is an exception or coroutine is cancelled, abort the
  479. # request.
  480. self._abort(request_id)
  481. raise e
  482. async def abort(self, request_id: str) -> None:
  483. """Abort a request.
  484. Abort a submitted request. If the request is finished or not found,
  485. this method will be a no-op.
  486. Args:
  487. request_id: The unique id of the request.
  488. """
  489. if not self.is_running:
  490. raise AsyncEngineDeadError(
  491. "Background loop is not running. If it was running, "
  492. "inspect the output to find the stacktrace of the "
  493. "error that caused the background loop to stop "
  494. "(AsyncEngineDeadError).")
  495. return self._abort(request_id)
  496. def _abort(self, request_id: str) -> None:
  497. """Abort a request.
  498. Abort a submitted request. If the request is finished or not found,
  499. this method will be a no-op.
  500. Args:
  501. request_id: The unique id of the request.
  502. """
  503. self._request_tracker.abort_request(request_id,
  504. verbose=self.log_requests)
  505. async def get_model_config(self) -> ModelConfig:
  506. """Get the model configuration of the Aphrodite engine."""
  507. if self.engine_use_ray:
  508. return await self.engine.get_model_config.remote()
  509. else:
  510. return self.engine.get_model_config()
  511. @classmethod
  512. def from_engine_args(cls,
  513. engine_args: AsyncEngineArgs,
  514. start_engine_loop: bool = True) -> "AsyncAphrodite":
  515. """Creates an async LLM engine from the engine arguments."""
  516. # Create the engine configs.
  517. engine_configs = engine_args.create_engine_configs()
  518. parallel_config = engine_configs[2]
  519. # Initialize the cluster.
  520. placement_group = initialize_cluster(parallel_config,
  521. engine_args.engine_use_ray)
  522. # Create the async LLM engine.
  523. engine = cls(parallel_config.worker_use_ray,
  524. engine_args.engine_use_ray,
  525. *engine_configs,
  526. placement_group,
  527. log_requests=not engine_args.disable_log_requests,
  528. log_stats=not engine_args.disable_log_stats,
  529. max_log_len=engine_args.max_log_len,
  530. start_engine_loop=start_engine_loop)
  531. return engine
  532. async def do_log_stats(self) -> None:
  533. if self.engine_use_ray:
  534. await self.engine.do_log_stats.remote()
  535. else:
  536. self.engine.do_log_stats()