llm.py 27 KB

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