serving_engine.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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: str,
  30. lora_modules=Optional[List[LoRA]]):
  31. self.engine = engine
  32. self.served_model = served_model
  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=self.served_model,
  70. root=self.served_model,
  71. permission=[ModelPermission()])
  72. ]
  73. lora_cards = [
  74. ModelCard(id=lora.lora_name,
  75. root=self.served_model,
  76. permission=[ModelPermission()])
  77. for lora in self.lora_requests
  78. ]
  79. model_cards.extend(lora_cards)
  80. return ModelList(data=model_cards)
  81. async def tokenize(self, prompt: Prompt):
  82. """Tokenize a given prompt."""
  83. tokenized_prompt = self.tokenizer.tokenize(prompt.prompt)
  84. token_ids = self.tokenizer.convert_tokens_to_ids(tokenized_prompt)
  85. return {"value": len(tokenized_prompt), "ids": token_ids}
  86. async def detokenize(self, token_ids: List[int]):
  87. """Detokenize a given list of token IDs."""
  88. tokens = self.tokenizer.convert_ids_to_tokens(token_ids)
  89. detokenized_text = self.tokenizer.convert_tokens_to_string(tokens)
  90. return {"value": detokenized_text}
  91. def _create_logprobs(
  92. self,
  93. token_ids: List[int],
  94. top_logprobs: Optional[List[Optional[Dict[int, Logprob]]]] = None,
  95. num_output_top_logprobs: Optional[int] = None,
  96. initial_text_offset: int = 0,
  97. ) -> LogProbs:
  98. """Create OpenAI-style logprobs."""
  99. logprobs = LogProbs()
  100. last_token_len = 0
  101. if num_output_top_logprobs:
  102. logprobs.top_logprobs = []
  103. for i, token_id in enumerate(token_ids):
  104. step_top_logprobs = top_logprobs[i]
  105. if step_top_logprobs is None:
  106. token = self.tokenizer.decode(token_id)
  107. logprobs.tokens.append(token)
  108. logprobs.token_logprobs.append(None)
  109. logprobs.top_logprobs.append(None)
  110. else:
  111. token_logprob = step_top_logprobs[token_id].logprob
  112. token = step_top_logprobs[token_id].decoded_token
  113. logprobs.tokens.append(token)
  114. logprobs.token_logprobs.append(token_logprob)
  115. if num_output_top_logprobs:
  116. logprobs.top_logprobs.append({
  117. p.decoded_token: p.logprob
  118. for i, p in step_top_logprobs.items()
  119. } if step_top_logprobs else None)
  120. if logprobs.top_logprobs:
  121. logprobs.top_logprobs = [{
  122. k: v if v > -1000 else -1000
  123. for k, v in top_logprob.items()
  124. } for top_logprob in logprobs.top_logprobs
  125. if top_logprob is not None
  126. ] # noqa: E501
  127. if len(logprobs.text_offset) == 0:
  128. logprobs.text_offset.append(initial_text_offset)
  129. else:
  130. logprobs.text_offset.append(logprobs.text_offset[-1] +
  131. last_token_len)
  132. last_token_len = len(token)
  133. return logprobs
  134. def create_error_response(
  135. self,
  136. message: str,
  137. err_type: str = "BadRequestError",
  138. status_code: HTTPStatus = HTTPStatus.BAD_REQUEST) -> ErrorResponse:
  139. return ErrorResponse(message=message,
  140. type=err_type,
  141. code=status_code.value)
  142. def create_streaming_error_response(
  143. self,
  144. message: str,
  145. err_type: str = "BadRequestError",
  146. status_code: HTTPStatus = HTTPStatus.BAD_REQUEST) -> str:
  147. json_str = json.dumps({
  148. "error":
  149. self.create_error_response(message=message,
  150. err_type=err_type,
  151. status_code=status_code).model_dump()
  152. })
  153. return json_str
  154. async def _check_model(self, request) -> Optional[ErrorResponse]:
  155. if request.model == self.served_model:
  156. return
  157. if request.model in [lora.lora_name for lora in self.lora_requests]:
  158. return
  159. return self.create_error_response(
  160. message=f"The model `{request.model}` does not exist.",
  161. err_type="NotFoundError",
  162. status_code=HTTPStatus.NOT_FOUND)
  163. def add_lora(self, lora: LoRA):
  164. if lora.name in [
  165. existing_lora.lora_name for existing_lora in self.lora_requests
  166. ]:
  167. logger.error(f"LoRA with name {lora.name} already exists.")
  168. return
  169. self.lora_requests.append(
  170. LoRARequest(
  171. lora_name=lora.name,
  172. lora_int_id=len(self.lora_requests) + 1,
  173. lora_local_path=lora.local_path,
  174. ))
  175. def remove_lora(self, lora_name: str):
  176. self.lora_requests = [
  177. lora for lora in self.lora_requests if lora.lora_name != lora_name
  178. ]
  179. def _maybe_get_lora(self, request) -> Optional[LoRARequest]:
  180. if request.model == self.served_model:
  181. return
  182. for lora in self.lora_requests:
  183. if request.model == lora.lora_name:
  184. return lora
  185. # if _check_model has been called earlier, this will be unreachable
  186. raise ValueError("The model `{request.model}` does not exist.")
  187. def _validate_prompt_and_tokenize(
  188. self,
  189. request: Union[ChatCompletionRequest, CompletionRequest],
  190. prompt: Optional[str] = None,
  191. prompt_ids: Optional[List[int]] = None,
  192. truncate_prompt_tokens: Optional[conint(ge=1)] = None
  193. ) -> Tuple[List[int], str]:
  194. if not (prompt or prompt_ids):
  195. raise ValueError("Either prompt or prompt_ids should be provided.")
  196. if (prompt and prompt_ids):
  197. raise ValueError(
  198. "Only one of prompt or prompt_ids should be provided.")
  199. if prompt_ids is None:
  200. tokenizer_kwargs = {} if truncate_prompt_tokens is None else {
  201. "truncation": True,
  202. "max_length": truncate_prompt_tokens,
  203. }
  204. input_ids = self.tokenizer(prompt, **tokenizer_kwargs).input_ids
  205. elif truncate_prompt_tokens is not None:
  206. input_ids = prompt_ids[-truncate_prompt_tokens:]
  207. else:
  208. input_ids = prompt_ids
  209. input_text = prompt if prompt is not None else self.tokenizer.decode(
  210. prompt_ids)
  211. token_num = len(input_ids)
  212. if request.max_tokens is None:
  213. request.max_tokens = self.max_model_len - token_num
  214. if token_num + request.max_tokens > self.max_model_len:
  215. raise ValueError(
  216. f"This model's maximum context length is "
  217. f"{self.max_model_len} tokens. However, you requested "
  218. f"{request.max_tokens + token_num} tokens "
  219. f"({token_num} in the messages, "
  220. f"{request.max_tokens} in the completion). "
  221. f"Please reduce the length of the messages or completion.", )
  222. else:
  223. return input_ids, input_text