test_config.py 39.9 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
import logging
4
import os
5
from dataclasses import MISSING, Field, asdict, dataclass, field
6
from unittest.mock import patch
7

8
import pytest
9
from pydantic import ValidationError
10

11
from vllm.compilation.backends import VllmBackend
12
13
14
15
from vllm.config import (
    CompilationConfig,
    ModelConfig,
    PoolerConfig,
16
    RendererConfig,
17
    SchedulerConfig,
18
19
20
21
    VllmConfig,
    update_config,
)
from vllm.config.compilation import CompilationMode, CUDAGraphMode
22
from vllm.config.load import LoadConfig
23
from vllm.config.utils import get_field
24
25
26
27
from vllm.config.vllm import (
    OPTIMIZATION_LEVEL_TO_CONFIG,
    OptimizationLevel,
)
28
29
from vllm.model_executor.layers.pooler import PoolingType
from vllm.platforms import current_platform
30

31

32
33
34
35
36
37
38
39
def test_compile_config_repr_succeeds():
    # setup: VllmBackend mutates the config object
    config = VllmConfig()
    backend = VllmBackend(config)
    backend.configure_post_pass()

    # test that repr(config) succeeds
    val = repr(config)
40
41
    assert "VllmConfig" in val
    assert "inductor_passes" in val
42
43


44
45
46
47
48
@dataclass
class _TestConfigFields:
    a: int
    b: dict = field(default_factory=dict)
    c: str = "default"
49
50


51
def test_get_field():
52
    with pytest.raises(ValueError):
53
        get_field(_TestConfigFields, "a")
54

55
    b = get_field(_TestConfigFields, "b")
56
57
58
59
    assert isinstance(b, Field)
    assert b.default is MISSING
    assert b.default_factory is dict

60
    c = get_field(_TestConfigFields, "c")
61
62
63
64
65
    assert isinstance(c, Field)
    assert c.default == "default"
    assert c.default_factory is MISSING


66
67
@dataclass
class _TestNestedConfig:
68
    a: _TestConfigFields = field(default_factory=lambda: _TestConfigFields(a=0))
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92


def test_update_config():
    # Simple update
    config1 = _TestConfigFields(a=0)
    new_config1 = update_config(config1, {"a": 42})
    assert new_config1.a == 42
    # Nonexistent field
    with pytest.raises(AssertionError):
        new_config1 = update_config(config1, {"nonexistent": 1})
    # Nested update with dataclass
    config2 = _TestNestedConfig()
    new_inner_config = _TestConfigFields(a=1, c="new_value")
    new_config2 = update_config(config2, {"a": new_inner_config})
    assert new_config2.a == new_inner_config
    # Nested update with dict
    config3 = _TestNestedConfig()
    new_config3 = update_config(config3, {"a": {"c": "new_value"}})
    assert new_config3.a.c == "new_value"
    # Nested update with invalid type
    with pytest.raises(AssertionError):
        new_config3 = update_config(config3, {"a": "new_value"})


93
# Can remove once --task option is fully deprecated
94
@pytest.mark.parametrize(
95
    ("model_id", "expected_runner_type", "expected_convert_type", "expected_task"),
96
    [
97
98
99
        ("distilbert/distilgpt2", "generate", "none", "generate"),
        ("intfloat/multilingual-e5-small", "pooling", "none", "embed"),
        ("jason9693/Qwen2.5-1.5B-apeach", "pooling", "classify", "classify"),
100
        ("cross-encoder/ms-marco-MiniLM-L-6-v2", "pooling", "none", "classify"),
101
102
        ("Qwen/Qwen2.5-Math-RM-72B", "pooling", "none", "reward"),
        ("openai/whisper-small", "generate", "none", "transcription"),
103
104
    ],
)
105
106
107
def test_auto_task(
    model_id, expected_runner_type, expected_convert_type, expected_task
):
108
    config = ModelConfig(model_id, task="auto")
109
110

    assert config.runner_type == expected_runner_type
111
    assert config.convert_type == expected_convert_type
112

113

114
115
# Can remove once --task option is fully deprecated
@pytest.mark.parametrize(
116
    ("model_id", "expected_runner_type", "expected_convert_type", "expected_task"),
117
118
119
120
    [
        ("distilbert/distilgpt2", "pooling", "embed", "embed"),
        ("intfloat/multilingual-e5-small", "pooling", "embed", "embed"),
        ("jason9693/Qwen2.5-1.5B-apeach", "pooling", "classify", "classify"),
121
        ("cross-encoder/ms-marco-MiniLM-L-6-v2", "pooling", "classify", "classify"),
122
123
124
125
        ("Qwen/Qwen2.5-Math-RM-72B", "pooling", "embed", "embed"),
        ("openai/whisper-small", "pooling", "embed", "embed"),
    ],
)
126
127
128
def test_score_task(
    model_id, expected_runner_type, expected_convert_type, expected_task
):
129
    config = ModelConfig(model_id, task="score")
130

131
132
133
134
135
    assert config.runner_type == expected_runner_type
    assert config.convert_type == expected_convert_type


# Can remove once --task option is fully deprecated
136
@pytest.mark.parametrize(
137
    ("model_id", "expected_runner_type", "expected_convert_type", "expected_task"),
138
    [
139
        ("openai/whisper-small", "generate", "none", "transcription"),
140
141
    ],
)
142
143
144
def test_transcription_task(
    model_id, expected_runner_type, expected_convert_type, expected_task
):
145
    config = ModelConfig(model_id, task="transcription")
