llm.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. from contextlib import contextmanager
  2. from typing import ClassVar, List, Optional, Sequence, Union, cast, overload
  3. from tqdm import tqdm
  4. from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast
  5. from aphrodite.common.outputs import EmbeddingRequestOutput, RequestOutput
  6. from aphrodite.common.pooling_params import PoolingParams
  7. from aphrodite.common.sampling_params import SamplingParams
  8. from aphrodite.common.utils import Counter, deprecate_kwargs
  9. from aphrodite.endpoints.chat_utils import (ChatCompletionMessageParam,
  10. apply_chat_template,
  11. parse_chat_messages)
  12. from aphrodite.engine.aphrodite_engine import AphroditeEngine
  13. from aphrodite.engine.args_tools import EngineArgs
  14. from aphrodite.inputs import PromptInputs, TextPrompt, TokensPrompt
  15. from aphrodite.inputs.parse import parse_and_batch_prompt
  16. from aphrodite.lora.request import LoRARequest
  17. from aphrodite.modeling.guided_decoding import (
  18. GuidedDecodingRequest, get_local_guided_decoding_logits_processor)
  19. from aphrodite.modeling.guided_decoding.guided_fields import LLMGuidedOptions
  20. from aphrodite.prompt_adapter.request import PromptAdapterRequest
  21. from aphrodite.transformers_utils.tokenizer import get_cached_tokenizer
  22. class LLM:
  23. """An LLM for generating texts from given prompts and sampling parameters.
  24. This class includes a tokenizer, a language model (possibly distributed
  25. across multiple GPUs), and GPU memory space allocated for intermediate
  26. states (aka KV cache). Given a batch of prompts and sampling parameters,
  27. this class generates texts from the model, using an intelligent batching
  28. mechanism and efficient memory management.
  29. Args:
  30. model: The name or path of a HuggingFace Transformers model.
  31. tokenizer: The name or path of a HuggingFace Transformers tokenizer.
  32. tokenizer_mode: The tokenizer mode. "auto" will use the fast tokenizer
  33. if available, and "slow" will always use the slow tokenizer.
  34. skip_tokenizer_init: If true, skip initialization of tokenizer and
  35. detokenizer. Expect valid prompt_token_ids and None for prompt
  36. from the input.
  37. trust_remote_code: Trust remote code (e.g., from HuggingFace) when
  38. downloading the model and tokenizer.
  39. tensor_parallel_size: The number of GPUs to use for distributed
  40. execution with tensor parallelism.
  41. dtype: The data type for the model weights and activations. Currently,
  42. we support `float32`, `float16`, and `bfloat16`. If `auto`, we use
  43. the `torch_dtype` attribute specified in the model config file.
  44. However, if the `torch_dtype` in the config is `float32`, we will
  45. use `float16` instead.
  46. quantization: The method used to quantize the model weights. Currently,
  47. we support "awq", "gptq", "squeezellm", and "fp8" (experimental).
  48. If None, we first check the `quantization_config` attribute in the
  49. model config file. If that is None, we assume the model weights are
  50. not quantized and use `dtype` to determine the data type of
  51. the weights.
  52. revision: The specific model version to use. It can be a branch name,
  53. a tag name, or a commit id.
  54. tokenizer_revision: The specific tokenizer version to use. It can be a
  55. branch name, a tag name, or a commit id.
  56. seed: The seed to initialize the random number generator for sampling.
  57. gpu_memory_utilization: The ratio (between 0 and 1) of GPU memory to
  58. reserve for the model weights, activations, and KV cache. Higher
  59. values will increase the KV cache size and thus improve the model's
  60. throughput. However, if the value is too high, it may cause out-of-
  61. memory (OOM) errors.
  62. swap_space: The size (GiB) of CPU memory per GPU to use as swap space.
  63. This can be used for temporarily storing the states of the requests
  64. when their `best_of` sampling parameters are larger than 1. If all
  65. requests will have `best_of=1`, you can safely set this to 0.
  66. Otherwise, too small values may cause out-of-memory (OOM) errors.
  67. cpu_offload_gb: The size (GiB) of CPU memory to use for offloading
  68. the model weights. This virtually increases the GPU memory space
  69. you can use to hold the model weights, at the cost of CPU-GPU data
  70. transfer for every forward pass.
  71. enforce_eager: Whether to enforce eager execution. If True, we will
  72. disable CUDA graph and always execute the model in eager mode.
  73. If False, we will use CUDA graph and eager execution in hybrid.
  74. max_context_len_to_capture: Maximum context len covered by CUDA graphs.
  75. When a sequence has context length larger than this, we fall back
  76. to eager mode (DEPRECATED. Use `max_seq_len_to_capture` instead).
  77. max_seq_len_to_capture: Maximum sequence len covered by CUDA graphs.
  78. When a sequence has context length larger than this, we fall back
  79. to eager mode.
  80. disable_custom_all_reduce: See ParallelConfig
  81. **kwargs: Arguments for :class:`~aphrodite.EngineArgs`. (See
  82. :ref:`engine_args`)
  83. Note:
  84. This class is intended to be used for offline inference. For online
  85. serving, use the :class:`~aphrodite.AsyncAphrodite` class instead.
  86. """
  87. DEPRECATE_LEGACY: ClassVar[bool] = False
  88. """A flag to toggle whether to deprecate the legacy generate/encode API."""
  89. @classmethod
  90. @contextmanager
  91. def deprecate_legacy_api(cls):
  92. cls.DEPRECATE_LEGACY = True
  93. yield
  94. cls.DEPRECATE_LEGACY = False
  95. def __init__(
  96. self,
  97. model: str,
  98. tokenizer: Optional[str] = None,
  99. tokenizer_mode: str = "auto",
  100. skip_tokenizer_init: bool = False,
  101. trust_remote_code: bool = False,
  102. tensor_parallel_size: int = 1,
  103. dtype: str = "auto",
  104. quantization: Optional[str] = None,
  105. revision: Optional[str] = None,
  106. tokenizer_revision: Optional[str] = None,
  107. seed: int = 0,
  108. gpu_memory_utilization: float = 0.9,
  109. swap_space: int = 4,
  110. cpu_offload_gb: float = 0,
  111. enforce_eager: Optional[bool] = None,
  112. max_context_len_to_capture: Optional[int] = None,
  113. max_seq_len_to_capture: int = 8192,
  114. disable_custom_all_reduce: bool = False,
  115. **kwargs,
  116. ) -> None:
  117. '''
  118. LLM constructor.
  119. Note: if enforce_eager is unset (enforce_eager is None)
  120. it defaults to False for decoder-only models and True
  121. for encoder/decoder models, since encoder/decoder models
  122. do not currently support CUDAGraph.
  123. '''
  124. if "disable_log_stats" not in kwargs:
  125. kwargs["disable_log_stats"] = True
  126. removed_vision_keys = ("image_token_id", "image_feature_size",
  127. "image_input_shape", "image_input_type")
  128. if any(k in kwargs for k in removed_vision_keys):
  129. raise TypeError(
  130. "There is no need to pass vision-related arguments anymore.")
  131. engine_args = EngineArgs(
  132. model=model,
  133. tokenizer=tokenizer,
  134. tokenizer_mode=tokenizer_mode,
  135. skip_tokenizer_init=skip_tokenizer_init,
  136. trust_remote_code=trust_remote_code,
  137. tensor_parallel_size=tensor_parallel_size,
  138. dtype=dtype,
  139. quantization=quantization,
  140. revision=revision,
  141. tokenizer_revision=tokenizer_revision,
  142. seed=seed,
  143. gpu_memory_utilization=gpu_memory_utilization,
  144. swap_space=swap_space,
  145. cpu_offload_gb=cpu_offload_gb,
  146. enforce_eager=enforce_eager,
  147. max_context_len_to_capture=max_context_len_to_capture,
  148. max_seq_len_to_capture=max_seq_len_to_capture,
  149. disable_custom_all_reduce=disable_custom_all_reduce,
  150. **kwargs,
  151. )
  152. self.llm_engine = AphroditeEngine.from_engine_args(engine_args)
  153. self.request_counter = Counter()
  154. def get_tokenizer(
  155. self) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:
  156. return self.llm_engine.tokenizer.tokenizer
  157. def set_tokenizer(
  158. self,
  159. tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast],
  160. ) -> None:
  161. # While CachedTokenizer is dynamic, have no choice but
  162. # compare class name. Misjudgment will arise from
  163. # user-defined tokenizer started with 'Cached'
  164. if tokenizer.__class__.__name__.startswith("Cached"):
  165. self.llm_engine.tokenizer.tokenizer = tokenizer
  166. else:
  167. self.llm_engine.tokenizer.tokenizer = get_cached_tokenizer(
  168. tokenizer)
  169. @overload # LEGACY: single (prompt + optional token ids)
  170. def generate(
  171. self,
  172. prompts: str,
  173. sampling_params: Optional[Union[SamplingParams,
  174. List[SamplingParams]]] = None,
  175. prompt_token_ids: Optional[List[int]] = None,
  176. use_tqdm: bool = True,
  177. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  178. ) -> List[RequestOutput]:
  179. ...
  180. @overload # LEGACY: multi (prompt + optional token ids)
  181. def generate(
  182. self,
  183. prompts: List[str],
  184. sampling_params: Optional[Union[SamplingParams,
  185. List[SamplingParams]]] = None,
  186. prompt_token_ids: Optional[List[List[int]]] = None,
  187. use_tqdm: bool = True,
  188. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  189. ) -> List[RequestOutput]:
  190. ...
  191. @overload # LEGACY: single (token ids + optional prompt)
  192. def generate(
  193. self,
  194. prompts: Optional[str] = None,
  195. sampling_params: Optional[Union[SamplingParams,
  196. List[SamplingParams]]] = None,
  197. *,
  198. prompt_token_ids: List[int],
  199. use_tqdm: bool = True,
  200. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  201. ) -> List[RequestOutput]:
  202. ...
  203. @overload # LEGACY: multi (token ids + optional prompt)
  204. def generate(
  205. self,
  206. prompts: Optional[List[str]] = None,
  207. sampling_params: Optional[Union[SamplingParams,
  208. List[SamplingParams]]] = None,
  209. *,
  210. prompt_token_ids: List[List[int]],
  211. use_tqdm: bool = True,
  212. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  213. ) -> List[RequestOutput]:
  214. ...
  215. @overload # LEGACY: single or multi token ids [pos-only]
  216. def generate(
  217. self,
  218. prompts: None,
  219. sampling_params: None,
  220. prompt_token_ids: Union[List[int], List[List[int]]],
  221. use_tqdm: bool = True,
  222. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  223. ) -> List[RequestOutput]:
  224. ...
  225. @overload
  226. def generate(
  227. self,
  228. inputs: Union[PromptInputs, Sequence[PromptInputs]],
  229. /, # We may enable `inputs` keyword after removing the old API
  230. *,
  231. sampling_params: Optional[Union[SamplingParams,
  232. Sequence[SamplingParams]]] = None,
  233. use_tqdm: bool = True,
  234. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  235. ) -> List[RequestOutput]:
  236. ...
  237. @deprecate_kwargs("prompts",
  238. "prompt_token_ids",
  239. is_deprecated=lambda: LLM.DEPRECATE_LEGACY,
  240. additional_message="Please use the 'inputs' parameter "
  241. "instead.")
  242. def generate(
  243. self,
  244. prompts: Union[Union[PromptInputs, Sequence[PromptInputs]],
  245. Optional[Union[str, List[str]]]] = None,
  246. sampling_params: Optional[Union[SamplingParams,
  247. Sequence[SamplingParams]]] = None,
  248. prompt_token_ids: Optional[Union[List[int], List[List[int]]]] = None,
  249. use_tqdm: bool = True,
  250. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  251. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  252. guided_options_request: Optional[Union[LLMGuidedOptions,
  253. GuidedDecodingRequest]] = None,
  254. ) -> List[RequestOutput]:
  255. """Generates the completions for the input prompts.
  256. This class automatically batches the given prompts, considering
  257. the memory constraint. For the best performance, put all of your prompts
  258. into a single list and pass it to this method.
  259. Args:
  260. inputs: A list of inputs to generate completions for.
  261. sampling_params: The sampling parameters for text generation. If
  262. None, we use the default sampling parameters.
  263. When it is a single value, it is applied to every prompt.
  264. When it is a list, the list must have the same length as the
  265. prompts and it is paired one by one with the prompt.
  266. use_tqdm: Whether to use tqdm to display the progress bar.
  267. lora_request: LoRA request to use for generation, if any.
  268. prompt_adapter_request: Prompt Adapter request to use for
  269. generation, if any.
  270. Returns:
  271. A list of `RequestOutput` objects containing the
  272. generated completions in the same order as the input prompts.
  273. Note:
  274. Using ``prompts`` and ``prompt_token_ids`` as keyword parameters is
  275. considered legacy and may be deprecated in the future. You should
  276. instead pass them via the ``inputs`` parameter.
  277. """
  278. if self.llm_engine.model_config.embedding_mode:
  279. raise ValueError(
  280. "LLM.generate() is only supported for (conditional) generation "
  281. "models (XForCausalLM, XForConditionalGeneration).")
  282. if prompt_token_ids is not None:
  283. inputs = self._convert_v1_inputs(
  284. prompts=cast(Optional[Union[str, List[str]]], prompts),
  285. prompt_token_ids=prompt_token_ids,
  286. )
  287. else:
  288. inputs = cast(Union[PromptInputs, Sequence[PromptInputs]], prompts)
  289. if isinstance(guided_options_request, dict):
  290. if len(guided_options_request) > 1:
  291. raise ValueError(
  292. "You can only use one guided decoding but multiple is "
  293. f"specified: {guided_options_request}")
  294. guided_options_request = GuidedDecodingRequest(
  295. **guided_options_request)
  296. if sampling_params is None:
  297. # Use default sampling params.
  298. sampling_params = SamplingParams()
  299. self._validate_and_add_requests(
  300. inputs=inputs,
  301. params=sampling_params,
  302. lora_request=lora_request,
  303. prompt_adapter_request=prompt_adapter_request,
  304. guided_options=guided_options_request,
  305. )
  306. outputs = self._run_engine(use_tqdm=use_tqdm)
  307. return AphroditeEngine.validate_outputs(outputs, RequestOutput)
  308. def chat(
  309. self,
  310. messages: List[ChatCompletionMessageParam],
  311. sampling_params: Optional[Union[SamplingParams,
  312. List[SamplingParams]]] = None,
  313. use_tqdm: bool = True,
  314. lora_request: Optional[LoRARequest] = None,
  315. chat_template: Optional[str] = None,
  316. add_generation_prompt: bool = True,
  317. ) -> List[RequestOutput]:
  318. """
  319. Generates responses for chat messages.
  320. Converts the messages to prompts using the tokenizer and calls
  321. the :meth:`generate` method to generate the responses.
  322. Args:
  323. messages: A list of messages to generate responses for. Each
  324. message is a list of dictionaries with 'role' and 'content'
  325. keys.
  326. sampling_params: The sampling parameters for text generation.
  327. If None, we use the default sampling parameters. When it
  328. is a single value, it is applied to every prompt. When it
  329. is a list, the list must have the same length as the
  330. prompts and it is paired one by one with the prompt.
  331. use_tqdm: Whether to use tqdm to display the progress bar.
  332. lora_request: LoRA request to use for generation, if any.
  333. chat_template: The template to use for structuring the chat.
  334. If not provided, the model's default chat template will be used.
  335. add_generation_prompt: If True, adds a generation template
  336. to each message.
  337. Returns:
  338. A list of ``RequestOutput`` objects containing the generated
  339. responses in the same order as the input messages.
  340. """
  341. tokenizer = self.get_tokenizer()
  342. model_config = self.llm_engine.get_model_config()
  343. conversations, _ = parse_chat_messages(messages, model_config,
  344. tokenizer)
  345. prompts = apply_chat_template(
  346. tokenizer,
  347. conversations,
  348. chat_template=chat_template,
  349. add_generation_prompt=add_generation_prompt)
  350. return self.generate(
  351. prompts,
  352. sampling_params,
  353. use_tqdm=use_tqdm,
  354. lora_request=lora_request,
  355. )
  356. @overload # LEGACY: single (prompt + optional token ids)
  357. def encode(
  358. self,
  359. prompts: str,
  360. pooling_params: Optional[Union[PoolingParams,
  361. Sequence[PoolingParams]]] = None,
  362. prompt_token_ids: Optional[List[int]] = None,
  363. use_tqdm: bool = True,
  364. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  365. ) -> List[EmbeddingRequestOutput]:
  366. ...
  367. @overload # LEGACY: multi (prompt + optional token ids)
  368. def encode(
  369. self,
  370. prompts: List[str],
  371. pooling_params: Optional[Union[PoolingParams,
  372. Sequence[PoolingParams]]] = None,
  373. prompt_token_ids: Optional[List[List[int]]] = None,
  374. use_tqdm: bool = True,
  375. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  376. ) -> List[EmbeddingRequestOutput]:
  377. ...
  378. @overload # LEGACY: single (token ids + optional prompt)
  379. def encode(
  380. self,
  381. prompts: Optional[str] = None,
  382. pooling_params: Optional[Union[PoolingParams,
  383. Sequence[PoolingParams]]] = None,
  384. *,
  385. prompt_token_ids: List[int],
  386. use_tqdm: bool = True,
  387. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  388. ) -> List[EmbeddingRequestOutput]:
  389. ...
  390. @overload # LEGACY: multi (token ids + optional prompt)
  391. def encode(
  392. self,
  393. prompts: Optional[List[str]] = None,
  394. pooling_params: Optional[Union[PoolingParams,
  395. Sequence[PoolingParams]]] = None,
  396. *,
  397. prompt_token_ids: List[List[int]],
  398. use_tqdm: bool = True,
  399. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  400. ) -> List[EmbeddingRequestOutput]:
  401. ...
  402. @overload # LEGACY: single or multi token ids [pos-only]
  403. def encode(
  404. self,
  405. prompts: None,
  406. pooling_params: None,
  407. prompt_token_ids: Union[List[int], List[List[int]]],
  408. use_tqdm: bool = True,
  409. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  410. ) -> List[EmbeddingRequestOutput]:
  411. ...
  412. @overload
  413. def encode(
  414. self,
  415. inputs: Union[PromptInputs, Sequence[PromptInputs]],
  416. /, # We may enable `inputs` keyword after removing the old API
  417. *,
  418. pooling_params: Optional[Union[PoolingParams,
  419. Sequence[PoolingParams]]] = None,
  420. use_tqdm: bool = True,
  421. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  422. ) -> List[EmbeddingRequestOutput]:
  423. ...
  424. @deprecate_kwargs("prompts",
  425. "prompt_token_ids",
  426. is_deprecated=lambda: LLM.DEPRECATE_LEGACY,
  427. additional_message="Please use the 'inputs' parameter "
  428. "instead.")
  429. def encode(
  430. self,
  431. prompts: Union[Union[PromptInputs, Sequence[PromptInputs]],
  432. Optional[Union[str, List[str]]]] = None,
  433. pooling_params: Optional[Union[PoolingParams,
  434. Sequence[PoolingParams]]] = None,
  435. prompt_token_ids: Optional[Union[List[int], List[List[int]]]] = None,
  436. use_tqdm: bool = True,
  437. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  438. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  439. ) -> List[EmbeddingRequestOutput]:
  440. """Generates the completions for the input prompts.
  441. This class automatically batches the given prompts, considering
  442. the memory constraint. For the best performance, put all of your prompts
  443. into a single list and pass it to this method.
  444. Args:
  445. inputs: The inputs to the LLM. You may pass a sequence of inputs for
  446. batch inference. See
  447. :class:`~aphrodite.inputs.PromptInputs`
  448. for more details about the format of each input.
  449. pooling_params: The pooling parameters for pooling. If None, we
  450. use the default pooling parameters.
  451. use_tqdm: Whether to use tqdm to display the progress bar.
  452. lora_request: LoRA request to use for generation, if any.
  453. prompt_adapter_request: Prompt Adapter request to use for
  454. generation, if any.
  455. Returns:
  456. A list of `EmbeddingRequestOutput` objects containing the
  457. generated embeddings in the same order as the input prompts.
  458. Note:
  459. Using ``prompts`` and ``prompt_token_ids`` as keyword parameters is
  460. considered legacy and may be deprecated in the future. You should
  461. instead pass them via the ``inputs`` parameter.
  462. """
  463. if not self.llm_engine.model_config.embedding_mode:
  464. raise ValueError(
  465. "LLM.encode() is only supported for embedding models (XModel)."
  466. )
  467. if prompt_token_ids is not None:
  468. inputs = self._convert_v1_inputs(
  469. prompts=cast(Optional[Union[str, List[str]]], prompts),
  470. prompt_token_ids=prompt_token_ids,
  471. )
  472. else:
  473. inputs = cast(Union[PromptInputs, Sequence[PromptInputs]], prompts)
  474. if pooling_params is None:
  475. # Use default pooling params.
  476. pooling_params = PoolingParams()
  477. self._validate_and_add_requests(
  478. inputs=inputs,
  479. params=pooling_params,
  480. lora_request=lora_request,
  481. prompt_adapter_request=prompt_adapter_request)
  482. outputs = self._run_engine(use_tqdm=use_tqdm)
  483. return AphroditeEngine.validate_outputs(outputs,
  484. EmbeddingRequestOutput)
  485. # LEGACY
  486. def _convert_v1_inputs(
  487. self,
  488. prompts: Optional[Union[str, List[str]]],
  489. prompt_token_ids: Optional[Union[List[int], List[List[int]]]],
  490. ):
  491. # skip_tokenizer_init is now checked in engine
  492. if prompts is not None:
  493. prompts = [p["content"] for p in parse_and_batch_prompt(prompts)]
  494. if prompt_token_ids is not None:
  495. prompt_token_ids = [
  496. p["content"] for p in parse_and_batch_prompt(prompt_token_ids)
  497. ]
  498. num_requests = None
  499. if prompts is not None:
  500. num_requests = len(prompts)
  501. if prompt_token_ids is not None:
  502. if (num_requests is not None
  503. and num_requests != len(prompt_token_ids)):
  504. raise ValueError("The lengths of prompts and prompt_token_ids "
  505. "must be the same.")
  506. num_requests = len(prompt_token_ids)
  507. if num_requests is None:
  508. raise ValueError("Either prompts or prompt_token_ids must be "
  509. "provided.")
  510. inputs: List[PromptInputs] = []
  511. for i in range(num_requests):
  512. if prompts is not None:
  513. item = TextPrompt(prompt=prompts[i])
  514. elif prompt_token_ids is not None:
  515. item = TokensPrompt(prompt_token_ids=prompt_token_ids[i])
  516. else:
  517. raise AssertionError
  518. inputs.append(item)
  519. return inputs
  520. def _validate_and_add_requests(
  521. self,
  522. inputs: Union[PromptInputs, Sequence[PromptInputs]],
  523. params: Union[SamplingParams, Sequence[SamplingParams], PoolingParams,
  524. Sequence[PoolingParams]],
  525. lora_request: Optional[Union[Sequence[LoRARequest], LoRARequest]],
  526. prompt_adapter_request: Optional[PromptAdapterRequest],
  527. guided_options: Optional[GuidedDecodingRequest] = None,
  528. ) -> None:
  529. if isinstance(inputs, (str, dict)):
  530. # Convert a single prompt to a list.
  531. inputs = [inputs]
  532. num_requests = len(inputs)
  533. if isinstance(params, list) and len(params) != num_requests:
  534. raise ValueError("The lengths of prompts and params "
  535. "must be the same.")
  536. if isinstance(lora_request,
  537. list) and len(lora_request) != num_requests:
  538. raise ValueError("The lengths of prompts and lora_request "
  539. "must be the same.")
  540. if isinstance(params, list):
  541. params = [
  542. self._add_guided_processor(param, guided_options)
  543. if isinstance(param, SamplingParams) else param
  544. for param in params
  545. ]
  546. elif isinstance(params, SamplingParams):
  547. params = self._add_guided_processor(params, guided_options)
  548. # Add requests to the engine.
  549. for i, request_inputs in enumerate(inputs):
  550. self._add_request(
  551. request_inputs,
  552. params[i] if isinstance(params, Sequence) else params,
  553. lora_request=lora_request[i] if isinstance(
  554. lora_request, Sequence) else lora_request,
  555. prompt_adapter_request=prompt_adapter_request,
  556. )
  557. def _add_request(
  558. self,
  559. inputs: PromptInputs,
  560. params: Union[SamplingParams, PoolingParams],
  561. lora_request: Optional[Union[List[LoRARequest],
  562. LoRARequest]] = None,
  563. prompt_adapter_request: Optional[PromptAdapterRequest] = None
  564. ) -> None:
  565. request_id = str(next(self.request_counter))
  566. self.llm_engine.add_request(
  567. request_id,
  568. inputs,
  569. params,
  570. lora_request=lora_request,
  571. prompt_adapter_request=prompt_adapter_request)
  572. def _add_guided_processor(
  573. self,
  574. params: SamplingParams,
  575. guided_options: Optional[GuidedDecodingRequest] = None):
  576. if guided_options:
  577. if guided_options.guided_decoding_backend is None:
  578. decoding_config = self.llm_engine.get_decoding_config()
  579. guided_options.guided_decoding_backend = (
  580. decoding_config.guided_decoding_backend)
  581. guided_logits_processor = get_local_guided_decoding_logits_processor( #noqa
  582. guided_options.guided_decoding_backend, guided_options,
  583. self.get_tokenizer())
  584. if guided_logits_processor:
  585. if params.logits_processors is None:
  586. params.logits_processors = []
  587. params.logits_processors.append(guided_logits_processor)
  588. return params
  589. def _run_engine(
  590. self, *, use_tqdm: bool
  591. ) -> List[Union[RequestOutput, EmbeddingRequestOutput]]:
  592. # Initialize tqdm.
  593. if use_tqdm:
  594. num_requests = self.llm_engine.get_num_unfinished_requests()
  595. pbar = tqdm(
  596. total=num_requests,
  597. desc="Processed prompts",
  598. dynamic_ncols=True,
  599. postfix=(f"est. speed input: {0:.2f} toks/s, "
  600. f"output: {0:.2f} toks/s"),
  601. )
  602. # Run the engine.
  603. outputs: List[Union[RequestOutput, EmbeddingRequestOutput]] = []
  604. total_in_toks = 0
  605. total_out_toks = 0
  606. while self.llm_engine.has_unfinished_requests():
  607. step_outputs = self.llm_engine.step()
  608. for output in step_outputs:
  609. if output.finished:
  610. outputs.append(output)
  611. if use_tqdm:
  612. if isinstance(output, RequestOutput):
  613. # Calculate tokens only for RequestOutput
  614. total_in_toks += len(output.prompt_token_ids)
  615. in_spd = total_in_toks / pbar.format_dict["elapsed"]
  616. total_out_toks += sum(
  617. len(stp.token_ids) for stp in output.outputs)
  618. out_spd = total_out_toks / pbar.format_dict[
  619. "elapsed"]
  620. pbar.postfix = (
  621. f"est. speed input: {in_spd:.2f} toks/s, "
  622. f"output: {out_spd:.2f} toks/s")
  623. pbar.update(1)
  624. if use_tqdm:
  625. pbar.close()
  626. # Sort the outputs by request ID.
  627. # This is necessary because some requests may be finished earlier than
  628. # its previous requests.
  629. return sorted(outputs, key=lambda x: int(x.request_id))
  630. def _is_encoder_decoder_model(self):
  631. return self.llm_engine.is_encoder_decoder_model()
  632. def _is_embedding_model(self):
  633. return self.llm_engine.is_embedding_model()