test_mistral.py 10.4 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
import copy
4
import json
5

6
7
import jsonschema
import jsonschema.exceptions
8
9
import pytest

10
11
from vllm.entrypoints.openai.tool_parsers.mistral_tool_parser import (
    MistralToolCall, MistralToolParser)
12
from vllm.sampling_params import GuidedDecodingParams, SamplingParams
13

14
from ...utils import check_logprobs_close
15

16
MODELS = [
17
    "mistralai/Mistral-7B-Instruct-v0.3",
18
19
]

20
21
MISTRAL_FORMAT_MODELS = [
    "mistralai/Mistral-7B-Instruct-v0.3",
22
23
24
25
    # uses the v3-Tekken tokenizer
    "mistralai/Ministral-8B-Instruct-2410",
    # Mistral-Nemo is to big for CI, but passes locally
    # "mistralai/Mistral-Nemo-Instruct-2407"
26
27
]

28
SAMPLING_PARAMS = SamplingParams(max_tokens=512, temperature=0.0, logprobs=5)
29
30
31
SYMBOLIC_LANG_PROMPTS = [
    "勇敢な船乗りについての詩を書く",  # japanese
    "寫一首關於勇敢的水手的詩",  # chinese
32
33
    "ပုံပြင်လေးပြောပြပါ်:\n",  # burmese
    "Repeat the phrase 'URGENCY🌶️':\nURGENCY🌶️\nURGENCY🌶️\n",  # see https://github.com/vllm-project/vllm/pull/9625
34
]
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

# for function calling
TOOLS = [{
    "type": "function",
    "function": {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {
                    "type":
                    "string",
                    "description":
                    "The city to find the weather for, e.g. 'San Francisco'"
                },
                "state": {
                    "type":
                    "string",
                    "description":
                    "the two-letter abbreviation for the state that the city is"
                    " in, e.g. 'CA' which would mean 'California'"
                },
                "unit": {
                    "type": "string",
                    "description": "The unit to fetch the temperature in",
                    "enum": ["celsius", "fahrenheit"]
                }
            },
            "required": ["city", "state", "unit"]
        }
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    },
}, {
    "type": "function",
    "function": {
        "name": "rewrite",
        "description": "Rewrites text",
        "parameters": {
            "type": "object",
            "required": [],
            "properties": {
                "text": {
                    "type": "string",
                    "description": "The input text to rewrite."
                }
            }
        }
82
83
    }
}]
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
MSGS = [
    {
        "role": "system",
        "content": "You are an assistant."
    },
    {
        "role":
        "user",
        "content":
        "Could you please rewrite the below article? \n\n My English needs improvving, maybe I make errors."  # noqa
    },
    {
        "role":
        "assistant",
        "content":
        "",
        "tool_calls": [{
            "id": "bbc5b7ede",
            "type": "function",
            "function": {
                "name":
                "rewrite",
                "arguments":
                '{\"text\":\"My English needs improvving, maybe I make errors.\"}'  # noqa
            }
        }]
    },
    {
        "role": "tool",
        "content":
        "{\"action\":\"rewrite\",\"outcome\":\"My English needs improving, maybe I make errors.\"}",  # noqa
        "tool_call_id": "bbc5b7ede",
        "name": "rewrite"
    },
    {
        "role": "assistant",
        "content": "---\n\nMy English needs improving, maybe I make errors"
    },
    {
        "role":
        "user",
        "content": ("Can you tell me what the temperate"
                    " will be in Dallas, in fahrenheit?")
    }
]
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
168
SAMPLE_JSON_SCHEMA = {
    "type": "object",
    "properties": {
        "name": {
            "type": "string"
        },
        "age": {
            "type": "integer"
        },
        "skills": {
            "type": "array",
            "items": {
                "type": "string",
                "maxLength": 10
            },
            "minItems": 3
        },
        "work_history": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "company": {
                        "type": "string"
                    },
                    "duration": {
                        "type": "number"
                    },
                    "position": {
                        "type": "string"
                    }
                },
                "required": ["company", "position"]
            }
        }
    },
    "required": ["name", "age", "skills", "work_history"]
}

169
170
171

@pytest.mark.parametrize("model", MODELS)
@pytest.mark.parametrize("dtype", ["bfloat16"])
172
173
@pytest.mark.parametrize("max_tokens", [64])
@pytest.mark.parametrize("num_logprobs", [5])
174
175
def test_models(hf_runner, vllm_runner, example_prompts, model: str,
                dtype: str, max_tokens: int, num_logprobs: int) -> None:
176
    # TODO(sang): Sliding window should be tested separately.
177
178
179
    with hf_runner(model, dtype=dtype) as hf_model:
        hf_outputs = hf_model.generate_greedy_logprobs_limit(
            example_prompts, max_tokens, num_logprobs)
180

181
182
    with vllm_runner(model, dtype=dtype,
                     tokenizer_mode="mistral") as vllm_model:
183
184
        vllm_outputs = vllm_model.generate_greedy_logprobs(
            example_prompts, max_tokens, num_logprobs)
185

186
187
188
189
190
191
    check_logprobs_close(
        outputs_0_lst=hf_outputs,
        outputs_1_lst=vllm_outputs,
        name_0="hf",
        name_1="vllm",
    )
192
193


