llm.py 11 KB

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