llm.py 25 KB

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