llm.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. 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: bool = False,
  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. if "disable_log_stats" not in kwargs:
  115. kwargs["disable_log_stats"] = True
  116. removed_vision_keys = ("image_token_id", "image_feature_size",
  117. "image_input_shape", "image_input_type")
  118. if any(k in kwargs for k in removed_vision_keys):
  119. raise TypeError(
  120. "There is no need to pass vision-related arguments anymore.")
  121. engine_args = EngineArgs(
  122. model=model,
  123. tokenizer=tokenizer,
  124. tokenizer_mode=tokenizer_mode,
  125. skip_tokenizer_init=skip_tokenizer_init,
  126. trust_remote_code=trust_remote_code,
  127. tensor_parallel_size=tensor_parallel_size,
  128. dtype=dtype,
  129. quantization=quantization,
  130. revision=revision,
  131. tokenizer_revision=tokenizer_revision,
  132. seed=seed,
  133. gpu_memory_utilization=gpu_memory_utilization,
  134. swap_space=swap_space,
  135. cpu_offload_gb=cpu_offload_gb,
  136. enforce_eager=enforce_eager,
  137. max_context_len_to_capture=max_context_len_to_capture,
  138. max_seq_len_to_capture=max_seq_len_to_capture,
  139. disable_custom_all_reduce=disable_custom_all_reduce,
  140. **kwargs,
  141. )
  142. self.llm_engine = AphroditeEngine.from_engine_args(engine_args)
  143. self.request_counter = Counter()
  144. def get_tokenizer(
  145. self) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:
  146. return self.llm_engine.tokenizer.tokenizer
  147. def set_tokenizer(
  148. self,
  149. tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast],
  150. ) -> None:
  151. # While CachedTokenizer is dynamic, have no choice but
  152. # compare class name. Misjudgment will arise from
  153. # user-defined tokenizer started with 'Cached'
  154. if tokenizer.__class__.__name__.startswith("Cached"):
  155. self.llm_engine.tokenizer.tokenizer = tokenizer
  156. else:
  157. self.llm_engine.tokenizer.tokenizer = get_cached_tokenizer(
  158. tokenizer)
  159. @overload # LEGACY: single (prompt + optional token ids)
  160. def generate(
  161. self,
  162. prompts: str,
  163. sampling_params: Optional[Union[SamplingParams,
  164. List[SamplingParams]]] = None,
  165. prompt_token_ids: Optional[List[int]] = None,
  166. use_tqdm: bool = True,
  167. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  168. ) -> List[RequestOutput]:
  169. ...
  170. @overload # LEGACY: multi (prompt + optional token ids)
  171. def generate(
  172. self,
  173. prompts: List[str],
  174. sampling_params: Optional[Union[SamplingParams,
  175. List[SamplingParams]]] = None,
  176. prompt_token_ids: Optional[List[List[int]]] = None,
  177. use_tqdm: bool = True,
  178. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  179. ) -> List[RequestOutput]:
  180. ...
  181. @overload # LEGACY: single (token ids + optional prompt)
  182. def generate(
  183. self,
  184. prompts: Optional[str] = None,
  185. sampling_params: Optional[Union[SamplingParams,
  186. List[SamplingParams]]] = None,
  187. *,
  188. prompt_token_ids: List[int],
  189. use_tqdm: bool = True,
  190. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  191. ) -> List[RequestOutput]:
  192. ...
  193. @overload # LEGACY: multi (token ids + optional prompt)
  194. def generate(
  195. self,
  196. prompts: Optional[List[str]] = None,
  197. sampling_params: Optional[Union[SamplingParams,
  198. List[SamplingParams]]] = None,
  199. *,
  200. prompt_token_ids: List[List[int]],
  201. use_tqdm: bool = True,
  202. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  203. ) -> List[RequestOutput]:
  204. ...
  205. @overload # LEGACY: single or multi token ids [pos-only]
  206. def generate(
  207. self,
  208. prompts: None,
  209. sampling_params: None,
  210. prompt_token_ids: Union[List[int], List[List[int]]],
  211. use_tqdm: bool = True,
  212. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  213. ) -> List[RequestOutput]:
  214. ...
  215. @overload
  216. def generate(
  217. self,
  218. inputs: Union[PromptInputs, Sequence[PromptInputs]],
  219. /, # We may enable `inputs` keyword after removing the old API
  220. *,
  221. sampling_params: Optional[Union[SamplingParams,
  222. Sequence[SamplingParams]]] = None,
  223. use_tqdm: bool = True,
  224. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  225. ) -> List[RequestOutput]:
  226. ...
  227. @deprecate_kwargs("prompts",
  228. "prompt_token_ids",
  229. is_deprecated=lambda: LLM.DEPRECATE_LEGACY,
  230. additional_message="Please use the 'inputs' parameter "
  231. "instead.")
  232. def generate(
  233. self,
  234. prompts: Union[Union[PromptInputs, Sequence[PromptInputs]],
  235. Optional[Union[str, List[str]]]] = None,
  236. sampling_params: Optional[Union[SamplingParams,
  237. Sequence[SamplingParams]]] = None,
  238. prompt_token_ids: Optional[Union[List[int], List[List[int]]]] = None,
  239. use_tqdm: bool = True,
  240. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  241. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  242. guided_options_request: Optional[Union[LLMGuidedOptions,
  243. GuidedDecodingRequest]] = None,
  244. ) -> List[RequestOutput]:
  245. """Generates the completions for the input prompts.
  246. This class automatically batches the given prompts, considering
  247. the memory constraint. For the best performance, put all of your prompts
  248. into a single list and pass it to this method.
  249. Args:
  250. inputs: A list of inputs to generate completions for.
  251. sampling_params: The sampling parameters for text generation. If
  252. None, we use the default sampling parameters.
  253. When it is a single value, it is applied to every prompt.
  254. When it is a list, the list must have the same length as the
  255. prompts and it is paired one by one with the prompt.
  256. use_tqdm: Whether to use tqdm to display the progress bar.
  257. lora_request: LoRA request to use for generation, if any.
  258. prompt_adapter_request: Prompt Adapter request to use for
  259. generation, if any.
  260. Returns:
  261. A list of `RequestOutput` objects containing the
  262. generated completions in the same order as the input prompts.
  263. Note:
  264. Using ``prompts`` and ``prompt_token_ids`` as keyword parameters is
  265. considered legacy and may be deprecated in the future. You should
  266. instead pass them via the ``inputs`` parameter.
  267. """
  268. if self.llm_engine.model_config.embedding_mode:
  269. raise ValueError(
  270. "LLM.generate() is only supported for generation models "
  271. "(XForCausalLM).")
  272. if prompt_token_ids is not None:
  273. inputs = self._convert_v1_inputs(
  274. prompts=cast(Optional[Union[str, List[str]]], prompts),
  275. prompt_token_ids=prompt_token_ids,
  276. )
  277. else:
  278. inputs = cast(Union[PromptInputs, Sequence[PromptInputs]], prompts)
  279. if isinstance(guided_options_request, dict):
  280. if len(guided_options_request) > 1:
  281. raise ValueError(
  282. "You can only use one guided decoding but multiple is "
  283. f"specified: {guided_options_request}")
  284. guided_options_request = GuidedDecodingRequest(
  285. **guided_options_request)
  286. if sampling_params is None:
  287. # Use default sampling params.
  288. sampling_params = SamplingParams()
  289. self._validate_and_add_requests(
  290. inputs=inputs,
  291. params=sampling_params,
  292. lora_request=lora_request,
  293. prompt_adapter_request=prompt_adapter_request,
  294. guided_options=guided_options_request,
  295. )
  296. outputs = self._run_engine(use_tqdm=use_tqdm)
  297. return AphroditeEngine.validate_outputs(outputs, RequestOutput)
  298. @overload # LEGACY: single (prompt + optional token ids)
  299. def encode(
  300. self,
  301. prompts: str,
  302. pooling_params: Optional[Union[PoolingParams,
  303. Sequence[PoolingParams]]] = None,
  304. prompt_token_ids: Optional[List[int]] = None,
  305. use_tqdm: bool = True,
  306. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  307. ) -> List[EmbeddingRequestOutput]:
  308. ...
  309. @overload # LEGACY: multi (prompt + optional token ids)
  310. def encode(
  311. self,
  312. prompts: List[str],
  313. pooling_params: Optional[Union[PoolingParams,
  314. Sequence[PoolingParams]]] = None,
  315. prompt_token_ids: Optional[List[List[int]]] = None,
  316. use_tqdm: bool = True,
  317. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  318. ) -> List[EmbeddingRequestOutput]:
  319. ...
  320. @overload # LEGACY: single (token ids + optional prompt)
  321. def encode(
  322. self,
  323. prompts: Optional[str] = None,
  324. pooling_params: Optional[Union[PoolingParams,
  325. Sequence[PoolingParams]]] = None,
  326. *,
  327. prompt_token_ids: List[int],
  328. use_tqdm: bool = True,
  329. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  330. ) -> List[EmbeddingRequestOutput]:
  331. ...
  332. @overload # LEGACY: multi (token ids + optional prompt)
  333. def encode(
  334. self,
  335. prompts: Optional[List[str]] = None,
  336. pooling_params: Optional[Union[PoolingParams,
  337. Sequence[PoolingParams]]] = None,
  338. *,
  339. prompt_token_ids: List[List[int]],
  340. use_tqdm: bool = True,
  341. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  342. ) -> List[EmbeddingRequestOutput]:
  343. ...
  344. @overload # LEGACY: single or multi token ids [pos-only]
  345. def encode(
  346. self,
  347. prompts: None,
  348. pooling_params: None,
  349. prompt_token_ids: Union[List[int], List[List[int]]],
  350. use_tqdm: bool = True,
  351. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  352. ) -> List[EmbeddingRequestOutput]:
  353. ...
  354. @overload
  355. def encode(
  356. self,
  357. inputs: Union[PromptInputs, Sequence[PromptInputs]],
  358. /, # We may enable `inputs` keyword after removing the old API
  359. *,
  360. pooling_params: Optional[Union[PoolingParams,
  361. Sequence[PoolingParams]]] = None,
  362. use_tqdm: bool = True,
  363. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  364. ) -> List[EmbeddingRequestOutput]:
  365. ...
  366. @deprecate_kwargs("prompts",
  367. "prompt_token_ids",
  368. is_deprecated=lambda: LLM.DEPRECATE_LEGACY,
  369. additional_message="Please use the 'inputs' parameter "
  370. "instead.")
  371. def encode(
  372. self,
  373. prompts: Union[Union[PromptInputs, Sequence[PromptInputs]],
  374. Optional[Union[str, List[str]]]] = None,
  375. pooling_params: Optional[Union[PoolingParams,
  376. Sequence[PoolingParams]]] = None,
  377. prompt_token_ids: Optional[Union[List[int], List[List[int]]]] = None,
  378. use_tqdm: bool = True,
  379. lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
  380. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  381. ) -> List[EmbeddingRequestOutput]:
  382. """Generates the completions for the input prompts.
  383. This class automatically batches the given prompts, considering
  384. the memory constraint. For the best performance, put all of your prompts
  385. into a single list and pass it to this method.
  386. Args:
  387. inputs: The inputs to the LLM. You may pass a sequence of inputs for
  388. batch inference. See
  389. :class:`~aphrodite.inputs.PromptInputs`
  390. for more details about the format of each input.
  391. pooling_params: The pooling parameters for pooling. If None, we
  392. use the default pooling parameters.
  393. use_tqdm: Whether to use tqdm to display the progress bar.
  394. lora_request: LoRA request to use for generation, if any.
  395. prompt_adapter_request: Prompt Adapter request to use for
  396. generation, if any.
  397. Returns:
  398. A list of `EmbeddingRequestOutput` objects containing the
  399. generated embeddings in the same order as the input prompts.
  400. Note:
  401. Using ``prompts`` and ``prompt_token_ids`` as keyword parameters is
  402. considered legacy and may be deprecated in the future. You should
  403. instead pass them via the ``inputs`` parameter.
  404. """
  405. if not self.llm_engine.model_config.embedding_mode:
  406. raise ValueError(
  407. "LLM.encode() is only supported for embedding models (XModel)."
  408. )
  409. if prompt_token_ids is not None:
  410. inputs = self._convert_v1_inputs(
  411. prompts=cast(Optional[Union[str, List[str]]], prompts),
  412. prompt_token_ids=prompt_token_ids,
  413. )
  414. else:
  415. inputs = cast(Union[PromptInputs, Sequence[PromptInputs]], prompts)
  416. if pooling_params is None:
  417. # Use default pooling params.
  418. pooling_params = PoolingParams()
  419. self._validate_and_add_requests(
  420. inputs=inputs,
  421. params=pooling_params,
  422. lora_request=lora_request,
  423. prompt_adapter_request=prompt_adapter_request)
  424. outputs = self._run_engine(use_tqdm=use_tqdm)
  425. return AphroditeEngine.validate_outputs(outputs,
  426. EmbeddingRequestOutput)
  427. # LEGACY
  428. def _convert_v1_inputs(
  429. self,
  430. prompts: Optional[Union[str, List[str]]],
  431. prompt_token_ids: Optional[Union[List[int], List[List[int]]]],
  432. ):
  433. # skip_tokenizer_init is now checked in engine
  434. if prompts is not None:
  435. prompts = [p["content"] for p in parse_and_batch_prompt(prompts)]
  436. if prompt_token_ids is not None:
  437. prompt_token_ids = [
  438. p["content"] for p in parse_and_batch_prompt(prompt_token_ids)
  439. ]
  440. num_requests = None
  441. if prompts is not None:
  442. num_requests = len(prompts)
  443. if prompt_token_ids is not None:
  444. if (num_requests is not None
  445. and num_requests != len(prompt_token_ids)):
  446. raise ValueError("The lengths of prompts and prompt_token_ids "
  447. "must be the same.")
  448. num_requests = len(prompt_token_ids)
  449. if num_requests is None:
  450. raise ValueError("Either prompts or prompt_token_ids must be "
  451. "provided.")
  452. inputs: List[PromptInputs] = []
  453. for i in range(num_requests):
  454. if prompts is not None:
  455. item = TextPrompt(prompt=prompts[i])
  456. elif prompt_token_ids is not None:
  457. item = TokensPrompt(prompt_token_ids=prompt_token_ids[i])
  458. else:
  459. raise AssertionError
  460. inputs.append(item)
  461. return inputs
  462. def _validate_and_add_requests(
  463. self,
  464. inputs: Union[PromptInputs, Sequence[PromptInputs]],
  465. params: Union[SamplingParams, Sequence[SamplingParams], PoolingParams,
  466. Sequence[PoolingParams]],
  467. lora_request: Optional[Union[Sequence[LoRARequest], LoRARequest]],
  468. prompt_adapter_request: Optional[PromptAdapterRequest],
  469. guided_options: Optional[GuidedDecodingRequest] = None,
  470. ) -> None:
  471. if isinstance(inputs, (str, dict)):
  472. # Convert a single prompt to a list.
  473. inputs = [inputs]
  474. num_requests = len(inputs)
  475. if isinstance(params, list) and len(params) != num_requests:
  476. raise ValueError("The lengths of prompts and params "
  477. "must be the same.")
  478. if isinstance(lora_request,
  479. list) and len(lora_request) != num_requests:
  480. raise ValueError("The lengths of prompts and lora_request "
  481. "must be the same.")
  482. if isinstance(params, list):
  483. params = [
  484. self._add_guided_processor(param, guided_options)
  485. if isinstance(param, SamplingParams) else param
  486. for param in params
  487. ]
  488. elif isinstance(params, SamplingParams):
  489. params = self._add_guided_processor(params, guided_options)
  490. # Add requests to the engine.
  491. for i, request_inputs in enumerate(inputs):
  492. self._add_request(
  493. request_inputs,
  494. params[i] if isinstance(params, Sequence) else params,
  495. lora_request=lora_request[i] if isinstance(
  496. lora_request, Sequence) else lora_request,
  497. prompt_adapter_request=prompt_adapter_request,
  498. )
  499. def _add_request(
  500. self,
  501. inputs: PromptInputs,
  502. params: Union[SamplingParams, PoolingParams],
  503. lora_request: Optional[Union[List[LoRARequest],
  504. LoRARequest]] = None,
  505. prompt_adapter_request: Optional[PromptAdapterRequest] = None
  506. ) -> None:
  507. request_id = str(next(self.request_counter))
  508. self.llm_engine.add_request(
  509. request_id,
  510. inputs,
  511. params,
  512. lora_request=lora_request,
  513. prompt_adapter_request=prompt_adapter_request)
  514. def _add_guided_processor(
  515. self,
  516. params: SamplingParams,
  517. guided_options: Optional[GuidedDecodingRequest] = None):
  518. if guided_options:
  519. if guided_options.guided_decoding_backend is None:
  520. decoding_config = self.llm_engine.get_decoding_config()
  521. guided_options.guided_decoding_backend = (
  522. decoding_config.guided_decoding_backend)
  523. guided_logits_processor = get_local_guided_decoding_logits_processor( #noqa
  524. guided_options.guided_decoding_backend, guided_options,
  525. self.get_tokenizer())
  526. if guided_logits_processor:
  527. if params.logits_processors is None:
  528. params.logits_processors = []
  529. params.logits_processors.append(guided_logits_processor)
  530. return params
  531. def _run_engine(
  532. self, *, use_tqdm: bool
  533. ) -> List[Union[RequestOutput, EmbeddingRequestOutput]]:
  534. # Initialize tqdm.
  535. if use_tqdm:
  536. num_requests = self.llm_engine.get_num_unfinished_requests()
  537. pbar = tqdm(
  538. total=num_requests,
  539. desc="Processed prompts",
  540. dynamic_ncols=True,
  541. postfix=(f"est. speed input: {0:.2f} toks/s, "
  542. f"output: {0:.2f} toks/s"),
  543. )
  544. # Run the engine.
  545. outputs: List[Union[RequestOutput, EmbeddingRequestOutput]] = []
  546. total_in_toks = 0
  547. total_out_toks = 0
  548. while self.llm_engine.has_unfinished_requests():
  549. step_outputs = self.llm_engine.step()
  550. for output in step_outputs:
  551. if output.finished:
  552. outputs.append(output)
  553. if use_tqdm:
  554. if isinstance(output, RequestOutput):
  555. # Calculate tokens only for RequestOutput
  556. total_in_toks += len(output.prompt_token_ids)
  557. in_spd = total_in_toks / pbar.format_dict["elapsed"]
  558. total_out_toks += sum(
  559. len(stp.token_ids) for stp in output.outputs)
  560. out_spd = total_out_toks / pbar.format_dict[
  561. "elapsed"]
  562. pbar.postfix = (
  563. f"est. speed input: {in_spd:.2f} toks/s, "
  564. f"output: {out_spd:.2f} toks/s")
  565. pbar.update(1)
  566. if use_tqdm:
  567. pbar.close()
  568. # Sort the outputs by request ID.
  569. # This is necessary because some requests may be finished earlier than
  570. # its previous requests.
  571. return sorted(outputs, key=lambda x: int(x.request_id))