chat_utils.py 11.8 KB
Newer Older
1
import asyncio
2
import codecs
3
from collections import defaultdict
4
from functools import lru_cache
5
from pathlib import Path
6
7
from typing import (Any, Awaitable, Dict, Iterable, List, Literal, Mapping,
                    Optional, Tuple, Union)
8

9
10
11
12
13
14
15
16
17
18
# yapf conflicts with isort for this block
# yapf: disable
from openai.types.chat import ChatCompletionContentPartImageParam
from openai.types.chat import (
    ChatCompletionContentPartParam as OpenAIChatCompletionContentPartParam)
from openai.types.chat import ChatCompletionContentPartTextParam
from openai.types.chat import (
    ChatCompletionMessageParam as OpenAIChatCompletionMessageParam)
# yapf: enable
# pydantic needs the TypedDict from typing_extensions
19
20
from pydantic import ConfigDict, TypeAdapter
from typing_extensions import Required, TypeAlias, TypedDict
21

22
from vllm.config import ModelConfig
23
24
from vllm.logger import init_logger
from vllm.multimodal import MultiModalDataDict
25
26
from vllm.multimodal.utils import (async_get_and_parse_audio,
                                   async_get_and_parse_image)
27
from vllm.transformers_utils.tokenizer import AnyTokenizer
28
29
30
31

logger = init_logger(__name__)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
class AudioURL(TypedDict, total=False):
    url: Required[str]
    """
    Either a URL of the audio or a data URL with base64 encoded audio data.
    """


class ChatCompletionContentPartAudioParam(TypedDict, total=False):
    audio_url: Required[AudioURL]

    type: Required[Literal["audio_url"]]
    """The type of the content part."""


46
47
48
49
50
51
52
class CustomChatCompletionContentPartParam(TypedDict, total=False):
    __pydantic_config__ = ConfigDict(extra="allow")  # type: ignore

    type: Required[str]
    """The type of the content part."""


53
54
55
ChatCompletionContentPartParam: TypeAlias = Union[
    OpenAIChatCompletionContentPartParam, ChatCompletionContentPartAudioParam,
    CustomChatCompletionContentPartParam, ]
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77


class CustomChatCompletionMessageParam(TypedDict, total=False):
    """Enables custom roles in the Chat Completion API."""
    role: Required[str]
    """The role of the message's author."""

    content: Union[str, List[ChatCompletionContentPartParam]]
    """The contents of the message."""

    name: str
    """An optional name for the participant.

    Provides the model information to differentiate between participants of the
    same role.
    """


ChatCompletionMessageParam = Union[OpenAIChatCompletionMessageParam,
                                   CustomChatCompletionMessageParam]


78
# TODO: Make fields ReadOnly once mypy supports it
79
80
81
82
83
class ConversationMessage(TypedDict):
    role: str
    content: str


