"tests/tool_parsers/test_qwen3coder_tool_parser.py" did not exist on "9bb38130cb19eb084d39f269cbeae2952789fafd"
test_utils.py 14.2 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
# ruff: noqa
4

5
import json
6
7
8
import os
import tempfile
from pathlib import Path
9
from unittest.mock import patch
10

11
import pytest
12
import torch
13
import yaml
14
from transformers import AutoTokenizer
15

16
from vllm.config import ParallelConfig, VllmConfig, set_current_vllm_config
17
from vllm.transformers_utils.detokenizer_utils import convert_ids_list_to_tokens
18

19
from vllm.utils import (
20
21
22
    FlexibleArgumentParser,
    bind_kv_cache,
)
23
from ..utils import create_new_process_for_each_test, flat_product
24

25

26
27
28
29
# Tests for FlexibleArgumentParser
@pytest.fixture
def parser():
    parser = FlexibleArgumentParser()
30
31
32
33
34
35
36
37
    parser.add_argument(
        "--image-input-type", choices=["pixel_values", "image_features"]
    )
    parser.add_argument("--model-name")
    parser.add_argument("--batch-size", type=int)
    parser.add_argument("--enable-feature", action="store_true")
    parser.add_argument("--hf-overrides", type=json.loads)
    parser.add_argument("-O", "--compilation-config", type=json.loads)
38
39
40
    return parser


41
42
43
@pytest.fixture
def parser_with_config():
    parser = FlexibleArgumentParser()
44
45
46
47
48
49
50
51
    parser.add_argument("serve")
    parser.add_argument("model_tag", nargs="?")
    parser.add_argument("--model", type=str)
    parser.add_argument("--served-model-name", type=str)
    parser.add_argument("--config", type=str)
    parser.add_argument("--port", type=int)
    parser.add_argument("--tensor-parallel-size", type=int)
    parser.add_argument("--trust-remote-code", action="store_true")
52
53
54
    return parser


55
def test_underscore_to_dash(parser):
56
57
    args = parser.parse_args(["--image_input_type", "pixel_values"])
    assert args.image_input_type == "pixel_values"
58
59
60


def test_mixed_usage(parser):
61
62
63
64
65
    args = parser.parse_args(
        ["--image_input_type", "image_features", "--model-name", "facebook/opt-125m"]
    )
    assert args.image_input_type == "image_features"
    assert args.model_name == "facebook/opt-125m"
66
67
68
69


def test_with_equals_sign(parser):
    args = parser.parse_args(
70
71
72
73
        ["--image_input_type=pixel_values", "--model-name=facebook/opt-125m"]
    )
    assert args.image_input_type == "pixel_values"
    assert args.model_name == "facebook/opt-125m"
74
75
76


def test_with_int_value(parser):
77
    args = parser.parse_args(["--batch_size", "32"])
78
    assert args.batch_size == 32
79
    args = parser.parse_args(["--batch-size", "32"])
80
81
82
83
    assert args.batch_size == 32


def test_with_bool_flag(parser):
84
    args = parser.parse_args(["--enable_feature"])
85
    assert args.enable_feature is True
86
    args = parser.parse_args(["--enable-feature"])
87
88
89
90
91
    assert args.enable_feature is True


def test_invalid_choice(parser):
    with pytest.raises(SystemExit):
92
        parser.parse_args(["--image_input_type", "invalid_choice"])
93
94
95


def test_missing_required_argument(parser):
96
    parser.add_argument("--required-arg", required=True)
97
98
    with pytest.raises(SystemExit):
        parser.parse_args([])
99
100


101
def test_cli_override_to_config(parser_with_config, cli_config_file):
102
103
104
    args = parser_with_config.parse_args(
        ["serve", "mymodel", "--config", cli_config_file, "--tensor-parallel-size", "3"]
    )
105
    assert args.tensor_parallel_size == 3
106
107
108
    args = parser_with_config.parse_args(
        ["serve", "mymodel", "--tensor-parallel-size", "3", "--config", cli_config_file]
    )
109
    assert args.tensor_parallel_size == 3
110
    assert args.port == 12312
111
112
113
114
115
116
117
118
119
120
121
122
    args = parser_with_config.parse_args(
        [
            "serve",
            "mymodel",
            "--tensor-parallel-size",
            "3",
            "--config",
            cli_config_file,
            "--port",
            "666",
        ]
    )
