llm.py 15.5 KB
Newer Older
1
from typing import List, Optional, Union
2

3
import torch
4
from tqdm import tqdm
Zhuohan Li's avatar
Zhuohan Li committed
5
from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast
6

Woosuk Kwon's avatar
Woosuk Kwon committed
7
8
from vllm.engine.arg_utils import EngineArgs
from vllm.engine.llm_engine import LLMEngine
9
from vllm.logger import init_logger
10
from vllm.lora.request import LoRARequest
11
12
from vllm.outputs import EmbeddingRequestOutput, RequestOutput
from vllm.pooling_params import PoolingParams
Woosuk Kwon's avatar
Woosuk Kwon committed
13
from vllm.sampling_params import SamplingParams
14
from vllm.sequence import MultiModalData
yhu422's avatar
yhu422 committed
15
from vllm.usage.usage_lib import UsageContext
Woosuk Kwon's avatar
Woosuk Kwon committed
16
from vllm.utils import Counter
17

18
19
logger = init_logger(__name__)

20
21

class LLM:
Woosuk Kwon's avatar
Woosuk Kwon committed
22
23
24
25
26
27
28
29
30
    """An LLM for generating texts from given prompts and sampling parameters.

    This class includes a tokenizer, a language model (possibly distributed
    across multiple GPUs), and GPU memory space allocated for intermediate
    states (aka KV cache). Given a batch of prompts and sampling parameters,
    this class generates texts from the model, using an intelligent batching
    mechanism and efficient memory management.

    NOTE: This class is intended to be used for offline inference. For online
31
    serving, use the `AsyncLLMEngine` class instead.
Zhuohan Li's avatar
Zhuohan Li committed
32
    NOTE: For the comprehensive list of arguments, see `EngineArgs`.
Woosuk Kwon's avatar
Woosuk Kwon committed
33
34
35

    Args:
        model: The name or path of a HuggingFace Transformers model.
36
        tokenizer: The name or path of a HuggingFace Transformers tokenizer.
37
38
        tokenizer_mode: The tokenizer mode. "auto" will use the fast tokenizer
            if available, and "slow" will always use the slow tokenizer.
39
40
41
        skip_tokenizer_init: If true, skip initialization of tokenizer and
            detokenizer. Expect valid prompt_token_ids and None for prompt
            from the input.
42
43
        trust_remote_code: Trust remote code (e.g., from HuggingFace) when
            downloading the model and tokenizer.
Woosuk Kwon's avatar
Woosuk Kwon committed
44
45
46
        tensor_parallel_size: The number of GPUs to use for distributed
            execution with tensor parallelism.
        dtype: The data type for the model weights and activations. Currently,
Woosuk Kwon's avatar
Woosuk Kwon committed
47
48
49
50
            we support `float32`, `float16`, and `bfloat16`. If `auto`, we use
            the `torch_dtype` attribute specified in the model config file.
            However, if the `torch_dtype` in the config is `float32`, we will
            use `float16` instead.
51
        quantization: The method used to quantize the model weights. Currently,
52
53
54
55
56
            we support "awq", "gptq", "squeezellm", and "fp8" (experimental).
            If None, we first check the `quantization_config` attribute in the
            model config file. If that is None, we assume the model weights are
            not quantized and use `dtype` to determine the data type of
            the weights.
Jasmond L's avatar
Jasmond L committed
57
58
        revision: The specific model version to use. It can be a branch name,
            a tag name, or a commit id.
59
60
        tokenizer_revision: The specific tokenizer version to use. It can be a
            branch name, a tag name, or a commit id.
61
62
63
64
65
66
67
68
69
70
71
        seed: The seed to initialize the random number generator for sampling.
        gpu_memory_utilization: The ratio (between 0 and 1) of GPU memory to
            reserve for the model weights, activations, and KV cache. Higher
            values will increase the KV cache size and thus improve the model's
            throughput. However, if the value is too high, it may cause out-of-
            memory (OOM) errors.
        swap_space: The size (GiB) of CPU memory per GPU to use as swap space.
            This can be used for temporarily storing the states of the requests
            when their `best_of` sampling parameters are larger than 1. If all
            requests will have `best_of=1`, you can safely set this to 0.
            Otherwise, too small values may cause out-of-memory (OOM) errors.
72
73
74
75
        enforce_eager: Whether to enforce eager execution. If True, we will
            disable CUDA graph and always execute the model in eager mode.
            If False, we will use CUDA graph and eager execution in hybrid.
        max_context_len_to_capture: Maximum context len covered by CUDA graphs.
76
77
78
            When a sequence has context length larger than this, we fall back
            to eager mode (DEPRECATED. Use `max_seq_len_to_capture` instead).
        max_seq_len_to_capture: Maximum sequence len covered by CUDA graphs.
79
80
            When a sequence has context length larger than this, we fall back
            to eager mode.
81
        disable_custom_all_reduce: See ParallelConfig
Woosuk Kwon's avatar
Woosuk Kwon committed
82
    """
