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

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

10
11
from vllm.sampling_params import SamplingParams

12
if TYPE_CHECKING:
13
14
15
16
17
    from vllm.multimodal.inputs import (
        MultiModalDataDict,
        MultiModalInputs,
        MultiModalUUIDDict,
    )
18
19
20
21
else:
    MultiModalDataDict = object
    MultiModalInputs = object
    MultiModalUUIDDict = object
22
23


24
class _CommonKeys(TypedDict):
25
    multi_modal_data: NotRequired[MultiModalDataDict | None]
26
27
28
29
30
    """
    Optional multi-modal data to pass to the model,
    if the model supports it.
    """

31
    mm_processor_kwargs: NotRequired[dict[str, Any] | None]
32
33
34
35
36
37
38
    """
    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.
    """

39
    multi_modal_uuids: NotRequired[MultiModalUUIDDict]
40
41
42
43
44
45
46
47
    """
    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.
    """

48
49
50
51
52
    cache_salt: NotRequired[str]
    """
    Optional cache salt to be used for prefix caching.
    """

53

54
55
56
57
58
59
60
61
class TextPrompt(_CommonKeys):
    """Schema for a text prompt."""

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


class TokensPrompt(_CommonKeys):
62
63
    """Schema for a tokenized prompt."""

64
    prompt_token_ids: list[int]
65
66
    """A list of token IDs to pass to the model."""

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

70
    token_type_ids: NotRequired[list[int]]
71
72
    """A list of token type IDs to pass to the cross encoder model."""

73

74
class EmbedsPrompt(_CommonKeys):
75
76
77
78
79
    """Schema for a prompt provided via token embeddings."""

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

80
81
82
    prompt: NotRequired[str]
    """The prompt text corresponding to the token embeddings, if available."""

83

84
class DataPrompt(_CommonKeys):
85
86
87
88
89
90
91
92
93
    """Represents generic inputs handled by IO processor plugins."""

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

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


94
SingletonPrompt: TypeAlias = str | TextPrompt | TokensPrompt | EmbedsPrompt
95
"""
96
Set of possible schemas for a single prompt:
97

98
99
100
- 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])
101
102
103
104
105

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
106
107
prompts explicitly, i.e. 
[`ExplicitEncoderDecoderPrompt`][vllm.inputs.data.ExplicitEncoderDecoderPrompt]
108

109
110
A prompt of type [`SingletonPrompt`][vllm.inputs.data.SingletonPrompt] may be 
employed as (1) input to a decoder-only model, (2) input to
111
112
113
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
114
115
more than one prompt, i.e. 
[`ExplicitEncoderDecoderPrompt`][vllm.inputs.data.ExplicitEncoderDecoderPrompt]
116
117
"""

118

119
120
121
122
123
124
_T1_co = TypeVar(
    "_T1_co", bound=SingletonPrompt, default=SingletonPrompt, covariant=True
)
_T2_co = TypeVar(
    "_T2_co", bound=SingletonPrompt, default=SingletonPrompt, covariant=True
)
125

126
127
128

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

133
    The encoder and decoder prompts, respectively, may be formatted
134
135
    according to any of the
    [`SingletonPrompt`][vllm.inputs.data.SingletonPrompt] schemas,
136
    and are not required to have the same schema.
137

138
139
140
    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.
141

142
143
144
    Note that an
    [`ExplicitEncoderDecoderPrompt`][vllm.inputs.data.ExplicitEncoderDecoderPrompt]
    may not be used as an input to a decoder-only model,
145
    and that the `encoder_prompt` and `decoder_prompt`
146
    fields of this data structure themselves must be
147
    [`SingletonPrompt`][vllm.inputs.data.SingletonPrompt] instances.
148
149
    """

150
    encoder_prompt: _T1_co
151

152
    decoder_prompt: _T2_co | None
153

154
    mm_processor_kwargs: NotRequired[dict[str, Any]]
155

156

157
PromptType: TypeAlias = SingletonPrompt | ExplicitEncoderDecoderPrompt[Any, Any]
158
159
160
161
"""
Set of possible schemas for an LLM input, including
both decoder-only and encoder/decoder input types:

162
163
164
- 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])
165
- A single data structure containing both an encoder and a decoder prompt
166
  ([`ExplicitEncoderDecoderPrompt`][vllm.inputs.data.ExplicitEncoderDecoderPrompt])