84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
class MultiModalItemTracker:
    """
    Tracks multi-modal items in a given request and ensures that the number
    of multi-modal items in a given request does not exceed the configured
    maximum per prompt.
    """

    def __init__(self, model_config: ModelConfig, tokenizer: AnyTokenizer):
        self._model_config = model_config
        self._tokenizer = tokenizer
        self._allowed_items = (model_config.multimodal_config.limit_per_prompt
                               if model_config.multimodal_config else {})
        self._consumed_items = {k: 0 for k in self._allowed_items}
        self._futures: List[Awaitable[MultiModalDataDict]] = []

    @staticmethod
    @lru_cache(maxsize=None)
    def _cached_token_str(tokenizer: AnyTokenizer, token_index: int):
        return tokenizer.decode(token_index)

    def add(self, modality: Literal["image", "audio"],
            mm_future: Awaitable[MultiModalDataDict]) -> Optional[str]:
        """
        Adds the multi-modal item to the current prompt and returns the
        placeholder string to use, if any.
        """
        allowed_count = self._allowed_items.get(modality, 1)
        current_count = self._consumed_items.get(modality, 0) + 1
        if current_count > allowed_count:
            raise ValueError(
                f"At most {allowed_count} {modality}(s) may be provided in "
                "one request.")

        self._consumed_items[modality] = current_count
        self._futures.append(mm_future)

        # TODO: Let user specify how to insert image tokens into prompt
        # (similar to chat template)
        model_type = self._model_config.hf_config.model_type
        if modality == "image":
            if model_type == "phi3_v":
                # Workaround since this token is not defined in the tokenizer
                return f"<|image_{current_count}|>"
            if model_type == "minicpmv":
                return "(<image>./</image>)"
            if model_type in ("blip-2", "chatglm", "fuyu", "paligemma"):
                # These models do not use image tokens in the prompt
                return None
            if model_type.startswith("llava"):
                return MultiModalItemTracker._cached_token_str(
                    self._tokenizer,
                    self._model_config.hf_config.image_token_index)
            if model_type in ("chameleon", "internvl_chat"):
                return "<image>"

            raise TypeError(f"Unknown model type: {model_type}")
        elif modality == "audio":
            if model_type == "ultravox":
                return "<|reserved_special_token_0|>"
            raise TypeError(f"Unknown model type: {model_type}")
        else:
            raise TypeError(f"Unknown modality: {modality}")

    @staticmethod
    async def _combine(futures: List[Awaitable[MultiModalDataDict]]):
        mm_lists: Mapping[str, List[object]] = defaultdict(list)

        # Merge all the multi-modal items
        for single_mm_data in (await asyncio.gather(*futures)):
            for mm_key, mm_item in single_mm_data.items():
                if isinstance(mm_item, list):
                    mm_lists[mm_key].extend(mm_item)
                else:
                    mm_lists[mm_key].append(mm_item)

        # Unpack any single item lists for models that don't expect multiple.
        return {
            mm_key: mm_list[0] if len(mm_list) == 1 else mm_list
            for mm_key, mm_list in mm_lists.items()
        }

    def all_mm_data(self) -> Optional[Awaitable[MultiModalDataDict]]:
        return MultiModalItemTracker._combine(
            self._futures) if self._futures else None
168
169


170
171
def load_chat_template(
        chat_template: Optional[Union[Path, str]]) -> Optional[str]:
172
173
174
175
176
177
    if chat_template is None:
        return None
    try:
        with open(chat_template, "r") as f:
            resolved_chat_template = f.read()
    except OSError as e:
178
179
180
        if isinstance(chat_template, Path):
            raise

181
182
183
184
185
186
        JINJA_CHARS = "{}\n"
        if not any(c in chat_template for c in JINJA_CHARS):
            msg = (f"The supplied chat template ({chat_template}) "
                   f"looks like a file path, but it failed to be "
                   f"opened. Reason: {e}")
            raise ValueError(msg) from e
187

188
189
190
        # If opening a file fails, set chat template to be args to
        # ensure we decode so our escape are interpreted correctly
        resolved_chat_template = codecs.decode(chat_template, "unicode_escape")
191

192
193
    logger.info("Using supplied chat template:\n%s", resolved_chat_template)
    return resolved_chat_template
194
195


196
# TODO: Let user specify how to insert multimodal tokens into prompt
197
# (similar to chat template)
198
def _get_full_multimodal_text_prompt(placeholder_counts: Dict[str, int],
199
200
                                     text_prompt: str) -> str:
    """Combine multimodal prompts for a multimodal language model"""
201

202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
    # Look through the text prompt to check for missing placeholders
    missing_placeholders = []
    for placeholder in placeholder_counts:

        # For any existing placeholder in the text prompt, we leave it as is
        placeholder_counts[placeholder] -= text_prompt.count(placeholder)

        if placeholder_counts[placeholder] < 0:
            raise ValueError(
                f"Found more '{placeholder}' placeholders in input prompt than "
                "actual multimodal data items.")

        missing_placeholders.extend([placeholder] *
                                    placeholder_counts[placeholder])

    # NOTE: For now we always add missing placeholders at the front of
    # the prompt. This may change to be customizable in the future.
    return "\n".join(missing_placeholders + [text_prompt])
220
221