146

147
    assert config.runner_type == expected_runner_type
148
    assert config.convert_type == expected_convert_type
149
150


151
152
153
154
155
156
157
158
159
160
161
162
163
@pytest.mark.parametrize(
    ("model_id", "expected_runner_type", "expected_convert_type"),
    [
        ("distilbert/distilgpt2", "generate", "none"),
        ("intfloat/multilingual-e5-small", "pooling", "none"),
        ("jason9693/Qwen2.5-1.5B-apeach", "pooling", "classify"),
        ("cross-encoder/ms-marco-MiniLM-L-6-v2", "pooling", "none"),
        ("Qwen/Qwen2.5-Math-RM-72B", "pooling", "none"),
        ("openai/whisper-small", "generate", "none"),
    ],
)
def test_auto_runner(model_id, expected_runner_type, expected_convert_type):
    config = ModelConfig(model_id, runner="auto")
164
165

    assert config.runner_type == expected_runner_type
166
    assert config.convert_type == expected_convert_type
167
168
169


@pytest.mark.parametrize(
170
    ("model_id", "expected_runner_type", "expected_convert_type"),
171
    [
172
173
174
175
176
177
        ("distilbert/distilgpt2", "pooling", "embed"),
        ("intfloat/multilingual-e5-small", "pooling", "none"),
        ("jason9693/Qwen2.5-1.5B-apeach", "pooling", "classify"),
        ("cross-encoder/ms-marco-MiniLM-L-6-v2", "pooling", "none"),
        ("Qwen/Qwen2.5-Math-RM-72B", "pooling", "none"),
        ("openai/whisper-small", "pooling", "embed"),
178
179
    ],
)
180
181
def test_pooling_runner(model_id, expected_runner_type, expected_convert_type):
    config = ModelConfig(model_id, runner="pooling")
182
183

    assert config.runner_type == expected_runner_type
184
    assert config.convert_type == expected_convert_type
185
186


187
188
189
190
191
192
193
194
195
196
197
@pytest.mark.parametrize(
    ("model_id", "expected_runner_type", "expected_convert_type"),
    [
        ("Qwen/Qwen2.5-1.5B-Instruct", "draft", "none"),
    ],
)
def test_draft_runner(model_id, expected_runner_type, expected_convert_type):
    config = ModelConfig(model_id, runner="draft")

    assert config.runner_type == expected_runner_type
    assert config.convert_type == expected_convert_type
198
199


200
201
202
203
204
205
206
207
208
209
MODEL_IDS_EXPECTED = [
    ("Qwen/Qwen1.5-7B", 32768),
    ("mistralai/Mistral-7B-v0.1", 4096),
    ("mistralai/Mistral-7B-Instruct-v0.2", 32768),
]


@pytest.mark.parametrize("model_id_expected", MODEL_IDS_EXPECTED)
def test_disable_sliding_window(model_id_expected):
    model_id, expected = model_id_expected
210
    model_config = ModelConfig(model_id, disable_sliding_window=True)
211
212
    assert model_config.max_model_len == expected

213

214
215
216
@pytest.mark.skipif(
    current_platform.is_rocm(), reason="Xformers backend is not supported on ROCm."
)
217
218
def test_get_pooling_config():
    model_id = "sentence-transformers/all-MiniLM-L12-v2"
219
    model_config = ModelConfig(model_id)
220

221
222
223
    assert model_config.pooler_config is not None
    assert model_config.pooler_config.normalize
    assert model_config.pooler_config.pooling_type == PoolingType.MEAN.name
224
225


226
227
228
@pytest.mark.skipif(
    current_platform.is_rocm(), reason="Xformers backend is not supported on ROCm."
)
229
230
def test_get_pooling_config_from_args():
    model_id = "sentence-transformers/all-MiniLM-L12-v2"
231
232
    pooler_config = PoolerConfig(pooling_type="CLS", normalize=True)
    model_config = ModelConfig(model_id, pooler_config=pooler_config)
233

234
    assert asdict(model_config.pooler_config) == asdict(pooler_config)
235
236


237
238
239
240
241
242
@pytest.mark.parametrize(
    ("model_id", "default_pooling_type", "pooling_type"),
    [
        ("tomaarsen/Qwen3-Reranker-0.6B-seq-cls", "LAST", "LAST"),  # LLM
        ("intfloat/e5-small", "CLS", "MEAN"),  # BertModel
        ("Qwen/Qwen2.5-Math-RM-72B", "ALL", "ALL"),  # reward
243
244
245
        ("Qwen/Qwen2.5-Math-PRM-7B", "STEP", "STEP"),  # step reward
    ],
)
246
247
248
249
250
251
def test_default_pooling_type(model_id, default_pooling_type, pooling_type):
    model_config = ModelConfig(model_id)
    assert model_config._model_info.default_pooling_type == default_pooling_type
    assert model_config.pooler_config.pooling_type == pooling_type


252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
@pytest.mark.parametrize(
    ("model_id", "expected_is_moe_model"),
    [
        ("RedHatAI/Qwen3-8B-speculator.eagle3", False),
        ("RedHatAI/Llama-3.1-8B-Instruct-NVFP4", False),
        ("RedHatAI/Llama-3.2-1B-FP8", False),
        ("RedHatAI/Mistral-Small-24B-Instruct-2501-quantized.w8a8", False),
        ("RedHatAI/gpt-oss-20b", True),
        ("RedHatAI/DeepSeek-V2.5-1210-FP8", True),
        ("RedHatAI/Llama-4-Scout-17B-16E-Instruct", True),
        ("RedHatAI/Mixtral-8x7B-Instruct-v0.1", True),
    ],
)
def test_moe_model_detection(model_id, expected_is_moe_model):
    model_config = ModelConfig(model_id)
    # Just check that is_moe_model field exists and is a boolean
    assert model_config.is_model_moe() == expected_is_moe_model