194
@pytest.mark.parametrize("model", MISTRAL_FORMAT_MODELS)
195
196
197
@pytest.mark.parametrize("dtype", ["bfloat16"])
@pytest.mark.parametrize("max_tokens", [64])
@pytest.mark.parametrize("num_logprobs", [5])
198
199
def test_mistral_format(vllm_runner, example_prompts, model: str, dtype: str,
                        max_tokens: int, num_logprobs: int) -> None:
200
201
202
203
204
205
206
207
208
209
    with vllm_runner(
            model,
            dtype=dtype,
            tokenizer_mode="mistral",
            load_format="mistral",
            config_format="mistral",
    ) as mistral_format_model:
        mistral_format_outputs = mistral_format_model.generate_greedy_logprobs(
            example_prompts, max_tokens, num_logprobs)

210
211
212
213
214
215
216
217
218
219
    with vllm_runner(
            model,
            dtype=dtype,
            tokenizer_mode="auto",
            load_format="safetensors",
            config_format="hf",
    ) as hf_format_model:
        hf_format_outputs = hf_format_model.generate_greedy_logprobs(
            example_prompts, max_tokens, num_logprobs)

220
221
222
223
224
225
    check_logprobs_close(
        outputs_0_lst=hf_format_outputs,
        outputs_1_lst=mistral_format_outputs,
        name_0="hf",
        name_1="mistral",
    )
226
227


228
@pytest.mark.parametrize("model", MISTRAL_FORMAT_MODELS)
229
@pytest.mark.parametrize("dtype", ["bfloat16"])
230
231
def test_mistral_symbolic_languages(vllm_runner, model: str,
                                    dtype: str) -> None:
232
233
234
235
236
237
238
239
240
241
242
    with vllm_runner(model,
                     dtype=dtype,
                     max_model_len=8192,
                     tokenizer_mode="mistral",
                     config_format="mistral",
                     load_format="mistral") as vllm_model:
        for prompt in SYMBOLIC_LANG_PROMPTS:
            msg = {"role": "user", "content": prompt}
            outputs = vllm_model.model.chat([msg],
                                            sampling_params=SAMPLING_PARAMS)
            assert "�" not in outputs[0].outputs[0].text.strip()
243
244


245
@pytest.mark.parametrize("model", MISTRAL_FORMAT_MODELS)
246
@pytest.mark.parametrize("dtype", ["bfloat16"])
247
def test_mistral_function_calling(vllm_runner, model: str, dtype: str) -> None:
248
249
250
251
252
    with vllm_runner(model,
                     dtype=dtype,
                     tokenizer_mode="mistral",
                     config_format="mistral",
                     load_format="mistral") as vllm_model:
253
254
255

        msgs = copy.deepcopy(MSGS)
        outputs = vllm_model.model.chat(msgs,
256
257
258
                                        tools=TOOLS,
                                        sampling_params=SAMPLING_PARAMS)

259
260
261
262
263
264
265
266
        tokenizer = vllm_model.model.get_tokenizer()
        tool_parser = MistralToolParser(tokenizer)

        model_output = outputs[0].outputs[0].text.strip()
        assert model_output.startswith(tool_parser.bot_token), model_output
        parsed_message = tool_parser.extract_tool_calls(model_output, None)

        assert parsed_message.tools_called
267
268

        assert MistralToolCall.is_valid_id(parsed_message.tool_calls[0].id)
269
270
271
272
273
        assert parsed_message.tool_calls[
            0].function.name == "get_current_weather"
        assert parsed_message.tool_calls[
            0].function.arguments == '{"city": "Dallas", "state": "TX", "unit": "fahrenheit"}'  # noqa
        assert parsed_message.content is None
274
275
276
277
278


@pytest.mark.parametrize("model", MODELS)
@pytest.mark.parametrize("guided_backend",
                         ["outlines", "lm-format-enforcer", "xgrammar"])
279
280
281
282
283
284
285
286
287
def test_mistral_guided_decoding(
    monkeypatch: pytest.MonkeyPatch,
    vllm_runner,
    model: str,
    guided_backend: str,
) -> None:
    with monkeypatch.context() as m:
        # Guided JSON not supported in xgrammar + V1 yet
        m.setenv("VLLM_USE_V1", "0")
288

289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
        with vllm_runner(
                model,
                dtype='bfloat16',
                tokenizer_mode="mistral",
                guided_decoding_backend=guided_backend,
        ) as vllm_model:
            guided_decoding = GuidedDecodingParams(json=SAMPLE_JSON_SCHEMA)
            params = SamplingParams(max_tokens=512,
                                    temperature=0.7,
                                    guided_decoding=guided_decoding)

            messages = [{
                "role": "system",
                "content": "you are a helpful assistant"
            }, {
                "role":
                "user",
                "content":
                f"Give an example JSON for an employee profile that "
                f"fits this schema: {SAMPLE_JSON_SCHEMA}"
            }]
            outputs = vllm_model.model.chat(messages, sampling_params=params)
311
312
313
314
315
316
317
318
319
320

        generated_text = outputs[0].outputs[0].text
        json_response = json.loads(generated_text)
        assert outputs is not None

        try:
            jsonschema.validate(instance=json_response,
                                schema=SAMPLE_JSON_SCHEMA)
        except jsonschema.exceptions.ValidationError:
            pytest.fail("Generated response is not valid with JSON schema")