123
124
    assert args.tensor_parallel_size == 3
    assert args.port == 666
125
126


127
def test_config_args(parser_with_config, cli_config_file):
128
    args = parser_with_config.parse_args(
129
130
        ["serve", "mymodel", "--config", cli_config_file]
    )
131
    assert args.tensor_parallel_size == 2
132
    assert args.trust_remote_code
133
134
135
136


def test_config_file(parser_with_config):
    with pytest.raises(FileNotFoundError):
137
        parser_with_config.parse_args(
138
139
            ["serve", "mymodel", "--config", "test_config.yml"]
        )
140
141
142

    with pytest.raises(ValueError):
        parser_with_config.parse_args(
143
144
            ["serve", "mymodel", "--config", "./data/test_config.json"]
        )
145
146

    with pytest.raises(ValueError):
147
148
149
150
151
152
153
154
155
156
157
        parser_with_config.parse_args(
            [
                "serve",
                "mymodel",
                "--tensor-parallel-size",
                "3",
                "--config",
                "--batch-size",
                "32",
            ]
        )
158
159


160
def test_no_model_tag(parser_with_config, cli_config_file):
161
    with pytest.raises(ValueError):
162
        parser_with_config.parse_args(["serve", "--config", cli_config_file])
163
164


165
166
167
168
169
def test_dict_args(parser):
    args = [
        "--model-name=something.something",
        "--hf-overrides.key1",
        "val1",
170
        # Test nesting
171
172
173
174
        "--hf-overrides.key2.key3",
        "val2",
        "--hf-overrides.key2.key4",
        "val3",
175
        # Test compile config and compilation mode
176
177
178
179
        "-O.use_inductor=true",
        "-O.backend",
        "custom",
        "-O1",
180
        # Test = sign
181
        "--hf-overrides.key5=val4",
182
183
184
185
186
        # Test underscore to dash conversion
        "--hf_overrides.key_6",
        "val5",
        "--hf_overrides.key-7.key_8",
        "val6",
187
188
189
190
191
192
193
194
195
        # Test data type detection
        "--hf_overrides.key9",
        "100",
        "--hf_overrides.key10",
        "100.0",
        "--hf_overrides.key11",
        "true",
        "--hf_overrides.key12.key13",
        "null",
196
197
198
199
200
201
202
        # Test '-' and '.' in value
        "--hf_overrides.key14.key15",
        "-minus.and.dot",
        # Test array values
        "-O.custom_ops+",
        "-quant_fp8",
        "-O.custom_ops+=+silu_mul,-rms_norm",
203
204
205
206
207
208
209
210
211
212
    ]
    parsed_args = parser.parse_args(args)
    assert parsed_args.model_name == "something.something"
    assert parsed_args.hf_overrides == {
        "key1": "val1",
        "key2": {
            "key3": "val2",
            "key4": "val3",
        },
        "key5": "val4",
213
214
215
216
        "key_6": "val5",
        "key-7": {
            "key_8": "val6",
        },
217
218
219
220
221
222
        "key9": 100,
        "key10": 100.0,
        "key11": True,
        "key12": {
            "key13": None,
        },
223
224
        "key14": {
            "key15": "-minus.and.dot",
225
        },
226
    }
227
    assert parsed_args.compilation_config == {
228
        "mode": 1,
229
230
231
232
233
234
235
236
237
238
239
240
241
242
        "use_inductor": True,
        "backend": "custom",
        "custom_ops": ["-quant_fp8", "+silu_mul", "-rms_norm"],
    }


def test_duplicate_dict_args(caplog_vllm, parser):
    args = [
        "--model-name=something.something",
        "--hf-overrides.key1",
        "val1",
        "--hf-overrides.key1",
        "val2",
        "-O1",
243
        "-O.mode",
244
245
246
247
248
249
250
        "2",
        "-O3",
    ]

    parsed_args = parser.parse_args(args)
    # Should be the last value
    assert parsed_args.hf_overrides == {"key1": "val2"}
251
    assert parsed_args.compilation_config == {"mode": 3}
252
253
254
255

    assert len(caplog_vllm.records) == 1
    assert "duplicate" in caplog_vllm.text
    assert "--hf-overrides.key1" in caplog_vllm.text
256
    assert "-O.mode" in caplog_vllm.text