@pytest.mark.parametrize(
    ("model_id", "quantized"),
    [
        ("RedHatAI/Qwen3-8B-speculator.eagle3", False),
        ("RedHatAI/Llama-3.1-8B-Instruct-NVFP4", True),
        ("RedHatAI/Llama-3.2-1B-FP8", True),
        ("RedHatAI/Mistral-Small-24B-Instruct-2501-quantized.w8a8", True),
        ("RedHatAI/gpt-oss-20b", True),
        ("RedHatAI/DeepSeek-V2.5-1210-FP8", True),
        ("RedHatAI/Mixtral-8x7B-Instruct-v0.1", False),
    ],
)
def test_is_quantized(model_id, quantized):
    model_config = ModelConfig(model_id)
    # Just check that quantized field exists and is a boolean
    assert model_config.is_quantized() == quantized


289
290
291
@pytest.mark.skipif(
    current_platform.is_rocm(), reason="Xformers backend is not supported on ROCm."
)
292
def test_get_bert_tokenization_sentence_transformer_config():
293
294
    model_id = "BAAI/bge-base-en-v1.5"
    bge_model_config = ModelConfig(model_id)
295
296
297
298
299
300
301

    bert_bge_model_config = bge_model_config._get_encoder_config()

    assert bert_bge_model_config["max_seq_length"] == 512
    assert bert_bge_model_config["do_lower_case"]


302
def test_rope_customization():
303
304
305
306
307
308
309
    TEST_ROPE_PARAMETERS = {
        "rope_theta": 16_000_000.0,
        "rope_type": "dynamic",
        "factor": 2.0,
    }
    LLAMA_ROPE_PARAMETERS = {"rope_theta": 500000.0, "rope_type": "default"}
    LONGCHAT_ROPE_PARAMETERS = {"rope_type": "linear", "factor": 8.0}
310

311
    llama_model_config = ModelConfig("meta-llama/Meta-Llama-3-8B-Instruct")
312
313
314
315
    assert (
        getattr(llama_model_config.hf_config, "rope_parameters", None)
        == LLAMA_ROPE_PARAMETERS
    )
316
317
318
319
    assert llama_model_config.max_model_len == 8192

    llama_model_config = ModelConfig(
        "meta-llama/Meta-Llama-3-8B-Instruct",
320
        hf_overrides={"rope_parameters": TEST_ROPE_PARAMETERS},
321
    )
322
    assert (
323
324
        getattr(llama_model_config.hf_config, "rope_parameters", None)
        == TEST_ROPE_PARAMETERS
325
    )
326
327
    assert llama_model_config.max_model_len == 16384

328
    longchat_model_config = ModelConfig("lmsys/longchat-13b-16k")
329
    # Check if LONGCHAT_ROPE_PARAMETERS entries are in longchat_model_config
330
    assert all(
331
332
        longchat_model_config.hf_config.rope_parameters.get(key) == value
        for key, value in LONGCHAT_ROPE_PARAMETERS.items()
333
    )
334
335
336
337
    assert longchat_model_config.max_model_len == 16384

    longchat_model_config = ModelConfig(
        "lmsys/longchat-13b-16k",
338
        hf_overrides={
339
            "rope_parameters": TEST_ROPE_PARAMETERS,
340
        },
341
    )
342
    assert (
343
344
        getattr(longchat_model_config.hf_config, "rope_parameters", None)
        == TEST_ROPE_PARAMETERS
345
    )
346
    assert longchat_model_config.max_model_len == 4096
347
348


349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
def test_nested_hf_overrides():
    """Test that nested hf_overrides work correctly."""
    # Test with a model that has text_config
    model_config = ModelConfig(
        "Qwen/Qwen2-VL-2B-Instruct",
        hf_overrides={
            "text_config": {
                "hidden_size": 1024,
            },
        },
    )
    assert model_config.hf_config.text_config.hidden_size == 1024

    # Test with deeply nested overrides
    model_config = ModelConfig(
        "Qwen/Qwen2-VL-2B-Instruct",
        hf_overrides={
            "text_config": {
                "hidden_size": 2048,
                "num_attention_heads": 16,
            },
            "vision_config": {
                "hidden_size": 512,
            },
        },
    )
    assert model_config.hf_config.text_config.hidden_size == 2048
    assert model_config.hf_config.text_config.num_attention_heads == 16
    assert model_config.hf_config.vision_config.hidden_size == 512


380
381
382
383
384
385
386
387
388
389
390
@pytest.mark.skipif(
    current_platform.is_rocm(), reason="Encoder Decoder models not supported on ROCm."
)
@pytest.mark.parametrize(
    ("model_id", "is_encoder_decoder"),
    [
        ("facebook/opt-125m", False),
        ("openai/whisper-tiny", True),
        ("meta-llama/Llama-3.2-1B-Instruct", False),
    ],
)
391
def test_is_encoder_decoder(model_id, is_encoder_decoder):
392
    config = ModelConfig(model_id)
393
394
395
396

    assert config.is_encoder_decoder == is_encoder_decoder