83
84
85
86

    def __init__(
        self,
        model: str,
87
        tokenizer: Optional[str] = None,
88
        tokenizer_mode: str = "auto",
89
        skip_tokenizer_init: bool = False,
90
        trust_remote_code: bool = False,
91
        tensor_parallel_size: int = 1,
Woosuk Kwon's avatar
Woosuk Kwon committed
92
        dtype: str = "auto",
93
        quantization: Optional[str] = None,
94
        revision: Optional[str] = None,
95
        tokenizer_revision: Optional[str] = None,
96
97
98
        seed: int = 0,
        gpu_memory_utilization: float = 0.9,
        swap_space: int = 4,
99
        enforce_eager: bool = False,
100
101
        max_context_len_to_capture: Optional[int] = None,
        max_seq_len_to_capture: int = 8192,
102
        disable_custom_all_reduce: bool = False,
103
104
105
106
        **kwargs,
    ) -> None:
        if "disable_log_stats" not in kwargs:
            kwargs["disable_log_stats"] = True
Zhuohan Li's avatar
Zhuohan Li committed
107
        engine_args = EngineArgs(
108
            model=model,
109
            tokenizer=tokenizer,
110
            tokenizer_mode=tokenizer_mode,
111
            skip_tokenizer_init=skip_tokenizer_init,
112
            trust_remote_code=trust_remote_code,
113
114
            tensor_parallel_size=tensor_parallel_size,
            dtype=dtype,
115
            quantization=quantization,
116
            revision=revision,
117
            tokenizer_revision=tokenizer_revision,
118
119
120
            seed=seed,
            gpu_memory_utilization=gpu_memory_utilization,
            swap_space=swap_space,
121
122
            enforce_eager=enforce_eager,
            max_context_len_to_capture=max_context_len_to_capture,
123
            max_seq_len_to_capture=max_seq_len_to_capture,
124
            disable_custom_all_reduce=disable_custom_all_reduce,
125
126
            **kwargs,
        )
yhu422's avatar
yhu422 committed
127
128
        self.llm_engine = LLMEngine.from_engine_args(
            engine_args, usage_context=UsageContext.LLM_CLASS)
129
130
        self.request_counter = Counter()

131
    def get_tokenizer(
132
            self) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:
133
        return self.llm_engine.tokenizer.tokenizer
134

135
136
137
138
    def set_tokenizer(
        self,
        tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast],
    ) -> None:
139
        self.llm_engine.tokenizer.tokenizer = tokenizer
140

141
142
    def generate(
        self,
Woosuk Kwon's avatar
Woosuk Kwon committed
143
        prompts: Optional[Union[str, List[str]]] = None,
144
145
        sampling_params: Optional[Union[SamplingParams,
                                        List[SamplingParams]]] = None,
146
        prompt_token_ids: Optional[List[List[int]]] = None,
147
        use_tqdm: bool = True,
148
        lora_request: Optional[LoRARequest] = None,
149
        multi_modal_data: Optional[MultiModalData] = None,
150
    ) -> List[RequestOutput]:
Woosuk Kwon's avatar
Woosuk Kwon committed
151
152
153
154
155
156
157
158
159
        """Generates the completions for the input prompts.

        NOTE: This class automatically batches the given prompts, considering
        the memory constraint. For the best performance, put all of your prompts
        into a single list and pass it to this method.

        Args:
            prompts: A list of prompts to generate completions for.
            sampling_params: The sampling parameters for text generation. If
160
161
162
163
                None, we use the default sampling parameters. 
                When it is a single value, it is applied to every prompt. 
                When it is a list, the list must have the same length as the 
                prompts and it is paired one by one with the prompt.
Woosuk Kwon's avatar
Woosuk Kwon committed
164
165
166
            prompt_token_ids: A list of token IDs for the prompts. If None, we
                use the tokenizer to convert the prompts to token IDs.
            use_tqdm: Whether to use tqdm to display the progress bar.
167
            lora_request: LoRA request to use for generation, if any.
168
            multi_modal_data: Multi modal data.
Woosuk Kwon's avatar
Woosuk Kwon committed
169
170

        Returns:
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
            A list of `RequestOutput` objects containing the
            generated completions in the same order as the input prompts.
        """
        if sampling_params is None:
            # Use default sampling params.
            sampling_params = SamplingParams()

        requests_data = self._validate_and_prepare_requests(
            prompts,
            sampling_params,
            prompt_token_ids,
            lora_request,
            multi_modal_data,
        )

        # Add requests to the engine and run the engine
        for request_data in requests_data:
            self._add_request(**request_data)

        return self._run_engine(use_tqdm)

    def encode(
        self,
        prompts: Optional[Union[str, List[str]]] = None,
        pooling_params: Optional[Union[PoolingParams,
                                       List[PoolingParams]]] = None,
        prompt_token_ids: Optional[List[List[int]]] = None,
        use_tqdm: bool = True,
        lora_request: Optional[LoRARequest] = None,
        multi_modal_data: Optional[MultiModalData] = None,
    ) -> List[EmbeddingRequestOutput]:
        """Generates the completions for the input prompts.

        NOTE: This class automatically batches the given prompts, considering
        the memory constraint. For the best performance, put all of your prompts
        into a single list and pass it to this method.

        Args:
            prompts: A list of prompts to generate completions for.
            pooling_params: The pooling parameters for pooling. If None, we
                use the default pooling parameters.
            prompt_token_ids: A list of token IDs for the prompts. If None, we
                use the tokenizer to convert the prompts to token IDs.
            use_tqdm: Whether to use tqdm to display the progress bar.
            lora_request: LoRA request to use for generation, if any.
            multi_modal_data: Multi modal data.

        Returns:
            A list of `EmbeddingRequestOutput` objects containing the
            generated embeddings in the same order as the input prompts.
        """
        if pooling_params is None:
            # Use default pooling params.
            pooling_params = PoolingParams()

        requests_data = self._validate_and_prepare_requests(
            prompts,
            pooling_params,
            prompt_token_ids,
            lora_request,
            multi_modal_data,
        )

        # Add requests to the engine and run the engine
        for request_data in requests_data:
            self._add_request(**request_data)

        return self._run_engine(use_tqdm)

    def _validate_and_prepare_requests(
        self,
        prompts: Optional[Union[str, List[str]]],
        params: Union[Union[SamplingParams, PoolingParams],
                      List[Union[SamplingParams,
                                 PoolingParams]]],  # Unified parameter
        prompt_token_ids: Optional[List[List[int]]] = None,
        lora_request: Optional[LoRARequest] = None,
        multi_modal_data: Optional[MultiModalData] = None,
    ) -> List[dict]:
        """Validates and prepares request data for adding to the engine.

        Ensures prompts and token IDs are consistent, and returns a list of
        dictionaries with request data for further processing.
Woosuk Kwon's avatar
Woosuk Kwon committed
254
255
256
257
        """
        if prompts is None and prompt_token_ids is None:
            raise ValueError("Either prompts or prompt_token_ids must be "
                             "provided.")
258
259
260
261
        if self.llm_engine.model_config.skip_tokenizer_init \
            and prompts is not None:
            raise ValueError("prompts must be None if skip_tokenizer_init "
                             "is True")
Woosuk Kwon's avatar
Woosuk Kwon committed
262
        if isinstance(prompts, str):
Woosuk Kwon's avatar
Woosuk Kwon committed
263
            # Convert a single prompt to a list.
