renderer.py 14.8 KB
Newer Older
1
2
3
4
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

import asyncio
5
import io
6
from abc import ABC, abstractmethod
7
from dataclasses import dataclass
8
from typing import Annotated
9

10
11
import pybase64
import torch
12
13
14
from pydantic import Field

from vllm.config import ModelConfig
15
from vllm.entrypoints.openai.protocol import VLLMValidationError
16
from vllm.inputs.data import EmbedsPrompt, TextPrompt, TokensPrompt
17
from vllm.inputs.parse import get_prompt_components, parse_raw_prompts
18
from vllm.tokenizers import TokenizerLike
19
from vllm.utils.async_utils import AsyncMicrobatchTokenizer
20
21


22
23
24
25
@dataclass(frozen=True)
class RenderConfig:
    """Configuration to control how prompts are prepared."""

26
    max_length: int | None = None
27
    """Maximum allowable total input token length. If provided,
28
    token inputs longer than this raise `ValueError`."""
29

30
    truncate_prompt_tokens: int | None = None
31
32
33
    """Number of tokens to keep. `None` means no truncation.
    `0` yields an empty list (and skips embeds).
    `-1` maps to `model_config.max_model_len`."""
34

35
    add_special_tokens: bool = True
36
37
    """Whether to add model-specific special tokens during tokenization."""

38
    cache_salt: str | None = None
39
40
    """String to disambiguate prefix cache entries."""

41
    needs_detokenization: bool | None = False
42
43
    """If True, detokenize IDs back to text for inclusion in outputs."""

44
    def verify_truncate_prompt_tokens(self, model_config: ModelConfig) -> int | None:
45
46
        """Validate and normalize `truncate_prompt_tokens` parameter."""
        truncate_prompt_tokens = self.truncate_prompt_tokens
47
48
        if truncate_prompt_tokens is None or truncate_prompt_tokens == 0:
            return truncate_prompt_tokens
49
50
51
52
53
54
55
56

        if truncate_prompt_tokens < 0:
            truncate_prompt_tokens = model_config.max_model_len

        max_length = self.max_length
        if max_length is not None and truncate_prompt_tokens > max_length:  # type: ignore[operator]
            raise ValueError(
                f"{truncate_prompt_tokens=} cannot be greater than "
57
58
                f"{max_length=}. Please select a smaller truncation size."
            )
59
60
61

        return truncate_prompt_tokens

62

63
64
65
class BaseRenderer(ABC):
    """
    Base class for unified input processing and rendering.
66

67
68
69
70
71
    The Renderer serves as a unified input processor that consolidates
    tokenization, chat template formatting, and multimodal input handling
    into a single component.
    It converts high-level API requests (OpenAI-style JSON) into token IDs and
    multimodal features ready for engine consumption.
72

73
74
75
76
77
78
79
80
81
82
83
    Key responsibilities:
    - Convert text prompts to token sequences with proper special tokens
    - Apply chat templates and format conversations
    - Handle multimodal inputs (images, audio, etc.) when applicable
    - Manage prompt truncation and length validation
    - Provide clean separation between API layer and engine core
    """

    def __init__(
        self,
        model_config: ModelConfig,
84
        tokenizer: TokenizerLike | None = None,
85
86
87
88
89
90
91
92
    ):
        super().__init__()
        self.model_config = model_config
        self.tokenizer = tokenizer

    @abstractmethod
    async def render_prompt(
        self,
93
        *,
94
        prompt_or_prompts: str | list[str] | list[int] | list[list[int]],
95
        config: RenderConfig,
96
    ) -> list[TokensPrompt]:
97
        """
98
99
100
101
102
103
104
105
        Convert text or token inputs into engine-ready TokensPrompt objects.

        This method accepts text or token inputs and produces a
        list of [`TokensPrompt`][vllm.inputs.data.TokensPrompt] objects
        for the engine.

        Args:
            prompt_or_prompts: One of:
106
107
108
109
                - `str`: Single text prompt.
                - `list[str]`: Batch of text prompts.
                - `list[int]`: Single pre-tokenized sequence.
                - `list[list[int]]`: Batch of pre-tokenized sequences.
110
            config: Render configuration controlling how prompts are prepared
111
                (e.g., tokenization and length handling).
112
113

        Returns:
114
            list[TokensPrompt]: Engine-ready token prompts.
115
116
117
118
119
120
121
122
123

        Raises:
            ValueError: If input formats are invalid or length limits exceeded.
        """
        raise NotImplementedError

    @abstractmethod
    async def render_prompt_and_embeds(
        self,
124
        *,
125
126
        prompt_or_prompts: str | list[str] | list[int] | list[list[int]] | None = None,
        prompt_embeds: bytes | list[bytes] | None = None,
127
        config: RenderConfig,
128
    ) -> list[TokensPrompt | EmbedsPrompt]:
129
130
        """
        Convert text/token and/or base64-encoded embeddings inputs into
131
        engine-ready prompt objects using a unified RenderConfig.
132

133
        At least one of `prompt_or_prompts` or `prompt_embeds` must be
134
        provided and non-empty. If both are omitted or empty (e.g., empty
135
        string and empty list), a `ValueError` is raised.
136

137
        Args:
138
139
140
            prompt_or_prompts: Text or token inputs to include.
            prompt_embeds: Base64-encoded bytes (or list thereof) containing a
                torch-saved tensor to be used as prompt embeddings.
141
            config: Render configuration controlling how prompts are prepared
142
                (e.g., tokenization and length handling).
143

144
        Returns:
145
            list[Union[TokensPrompt, EmbedsPrompt]]:
146
147
                Engine-ready prompt objects.

148
        Raises:
149
            ValueError: If both `prompt_or_prompts` and `prompt_embeds`
150
151
                are omitted or empty (decoder prompt cannot be empty), or if
                length limits are exceeded.
152
153
154
        """
        raise NotImplementedError

155
    def load_prompt_embeds(
156
        self,
157
158
159
        prompt_embeds: bytes | list[bytes],
        truncate_prompt_tokens: Annotated[int, Field(ge=0)] | None = None,
        cache_salt: str | None = None,
160
    ) -> list[EmbedsPrompt]:
161
        """Load and validate base64-encoded embeddings into prompt objects."""
162
        if not self.model_config.enable_prompt_embeds:
163
164
165
            raise VLLMValidationError(
                "You must set `--enable-prompt-embeds` to input `prompt_embeds`.",
                parameter="prompt_embeds",
166
            )
167

168
        def _load_and_validate_embed(embed: bytes) -> EmbedsPrompt:
169
170
171
172
173
174
175
176
177
178
179
180
181
182
            # Enable sparse tensor integrity checks to prevent out-of-bounds
            # writes from maliciously crafted tensors
            with torch.sparse.check_sparse_tensor_invariants():
                tensor = torch.load(
                    io.BytesIO(pybase64.b64decode(embed, validate=True)),
                    weights_only=True,
                    map_location=torch.device("cpu"),
                )
                assert isinstance(tensor, torch.Tensor) and tensor.dtype in (
                    torch.float32,
                    torch.bfloat16,
                    torch.float16,
                )
                tensor = tensor.to_dense()
183
184
185
186
187
            if tensor.dim() > 2:
                tensor = tensor.squeeze(0)
                assert tensor.dim() == 2
            if truncate_prompt_tokens is not None:
                tensor = tensor[-truncate_prompt_tokens:]
188
            embeds_prompt = EmbedsPrompt(prompt_embeds=tensor)
189
190
191
192
193
194
            if cache_salt is not None:
                embeds_prompt["cache_salt"] = cache_salt
            return embeds_prompt

        if isinstance(prompt_embeds, list):
            return [_load_and_validate_embed(embed) for embed in prompt_embeds]
195
196

        return [_load_and_validate_embed(prompt_embeds)]
197

198
199
200
201
202