397
398
399
400
401
402
403
@pytest.mark.parametrize(
    ("model_id", "uses_mrope"),
    [
        ("facebook/opt-125m", False),
        ("Qwen/Qwen2-VL-2B-Instruct", True),
    ],
)
404
def test_uses_mrope(model_id, uses_mrope):
405
    config = ModelConfig(model_id)
406
407

    assert config.uses_mrope == uses_mrope
408
409
410
411
412


def test_generation_config_loading():
    model_id = "Qwen/Qwen2.5-1.5B-Instruct"

413
    # When set generation_config to "vllm", the default generation config
414
    # will not be loaded.
415
    model_config = ModelConfig(model_id, generation_config="vllm")
416
417
418
419
    assert model_config.get_diff_sampling_param() == {}

    # When set generation_config to "auto", the default generation config
    # should be loaded.
420
    model_config = ModelConfig(model_id, generation_config="auto")
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436

    correct_generation_config = {
        "repetition_penalty": 1.1,
        "temperature": 0.7,
        "top_p": 0.8,
        "top_k": 20,
    }

    assert model_config.get_diff_sampling_param() == correct_generation_config

    # The generation config could be overridden by the user.
    override_generation_config = {"temperature": 0.5, "top_k": 5}

    model_config = ModelConfig(
        model_id,
        generation_config="auto",
437
438
        override_generation_config=override_generation_config,
    )
439
440
441
442
443
444

    override_result = correct_generation_config.copy()
    override_result.update(override_generation_config)

    assert model_config.get_diff_sampling_param() == override_result

445
    # When generation_config is set to "vllm" and override_generation_config
446
447
448
    # is set, the override_generation_config should be used directly.
    model_config = ModelConfig(
        model_id,
449
        generation_config="vllm",
450
451
        override_generation_config=override_generation_config,
    )
452
453

    assert model_config.get_diff_sampling_param() == override_generation_config
454
455


456
457
458
459
460
461
462
@pytest.mark.parametrize(
    "pt_load_map_location",
    [
        "cuda",
        {"": "cuda"},
    ],
)
463
464
465
466
467
def test_load_config_pt_load_map_location(pt_load_map_location):
    load_config = LoadConfig(pt_load_map_location=pt_load_map_location)
    config = VllmConfig(load_config=load_config)

    assert config.load_config.pt_load_map_location == pt_load_map_location
468
469
470


@pytest.mark.parametrize(
471
472
    ("model_id", "max_model_len", "expected_max_len", "should_raise"),
    [
473
474
475
        ("BAAI/bge-reranker-base", None, 512, False),
        ("BAAI/bge-reranker-base", 256, 256, False),
        ("BAAI/bge-reranker-base", 513, 512, True),
476
477
        ("deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", None, 131072, False),
        ("deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", 131073, 131072, True),
478
479
    ],
)
480
def test_recalculate_max_model_len(
481
482
    model_id, max_model_len, expected_max_len, should_raise
):
483
    """Test recalculate_max_model_len with different configurations."""
484
    model_config = ModelConfig(model_id)
485
486
487

    if should_raise:
        with pytest.raises(ValueError):
488
489
490
491
492
            model_config.recalculate_max_model_len(
                max_model_len,
                tokenizer=model_id,
                tokenizer_revision=None,
            )
493
    else:
494
495
496
497
498
499
        model_config.recalculate_max_model_len(
            max_model_len,
            tokenizer=model_id,
            tokenizer_revision=None,
        )
        assert model_config.max_model_len == expected_max_len
500
501


502
503
class MockModelConfig:
    """Simple mock object for testing maybe_pull_model_for_runai"""
504

505
    def __init__(self, model: str):
506
        self.model = model
507
508
509
510
511
512
513
514


class MockRendererConfig:
    """Simple mock object for testing maybe_pull_tokenizer_for_runai"""

    def __init__(self, model_config: MockModelConfig):
        self.model_config = model_config
        self.tokenizer = model_config.model
515
516


517
518
519
520
521
522
523
524
@pytest.mark.parametrize(
    "s3_url",
    [
        "s3://example-bucket-1/model/",
        "s3://example-bucket-2/model/",
    ],
)
@patch("vllm.transformers_utils.runai_utils.ObjectStorageModel.pull_files")
525
526
527
528
529
530
531
def test_s3_url_model_tokenizer_paths(mock_pull_files, s3_url):
    """Test that S3 URLs create deterministic local directories for model and
    tokenizer."""
    # Mock pull_files to avoid actually downloading files during tests
    mock_pull_files.return_value = None

    # Create first mock and run the method
532
533
534
535
    model_config1 = MockModelConfig(model=s3_url)
    renderer_config1 = MockRendererConfig(model_config=model_config1)
    ModelConfig.maybe_pull_model_for_runai(model_config1, s3_url)
    RendererConfig.maybe_pull_tokenizer_for_runai(renderer_config1, s3_url)
536
537

    # Check that model and tokenizer point to existing directories
538
539
    assert os.path.exists(model_config1.model), (
        f"Model directory does not exist: {model_config1.model}"
540
    )
541
542
    assert os.path.isdir(model_config1.model), (
        f"Model path is not a directory: {model_config1.model}"
543
    )
544
545
    assert os.path.exists(renderer_config1.tokenizer), (
        f"Tokenizer directory does not exist: {renderer_config1.tokenizer}"
546
    )
547
548
    assert os.path.isdir(renderer_config1.tokenizer), (
        f"Tokenizer path is not a directory: {renderer_config1.tokenizer}"
549
    )
550
551

    # Verify that the paths are different from the original S3 URL
