"vscode:/vscode.git/clone" did not exist on "f7cf5b512ee41f36613deb2471a44de5f304f70d"
data.py 11.7 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
from collections.abc import Iterable
from typing import TYPE_CHECKING, Any, Generic, Literal, Optional, Union, cast
5

6
import torch
7
from typing_extensions import NotRequired, TypedDict, TypeIs, TypeVar
8
9

if TYPE_CHECKING:
10
11
    from vllm.multimodal.inputs import (MultiModalDataDict, MultiModalInputs,
                                        MultiModalUUIDDict)
12
13
14
15
16
17
18
19


class TextPrompt(TypedDict):
    """Schema for a text prompt."""

    prompt: str
    """The input text to be tokenized before passing to the model."""

20
    multi_modal_data: NotRequired["MultiModalDataDict"]
21
22
23
24
25
    """
    Optional multi-modal data to pass to the model,
    if the model supports it.
    """

26
    mm_processor_kwargs: NotRequired[dict[str, Any]]
27
28
29
30
31
32
    """
    Optional multi-modal processor kwargs to be forwarded to the
    multimodal input mapper & processor. Note that if multiple modalities
    have registered mappers etc for the model being considered, we attempt
    to pass the mm_processor_kwargs to each of them.
    """
33

34
35
36
37
38
39
40
41
42
    multi_modal_uuids: NotRequired["MultiModalUUIDDict"]
    """
    Optional user-specified UUIDs for multimodal items, mapped by modality.
    Lists must match the number of items per modality and may contain `None`.
    For `None` entries, the hasher will compute IDs automatically; non-None
    entries override the default hashes for caching, and MUST be unique per
    multimodal item.
    """

43
44
45
46
47
    cache_salt: NotRequired[str]
    """
    Optional cache salt to be used for prefix caching.
    """

48
49
50
51

class TokensPrompt(TypedDict):
    """Schema for a tokenized prompt."""

52
    prompt_token_ids: list[int]
53
54
    """A list of token IDs to pass to the model."""

55
56
57
    prompt: NotRequired[str]
    """The prompt text corresponding to the token IDs, if available."""

58
    token_type_ids: NotRequired[list[int]]
59
60
    """A list of token type IDs to pass to the cross encoder model."""

61
    multi_modal_data: NotRequired["MultiModalDataDict"]
62
    """
63
    Optional multi-modal data to pass to the model,
64
65
66
    if the model supports it.
    """

67
    mm_processor_kwargs: NotRequired[dict[str, Any]]
68
    """
69
    Optional multi-modal processor kwargs to be forwarded to the
70
71
72
73
74
    multimodal input mapper & processor. Note that if multiple modalities
    have registered mappers etc for the model being considered, we attempt
    to pass the mm_processor_kwargs to each of them.
    """

75
76
77
78
79
80
81
82
    multi_modal_uuids: NotRequired["MultiModalUUIDDict"]
    """
    Optional user-specified UUIDs for multimodal items, mapped by modality.
    Lists must match the number of items per modality and may contain `None`.
    For `None` entries, the hasher will compute IDs automatically; non-None
    entries override the default hashes for caching.
    """

83
84
85
86
87
    cache_salt: NotRequired[str]
    """
    Optional cache salt to be used for prefix caching.
    """

88

89
90
91
92
93
94
class EmbedsPrompt(TypedDict):
    """Schema for a prompt provided via token embeddings."""

    prompt_embeds: torch.Tensor
    """The embeddings of the prompt."""

95
96
97
98
99
    cache_salt: NotRequired[str]
    """
    Optional cache salt to be used for prefix caching.
    """

100

101
102
103
104
105
106
107
108
109
110
class DataPrompt(TypedDict):
    """Represents generic inputs handled by IO processor plugins."""

    data: Any
    """The input data"""

    data_format: str
    """The input data format"""


111
SingletonPrompt = Union[str, TextPrompt, TokensPrompt, EmbedsPrompt]
112
"""
113
Set of possible schemas for a single prompt:
114

115
116
117
- A text prompt ([`str`][] or [`TextPrompt`][vllm.inputs.data.TextPrompt])
- A tokenized prompt ([`TokensPrompt`][vllm.inputs.data.TokensPrompt])
- An embeddings prompt ([`EmbedsPrompt`][vllm.inputs.data.EmbedsPrompt])
118
119
120
121
122

Note that "singleton" is as opposed to a data structure
which encapsulates multiple prompts, i.e. of the sort
which may be utilized for encoder/decoder models when
the user desires to express both the encoder & decoder
luopl's avatar
luopl committed
123
prompts explicitly, i.e.
124
[`ExplicitEncoderDecoderPrompt`][vllm.inputs.data.ExplicitEncoderDecoderPrompt]
125

luopl's avatar
luopl committed
126
A prompt of type [`SingletonPrompt`][vllm.inputs.data.SingletonPrompt] may be
127
employed as (1) input to a decoder-only model, (2) input to
128
129
130
the encoder of an encoder/decoder model, in the scenario
where the decoder-prompt is not specified explicitly, or
(3) as a member of a larger data structure encapsulating
luopl's avatar
luopl committed
131
more than one prompt, i.e.
132
[`ExplicitEncoderDecoderPrompt`][vllm.inputs.data.ExplicitEncoderDecoderPrompt]
133
134
"""