222
223
224
225
226
_TextParser = TypeAdapter(ChatCompletionContentPartTextParam)
_ImageParser = TypeAdapter(ChatCompletionContentPartImageParam)
_AudioParser = TypeAdapter(ChatCompletionContentPartAudioParam)


227
228
229
def _parse_chat_message_content_parts(
    role: str,
    parts: Iterable[ChatCompletionContentPartParam],
230
231
    mm_tracker: MultiModalItemTracker,
) -> List[ConversationMessage]:
232
    texts: List[str] = []
233
234
235

    # multimodal placeholder_string : count
    mm_placeholder_counts: Dict[str, int] = {}
236
237
238
239

    for part in parts:
        part_type = part["type"]
        if part_type == "text":
240
            text = _TextParser.validate_python(part)["text"]
241
242
            texts.append(text)
        elif part_type == "image_url":
243
            image_url = _ImageParser.validate_python(part)["image_url"]
244
245
246
247
248
249

            if image_url.get("detail", "auto") != "auto":
                logger.warning(
                    "'image_url.detail' is currently not supported and "
                    "will be ignored.")

250
251
252
253
254
            image_coro = async_get_and_parse_image(image_url["url"])
            placeholder = mm_tracker.add("image", image_coro)
            if placeholder:
                mm_placeholder_counts[placeholder] = mm_placeholder_counts.get(
                    placeholder, 0) + 1
255
        elif part_type == "audio_url":
256
            audio_url = _AudioParser.validate_python(part)["audio_url"]
257
258
259
260
261
            audio_coro = async_get_and_parse_audio(audio_url["url"])
            placeholder = mm_tracker.add("audio", audio_coro)
            if placeholder:
                mm_placeholder_counts[placeholder] = mm_placeholder_counts.get(
                    placeholder, 0) + 1
262
263
264
265
        else:
            raise NotImplementedError(f"Unknown part type: {part_type}")

    text_prompt = "\n".join(texts)
266
267
268
    if mm_placeholder_counts:
        text_prompt = _get_full_multimodal_text_prompt(mm_placeholder_counts,
                                                       text_prompt)
269

270
    return [ConversationMessage(role=role, content=text_prompt)]
271
272


273
def _parse_chat_message_content(
274
275
        message: ChatCompletionMessageParam,
        mm_tracker: MultiModalItemTracker) -> List[ConversationMessage]:
276
277
278
279
    role = message["role"]
    content = message.get("content")

    if content is None:
280
        return []
281
    if isinstance(content, str):
282
        return [ConversationMessage(role=role, content=content)]
283

284
285
286
    return _parse_chat_message_content_parts(
        role,
        content,  # type: ignore
287
        mm_tracker,
288
    )
289
290
291
292
293


def parse_chat_messages(
    messages: List[ChatCompletionMessageParam],
    model_config: ModelConfig,
294
    tokenizer: AnyTokenizer,
295
) -> Tuple[List[ConversationMessage], Optional[Awaitable[MultiModalDataDict]]]:
296
    conversation: List[ConversationMessage] = []
297
    mm_tracker = MultiModalItemTracker(model_config, tokenizer)
298
299

    for msg in messages:
300
        sub_messages = _parse_chat_message_content(msg, mm_tracker)
301

302
        conversation.extend(sub_messages)
303

304
    return conversation, mm_tracker.all_mm_data()
305
306
307
308
309
310
311
312
313


def apply_chat_template(
    tokenizer: AnyTokenizer,
    conversation: List[ConversationMessage],
    chat_template: Optional[str],
    *,
    tokenize: bool = False,  # Different from HF's default
    **kwargs: Any,
314
) -> Union[str, List[int]]:
315
316
317
318
319
320
321
322
323
324
325
326
327
    if chat_template is None and tokenizer.chat_template is None:
        raise ValueError(
            "As of transformers v4.44, default chat template is no longer "
            "allowed, so you must provide a chat template if the tokenizer "
            "does not define one.")

    prompt = tokenizer.apply_chat_template(
        conversation=conversation,
        chat_template=chat_template,
        tokenize=tokenize,
        **kwargs,
    )
    return prompt