552
553
554
555
    assert model_config1.model != s3_url, (
        "Model path should be converted to local directory"
    )
    assert renderer_config1.tokenizer != s3_url, (
556
557
        "Tokenizer path should be converted to local directory"
    )
558
559

    # Store the original paths
560
561
    created_model_dir = model_config1.model
    create_tokenizer_dir = renderer_config1.tokenizer
562
563

    # Create a new mock and run the method with the same S3 URL
564
565
566
567
    model_config2 = MockModelConfig(model=s3_url)
    renderer_config2 = MockRendererConfig(model_config=model_config2)
    ModelConfig.maybe_pull_model_for_runai(model_config2, s3_url)
    RendererConfig.maybe_pull_tokenizer_for_runai(renderer_config2, s3_url)
568
569

    # Check that the new directories exist
570
571
    assert os.path.exists(model_config2.model), (
        f"Model directory does not exist: {model_config2.model}"
572
    )
573
574
    assert os.path.isdir(model_config2.model), (
        f"Model path is not a directory: {model_config2.model}"
575
    )
576
577
    assert os.path.exists(renderer_config2.tokenizer), (
        f"Tokenizer directory does not exist: {renderer_config2.tokenizer}"
578
    )
579
580
    assert os.path.isdir(renderer_config2.tokenizer), (
        f"Tokenizer path is not a directory: {renderer_config2.tokenizer}"
581
    )
582
583

    # Verify that the paths are deterministic (same as before)
584
    assert model_config2.model == created_model_dir, (
585
        f"Model paths are not deterministic. "
586
        f"Original: {created_model_dir}, New: {model_config2.model}"
587
    )
588
    assert renderer_config2.tokenizer == create_tokenizer_dir, (
589
        f"Tokenizer paths are not deterministic. "
590
        f"Original: {create_tokenizer_dir}, New: {renderer_config2.tokenizer}"
591
    )
592
593


594
@patch("vllm.transformers_utils.runai_utils.ObjectStorageModel.pull_files")
595
596
597
598
599
600
601
602
603
def test_s3_url_different_models_create_different_directories(mock_pull_files):
    """Test that different S3 URLs create different local directories."""
    # Mock pull_files to avoid actually downloading files during tests
    mock_pull_files.return_value = None

    s3_url1 = "s3://example-bucket-1/model/"
    s3_url2 = "s3://example-bucket-2/model/"

    # Create mocks with different S3 URLs and run the method
604
605
606
607
    model_config1 = MockModelConfig(model=s3_url1)
    renderer_config1 = MockRendererConfig(model_config=model_config1)
    ModelConfig.maybe_pull_model_for_runai(model_config1, s3_url1)
    RendererConfig.maybe_pull_tokenizer_for_runai(renderer_config1, s3_url1)
608

609
610
611
612
    model_config2 = MockModelConfig(model=s3_url2)
    renderer_config2 = MockRendererConfig(model_config=model_config2)
    ModelConfig.maybe_pull_model_for_runai(model_config2, s3_url2)
    RendererConfig.maybe_pull_tokenizer_for_runai(renderer_config2, s3_url2)
613
614

    # Verify that different URLs produce different directories
615
    assert model_config1.model != model_config2.model, (
616
        f"Different S3 URLs should create different model directories. "
617
        f"URL1 model: {model_config1.model}, URL2 model: {model_config2.model}"
618
    )
619
    assert renderer_config1.tokenizer != renderer_config2.tokenizer, (
620
        f"Different S3 URLs should create different tokenizer directories. "
621
622
        f"URL1 tokenizer: {renderer_config1.tokenizer}, "
        f"URL2 tokenizer: {renderer_config2.tokenizer}"
623
    )
624
625

    # Verify that both sets of directories exist
626
627
628
629
630
631
632
633
    assert os.path.exists(model_config1.model) and os.path.isdir(model_config1.model)
    assert os.path.exists(renderer_config1.tokenizer) and os.path.isdir(
        renderer_config1.tokenizer
    )
    assert os.path.exists(model_config2.model) and os.path.isdir(model_config2.model)
    assert os.path.exists(renderer_config2.tokenizer) and os.path.isdir(
        renderer_config2.tokenizer
    )
634
635