135
136
137
138
139
140
141
142
143
144
145

def is_tokens_prompt(prompt: SingletonPrompt) -> TypeIs[TokensPrompt]:
    return (isinstance(prompt, dict) and "prompt_token_ids" in prompt
            and "prompt_embeds" not in prompt)


def is_embeds_prompt(prompt: SingletonPrompt) -> TypeIs[EmbedsPrompt]:
    return (isinstance(prompt, dict) and "prompt_token_ids" not in prompt
            and "prompt_embeds" in prompt)


146
_T1_co = TypeVar("_T1_co",
147
148
                 bound=SingletonPrompt,
                 default=SingletonPrompt,
149
150
                 covariant=True)
_T2_co = TypeVar("_T2_co",
151
152
                 bound=SingletonPrompt,
                 default=SingletonPrompt,
153
                 covariant=True)
154

155
156
157

# TODO: Make fields ReadOnly once mypy supports it
class ExplicitEncoderDecoderPrompt(TypedDict, Generic[_T1_co, _T2_co]):
158
159
160
    """
    Represents an encoder/decoder model input prompt,
    comprising an explicit encoder prompt and a decoder prompt.
161

162
    The encoder and decoder prompts, respectively, may be formatted
163
164
    according to any of the
    [`SingletonPrompt`][vllm.inputs.data.SingletonPrompt] schemas,
165
    and are not required to have the same schema.
166

167
168
169
    Only the encoder prompt may have multi-modal data. mm_processor_kwargs
    should be at the top-level, and should not be set in the encoder/decoder
    prompts, since they are agnostic to the encoder/decoder.
170

171
172
173
    Note that an
    [`ExplicitEncoderDecoderPrompt`][vllm.inputs.data.ExplicitEncoderDecoderPrompt]
    may not be used as an input to a decoder-only model,
174
    and that the `encoder_prompt` and `decoder_prompt`
175
    fields of this data structure themselves must be
176
    [`SingletonPrompt`][vllm.inputs.data.SingletonPrompt] instances.
177
178
    """

179
    encoder_prompt: _T1_co
180

181
    decoder_prompt: Optional[_T2_co]
182

183
    mm_processor_kwargs: NotRequired[dict[str, Any]]
184
185


186
PromptType = Union[SingletonPrompt, ExplicitEncoderDecoderPrompt]
187
188
189
190
"""
Set of possible schemas for an LLM input, including
both decoder-only and encoder/decoder input types:

191
192
193
- A text prompt ([`str`][] or [`TextPrompt`][vllm.inputs.data.TextPrompt])
- A tokenized prompt ([`TokensPrompt`][vllm.inputs.data.TokensPrompt])
- An embeddings prompt ([`EmbedsPrompt`][vllm.inputs.data.EmbedsPrompt])
194
- A single data structure containing both an encoder and a decoder prompt
195
  ([`ExplicitEncoderDecoderPrompt`][vllm.inputs.data.ExplicitEncoderDecoderPrompt])
196
197
198
"""


199
200
201
202
203
204
class TokenInputs(TypedDict):
    """Represents token-based inputs."""

    type: Literal["token"]
    """The type of inputs."""

205
    prompt_token_ids: list[int]
206
207
208
209
210
211
212
    """The token IDs of the prompt."""

    prompt: NotRequired[str]
    """
    The original prompt text corresponding to the token IDs, if available.
    """

213
214
215
216
217
    cache_salt: NotRequired[str]
    """
    Optional cache salt to be used for prefix caching.
    """

218

219
def token_inputs(
220
    prompt_token_ids: list[int],
221
    prompt: Optional[str] = None,
222
    cache_salt: Optional[str] = None,
luopl's avatar
luopl committed
223
    qfeat: Optional[list] = None,
224
) -> TokenInputs:
225
226
    """Construct [`TokenInputs`][vllm.inputs.data.TokenInputs] from optional
    values."""
luopl's avatar
luopl committed
227
228
229
    # print("************* {} ***************".format(qfeat))
    if isinstance(prompt_token_ids, torch.Tensor):
        prompt_token_ids = prompt_token_ids.tolist()
230
231
232
233
    inputs = TokenInputs(type="token", prompt_token_ids=prompt_token_ids)

    if prompt is not None:
        inputs["prompt"] = prompt
234
235
    if cache_salt is not None:
        inputs["cache_salt"] = cache_salt
luopl's avatar
luopl committed
236
237
    if qfeat is not None:
        inputs["qfeat"] = qfeat
238
239
240
    return inputs


241
242
243
244
245
246
247
248
249
class EmbedsInputs(TypedDict):
    """Represents embeddings-based inputs."""

    type: Literal["embeds"]
    """The type of inputs."""

    prompt_embeds: torch.Tensor
    """The embeddings of the prompt."""