class CompletionRenderer(BaseRenderer):
    def __init__(
        self,
        model_config: ModelConfig,
203
204
        tokenizer: TokenizerLike | None = None,
        async_tokenizer_pool: dict[TokenizerLike, AsyncMicrobatchTokenizer]
205
        | None = None,
206
207
    ):
        super().__init__(model_config, tokenizer)
208
        self.async_tokenizer_pool = async_tokenizer_pool
209
        self.async_tokenizer: AsyncMicrobatchTokenizer | None = None
210
211
212

    async def render_prompt(
        self,
213
        *,
214
        prompt_or_prompts: str | list[str] | list[int] | list[list[int]],
215
        config: RenderConfig,
216
    ) -> list[TokensPrompt]:
217
        """Implementation of prompt rendering for completion-style requests.
218

219
220
221
        Uses async tokenizer pooling for improved performance. See base class
        for detailed parameter documentation.
        """
222
        truncate_prompt_tokens = config.verify_truncate_prompt_tokens(self.model_config)
223
224
        if truncate_prompt_tokens == 0:
            return []
225

226
227
228
229
230
231
232
233
        tasks = (
            self._create_prompt(
                prompt_input,
                config=config,
                truncate_prompt_tokens=truncate_prompt_tokens,
            )
            for prompt_input in parse_raw_prompts(prompt_or_prompts)
        )
234
235

        return await asyncio.gather(*tasks)
236
237
238

    async def render_prompt_and_embeds(
        self,
239
        *,
240
241
        prompt_or_prompts: str | list[str] | list[int] | list[list[int]] | None = None,
        prompt_embeds: bytes | list[bytes] | None = None,
242
        config: RenderConfig,
243
    ) -> list[TokensPrompt | EmbedsPrompt]:
244
245
246
247
        """
        Render text/token prompts and/or precomputed embedding prompts. At
        least one of `prompt_or_prompts` or `prompt_embeds` must be provided.
        """
248
        truncate_prompt_tokens = config.verify_truncate_prompt_tokens(self.model_config)
249
250
251
        if truncate_prompt_tokens == 0:
            return []

252
        rendered: list[TokensPrompt | EmbedsPrompt] = []
253
254
255

        if prompt_embeds is not None:
            rendered.extend(
256
257
258
259
                self.load_prompt_embeds(
                    prompt_embeds, truncate_prompt_tokens, config.cache_salt
                )
            )
260
261
262
263
264
        if prompt_or_prompts is None or prompt_or_prompts == "":
            return rendered

        token_prompts = await self.render_prompt(
            prompt_or_prompts=prompt_or_prompts,
265
            config=config,
266
267
268
269
270
        )
        rendered.extend(token_prompts)

        return rendered

271
    def _maybe_apply_truncation(
272
        self, token_ids: list[int], truncate_prompt_tokens: int | None
273
    ) -> list[int]:
274
275
276
277
278
279
280
281
        """Apply truncation to token sequence."""
        if truncate_prompt_tokens is None:
            return token_ids
        if truncate_prompt_tokens >= len(token_ids):
            return token_ids

        return token_ids[-truncate_prompt_tokens:]

282
283
    async def _create_prompt(
        self,
284
        prompt_input: TextPrompt | TokensPrompt,
285
        config: RenderConfig,
286
        truncate_prompt_tokens: int | None,
287
    ) -> TokensPrompt:
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
        prompt, prompt_token_ids, _ = get_prompt_components(prompt_input)

        if prompt_token_ids is not None:
            # NOTE: detokenization is needed when echo is enabled,
            # where the input token IDs are decoded back to text.
            return await self._create_prompt_from_token_ids(
                prompt_token_ids,
                config.max_length,
                truncate_prompt_tokens,
                config.cache_salt,
                config.needs_detokenization,
            )

        if prompt is not None:
            return await self._create_prompt_from_text(
                prompt,
                config.max_length,
                truncate_prompt_tokens,
                config.add_special_tokens,
                config.cache_salt,
            )

        # TODO: Also handle embeds prompt using this method
        raise NotImplementedError

    async def _create_prompt_from_text(
314
315
        self,
        text: str,
316
317
        max_length: int | None,
        truncate_prompt_tokens: int | None,
318
        add_special_tokens: bool,
319
        cache_salt: str | None,
320
    ) -> TokensPrompt:
321
322
323
324
        """Tokenize text input asynchronously."""
        async_tokenizer = self._get_async_tokenizer()

        # Handle encoder-specific preprocessing
325
326
327
328
        if (
            self.model_config.encoder_config is not None
            and self.model_config.encoder_config.get("do_lower_case", False)
        ):
329
330
331
332
            text = text.lower()

        # Tokenize texts
        if truncate_prompt_tokens is None:
333
            encoded = await async_tokenizer(text, add_special_tokens=add_special_tokens)
334
335
336
337
338
        else:
            encoded = await async_tokenizer(
                text,
                add_special_tokens=add_special_tokens,
                truncation=True,
339
340
                max_length=truncate_prompt_tokens,
            )
341

342
343
344
        return self._create_tokens_prompt(
            encoded.input_ids, max_length, cache_salt, text
        )
345

346
    async def _create_prompt_from_token_ids(
347
348
        self,
        token_ids: list[int],
349
350
351
352
        max_length: int | None,
        truncate_prompt_tokens: int | None,
        cache_salt: str | None,
        needs_detokenization: bool | None = False,
353
    ) -> TokensPrompt:
354
        """Optionally detokenize token IDs and build a tokens prompt."""
355
        token_ids = self._maybe_apply_truncation(token_ids, truncate_prompt_tokens)
356
357

        prompt = None
358
        if needs_detokenization:
359
360
361
            async_tokenizer = self._get_async_tokenizer()
            prompt = await async_tokenizer.decode(token_ids)

362
363
364
365
366
367
        return self._create_tokens_prompt(
            token_ids=token_ids,
            max_length=max_length,
            cache_salt=cache_salt,
            prompt=prompt,
        )
368
369
370

    def _get_async_tokenizer(self) -> AsyncMicrobatchTokenizer:
        """Get or create async tokenizer using shared pool."""
371
372
373
374
375
        async_tokenizer = self.async_tokenizer
        if async_tokenizer is not None:
            return async_tokenizer

        tokenizer = self.tokenizer
376
        if tokenizer is None:
377
            raise ValueError("No tokenizer available for text input processing")
378

379
380
381
382
383
384
385
386
387
        if self.async_tokenizer_pool is None:
            async_tokenizer = AsyncMicrobatchTokenizer(tokenizer)
        else:
            async_tokenizer = self.async_tokenizer_pool.get(tokenizer)
            if async_tokenizer is None:
                async_tokenizer = AsyncMicrobatchTokenizer(tokenizer)
                self.async_tokenizer_pool[tokenizer] = async_tokenizer
        self.async_tokenizer = async_tokenizer
        return async_tokenizer
388
389
390
391

    def _create_tokens_prompt(
        self,
        token_ids: list[int],
392
393
394
        max_length: int | None = None,
        cache_salt: str | None = None,
        prompt: str | None = None,
395
396
    ) -> TokensPrompt:
        """Create validated TokensPrompt."""
397
        if max_length is not None and len(token_ids) > max_length:
398
            raise VLLMValidationError(
399
                f"This model's maximum context length is {max_length} tokens. "
400
                f"However, your request has {len(token_ids)} input tokens. "
401
402
403
                "Please reduce the length of the input messages.",
                parameter="input_tokens",
                value=len(token_ids),
404
            )
405

406
        tokens_prompt = TokensPrompt(prompt_token_ids=token_ids)
407
408
        if cache_salt is not None:
            tokens_prompt["cache_salt"] = cache_salt
409
410
        if prompt is not None:
            tokens_prompt["prompt"] = prompt
411
        return tokens_prompt