|
| 1 | +"""Module for running language models locally using the vLLM library.""" |
| 2 | + |
| 3 | + |
| 4 | +from logging import INFO, Logger |
| 5 | + |
| 6 | +try: |
| 7 | + import torch |
| 8 | + from transformers import AutoTokenizer |
| 9 | + from vllm import LLM, SamplingParams |
| 10 | +except ImportError as e: |
| 11 | + import logging |
| 12 | + |
| 13 | + logger = logging.getLogger(__name__) |
| 14 | + logger.warning(f"Could not import vllm, torch or transformers in vllm.py: {e}") |
| 15 | + |
| 16 | +from promptolution.llms.base_llm import BaseLLM |
| 17 | + |
| 18 | +logger = Logger(__name__) |
| 19 | +logger.setLevel(INFO) |
| 20 | + |
| 21 | + |
| 22 | +class VLLM(BaseLLM): |
| 23 | + """A class for running language models using the vLLM library. |
| 24 | +
|
| 25 | + This class sets up a vLLM inference engine with specified model parameters |
| 26 | + and provides a method to generate responses for given prompts. |
| 27 | +
|
| 28 | + Attributes: |
| 29 | + llm (vllm.LLM): The vLLM inference engine. |
| 30 | + tokenizer (transformers.PreTrainedTokenizer): The tokenizer for the model. |
| 31 | + sampling_params (vllm.SamplingParams): Parameters for text generation. |
| 32 | +
|
| 33 | + Methods: |
| 34 | + get_response: Generate responses for a list of prompts. |
| 35 | + """ |
| 36 | + |
| 37 | + def __init__( |
| 38 | + self, |
| 39 | + model_id: str, |
| 40 | + batch_size: int = 64, |
| 41 | + max_generated_tokens: int = 256, |
| 42 | + temperature: float = 0.1, |
| 43 | + top_p: float = 0.9, |
| 44 | + model_storage_path: str = None, |
| 45 | + token: str = None, |
| 46 | + dtype: str = "auto", |
| 47 | + tensor_parallel_size: int = 1, |
| 48 | + gpu_memory_utilization: float = 0.95, |
| 49 | + max_model_len: int = 2048, |
| 50 | + trust_remote_code: bool = False, |
| 51 | + ): |
| 52 | + """Initialize the VLLM with a specific model. |
| 53 | +
|
| 54 | + Args: |
| 55 | + model_id (str): The identifier of the model to use. |
| 56 | + batch_size (int, optional): The batch size for text generation. Defaults to 8. |
| 57 | + max_generated_tokens (int, optional): Maximum number of tokens to generate. Defaults to 256. |
| 58 | + temperature (float, optional): Sampling temperature. Defaults to 0.1. |
| 59 | + top_p (float, optional): Top-p sampling parameter. Defaults to 0.9. |
| 60 | + model_storage_path (str, optional): Directory to store the model. Defaults to None. |
| 61 | + token: (str, optional): Token for accessing the model - not used in implementation yet. |
| 62 | + dtype (str, optional): Data type for model weights. Defaults to "float16". |
| 63 | + tensor_parallel_size (int, optional): Number of GPUs for tensor parallelism. Defaults to 1. |
| 64 | + gpu_memory_utilization (float, optional): Fraction of GPU memory to use. Defaults to 0.95. |
| 65 | + max_model_len (int, optional): Maximum sequence length for the model. Defaults to 2048. |
| 66 | + trust_remote_code (bool, optional): Whether to trust remote code. Defaults to False. |
| 67 | +
|
| 68 | + Note: |
| 69 | + This method sets up a vLLM engine with specified parameters for efficient inference. |
| 70 | + """ |
| 71 | + self.batch_size = batch_size |
| 72 | + self.dtype = dtype |
| 73 | + self.tensor_parallel_size = tensor_parallel_size |
| 74 | + self.gpu_memory_utilization = gpu_memory_utilization |
| 75 | + self.max_model_len = max_model_len |
| 76 | + self.trust_remote_code = trust_remote_code |
| 77 | + |
| 78 | + # Configure sampling parameters |
| 79 | + self.sampling_params = SamplingParams(temperature=temperature, top_p=top_p, max_tokens=max_generated_tokens) |
| 80 | + |
| 81 | + # Initialize the vLLM engine |
| 82 | + self.llm = LLM( |
| 83 | + model=model_id, |
| 84 | + tokenizer=model_id, |
| 85 | + dtype=self.dtype, |
| 86 | + tensor_parallel_size=self.tensor_parallel_size, |
| 87 | + gpu_memory_utilization=self.gpu_memory_utilization, |
| 88 | + max_model_len=self.max_model_len, |
| 89 | + download_dir=model_storage_path, |
| 90 | + trust_remote_code=self.trust_remote_code, |
| 91 | + ) |
| 92 | + |
| 93 | + # Initialize tokenizer separately for potential pre-processing |
| 94 | + self.tokenizer = AutoTokenizer.from_pretrained(model_id) |
| 95 | + |
| 96 | + def get_response(self, inputs: list[str]): |
| 97 | + """Generate responses for a list of prompts using the vLLM engine. |
| 98 | +
|
| 99 | + Args: |
| 100 | + prompts (list[str]): A list of input prompts. |
| 101 | +
|
| 102 | + Returns: |
| 103 | + list[str]: A list of generated responses corresponding to the input prompts. |
| 104 | +
|
| 105 | + Note: |
| 106 | + This method uses vLLM's batched generation capabilities for efficient inference. |
| 107 | + """ |
| 108 | + prompts = [ |
| 109 | + self.tokenizer.apply_chat_template( |
| 110 | + [ |
| 111 | + { |
| 112 | + "role": "system", |
| 113 | + "content": "You are a helpful assistant.", |
| 114 | + }, |
| 115 | + {"role": "user", "content": input}, |
| 116 | + ], |
| 117 | + tokenize=False, |
| 118 | + ) |
| 119 | + for input in inputs |
| 120 | + ] |
| 121 | + |
| 122 | + # generate responses for self.batch_size prompts at the same time |
| 123 | + all_responses = [] |
| 124 | + for i in range(0, len(prompts), self.batch_size): |
| 125 | + batch = prompts[i : i + self.batch_size] |
| 126 | + outputs = self.llm.generate(batch, self.sampling_params) |
| 127 | + responses = [output.outputs[0].text for output in outputs] |
| 128 | + all_responses.extend(responses) |
| 129 | + |
| 130 | + return all_responses |
| 131 | + |
| 132 | + def __del__(self): |
| 133 | + """Cleanup method to delete the LLM instance and free up GPU memory.""" |
| 134 | + del self.llm |
| 135 | + torch.cuda.empty_cache() |
0 commit comments