636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
@pytest.mark.parametrize(
    ("model_id", "expected_attn_type", "expected_result", "reason"),
    [
        # pooling models
        (
            "jason9693/Qwen2.5-1.5B-apeach",
            "decoder",
            True,
            "Pooling models with causal attn and last pooling support chunked prefill.",
        ),
        (
            "Qwen/Qwen3-Embedding-0.6B",
            "decoder",
            True,
            "Pooling models with causal attn and last pooling support chunked prefill.",
        ),
        (
            "Qwen/Qwen2.5-Math-PRM-7B",
            "decoder",
            False,
            "Pooling models with step pooling does not support chunked prefill.",
        ),
        (
            "internlm/internlm2-1_8b-reward",
            "decoder",
661
662
            True,
            "Pooling models with causal attn and all pooling support chunked prefill.",
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
        ),
        (
            "BAAI/bge-base-en",
            "encoder_only",
            False,
            "Pooling models with bidirectional attn does not support chunked prefill.",
        ),
        (
            "boltuix/NeuroBERT-NER",
            "encoder_only",
            False,
            "Pooling models with bidirectional attn does not support chunked prefill.",
        ),
        (
            "papluca/xlm-roberta-base-language-detection",
            "encoder_only",
            False,
            "Pooling models with bidirectional attn does not support chunked prefill.",
        ),
        (
            "Alibaba-NLP/gte-Qwen2-1.5B-instruct",
            "encoder_only",
            False,
            "Pooling models with bidirectional attn does not support chunked prefill.",
        ),
        (
            "intfloat/e5-small",
            "encoder_only",
            False,
            "Pooling models with bidirectional attn does not support chunked prefill.",
        ),
        # multimodal models
        (
            "openai/clip-vit-base-patch32",
            "decoder",
            True,
            "Pooling models with causal attn and last pooling support chunked prefill.",
        ),
        (
            "google/siglip-base-patch16-224",
            "encoder_only",
            False,
            "Pooling models with bidirectional attn does not support chunked prefill.",
        ),
        # generate models
        (
            "Qwen/Qwen3-0.6B",
            "decoder",
            True,
            "Generative models support chunked prefill.",
        ),
        (
            "Qwen/Qwen3-Next-80B-A3B-Instruct",
            "hybrid",
            True,
            "Generative models support chunked prefill.",
        ),
        (
            "ibm-granite/granite-4.0-h-small",
            "hybrid",
            True,
            "Generative models support chunked prefill.",
        ),
        (
            "state-spaces/mamba-130m-hf",
            "attention_free",
            True,
            "Generative models support chunked prefill.",
        ),
        # encoder_decoder models
        (
            "openai/whisper-small",
            "encoder_decoder",
            False,
            "Encoder decoder models does not support chunked prefill.",
        ),
    ],
)
def test_is_chunked_prefill_supported(
    model_id: str,
    expected_attn_type: str,
    expected_result: bool,
    reason: str,
    caplog_vllm,
):
    model_config = ModelConfig(model_id, trust_remote_code=True)
    assert model_config.attn_type == expected_attn_type
750
    with caplog_vllm.at_level(level=logging.DEBUG, logger="vllm"):
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
        assert model_config.is_chunked_prefill_supported == expected_result
    assert reason in caplog_vllm.text


@pytest.mark.parametrize(
    ("model_id", "expected_attn_type", "expected_result", "reason"),
    [
        # pooling models
        (
            "jason9693/Qwen2.5-1.5B-apeach",
            "decoder",
            True,
            "Pooling models with causal attn and last pooling support prefix caching.",
        ),
        (
            "Qwen/Qwen3-Embedding-0.6B",
            "decoder",
            True,
            "Pooling models with causal attn and last pooling support prefix caching.",
        ),
        (
            "Qwen/Qwen2.5-Math-PRM-7B",
            "decoder",
            False,
            "Pooling models with step pooling does not support prefix caching.",
        ),
        (
            "internlm/internlm2-1_8b-reward",
            "decoder",
780
781
            True,
            "Pooling models with causal attn and all pooling support prefix caching.",
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
        ),
        (
            "BAAI/bge-base-en",
            "encoder_only",
            False,
            "Pooling models with bidirectional attn does not support prefix caching.",
        ),
        (
            "boltuix/NeuroBERT-NER",
            "encoder_only",
            False,
            "Pooling models with bidirectional attn does not support prefix caching.",
        ),
        (
            "papluca/xlm-roberta-base-language-detection",
            "encoder_only",
            False,
            "Pooling models with bidirectional attn does not support prefix caching.",
        ),
        (
            "Alibaba-NLP/gte-Qwen2-1.5B-instruct",
            "encoder_only",
            False,
            "Pooling models with bidirectional attn does not support prefix caching.",
        ),
        (
            "intfloat/e5-small",
            "encoder_only",
            False,
            "Pooling models with bidirectional attn does not support prefix caching.",
        ),
        # multimodal models
        (
            "openai/clip-vit-base-patch32",
            "decoder",
            True,
            "Pooling models with causal attn and last pooling support prefix caching.",
        ),
        (
            "google/siglip-base-patch16-224",
            "encoder_only",
            False,
            "Pooling models with bidirectional attn does not support prefix caching.",
        ),
        # generate models
        (
            "Qwen/Qwen3-0.6B",
            "decoder",
            True,
            "Generative models support prefix caching.",
        ),
        (
            "Qwen/Qwen3-Next-80B-A3B-Instruct",
            "hybrid",
            False,
            "Hybrid models does not support prefix caching since the feature is still experimental.",  # noqa: E501
        ),
        (
            "ibm-granite/granite-4.0-h-small",
            "hybrid",
            False,
            "Hybrid models does not support prefix caching since the feature is still experimental.",  # noqa: E501
        ),
        (
            "state-spaces/mamba-130m-hf",
            "attention_free",
            False,
            "Attention free models does not support prefix caching since the feature is still experimental.",  # noqa: E501
        ),
        # encoder_decoder models
        (
            "openai/whisper-small",
            "encoder_decoder",
            False,
            "Encoder decoder models does not support prefix caching.",
        ),
    ],
)
def test_is_prefix_caching_supported(
    model_id: str,
    expected_attn_type: str,
    expected_result: bool,
    reason: str,
    caplog_vllm,
):
    model_config = ModelConfig(model_id, trust_remote_code=True)
    assert model_config.attn_type == expected_attn_type
869
    with caplog_vllm.at_level(level=logging.DEBUG, logger="vllm"):
870
871
872
873
        assert model_config.is_prefix_caching_supported == expected_result
    assert reason in caplog_vllm.text