257
258


259
260
261
262
def test_bind_kv_cache():
    from vllm.attention import Attention

    ctx = {
263
264
265
266
        "layers.0.self_attn": Attention(32, 128, 0.1),
        "layers.1.self_attn": Attention(32, 128, 0.1),
        "layers.2.self_attn": Attention(32, 128, 0.1),
        "layers.3.self_attn": Attention(32, 128, 0.1),
267
268
    }
    kv_cache = [
269
270
271
272
        torch.zeros((1,)),
        torch.zeros((1,)),
        torch.zeros((1,)),
        torch.zeros((1,)),
273
274
    ]
    bind_kv_cache(ctx, [kv_cache])
275
276
277
278
279
    assert ctx["layers.0.self_attn"].kv_cache[0] is kv_cache[0]
    assert ctx["layers.1.self_attn"].kv_cache[0] is kv_cache[1]
    assert ctx["layers.2.self_attn"].kv_cache[0] is kv_cache[2]
    assert ctx["layers.3.self_attn"].kv_cache[0] is kv_cache[3]

280

281
282
283
284
def test_bind_kv_cache_kv_sharing():
    from vllm.attention import Attention

    ctx = {
285
286
287
288
        "layers.0.self_attn": Attention(32, 128, 0.1),
        "layers.1.self_attn": Attention(32, 128, 0.1),
        "layers.2.self_attn": Attention(32, 128, 0.1),
        "layers.3.self_attn": Attention(32, 128, 0.1),
289
290
    }
    kv_cache = [
291
292
293
294
        torch.zeros((1,)),
        torch.zeros((1,)),
        torch.zeros((1,)),
        torch.zeros((1,)),
295
296
    ]
    shared_kv_cache_layers = {
297
298
        "layers.2.self_attn": "layers.1.self_attn",
        "layers.3.self_attn": "layers.0.self_attn",
299
300
    }
    bind_kv_cache(ctx, [kv_cache], shared_kv_cache_layers)
301
302
303
304
305
    assert ctx["layers.0.self_attn"].kv_cache[0] is kv_cache[0]
    assert ctx["layers.1.self_attn"].kv_cache[0] is kv_cache[1]
    assert ctx["layers.2.self_attn"].kv_cache[0] is kv_cache[1]
    assert ctx["layers.3.self_attn"].kv_cache[0] is kv_cache[0]

306

307
308
309
310
311
def test_bind_kv_cache_non_attention():
    from vllm.attention import Attention

    # example from Jamba PP=2
    ctx = {
312
313
        "model.layers.20.attn": Attention(32, 128, 0.1),
        "model.layers.28.attn": Attention(32, 128, 0.1),
314
315
    }
    kv_cache = [
316
317
        torch.zeros((1,)),
        torch.zeros((1,)),
318
319
    ]
    bind_kv_cache(ctx, [kv_cache])
320
321
    assert ctx["model.layers.20.attn"].kv_cache[0] is kv_cache[0]
    assert ctx["model.layers.28.attn"].kv_cache[0] is kv_cache[1]
322
323
324


def test_bind_kv_cache_pp():
325
    with patch("vllm.utils.torch_utils.cuda_device_count_stateless", lambda: 2):
326
        # this test runs with 1 GPU, but we simulate 2 GPUs
327
        cfg = VllmConfig(parallel_config=ParallelConfig(pipeline_parallel_size=2))
328
329
330
331
    with set_current_vllm_config(cfg):
        from vllm.attention import Attention

        ctx = {
332
            "layers.0.self_attn": Attention(32, 128, 0.1),
333
        }
334
        kv_cache = [[torch.zeros((1,))], [torch.zeros((1,))]]
335
        bind_kv_cache(ctx, kv_cache)
336
337
        assert ctx["layers.0.self_attn"].kv_cache[0] is kv_cache[0][0]
        assert ctx["layers.0.self_attn"].kv_cache[1] is kv_cache[1][0]
338
339


340
341
342
def test_model_specification(
    parser_with_config, cli_config_file, cli_config_file_with_model
):
343
    # Test model in CLI takes precedence over config
344
    args = parser_with_config.parse_args(
345
346
347
348
        ["serve", "cli-model", "--config", cli_config_file_with_model]
    )
    assert args.model_tag == "cli-model"
    assert args.served_model_name == "mymodel"
