"vllm/vscode:/vscode.git/clone" did not exist on "5e25b122366a639f6da9fa568b532d6932c45aff"
test_mistral.py 11.2 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
import pytest
7
import os
8

9
from vllm.entrypoints.openai.tool_parsers.mistral_tool_parser import (
10
11
12
    MistralToolCall,
    MistralToolParser,
)
13
from vllm.sampling_params import SamplingParams
14
from vllm.tokenizers import MistralTokenizer
15

16
from ...utils import check_logprobs_close
17
from ....utils import models_path_prefix
18

19
MODELS = [
20
    os.path.join(models_path_prefix, "mistralai/Mistral-7B-Instruct-v0.3"),
21
22
]

23
MISTRAL_FORMAT_MODELS = [
24
    os.path.join(models_path_prefix, "mistralai/Mistral-7B-Instruct-v0.3"),
25
    # uses the v3-Tekken tokenizer
zhuwenwen's avatar
zhuwenwen committed
26
    os.path.join(models_path_prefix, "mistralai/Ministral-8B-Instruct-2410"),
27
    # Mistral-Nemo is too big for CI, but passes locally
28
    # "mistralai/Mistral-Nemo-Instruct-2407"
29
30
]

31
SAMPLING_PARAMS = SamplingParams(max_tokens=512, temperature=0.0, logprobs=5)
32
33
34
SYMBOLIC_LANG_PROMPTS = [
    "勇敢な船乗りについての詩を書く",  # japanese
    "寫一首關於勇敢的水手的詩",  # chinese
35
36
    "ပုံပြင်လေးပြောပြပါ်:\n",  # burmese
    "Repeat the phrase 'URGENCY🌶️':\nURGENCY🌶️\nURGENCY🌶️\n",  # see https://github.com/vllm-project/vllm/pull/9625
37
]
38
39

# for function calling
40
41
42
43
44
45
46
47
48
49
50
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
51
52
                        "description": "The city to find the weather for, e.g. "
                        "'San Francisco'",
53
54
55
                    },
                    "state": {
                        "type": "string",
56
57
                        "description": "the two-letter abbreviation for the state that "
                        "the city is in, e.g. 'CA' which would mean 'California'",
58
59
60
61
62
63
                    },
                    "unit": {
                        "type": "string",
                        "description": "The unit to fetch the temperature in",
                        "enum": ["celsius", "fahrenheit"],
                    },
64
                },
65
                "required": ["city", "state", "unit"],
66
            },
67
        },
68
69
    },
    {
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
        "type": "function",
        "function": {
            "name": "rewrite",
            "description": "Rewrites text",
            "parameters": {
                "type": "object",
                "required": [],
                "properties": {
                    "text": {
                        "type": "string",
                        "description": "The input text to rewrite.",
                    }
                },
            },
        },
85
    },
86
87
88
]
MSGS = [
    {"role": "system", "content": "You are an assistant."},
89
    {
90
        "role": "user",
91
92
        "content": "Could you please rewrite the below article? \n\n My English needs "
        "improvving, maybe I make errors.",
93
94
    },
    {
95
96
97
98
99
100
101
102
        "role": "assistant",
        "content": "",
        "tool_calls": [
            {
                "id": "bbc5b7ede",
                "type": "function",
                "function": {
                    "name": "rewrite",
103
104
                    "arguments": '{"text":"My English needs improvving, maybe '
                    'I make errors."}',
105
                },
106
            }
107
        ],
108
109
110
    },
    {
        "role": "tool",
111
112
        "content": '{"action":"rewrite","outcome":"My English needs improving, maybe '
        'I make errors."}',
113
        "tool_call_id": "bbc5b7ede",
114
        "name": "rewrite",
115
116
117
    },
    {
        "role": "assistant",
118
        "content": "---\n\nMy English needs improving, maybe I make errors",
119
120
    },
    {
121
122
123
124
125
        "role": "user",
        "content": (
            "Can you tell me what the temperate will be in Dallas, in fahrenheit?"
        ),
    },
126
]
127

128
129
130
SAMPLE_JSON_SCHEMA = {
    "type": "object",
    "properties": {
131
132
        "name": {"type": "string"},
        "age": {"type": "integer"},
133
134
        "skills": {
            "type": "array",
135
136
            "items": {"type": "string", "maxLength": 10},
            "minItems": 3,
137
138
139
140
141
142
        },
        "work_history": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
143
144
145
                    "company": {"type": "string"},
                    "duration": {"type": "number"},
                    "position": {"type": "string"},
146
                },
147
148
149
                "required": ["company", "position"],
            },
        },
150
    },
151
    "required": ["name", "age", "skills", "work_history"],
152
153
}

154
155
156