874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
@pytest.mark.parametrize(
    ("backend", "custom_ops", "expected"),
    [
        ("eager", [], True),
        ("eager", ["+fused_layernorm"], True),
        ("eager", ["all", "-fused_layernorm"], False),
        ("inductor", [], False),
        ("inductor", ["none", "+fused_layernorm"], True),
        ("inductor", ["none", "-fused_layernorm"], False),
    ],
)
def test_is_custom_op_enabled(backend: str, custom_ops: list[str], expected: bool):
    """Test that is_custom_op_enabled works correctly."""
    config = VllmConfig(
        compilation_config=CompilationConfig(backend=backend, custom_ops=custom_ops)
    )
    assert config.compilation_config.is_custom_op_enabled("fused_layernorm") is expected


def test_vllm_config_defaults_are_none():
    """Verify that optimization-level defaults are None when not set by user."""
    # Test all optimization levels to ensure defaults work correctly
    for opt_level in OptimizationLevel:
        config = object.__new__(VllmConfig)
        config.compilation_config = CompilationConfig()
        config.optimization_level = opt_level
        config.model_config = None

        # Use the global optimization level defaults
        default_config = OPTIMIZATION_LEVEL_TO_CONFIG[opt_level]

        # Verify that all pass_config values are None before defaults are applied
        for pass_k in default_config["compilation_config"]["pass_config"]:
            assert getattr(config.compilation_config.pass_config, pass_k) is None

        # Verify that other config values are None before defaults are applied
        for k in default_config["compilation_config"]:
            if k != "pass_config":
                assert getattr(config.compilation_config, k) is None


@pytest.mark.parametrize(
    ("model_id", "compiliation_config", "optimization_level"),
    [
        (
            None,
            CompilationConfig(backend="eager", custom_ops=["+quant_fp8"]),
            OptimizationLevel.O0,
        ),
        (None, CompilationConfig(), OptimizationLevel.O0),
        (None, CompilationConfig(), OptimizationLevel.O1),
        (None, CompilationConfig(), OptimizationLevel.O2),
        (None, CompilationConfig(), OptimizationLevel.O3),
        (
            "RedHatAI/Qwen3-8B-speculator.eagle3",
            CompilationConfig(backend="inductor", custom_ops=["+quant_fp8"]),
            OptimizationLevel.O2,
        ),
        (
            "RedHatAI/Qwen3-8B-speculator.eagle3",
            CompilationConfig(),
            OptimizationLevel.O0,
        ),
        (
            "RedHatAI/Qwen3-8B-speculator.eagle3",
            CompilationConfig(),
            OptimizationLevel.O1,
        ),
        (
            "RedHatAI/Qwen3-8B-speculator.eagle3",
            CompilationConfig(),
            OptimizationLevel.O2,
        ),
        (
            "RedHatAI/Qwen3-8B-speculator.eagle3",
            CompilationConfig(),
            OptimizationLevel.O3,
        ),
        ("RedHatAI/DeepSeek-V2.5-1210-FP8", CompilationConfig(), OptimizationLevel.O0),
        ("RedHatAI/DeepSeek-V2.5-1210-FP8", CompilationConfig(), OptimizationLevel.O1),
        ("RedHatAI/DeepSeek-V2.5-1210-FP8", CompilationConfig(), OptimizationLevel.O2),
        ("RedHatAI/DeepSeek-V2.5-1210-FP8", CompilationConfig(), OptimizationLevel.O3),
    ],
)
def test_vllm_config_defaults(model_id, compiliation_config, optimization_level):
    """Test that optimization-level defaults are correctly applied."""

    model_config = None
    if model_id is not None:
        model_config = ModelConfig(model_id)
        vllm_config = VllmConfig(
            model_config=model_config,
            compilation_config=compiliation_config,
            optimization_level=optimization_level,
        )
    else:
        vllm_config = VllmConfig(
            compilation_config=compiliation_config,
            optimization_level=optimization_level,
        )
    # Use the global optimization level defaults
    default_config = OPTIMIZATION_LEVEL_TO_CONFIG[optimization_level]

    # Verify pass_config defaults (nested under compilation_config)
    pass_config_dict = default_config["compilation_config"]["pass_config"]
    for pass_k, pass_v in pass_config_dict.items():
        actual = getattr(vllm_config.compilation_config.pass_config, pass_k)
        expected = pass_v(vllm_config) if callable(pass_v) else pass_v
        assert actual == expected, (
            f"pass_config.{pass_k}: expected {expected}, got {actual}"
        )

    # Verify other compilation_config defaults
    compilation_config_dict = default_config["compilation_config"]
    for k, v in compilation_config_dict.items():
        if k != "pass_config":
            actual = getattr(vllm_config.compilation_config, k)
            expected = v(vllm_config) if callable(v) else v
            assert actual == expected, (
                f"compilation_config.{k}: expected {expected}, got {actual}"
            )


def test_vllm_config_callable_defaults():
    """Test that callable defaults work in the config system.

    Verifies that lambdas in default configs can inspect VllmConfig properties
    (e.g., is_quantized, is_model_moe) to conditionally set optimization flags.
    """
    config_no_model = VllmConfig(optimization_level=OptimizationLevel.O2)

    # Callable that checks if model exists
    has_model = lambda cfg: cfg.model_config is not None
    assert has_model(config_no_model) is False

    # Test with quantized model
    quantized_model = ModelConfig("RedHatAI/Llama-3.2-1B-FP8")
    config_quantized = VllmConfig(
        model_config=quantized_model, optimization_level=OptimizationLevel.O2
    )
    enable_if_quantized = lambda cfg: (
        cfg.model_config is not None and cfg.model_config.is_quantized()
    )
    assert enable_if_quantized(config_quantized) is True
    assert enable_if_quantized(config_no_model) is False

    # Test with MoE model
    moe_model = ModelConfig("deepseek-ai/DeepSeek-V2-Lite")
    config_moe = VllmConfig(
        model_config=moe_model, optimization_level=OptimizationLevel.O2
    )
    enable_if_sequential = lambda cfg: (
        cfg.model_config is not None and not cfg.model_config.is_model_moe()
    )
    assert enable_if_sequential(config_moe) is False
    assert enable_if_sequential(config_quantized) is True