Woosuk Kwon's avatar
Woosuk Kwon committed
264
            prompts = [prompts]
265
266
267
268
        if (prompts is not None and prompt_token_ids is not None
                and len(prompts) != len(prompt_token_ids)):
            raise ValueError("The lengths of prompts and prompt_token_ids "
                             "must be the same.")
269
270
271
272
273
274
275

        if prompts is not None:
            num_requests = len(prompts)
        else:
            assert prompt_token_ids is not None
            num_requests = len(prompt_token_ids)

276
277
        if isinstance(params, list) and len(params) != num_requests:
            raise ValueError("The lengths of prompts and params "
278
                             "must be the same.")
279
280
281
        if multi_modal_data:
            multi_modal_data.data = multi_modal_data.data.to(torch.float16)

Zhuohan Li's avatar
Zhuohan Li committed
282
        # Add requests to the engine.
283
        requests_data = []
Woosuk Kwon's avatar
Woosuk Kwon committed
284
285
        for i in range(num_requests):
            prompt = prompts[i] if prompts is not None else None
286
287
            token_ids = None if prompt_token_ids is None else prompt_token_ids[
                i]
288
289
290
291
292
293
294
295

            multi_modal_item = MultiModalData(
                type=multi_modal_data.type,
                data=multi_modal_data.data[i].unsqueeze(0),
            ) if multi_modal_data else None

            requests_data.append({
                "prompt":
296
                prompt,
297
298
299
                "params":
                params[i] if isinstance(params, list) else params,
                "prompt_token_ids":
300
                token_ids,
301
302
303
304
305
306
307
                "lora_request":
                lora_request,
                "multi_modal_data":
                multi_modal_item,
            })

        return requests_data
308

309
310
    def _add_request(
        self,
Woosuk Kwon's avatar
Woosuk Kwon committed
311
        prompt: Optional[str],
312
        params: Union[SamplingParams, PoolingParams],
313
        prompt_token_ids: Optional[List[int]],
314
        lora_request: Optional[LoRARequest] = None,
315
        multi_modal_data: Optional[MultiModalData] = None,
316
317
    ) -> None:
        request_id = str(next(self.request_counter))
318
319
        self.llm_engine.add_request(request_id,
                                    prompt,
320
                                    params,
321
                                    prompt_token_ids,
322
323
                                    lora_request=lora_request,
                                    multi_modal_data=multi_modal_data)
324

325
326
327
    def _run_engine(
            self, use_tqdm: bool
    ) -> List[Union[RequestOutput, EmbeddingRequestOutput]]:
328
329
        # Initialize tqdm.
        if use_tqdm:
Zhuohan Li's avatar
Zhuohan Li committed
330
            num_requests = self.llm_engine.get_num_unfinished_requests()
331
332
333
334
335
336
            pbar = tqdm(
                total=num_requests,
                desc="Processed prompts",
                dynamic_ncols=True,
                postfix=f"Generation Speed: {0:.2f} toks/s",
            )
Zhuohan Li's avatar
Zhuohan Li committed
337
        # Run the engine.
338
        outputs: List[Union[RequestOutput, EmbeddingRequestOutput]] = []
339
        total_toks = 0
Zhuohan Li's avatar
Zhuohan Li committed
340
341
        while self.llm_engine.has_unfinished_requests():
            step_outputs = self.llm_engine.step()
342
            for output in step_outputs:
343
                if output.finished:
344
345
                    outputs.append(output)
                    if use_tqdm:
346
347
348
349
350
351
                        if isinstance(output, RequestOutput):
                            # Calculate tokens only for RequestOutput
                            total_toks += sum(
                                len(stp.token_ids) for stp in output.outputs)
                            spd = total_toks / pbar.format_dict["elapsed"]
                            pbar.postfix = f"Generation Speed: {spd:.2f} toks/s"
352
353
354
                        pbar.update(1)
        if use_tqdm:
            pbar.close()
355
356
357
358
        # Sort the outputs by request ID.
        # This is necessary because some requests may be finished earlier than
        # its previous requests.
        outputs = sorted(outputs, key=lambda x: int(x.request_id))
359
        return outputs