250
251
252
253
254
    cache_salt: NotRequired[str]
    """
    Optional cache salt to be used for prefix caching.
    """

255

256
257
258
259
def embeds_inputs(
    prompt_embeds: torch.Tensor,
    cache_salt: Optional[str] = None,
) -> EmbedsInputs:
260
261
    """Construct [`EmbedsInputs`][vllm.inputs.data.EmbedsInputs] from optional
    values."""
262
263
264
265
    inputs = EmbedsInputs(type="embeds", prompt_embeds=prompt_embeds)

    if cache_salt is not None:
        inputs["cache_salt"] = cache_salt
266
267
268
269
270

    return inputs


DecoderOnlyInputs = Union[TokenInputs, EmbedsInputs, "MultiModalInputs"]
271
"""
272
The inputs in [`LLMEngine`][vllm.engine.llm_engine.LLMEngine] before they are
273
274
275
276
277
278
279
passed to the model executor.
This specifies the data required for decoder-only models.
"""


class EncoderDecoderInputs(TypedDict):
    """
280
281
    The inputs in [`LLMEngine`][vllm.engine.llm_engine.LLMEngine] before they
    are passed to the model executor.
282
283
284

    This specifies the required data for encoder-decoder models.
    """
285

286
    encoder: Union[TokenInputs, "MultiModalInputs"]
287
288
    """The inputs for the encoder portion."""

289
    decoder: Union[TokenInputs, "MultiModalInputs"]
290
291
292
    """The inputs for the decoder portion."""


293
SingletonInputs = Union[TokenInputs, EmbedsInputs, "MultiModalInputs"]
294
"""
295
296
A processed [`SingletonPrompt`][vllm.inputs.data.SingletonPrompt] which can be
passed to [`Sequence`][collections.abc.Sequence].
297
298
299
300
"""

ProcessorInputs = Union[DecoderOnlyInputs, EncoderDecoderInputs]
"""
301
The outputs from [`vllm.inputs.preprocess.InputPreprocessor`][].
302
303
"""

304
305
_T1 = TypeVar("_T1", bound=SingletonPrompt, default=SingletonPrompt)
_T2 = TypeVar("_T2", bound=SingletonPrompt, default=SingletonPrompt)
306
307


308
309
310
def build_explicit_enc_dec_prompt(
    encoder_prompt: _T1,
    decoder_prompt: Optional[_T2],
311
    mm_processor_kwargs: Optional[dict[str, Any]] = None,
312
) -> ExplicitEncoderDecoderPrompt[_T1, _T2]:
313
314
315
316
317
    if mm_processor_kwargs is None:
        mm_processor_kwargs = {}
    return ExplicitEncoderDecoderPrompt(
        encoder_prompt=encoder_prompt,
        decoder_prompt=decoder_prompt,
318
319
        mm_processor_kwargs=mm_processor_kwargs,
    )
320
321
322
323
324


def zip_enc_dec_prompts(
    enc_prompts: Iterable[_T1],
    dec_prompts: Iterable[Optional[_T2]],
325
326
327
    mm_processor_kwargs: Optional[Union[Iterable[dict[str, Any]],
                                        dict[str, Any]]] = None,
) -> list[ExplicitEncoderDecoderPrompt[_T1, _T2]]:
328
    """
329
    Zip encoder and decoder prompts together into a list of
330
331
    [`ExplicitEncoderDecoderPrompt`][vllm.inputs.data.ExplicitEncoderDecoderPrompt]
    instances.
332

333
334
335
    ``mm_processor_kwargs`` may also be provided; if a dict is passed, the same
    dictionary will be used for every encoder/decoder prompt. If an iterable is
    provided, it will be zipped with the encoder/decoder prompts.
336
337
    """
    if mm_processor_kwargs is None:
338
        mm_processor_kwargs = cast(dict[str, Any], {})
339
    if isinstance(mm_processor_kwargs, dict):
340
        return [
341
            build_explicit_enc_dec_prompt(
342
343
344
345
346
                encoder_prompt,
                decoder_prompt,
                cast(dict[str, Any], mm_processor_kwargs),
            ) for (encoder_prompt,
                   decoder_prompt) in zip(enc_prompts, dec_prompts)
347
        ]
348
    return [
349
350
351
352
        build_explicit_enc_dec_prompt(encoder_prompt, decoder_prompt,
                                      mm_proc_kwargs)
        for (encoder_prompt, decoder_prompt, mm_proc_kwargs
             ) in zip(enc_prompts, dec_prompts, mm_processor_kwargs)
353
354
    ]

355

356
357
def to_enc_dec_tuple_list(
    enc_dec_prompts: Iterable[ExplicitEncoderDecoderPrompt[_T1, _T2]],
358
) -> list[tuple[_T1, Optional[_T2]]]:
359
360
    return [(enc_dec_prompt["encoder_prompt"],
             enc_dec_prompt["decoder_prompt"])
zhuwenwen's avatar
zhuwenwen committed
361
            for enc_dec_prompt in enc_dec_prompts]