@pytest.mark.parametrize("model", MODELS)
@pytest.mark.parametrize("dtype", ["bfloat16"])
157
158
@pytest.mark.parametrize("max_tokens", [64])
@pytest.mark.parametrize("num_logprobs", [5])
159
160
161
162
163
164
165
166
167
def test_models(
    hf_runner,
    vllm_runner,
    example_prompts,
    model: str,
    dtype: str,
    max_tokens: int,
    num_logprobs: int,
) -> None:
168
    # TODO(sang): Sliding window should be tested separately.
169
170
    with hf_runner(model, dtype=dtype) as hf_model:
        hf_outputs = hf_model.generate_greedy_logprobs_limit(
171
172
            example_prompts, max_tokens, num_logprobs
        )
173

174
    with vllm_runner(model, dtype=dtype, tokenizer_mode="mistral") as vllm_model:
175
        vllm_outputs = vllm_model.generate_greedy_logprobs(
176
177
            example_prompts, max_tokens, num_logprobs
        )
178

179
180
181
182
183
184
    check_logprobs_close(
        outputs_0_lst=hf_outputs,
        outputs_1_lst=vllm_outputs,
        name_0="hf",
        name_1="vllm",
    )
185
186


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

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

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


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


246
@pytest.mark.parametrize("model", MISTRAL_FORMAT_MODELS)
247
@pytest.mark.parametrize("dtype", ["bfloat16"])
248
def test_mistral_function_calling(vllm_runner, model: str, dtype: str) -> None:
249
250
251
252
253
254
255
    with vllm_runner(
        model,
        dtype=dtype,
        tokenizer_mode="mistral",
        config_format="mistral",
        load_format="mistral",
    ) as vllm_model:
256
        msgs = copy.deepcopy(MSGS)
257
258
259
        outputs = vllm_model.llm.chat(
            msgs, tools=TOOLS, sampling_params=SAMPLING_PARAMS
        )
260

261
        tokenizer = vllm_model.llm.get_tokenizer()
262
263
264
265
266
267
268
        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
269
270

        assert MistralToolCall.is_valid_id(parsed_message.tool_calls[0].id)
271
272
273
274
275
        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
276
        assert parsed_message.content is None
277
278


279
def test_mistral_function_call_nested_json():
280
    """Ensure that the function-name regex captures the entire outermost
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
    JSON block, including nested braces."""

    # Create a minimal stub tokenizer that provides the few attributes the
    # parser accesses (`version` and `get_vocab`).
    class _StubMistralTokenizer(MistralTokenizer):
        version = 11  # Satisfy the version check

        def __init__(self):
            pass

        @staticmethod
        def get_vocab():
            # Provide the special TOOL_CALLS token expected by the parser.
            return {"[TOOL_CALLS]": 0}

    tokenizer = _StubMistralTokenizer()
    parser = MistralToolParser(tokenizer)

    # Craft a model output featuring nested JSON inside the arguments.
    args_dict = {
        "city": "Dallas",
        "state": "TX",
        "unit": "fahrenheit",
304
        "sub_dict": {"foo": "bar", "inner": {"x": 1, "y": 2}},
305
306
    }

307
    model_output = f"{parser.bot_token}get_current_weather{json.dumps(args_dict)}"
308
309
310
311
312
313
314
315
316
317
318
319

    parsed = parser.extract_tool_calls(model_output, None)

    # Assertions: the tool call is detected and the full nested JSON is parsed
    # without truncation.
    assert parsed.tools_called

    assert MistralToolCall.is_valid_id(parsed.tool_calls[0].id)
    assert parsed.tool_calls[0].function.name == "get_current_weather"
    assert json.loads(parsed.tool_calls[0].function.arguments) == args_dict
    # No additional content outside the tool call should be returned.
    assert parsed.content is None
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354

    # multiple calls
    multiple_args_dict = [
        {
            "city": "Dallas",
            "state": "TX",
            "unit": "fahrenheit",
            "sub_dict": {"foo": "bar", "inner": {"x": 1, "y": 2}},
        },
        {},
        {"a": 0},
        {"a": 1, "b": "c"},
    ]
    names = ["get_current_weather", "get_current_weather_2", "random", "random_2"]

    model_output = "".join(
        [
            f"{parser.bot_token}{name}{json.dumps(args)}"
            for name, args in zip(names, multiple_args_dict)
        ]
    )

    parsed = parser.extract_tool_calls(model_output, None)

    # Assertions: the tool call is detected and the full nested JSON is parsed
    # without truncation.
    assert parsed.tools_called
    assert len(parsed.tool_calls) == len(multiple_args_dict)

    for i, tool_call in enumerate(parsed.tool_calls):
        assert MistralToolCall.is_valid_id(tool_call.id)
        assert tool_call.function.name == names[i]
        assert json.loads(tool_call.function.arguments) == multiple_args_dict[i]
        # No additional content outside the tool call should be returned.
        assert parsed.content is None