def test_vllm_config_explicit_overrides():
    """Test that explicit property overrides work correctly with callable defaults.

    When users explicitly set configuration properties, those values
    take precedence over callable defaults, across different models and
    optimization levels.
    """
    from vllm.config.compilation import PassConfig

    quantized_model = ModelConfig("RedHatAI/Llama-3.2-1B-FP8")
    moe_model = ModelConfig("deepseek-ai/DeepSeek-V2-Lite")
    regular_model = ModelConfig("Qwen/Qwen1.5-7B")

    # Explicit compilation mode override on O0 (where default is NONE)
    compilation_config = CompilationConfig(mode=CompilationMode.VLLM_COMPILE)
    config = VllmConfig(
        optimization_level=OptimizationLevel.O0,
        compilation_config=compilation_config,
    )
    assert config.compilation_config.mode == CompilationMode.VLLM_COMPILE
    assert config.compilation_config.cudagraph_mode == CUDAGraphMode.NONE

    # Explicit pass config flags to override defaults
1055
    pass_config = PassConfig(eliminate_noops=True, fuse_attn_quant=True)
1056
1057
1058
1059
1060
    compilation_config = CompilationConfig(pass_config=pass_config)
    config = VllmConfig(
        optimization_level=OptimizationLevel.O0,
        compilation_config=compilation_config,
    )
1061
1062
    assert config.compilation_config.pass_config.eliminate_noops is True
    assert config.compilation_config.pass_config.fuse_attn_quant is True
1063
1064

    # Explicit cudagraph mode override on quantized model at O2
1065
    pass_config = PassConfig(fuse_gemm_comms=True)
1066
1067
1068
1069
1070
1071
1072
1073
1074
    compilation_config = CompilationConfig(
        cudagraph_mode=CUDAGraphMode.NONE, pass_config=pass_config
    )
    config = VllmConfig(
        model_config=quantized_model,
        optimization_level=OptimizationLevel.O2,
        compilation_config=compilation_config,
    )
    assert config.compilation_config.cudagraph_mode == CUDAGraphMode.NONE
1075
    assert config.compilation_config.pass_config.fuse_gemm_comms is True
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
    # Mode should still use default for O2
    assert config.compilation_config.mode == CompilationMode.VLLM_COMPILE

    # Different optimization levels with same model
    config_o0 = VllmConfig(
        model_config=regular_model, optimization_level=OptimizationLevel.O0
    )
    config_o2 = VllmConfig(
        model_config=regular_model, optimization_level=OptimizationLevel.O2
    )
    assert config_o0.compilation_config.mode == CompilationMode.NONE
    assert config_o2.compilation_config.mode == CompilationMode.VLLM_COMPILE
    assert config_o0.compilation_config.cudagraph_mode == CUDAGraphMode.NONE
    assert (
        config_o2.compilation_config.cudagraph_mode == CUDAGraphMode.FULL_AND_PIECEWISE
    )

    # Same optimization level across different model types
    config_moe_o2 = VllmConfig(
        model_config=moe_model, optimization_level=OptimizationLevel.O2
    )
    config_regular_o2 = VllmConfig(
        model_config=regular_model, optimization_level=OptimizationLevel.O2
    )
    config_quantized_o2 = VllmConfig(
        model_config=quantized_model, optimization_level=OptimizationLevel.O2
    )
    # All should have same base compilation settings at O2
    assert config_moe_o2.compilation_config.mode == CompilationMode.VLLM_COMPILE
    assert config_regular_o2.compilation_config.mode == CompilationMode.VLLM_COMPILE
    assert config_quantized_o2.compilation_config.mode == CompilationMode.VLLM_COMPILE
    assert (
        config_moe_o2.compilation_config.cudagraph_mode
        == CUDAGraphMode.FULL_AND_PIECEWISE
    )
    assert (
        config_regular_o2.compilation_config.cudagraph_mode
        == CUDAGraphMode.FULL_AND_PIECEWISE
    )

    # Override one field but not others
    pass_config = PassConfig(enable_noop=False)
    compilation_config = CompilationConfig(pass_config=pass_config)
    config = VllmConfig(
        model_config=regular_model,
        optimization_level=OptimizationLevel.O2,
        compilation_config=compilation_config,
    )
    # Explicit override should be respected
1125
    assert config.compilation_config.pass_config.eliminate_noops is False
1126
1127
1128
    # Other fields should still use defaults
    assert config.compilation_config.mode == CompilationMode.VLLM_COMPILE
    assert config.compilation_config.cudagraph_mode == CUDAGraphMode.FULL_AND_PIECEWISE
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139


def test_scheduler_config_init():
    with pytest.raises(ValidationError):
        # Positional InitVars missing
        # (InitVars cannot have defaults otherwise they will become attributes)
        SchedulerConfig()

    with pytest.raises(AttributeError):
        # InitVar does not become an attribute
        print(SchedulerConfig.default_factory().max_model_len)