serving_engine.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import asyncio
  2. import json
  3. from dataclasses import dataclass
  4. from http import HTTPStatus
  5. from typing import Dict, List, Optional, Tuple, Union
  6. from loguru import logger
  7. from pydantic import conint
  8. from aphrodite.common.sequence import Logprob
  9. from aphrodite.endpoints.openai.protocol import (
  10. ChatCompletionRequest,
  11. CompletionRequest,
  12. ErrorResponse,
  13. LogProbs,
  14. ModelCard,
  15. ModelList,
  16. ModelPermission,
  17. Prompt,
  18. )
  19. from aphrodite.engine.async_aphrodite import AsyncAphrodite
  20. from aphrodite.lora.request import LoRARequest
  21. from aphrodite.transformers_utils.tokenizer import get_tokenizer
  22. @dataclass
  23. class LoRA:
  24. name: str
  25. local_path: str
  26. class OpenAIServing:
  27. def __init__(self,
  28. engine: AsyncAphrodite,
  29. served_model_names: List[str],
  30. lora_modules=Optional[List[LoRA]]):
  31. self.engine = engine
  32. self.served_model_names = served_model_names
  33. if lora_modules is None:
  34. self.lora_requests = []
  35. else:
  36. self.lora_requests = [
  37. LoRARequest(
  38. lora_name=lora.name,
  39. lora_int_id=i,
  40. lora_local_path=lora.local_path,
  41. ) for i, lora in enumerate(lora_modules, start=1)
  42. ]
  43. self.max_model_len = 0
  44. self.tokenizer = None
  45. try:
  46. event_loop = asyncio.get_running_loop()
  47. except RuntimeError:
  48. event_loop = None
  49. if event_loop is not None and event_loop.is_running():
  50. # If the current is instanced by Ray Serve,
  51. # there is already a running event loop
  52. event_loop.create_task(self._post_init())
  53. else:
  54. # When using single Aphrodite without engine_use_ray
  55. asyncio.run(self._post_init())
  56. async def _post_init(self):
  57. engine_model_config = await self.engine.get_model_config()
  58. self.max_model_len = engine_model_config.max_model_len
  59. # A separate tokenizer to map token IDs to strings.
  60. self.tokenizer = get_tokenizer(
  61. engine_model_config.tokenizer,
  62. tokenizer_mode=engine_model_config.tokenizer_mode,
  63. trust_remote_code=engine_model_config.trust_remote_code,
  64. revision=engine_model_config.revision,
  65. truncation_side="left")
  66. async def show_available_models(self) -> ModelList:
  67. """Show available models. Right now we only have one model."""
  68. model_cards = [
  69. ModelCard(id=served_model_name,
  70. root=self.served_model_names[0],
  71. permission=[ModelPermission()])
  72. for served_model_name in self.served_model_names
  73. ]
  74. lora_cards = [
  75. ModelCard(id=lora.lora_name,
  76. root=self.served_model_names[0],
  77. permission=[ModelPermission()])
  78. for lora in self.lora_requests
  79. ]
  80. model_cards.extend(lora_cards)
  81. return ModelList(data=model_cards)
  82. async def tokenize(self, prompt: Prompt):
  83. """Tokenize a given prompt."""
  84. tokenized_prompt = self.tokenizer.tokenize(prompt.prompt)
  85. token_ids = self.tokenizer.convert_tokens_to_ids(tokenized_prompt)
  86. return {"value": len(tokenized_prompt), "ids": token_ids}
  87. async def detokenize(self, token_ids: List[int]):
  88. """Detokenize a given list of token IDs."""
  89. tokens = self.tokenizer.convert_ids_to_tokens(token_ids)
  90. detokenized_text = self.tokenizer.convert_tokens_to_string(tokens)
  91. return {"value": detokenized_text}
  92. def _create_logprobs(
  93. self,
  94. token_ids: List[int],
  95. top_logprobs: Optional[List[Optional[Dict[int, Logprob]]]] = None,
  96. num_output_top_logprobs: Optional[int] = None,
  97. initial_text_offset: int = 0,
  98. ) -> LogProbs:
  99. """Create OpenAI-style logprobs."""
  100. logprobs = LogProbs()
  101. last_token_len = 0
  102. if num_output_top_logprobs:
  103. logprobs.top_logprobs = []
  104. for i, token_id in enumerate(token_ids):
  105. step_top_logprobs = top_logprobs[i]
  106. if step_top_logprobs is None:
  107. token = self.tokenizer.decode(token_id)
  108. logprobs.tokens.append(token)
  109. logprobs.token_logprobs.append(None)
  110. logprobs.top_logprobs.append(None)
  111. else:
  112. token_logprob = step_top_logprobs[token_id].logprob
  113. token = step_top_logprobs[token_id].decoded_token
  114. logprobs.tokens.append(token)
  115. logprobs.token_logprobs.append(token_logprob)
  116. if num_output_top_logprobs:
  117. logprobs.top_logprobs.append({
  118. # Convert float("-inf") to the
  119. # JSON-serializable float that OpenAI uses
  120. p.decoded_token: max(p.logprob, -9999.0)
  121. for i, p in step_top_logprobs.items()
  122. } if step_top_logprobs else None)
  123. # TODO: Check if this is still needed
  124. if logprobs.top_logprobs:
  125. logprobs.top_logprobs = [{
  126. k: v if v > -1000 else -1000
  127. for k, v in top_logprob.items()
  128. } for top_logprob in logprobs.top_logprobs
  129. if top_logprob is not None
  130. ] # noqa: E501
  131. if len(logprobs.text_offset) == 0:
  132. logprobs.text_offset.append(initial_text_offset)
  133. else:
  134. logprobs.text_offset.append(logprobs.text_offset[-1] +
  135. last_token_len)
  136. last_token_len = len(token)
  137. return logprobs
  138. def create_error_response(
  139. self,
  140. message: str,
  141. err_type: str = "BadRequestError",
  142. status_code: HTTPStatus = HTTPStatus.BAD_REQUEST) -> ErrorResponse:
  143. return ErrorResponse(message=message,
  144. type=err_type,
  145. code=status_code.value)
  146. def create_streaming_error_response(
  147. self,
  148. message: str,
  149. err_type: str = "BadRequestError",
  150. status_code: HTTPStatus = HTTPStatus.BAD_REQUEST) -> str:
  151. json_str = json.dumps({
  152. "error":
  153. self.create_error_response(message=message,
  154. err_type=err_type,
  155. status_code=status_code).model_dump()
  156. })
  157. return json_str
  158. async def _check_model(self, request) -> Optional[ErrorResponse]:
  159. if request.model in self.served_model_names:
  160. return
  161. if request.model in [lora.lora_name for lora in self.lora_requests]:
  162. return
  163. return self.create_error_response(
  164. message=f"The model `{request.model}` does not exist.",
  165. err_type="NotFoundError",
  166. status_code=HTTPStatus.NOT_FOUND)
  167. def add_lora(self, lora: LoRA):
  168. if lora.name in [
  169. existing_lora.lora_name for existing_lora in self.lora_requests
  170. ]:
  171. logger.error(f"LoRA with name {lora.name} already exists.")
  172. return
  173. self.lora_requests.append(
  174. LoRARequest(
  175. lora_name=lora.name,
  176. lora_int_id=len(self.lora_requests) + 1,
  177. lora_local_path=lora.local_path,
  178. ))
  179. def remove_lora(self, lora_name: str):
  180. self.lora_requests = [
  181. lora for lora in self.lora_requests if lora.lora_name != lora_name
  182. ]
  183. def _maybe_get_lora(self, request) -> Optional[LoRARequest]:
  184. if request.model in self.served_model_names:
  185. return
  186. for lora in self.lora_requests:
  187. if request.model == lora.lora_name:
  188. return lora
  189. # if _check_model has been called earlier, this will be unreachable
  190. raise ValueError("The model `{request.model}` does not exist.")
  191. def _validate_prompt_and_tokenize(
  192. self,
  193. request: Union[ChatCompletionRequest, CompletionRequest],
  194. prompt: Optional[str] = None,
  195. prompt_ids: Optional[List[int]] = None,
  196. truncate_prompt_tokens: Optional[conint(ge=1)] = None
  197. ) -> Tuple[List[int], str]:
  198. if not (prompt or prompt_ids):
  199. raise ValueError("Either prompt or prompt_ids should be provided.")
  200. if (prompt and prompt_ids):
  201. raise ValueError(
  202. "Only one of prompt or prompt_ids should be provided.")
  203. if prompt_ids is None:
  204. tokenizer_kwargs = {} if truncate_prompt_tokens is None else {
  205. "truncation": True,
  206. "max_length": truncate_prompt_tokens,
  207. }
  208. input_ids = self.tokenizer(prompt, **tokenizer_kwargs).input_ids
  209. elif truncate_prompt_tokens is not None:
  210. input_ids = prompt_ids[-truncate_prompt_tokens:]
  211. else:
  212. input_ids = prompt_ids
  213. input_text = prompt if prompt is not None else self.tokenizer.decode(
  214. prompt_ids)
  215. token_num = len(input_ids)
  216. if request.max_tokens is None:
  217. request.max_tokens = self.max_model_len - token_num
  218. if token_num + request.max_tokens > self.max_model_len:
  219. raise ValueError(
  220. f"This model's maximum context length is "
  221. f"{self.max_model_len} tokens. However, you requested "
  222. f"{request.max_tokens + token_num} tokens "
  223. f"({token_num} in the messages, "
  224. f"{request.max_tokens} in the completion). "
  225. f"Please reduce the length of the messages or completion.", )
  226. else:
  227. return input_ids, input_text