llm.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. from typing import List, Optional, Union
  2. from tqdm import tqdm
  3. from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast
  4. from aphrodite.lora.request import LoRARequest
  5. from aphrodite.engine.args_tools import EngineArgs
  6. from aphrodite.engine.aphrodite_engine import AphroditeEngine
  7. from aphrodite.common.outputs import RequestOutput
  8. from aphrodite.common.sampling_params import SamplingParams
  9. from aphrodite.common.utils import Counter
  10. class LLM:
  11. """An LLM for generating texts from given prompts and sampling parameters.
  12. This class includes a tokenizer, a language model (possibly distributed
  13. across multiple GPUs), and GPU memory space allocated for intermediate
  14. states (aka KV cache). Given a batch of prompts and sampling parameters,
  15. this class generates texts from the model, using an intelligent batching
  16. mechanism and efficient memory management.
  17. NOTE: This class is intended to be used for offline inference. For online
  18. serving, use the `AsyncLLMEngine` class instead.
  19. NOTE: For the comprehensive list of arguments, see `EngineArgs`.
  20. Args:
  21. model: The name or path of a HuggingFace Transformers model.
  22. tokenizer: The name or path of a HuggingFace Transformers tokenizer.
  23. tokenizer_mode: The tokenizer mode. "auto" will use the fast tokenizer
  24. if available, and "slow" will always use the slow tokenizer.
  25. trust_remote_code: Trust remote code (e.g., from HuggingFace) when
  26. downloading the model and tokenizer.
  27. tensor_parallel_size: The number of GPUs to use for distributed
  28. execution with tensor parallelism.
  29. dtype: The data type for the model weights and activations. Currently,
  30. we support `float32`, `float16`, and `bfloat16`. If `auto`, we use
  31. the `torch_dtype` attribute specified in the model config file.
  32. However, if the `torch_dtype` in the config is `float32`, we will
  33. use `float16` instead.
  34. quantization: The method used to quantize the model weights. Currently,
  35. we support "awq", "gptq", "quip" and "squeezellm". If None,
  36. we first check the `quantization_config` attribute in the model
  37. config file. If that is None, we assume the model weights are not
  38. quantized and use `dtype` to determine the data type of the weights.
  39. revision: The specific model version to use. It can be a branch name,
  40. a tag name, or a commit id.
  41. seed: The seed to initialize the random number generator for sampling.
  42. gpu_memory_utilization: The ratio (between 0 and 1) of GPU memory to
  43. reserve for the model weights, activations, and KV cache. Higher
  44. values will increase the KV cache size and thus improve the model's
  45. throughput. However, if the value is too high, it may cause out-of-
  46. memory (OOM) errors.
  47. swap_space: The size (GiB) of CPU memory per GPU to use as swap space.
  48. This can be used for temporarily storing the states of the requests
  49. when their `best_of` sampling parameters are larger than 1. If all
  50. requests will have `best_of=1`, you can safely set this to 0.
  51. Otherwise, too small values may cause out-of-memory (OOM) errors.
  52. enforce_eager: Whether to enforce eager execution. If True, we will
  53. disable CUDA graph and always execute the model in eager mode.
  54. If False, we will use CUDA graph and eager execution in hybrid.
  55. max_context_len_to_capture: Maximum context len covered by CUDA graphs.
  56. When a sequence has context length larger than this, we fall back
  57. to eager mode.
  58. disable_custom_all_reduce: See ParallelConfig.
  59. """
  60. def __init__(
  61. self,
  62. model: str,
  63. tokenizer: Optional[str] = None,
  64. tokenizer_mode: str = "auto",
  65. trust_remote_code: bool = False,
  66. tensor_parallel_size: int = 1,
  67. dtype: str = "auto",
  68. quantization: Optional[str] = None,
  69. revision: Optional[str] = None,
  70. seed: int = 0,
  71. gpu_memory_utilization: float = 0.9,
  72. swap_space: int = 4,
  73. enforce_eager: bool = False,
  74. max_context_len_to_capture: int = 8192,
  75. disable_custom_all_reduce: bool = False,
  76. **kwargs,
  77. ) -> None:
  78. if "disable_log_stats" not in kwargs:
  79. kwargs["disable_log_stats"] = True
  80. engine_args = EngineArgs(
  81. model=model,
  82. tokenizer=tokenizer,
  83. tokenizer_mode=tokenizer_mode,
  84. trust_remote_code=trust_remote_code,
  85. tensor_parallel_size=tensor_parallel_size,
  86. dtype=dtype,
  87. quantization=quantization,
  88. revision=revision,
  89. seed=seed,
  90. gpu_memory_utilization=gpu_memory_utilization,
  91. swap_space=swap_space,
  92. enforce_eager=enforce_eager,
  93. max_context_len_to_capture=max_context_len_to_capture,
  94. disable_custom_all_reduce=disable_custom_all_reduce,
  95. **kwargs,
  96. )
  97. self.llm_engine = AphroditeEngine.from_engine_args(engine_args)
  98. self.request_counter = Counter()
  99. def get_tokenizer(
  100. self) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:
  101. return self.llm_engine.tokenizer
  102. def set_tokenizer(
  103. self,
  104. tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast],
  105. ) -> None:
  106. self.llm_engine.tokenizer = tokenizer
  107. def generate(
  108. self,
  109. prompts: Optional[Union[str, List[str]]] = None,
  110. sampling_params: Optional[SamplingParams] = None,
  111. prompt_token_ids: Optional[List[List[int]]] = None,
  112. use_tqdm: bool = True,
  113. lora_request: Optional[LoRARequest] = None,
  114. ) -> List[RequestOutput]:
  115. """Generates the completions for the input prompts.
  116. NOTE: This class automatically batches the given prompts, considering
  117. the memory constraint. For the best performance, put all of your prompts
  118. into a single list and pass it to this method.
  119. Args:
  120. prompts: A list of prompts to generate completions for.
  121. sampling_params: The sampling parameters for text generation. If
  122. None, we use the default sampling parameters.
  123. prompt_token_ids: A list of token IDs for the prompts. If None, we
  124. use the tokenizer to convert the prompts to token IDs.
  125. use_tqdm: Whether to use tqdm to display the progress bar.
  126. lora_request: LoRA request to use for generation, if any.
  127. Returns:
  128. A list of `RequestOutput` objects containing the generated
  129. completions in the same order as the input prompts.
  130. """
  131. if prompts is None and prompt_token_ids is None:
  132. raise ValueError("Either prompts or prompt_token_ids must be "
  133. "provided.")
  134. if isinstance(prompts, str):
  135. # Convert a single prompt to a list.
  136. prompts = [prompts]
  137. if prompts is not None and prompt_token_ids is not None:
  138. if len(prompts) != len(prompt_token_ids):
  139. raise ValueError("The lengths of prompts and prompt_token_ids "
  140. "must be the same.")
  141. if sampling_params is None:
  142. # Use default sampling params.
  143. sampling_params = SamplingParams()
  144. # Add requests to the engine.
  145. num_requests = len(prompts) if prompts is not None else len(
  146. prompt_token_ids)
  147. for i in range(num_requests):
  148. prompt = prompts[i] if prompts is not None else None
  149. token_ids = None if prompt_token_ids is None else prompt_token_ids[
  150. i]
  151. self._add_request(prompt,
  152. sampling_params,
  153. token_ids,
  154. lora_request=lora_request)
  155. return self._run_engine(use_tqdm)
  156. def _add_request(
  157. self,
  158. prompt: Optional[str],
  159. sampling_params: SamplingParams,
  160. prompt_token_ids: Optional[List[int]],
  161. lora_request: Optional[LoRARequest] = None,
  162. ) -> None:
  163. request_id = str(next(self.request_counter))
  164. self.llm_engine.add_request(request_id,
  165. prompt,
  166. sampling_params,
  167. prompt_token_ids,
  168. lora_request=lora_request)
  169. def _run_engine(self, use_tqdm: bool) -> List[RequestOutput]:
  170. # Initialize tqdm.
  171. if use_tqdm:
  172. num_requests = self.llm_engine.get_num_unfinished_requests()
  173. pbar = tqdm(total=num_requests, desc="Processed prompts")
  174. # Run the engine.
  175. outputs: List[RequestOutput] = []
  176. while self.llm_engine.has_unfinished_requests():
  177. step_outputs = self.llm_engine.step()
  178. for output in step_outputs:
  179. if output.finished:
  180. outputs.append(output)
  181. if use_tqdm:
  182. pbar.update(1)
  183. if use_tqdm:
  184. pbar.close()
  185. # Sort the outputs by request ID.
  186. # This is necessary because some requests may be finished earlier than
  187. # its previous requests.
  188. outputs = sorted(outputs, key=lambda x: int(x.request_id))
  189. return outputs