167
168
169
"""


170
171
class TokenInputs(TypedDict):
    """Represents token-based inputs."""
172
173
174
175

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

176
    prompt_token_ids: list[int]
177
178
    """The token IDs of the prompt."""

179
180
181
182
183
    cache_salt: NotRequired[str]
    """
    Optional cache salt to be used for prefix caching.
    """

184

185
def token_inputs(
186
    prompt_token_ids: list[int],
187
    cache_salt: str | None = None,
188
) -> TokenInputs:
189
190
    """Construct [`TokenInputs`][vllm.inputs.data.TokenInputs] from optional
    values."""
191
    inputs = TokenInputs(type="token", prompt_token_ids=prompt_token_ids)
192

193
194
    if cache_salt is not None:
        inputs["cache_salt"] = cache_salt
195
196
197
198

    return inputs


199
200
201
202
203
204
205
206
207
class EmbedsInputs(TypedDict):
    """Represents embeddings-based inputs."""

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

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

208
209
210
211
212
    cache_salt: NotRequired[str]
    """
    Optional cache salt to be used for prefix caching.
    """

213

214
215
def embeds_inputs(
    prompt_embeds: torch.Tensor,
216
    cache_salt: str | None = None,
217
) -> EmbedsInputs:
218
219
    """Construct [`EmbedsInputs`][vllm.inputs.data.EmbedsInputs] from optional
    values."""
220
221
222
223
    inputs = EmbedsInputs(type="embeds", prompt_embeds=prompt_embeds)

    if cache_salt is not None:
        inputs["cache_salt"] = cache_salt
224
225
226
227

    return inputs


228
DecoderOnlyInputs: TypeAlias = TokenInputs | EmbedsInputs | MultiModalInputs
229
"""
230
The inputs in [`LLMEngine`][vllm.engine.llm_engine.LLMEngine] before they are
231
232
233
234
235
passed to the model executor.
This specifies the data required for decoder-only models.
"""


236
class EncoderDecoderInputs(TypedDict):
237
    """
238
239
    The inputs in [`LLMEngine`][vllm.engine.llm_engine.LLMEngine] before they
    are passed to the model executor.
240
241
242

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

244
    encoder: TokenInputs | MultiModalInputs
245
    """The inputs for the encoder portion."""
246

247
    decoder: TokenInputs | MultiModalInputs
248
    """The inputs for the decoder portion."""
249

250

251
SingletonInputs: TypeAlias = TokenInputs | EmbedsInputs | MultiModalInputs
252
"""
253
254
A processed [`SingletonPrompt`][vllm.inputs.data.SingletonPrompt] which can be
passed to [`Sequence`][collections.abc.Sequence].
255
256
"""

257
ProcessorInputs: TypeAlias = DecoderOnlyInputs | EncoderDecoderInputs
258
"""
259
The outputs from [`vllm.inputs.preprocess.InputPreprocessor`][].
260
"""
261

262
263
_T1 = TypeVar("_T1", bound=SingletonPrompt, default=SingletonPrompt)
_T2 = TypeVar("_T2", bound=SingletonPrompt, default=SingletonPrompt)
264
265


266
267
def build_explicit_enc_dec_prompt(
    encoder_prompt: _T1,
268
269
    decoder_prompt: _T2 | None,
    mm_processor_kwargs: dict[str, Any] | None = None,
270
) -> ExplicitEncoderDecoderPrompt[_T1, _T2]:
271
272
273
274
275
    if mm_processor_kwargs is None:
        mm_processor_kwargs = {}
    return ExplicitEncoderDecoderPrompt(
        encoder_prompt=encoder_prompt,
        decoder_prompt=decoder_prompt,
276
277
        mm_processor_kwargs=mm_processor_kwargs,
    )
278
279
280
281


def zip_enc_dec_prompts(
    enc_prompts: Iterable[_T1],
282
283
    dec_prompts: Iterable[_T2 | None],
    mm_processor_kwargs: Iterable[dict[str, Any]] | dict[str, Any] | None = None,
284
) -> list[ExplicitEncoderDecoderPrompt[_T1, _T2]]:
285
    """
286
    Zip encoder and decoder prompts together into a list of
287
288
    [`ExplicitEncoderDecoderPrompt`][vllm.inputs.data.ExplicitEncoderDecoderPrompt]
    instances.
289

290
    `mm_processor_kwargs` may also be provided; if a dict is passed, the same
291
292
    dictionary will be used for every encoder/decoder prompt. If an iterable is
    provided, it will be zipped with the encoder/decoder prompts.
293
294
    """
    if mm_processor_kwargs is None:
295
        mm_processor_kwargs = cast(dict[str, Any], {})
296
    if isinstance(mm_processor_kwargs, dict):
297
        return [
298
            build_explicit_enc_dec_prompt(
299
300
301
                encoder_prompt,
                decoder_prompt,
                cast(dict[str, Any], mm_processor_kwargs),
302
303
            )
            for (encoder_prompt, decoder_prompt) in zip(enc_prompts, dec_prompts)
304
        ]
305
    return [
306
307
308
309
        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
        )
310
311
    ]

312

313
314
def to_enc_dec_tuple_list(
    enc_dec_prompts: Iterable[ExplicitEncoderDecoderPrompt[_T1, _T2]],
315
) -> list[tuple[_T1, _T2 | None]]:
316
317
318
319
    return [
        (enc_dec_prompt["encoder_prompt"], enc_dec_prompt["decoder_prompt"])
        for enc_dec_prompt in enc_dec_prompts
    ]
320
321
322
323
324
325
326
327
328
329
330
331


@dataclass
class StreamingInput:
    """Input data for a streaming generation request.

    This is used with generate() to support multi-turn streaming sessions
    where inputs are provided via an async generator.
    """

    prompt: PromptType
    sampling_params: SamplingParams | None = None