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

4
from vllm.config import VllmConfig
5
6
7
8
9
10
11
12
13
14
from vllm.entrypoints.chat_utils import (
    ChatCompletionMessageParam,
    ConversationMessage,
    parse_chat_messages,
    parse_chat_messages_async,
)
from vllm.logger import init_logger
from vllm.tokenizers.mistral import MistralTokenizer
from vllm.utils.async_utils import make_async

15
from .base import BaseRenderer
16
17
from .inputs import DictPrompt
from .inputs.preprocess import parse_dec_only_prompt
18
from .params import ChatParams
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

logger = init_logger(__name__)


def safe_apply_chat_template(
    tokenizer: MistralTokenizer,
    messages: list[ChatCompletionMessageParam],
    **kwargs,
) -> str | list[int]:
    from mistral_common.exceptions import MistralCommonException

    try:
        return tokenizer.apply_chat_template(messages, **kwargs)
    # mistral-common uses assert statements to stop processing of input
    # if input does not comply with the expected format.
    # We convert those assertion errors to ValueErrors so they can be
    # properly caught in the preprocessing_input step
    except (AssertionError, MistralCommonException) as e:
        raise ValueError(str(e)) from e

    # External library exceptions can sometimes occur despite the framework's
    # internal exception management capabilities.
    except Exception as e:
        # Log and report any library-related exceptions for further
        # investigation.
        logger.exception(
            "An error occurred in `mistral_common` while applying chat template"
        )
        raise ValueError(str(e)) from e


50
51
52
53
54
55
56
class MistralRenderer(BaseRenderer[MistralTokenizer]):
    def __init__(
        self,
        config: VllmConfig,
        tokenizer: MistralTokenizer | None,
    ) -> None:
        super().__init__(config, tokenizer)
57
58

        self._apply_chat_template_async = make_async(
59
            safe_apply_chat_template, executor=self._executor
60
61
62
63
64
        )

    def render_messages(
        self,
        messages: list[ChatCompletionMessageParam],
65
        params: ChatParams,
66
    ) -> tuple[list[ConversationMessage], DictPrompt]:
67
68
69
        tokenizer = self.get_tokenizer()
        conversation, mm_data, mm_uuids = parse_chat_messages(
            messages,
70
            self.model_config,
71
            content_format="string",
72
            media_io_kwargs=params.media_io_kwargs,
73
            mm_processor_kwargs=params.mm_processor_kwargs,
74
75
        )

76
77
78
79
        prompt_raw = safe_apply_chat_template(
            tokenizer,
            messages,
            **params.get_apply_chat_template_kwargs(),
80
        )
81

82
        prompt = parse_dec_only_prompt(prompt_raw)
83
84
85
86
87
        if mm_data is not None:
            prompt["multi_modal_data"] = mm_data
        if mm_uuids is not None:
            prompt["multi_modal_uuids"] = mm_uuids

88
        return conversation, prompt
89
90
91
92

    async def render_messages_async(
        self,
        messages: list[ChatCompletionMessageParam],
93
        params: ChatParams,
94
    ) -> tuple[list[ConversationMessage], DictPrompt]:
95
96
97
        tokenizer = self.get_tokenizer()
        conversation, mm_data, mm_uuids = await parse_chat_messages_async(
            messages,
98
            self.model_config,
99
            content_format="string",
100
            media_io_kwargs=params.media_io_kwargs,
101
            mm_processor_kwargs=params.mm_processor_kwargs,
102
103
104
        )

        prompt_raw = await self._apply_chat_template_async(
105
106
107
            tokenizer,
            messages,
            **params.get_apply_chat_template_kwargs(),
108
109
        )

110
        prompt = parse_dec_only_prompt(prompt_raw)
111
112
113
114
115
        if mm_data is not None:
            prompt["multi_modal_data"] = mm_data
        if mm_uuids is not None:
            prompt["multi_modal_uuids"] = mm_uuids

116
        return conversation, prompt