349
350

    # Test model from config file works
351
352
353
354
355
356
357
358
359
    args = parser_with_config.parse_args(
        [
            "serve",
            "--config",
            cli_config_file_with_model,
        ]
    )
    assert args.model == "config-model"
    assert args.served_model_name == "mymodel"
360
361
362

    # Test no model specified anywhere raises error
    with pytest.raises(ValueError, match="No model specified!"):
363
        parser_with_config.parse_args(["serve", "--config", cli_config_file])
364
365

    # Test using --model option raises error
366
367
368
369
370
371
372
373
374
375
376
    # with pytest.raises(
    #         ValueError,
    #         match=
    #     ("With `vllm serve`, you should provide the model as a positional "
    #      "argument or in a config file instead of via the `--model` option."),
    # ):
    #     parser_with_config.parse_args(['serve', '--model', 'my-model'])

    # Test using --model option back-compatibility
    # (when back-compatibility ends, the above test should be uncommented
    # and the below test should be removed)
377
378
379
380
381
382
383
384
385
386
387
388
    args = parser_with_config.parse_args(
        [
            "serve",
            "--tensor-parallel-size",
            "2",
            "--model",
            "my-model",
            "--trust-remote-code",
            "--port",
            "8001",
        ]
    )
389
390
391
392
393
    assert args.model is None
    assert args.tensor_parallel_size == 2
    assert args.trust_remote_code is True
    assert args.port == 8001

394
395
396
397
398
399
400
401
402
    args = parser_with_config.parse_args(
        [
            "serve",
            "--tensor-parallel-size=2",
            "--model=my-model",
            "--trust-remote-code",
            "--port=8001",
        ]
    )
403
404
405
406
    assert args.model is None
    assert args.tensor_parallel_size == 2
    assert args.trust_remote_code is True
    assert args.port == 8001
407
408

    # Test other config values are preserved
409
410
411
412
413
414
415
416
    args = parser_with_config.parse_args(
        [
            "serve",
            "cli-model",
            "--config",
            cli_config_file_with_model,
        ]
    )
417
418
419
420
421
    assert args.tensor_parallel_size == 2
    assert args.trust_remote_code is True
    assert args.port == 12312


422
423
424
425
def test_convert_ids_list_to_tokens():
    tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-1.5B-Instruct")
    token_ids = tokenizer.encode("Hello, world!")
    # token_ids = [9707, 11, 1879, 0]
426
    assert tokenizer.convert_ids_to_tokens(token_ids) == ["Hello", ",", "Ġworld", "!"]
427
    tokens = convert_ids_list_to_tokens(tokenizer, token_ids)
428
    assert tokens == ["Hello", ",", " world", "!"]
429
430


431
432
433
434
435
436
def test_load_config_file(tmp_path):
    # Define the configuration data
    config_data = {
        "enable-logging": True,
        "list-arg": ["item1", "item2"],
        "port": 12323,
437
        "tensor-parallel-size": 4,
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
    }

    # Write the configuration data to a temporary YAML file
    config_file_path = tmp_path / "config.yaml"
    with open(config_file_path, "w") as config_file:
        yaml.dump(config_data, config_file)

    # Initialize the parser
    parser = FlexibleArgumentParser()

    # Call the function with the temporary file path
    processed_args = parser.load_config_file(str(config_file_path))

    # Expected output
    expected_args = [
        "--enable-logging",
        "--list-arg",
        "item1",
        "item2",
        "--port",
        "12323",
        "--tensor-parallel-size",
        "4",
    ]

    # Assert that the processed arguments match the expected output
    assert processed_args == expected_args
    os.remove(str(config_file_path))
466
467


468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
def test_flat_product():
    # Check regular itertools.product behavior
    result1 = list(flat_product([1, 2, 3], ["a", "b"]))
    assert result1 == [
        (1, "a"),
        (1, "b"),
        (2, "a"),
        (2, "b"),
        (3, "a"),
        (3, "b"),
    ]

    # check that the tuples get flattened
    result2 = list(flat_product([(1, 2), (3, 4)], ["a", "b"], [(5, 6)]))
    assert result2 == [
        (1, 2, "a", 5, 6),
        (1, 2, "b", 5, 6),
        (3, 4, "a", 5, 6),
        (3, 4, "b", 5, 6),
    ]