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

4
import warnings
5
from collections.abc import Sequence
6
from dataclasses import dataclass
7
from typing import Any
8

9
import torch
10
import torch.nn.functional as F
11
from transformers import PretrainedConfig
12

13
from vllm.config.model import AttnTypeStr, ModelConfig, ModelDType, RunnerOption
14
from vllm.config.pooler import SequencePoolingType, TokenPoolingType
15
from vllm.logprobs import Logprob, PromptLogprobs, SampleLogprobs
16
from vllm.multimodal.processing import InputProcessingContext
17
from vllm.tokenizers import cached_tokenizer_from_config
18

19
from .. import ci_envs
20
21
from .registry import HF_EXAMPLE_MODELS

22
TokensText = tuple[list[int], str]
23
24


25
26
27
28
29
30
31
def check_outputs_equal(
    *,
    outputs_0_lst: Sequence[TokensText],
    outputs_1_lst: Sequence[TokensText],
    name_0: str,
    name_1: str,
):
32
    """
33
    Compare the two sequences generated by different models,
34
35
36
37
    which should be equal.
    """
    assert len(outputs_0_lst) == len(outputs_1_lst)

38
39
40
    for prompt_idx, (outputs_0, outputs_1) in enumerate(
        zip(outputs_0_lst, outputs_1_lst)
    ):
41
42
43
        output_ids_0, output_str_0 = outputs_0
        output_ids_1, output_str_1 = outputs_1

44
        # The text and token outputs should exactly match
45
46
47
48
49
        fail_msg = (
            f"Test{prompt_idx}:"
            f"\n{name_0}:\t{output_str_0!r}"
            f"\n{name_1}:\t{output_str_1!r}"
        )
50
51
52

        assert output_str_0 == output_str_1, fail_msg
        assert output_ids_0 == output_ids_1, fail_msg
53
54


55
56
57
58
59
60
# Representation of generated sequence as a tuple of
# * Token ID list
# * String
# * List of top sample logprobs for each sampled token
#
# Assumes prompt logprobs were not requested.
61
TokensTextLogprobs = tuple[
62
    list[int], str, list[dict[int, float]] | SampleLogprobs | None
63
]
64

65
66
67
68
69
70
71
# Allow for tokens to be represented as str's rather than IDs;
# tuple of
# * Token string representations list
# * String
# * Optional list of top sample logprobs for each sampled token
#
# Assumes prompt logprobs were not requested.
72
TextTextLogprobs = tuple[
73
    list[str], str, list[dict[str, float]] | list[dict[str, Logprob]] | None
74
]
75

76
77
78
79
80
81
82
# Representation of generated sequence as a tuple of
# * Token ID list
# * String
# * Optional list of top sample logprobs for each sampled token
# * Optional list of top prompt logprobs for each prompt token
#
# Allows prompt logprobs to be requested.
83
TokensTextLogprobsPromptLogprobs = tuple[
84
85
    list[int],
    str,
86
87
    list[dict[int, float]] | SampleLogprobs | None,
    list[dict[int, float] | None] | PromptLogprobs | None,
88
]
89

90

91
92
def check_logprobs_close(
    *,
93
    outputs_0_lst: Sequence[
94
        TokensTextLogprobs | TokensTextLogprobsPromptLogprobs | TextTextLogprobs
95
96
    ],
    outputs_1_lst: Sequence[
97
        TokensTextLogprobs | TokensTextLogprobsPromptLogprobs | TextTextLogprobs
98
    ],
99
100
    name_0: str,
    name_1: str,
101
    num_outputs_0_skip_tokens: int = 0,
102
    warn_on_mismatch: bool = True,
103
104
105
    always_check_logprobs: bool = False,
) -> None:
    """Compare the logprobs of two sequences generated by different models,
106
    which should be similar but not necessarily equal.
107

108
109
110
111
112
113
114
115
116
117
118
119
    How sample logprobs are compared:
    * `always_check_logprobs == True`: set of highest-logprob token ids
      must match between seq0 and seq1 at all sampled token offsets
    * `always_check_logprobs == False`: highest-logprob token ids are
      only compared at sampled token offsets for which generated token
      ids don't match

    Prompt logprobs must be provided either for both input sequences, or
    for neither. If prompt logprobs are provided, then highest-logprob
    prompt token ids must match between seq0 and seq1 at all prompt token
    offsets.

120
121
122
123
124
125
    Args:
      outputs_0_lst: First sequence to compare
      outputs_0_lst: Second sequence to compare
      name_0: sequence #0 name
      name_1: sequence #1 name
      num_outputs_0_skip_tokens: If > 0, specifies the number of initial
126
127
128
129
130
                                 sequence #0 tokens & logprobs to discard
                                 before comparison, i.e. all
                                 of sequence #1 will be compared to
                                 sequence #0 beginning at index
                                 num_outputs_0_skip_tokens
131
      warn_on_mismatch: Issue a warning if there is token-wise or text-wise
132
                        mismatch between the two sequences
133
      always_check_logprobs: If true, check logprobs even when tokens match
134
    """
135
136
    assert len(outputs_0_lst) == len(outputs_1_lst)

137
    # Loop through responses to each prompt.
138
139
140
    for prompt_idx, (outputs_0, outputs_1) in enumerate(
        zip(outputs_0_lst, outputs_1_lst)
    ):
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
        assert len(outputs_0) == len(outputs_1)
        if len(outputs_0) == 3:
            assert len(outputs_1) == 3
            # Break out tokens, text & sample logprobs
            # (prompt logprobs were not provided)
            output_ids_0, output_str_0, logprobs_0 = outputs_0
            output_ids_1, output_str_1, logprobs_1 = outputs_1
        elif len(outputs_0) == 4:
            assert len(outputs_1) == 4
            # Break out tokens, text, sample logprobs & prompt logprobs
            (
                output_ids_0,
                output_str_0,
                logprobs_0,
                prompt_logprobs_0,
            ) = outputs_0
            (
                output_ids_1,
                output_str_1,
                logprobs_1,
                prompt_logprobs_1,
            ) = outputs_1

            # Test prompt logprobs closeness
165
            if prompt_logprobs_0 is not None and prompt_logprobs_1 is not None:
166
                # Both sequences' prompt logprobs lists are not `None`
167
168
169
                # (although individual list elements may be `None`);
                # for each token's logprobs:
                for idx, (logprobs_elem_0, logprobs_elem_1) in enumerate(
170
171
                    zip(prompt_logprobs_0, prompt_logprobs_1)
                ):
172
173
174
                    fail_msg = (
                        f"Prompt logprobs test:"
                        f"\n{name_0}:\tPrompt index {idx}\t{logprobs_elem_0}"
175
176
                        f"\n{name_1}:\tPrompt index {idx}\t{logprobs_elem_1}"
                    )
177
178
179
180
181
182
183
184
185
186

                    if logprobs_elem_0 is None:
                        # If the seq 0 token's logprobs are `None`,
                        # the seq 1 token's logprobs must be `None`
                        assert logprobs_elem_1 is None, fail_msg
                    else:
                        # If the seq 0 token's logprobs are not `None`,
                        # the seq 1 token's logprobs must not be `None`
                        assert logprobs_elem_1 is not None, fail_msg
                        # Logprobs check: top-k token choices must be the same
187
188
189
                        assert set(logprobs_elem_0.keys()) == set(
                            logprobs_elem_1.keys()
                        ), fail_msg
190
191
            else:
                # Both sequence logprobs lists must be `None`
192
193
194
195
196
                fail_msg = (
                    f"Prompt logprobs test:"
                    f"\n{name_0}:\tlogprobs\t{prompt_logprobs_0}"
                    f"\n{name_1}:\tlogprobs\t{prompt_logprobs_1}"
                )
197

198
                assert prompt_logprobs_0 is None and prompt_logprobs_1 is None, fail_msg
199
        else:
200
201
202
203
204
            raise ValueError(
                f"Outputs tuple must have 3 or 4 elements but "
                f"{len(outputs_0)} elements were provided: "
                f"{outputs_0}"
            )
205

206
207
208
209
210
        if logprobs_0 is None:
            logprobs_0 = [None] * len(output_ids_0)
        if logprobs_1 is None:
            logprobs_1 = [None] * len(output_ids_1)

211
212
213
214
215
216
217
218
219
        # Skip specified number of initial sequence #0 tokens
        # & logprobs, leaving output text as-is for simplicity
        # (text mismatches may generate warnings but do not
        # cause the test to fail.)
        if num_outputs_0_skip_tokens < 0:
            raise ValueError("num_outputs_0_skip_tokens must be non-negative")
        output_ids_0 = output_ids_0[num_outputs_0_skip_tokens:]
        logprobs_0 = logprobs_0[num_outputs_0_skip_tokens:]

220
        # Loop through generated tokens.
221
222
223
        for idx, (output_id_0, output_id_1) in enumerate(
            zip(output_ids_0, output_ids_1)
        ):
224
225
226
227
228
229
            is_tok_mismatch = output_id_0 != output_id_1

            # If generated tokens don't match
            # or it is desired to always check logprobs,
            # then
            if is_tok_mismatch or always_check_logprobs:
230
231
232
                logprobs_elem_0 = logprobs_0[idx]
                logprobs_elem_1 = logprobs_1[idx]

233
                # Each predicted token must be in top N logprobs of the other
234
                fail_msg = (
235
                    f"Test{prompt_idx}:"
236
                    f"\nMatched tokens:\t{output_ids_0[:idx]}"
237
                    f"\n{name_0}:\t{output_str_0!r}\t{logprobs_elem_0}"
238
239
                    f"\n{name_1}:\t{output_str_1!r}\t{logprobs_elem_1}"
                )
240
241
242
243
244
245

                assert logprobs_elem_0 is not None, fail_msg
                assert logprobs_elem_1 is not None, fail_msg
                assert output_id_0 in logprobs_elem_1, fail_msg
                assert output_id_1 in logprobs_elem_0, fail_msg

246
                if warn_on_mismatch and is_tok_mismatch:
247
248
249
250
251
252
                    with warnings.catch_warnings():
                        # This ensures that repeated warnings are shown
                        # in the output, not just the first occurrence
                        warnings.simplefilter("always")

                        warnings.warn(fail_msg, stacklevel=2)
253
254
255

                # Break out since sequences will now diverge.
                break
256
257
258
259
        else:
            if output_str_0 != output_str_1 and warn_on_mismatch:
                # The token outputs exactly match,
                # so the text outputs should exactly match as well
260
261
262
263
264
                fail_msg = (
                    f"Test{prompt_idx}:"
                    f"\n{name_0}:\t{output_str_0!r}"
                    f"\n{name_1}:\t{output_str_1!r}"
                )
265
266
267
268
269
270
271

                with warnings.catch_warnings():
                    # This ensures that repeated warnings are shown
                    # in the output, not just the first occurrence
                    warnings.simplefilter("always")

                    warnings.warn(fail_msg, stacklevel=2)
272
273


274
def build_model_context(
275
    model_id: str,
276
    runner: RunnerOption = "auto",
277
    dtype: ModelDType = "auto",
278
279
280
    model_config_kwargs: dict[str, Any] | None = None,
    mm_processor_kwargs: dict[str, Any] | None = None,
    limit_mm_per_prompt: dict[str, int] | None = None,
281
    mm_processor_cache_gb: int = 0,
282
):
283
    """Creates an InputProcessingContext for a given model.
284

285
    Args:
286
        model_id: ID of the model being considered.
287
288
289
290
291
        mm_processor_kwargs: optional processor kwargs for to be leveraged
            in the input processor, mapper, dummy data creation, etc.
        limit_mm_per_prompt: Multimodal limits.

    Returns:
292
        InputProcessingContext for the model being considered.
293
    """
294
295
    model_info = HF_EXAMPLE_MODELS.find_hf_info(model_id)
    model_info.check_available_online(on_fail="skip")
296
297
298
299
300
    model_info.check_transformers_version(
        on_fail="skip",
        check_max_version=False,
        check_version_reason="vllm",
    )
301

302
    model_config_kwargs = model_config_kwargs or {}
303
    limit_mm_per_prompt = limit_mm_per_prompt or {}
304
    model_config = ModelConfig(
305
        model_id,
306
        runner=runner,
307
308
309
310
        tokenizer=model_info.tokenizer or model_id,
        tokenizer_mode=model_info.tokenizer_mode,
        revision=model_info.revision,
        trust_remote_code=model_info.trust_remote_code,
311
        dtype=dtype,
312
313
314
        seed=0,
        mm_processor_kwargs=mm_processor_kwargs,
        limit_mm_per_prompt=limit_mm_per_prompt,
315
        mm_processor_cache_gb=mm_processor_cache_gb,
316
317
318
319
320
        hf_overrides=model_info.hf_overrides,
        skip_tokenizer_init=model_info.require_embed_inputs,
        enable_prompt_embeds=model_info.require_embed_inputs,
        enable_mm_embeds=model_info.require_embed_inputs,
        enforce_eager=model_info.enforce_eager,
321
        **model_config_kwargs,
322
    )
323

324
325
326
327
    return InputProcessingContext(
        model_config,
        tokenizer=cached_tokenizer_from_config(model_config),
    )
328
329
330
331
332
333
334
335
336
337
338
339
340


def check_embeddings_close(
    *,
    embeddings_0_lst: Sequence[list[float]],
    embeddings_1_lst: Sequence[list[float]],
    name_0: str,
    name_1: str,
    tol: float = 1e-3,
) -> None:
    assert len(embeddings_0_lst) == len(embeddings_1_lst)

    for prompt_idx, (embeddings_0, embeddings_1) in enumerate(
341
342
        zip(embeddings_0_lst, embeddings_1_lst)
    ):
343
        assert len(embeddings_0) == len(embeddings_1), (
344
345
            f"Length mismatch: {len(embeddings_0)} vs. {len(embeddings_1)}"
        )
346

347
348
349
        sim = F.cosine_similarity(
            torch.tensor(embeddings_0), torch.tensor(embeddings_1), dim=0
        )
350

351
352
353
354
355
356
        fail_msg = (
            f"Test{prompt_idx}:"
            f"\nCosine similarity: \t{sim:.4f}"
            f"\n{name_0}:\t{embeddings_0[:16]!r}"
            f"\n{name_1}:\t{embeddings_1[:16]!r}"
        )
357
358
359
360
361
362
363
364
365
366
367

        assert sim >= 1 - tol, fail_msg


def matryoshka_fy(tensor: torch.Tensor, dimensions: int):
    tensor = torch.tensor(tensor)
    tensor = tensor[..., :dimensions]
    tensor = F.normalize(tensor, p=2, dim=1)
    return tensor


368
369
370
371
372
373
374
def softmax(data):
    if data.shape[-1] == 1:
        return F.sigmoid(data)
    else:
        return F.softmax(data, dim=-1)


375
376
@dataclass
class ModelInfo:
377
378
    name: str
    architecture: str = ""
379
    dtype: str = "auto"
380
    max_model_len: int | None = None
381
    hf_dtype: str = "float32"
382
    hf_overrides: dict[str, Any] | None = None
383
384
    seq_pooling_type: SequencePoolingType | None = None
    tok_pooling_type: TokenPoolingType | None = None
385
386
387
    attn_type: AttnTypeStr | None = None
    is_prefix_caching_supported: bool | None = None
    is_chunked_prefill_supported: bool | None = None
388
    enable_test: bool = True
389
390


391
392
@dataclass
class EmbedModelInfo(ModelInfo):
393
    mteb_score: float | None = None
394
    is_matryoshka: bool = False
395
    matryoshka_dimensions: list[int] | None = None
396
397
398
399


@dataclass
class RerankModelInfo(ModelInfo):
400
    mteb_score: float | None = None
401
    chat_template_name: str | None = None
402
403


404
405
406
@dataclass
class GenerateModelInfo(ModelInfo):
    hf_dtype: str = "auto"
407
    hf_ppl: float | None = None
408
409


410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
def get_vllm_extra_kwargs(model_info: ModelInfo, vllm_extra_kwargs):
    # A model family has many models with the same architecture,
    # and we don't need to test each one.
    if not ci_envs.VLLM_CI_NO_SKIP and not model_info.enable_test:
        import pytest

        pytest.skip("Skipping test.")

    # Allow vllm to test using the given dtype, such as float32
    vllm_extra_kwargs = vllm_extra_kwargs or {}
    vllm_extra_kwargs["dtype"] = ci_envs.VLLM_CI_DTYPE or model_info.dtype

    # Allow vllm to test using hf_overrides
    if model_info.hf_overrides is not None:
        vllm_extra_kwargs["hf_overrides"] = model_info.hf_overrides

    # Allow changing the head dtype used by vllm in tests
    if ci_envs.VLLM_CI_HEAD_DTYPE is not None:
        if "hf_overrides" not in vllm_extra_kwargs:
            vllm_extra_kwargs["hf_overrides"] = {}
        vllm_extra_kwargs["hf_overrides"]["head_dtype"] = ci_envs.VLLM_CI_HEAD_DTYPE

    # Allow control over whether tests use enforce_eager
    if ci_envs.VLLM_CI_ENFORCE_EAGER is not None:
        vllm_extra_kwargs["enforce_eager"] = ci_envs.VLLM_CI_ENFORCE_EAGER

    return vllm_extra_kwargs


439
440
def dummy_hf_overrides(
    hf_config: PretrainedConfig,
441
442
    *,
    model_arch: str = "",
443
    exist_overrides: dict[str, Any] | None = None,
444
    use_original_num_layers: bool = False,
445
446
447
448
449
450
451
452
453
454
455
) -> PretrainedConfig:
    """
    Dummy HF overrides function used to create dummy model
    with only minimum nums of layer.
    """
    hf_config.update(exist_overrides or {})

    text_config = hf_config.get_text_config()

    # Ensure at least 2 expert per group
    # Since `grouped_topk` assumes top-2
456
    n_group = getattr(text_config, "n_group", None)
457
458
459
    # Kimi uses `num_expert_group` instead of `n_group`.
    if n_group is None:
        n_group = getattr(text_config, "num_expert_group", None)
460
461
462
463
    num_experts = n_group * 2 if n_group is not None else 2

    # we use three layers for Gemma-3n to check
    # both normal layer and kv_shared_layer
464
465
    if use_original_num_layers:
        # Use the original number of layers from the config
466
467
        num_layers = getattr(text_config, "num_layers", 1)
        num_hidden_layers = getattr(text_config, "num_hidden_layers", 1)
468
469
470
    else:
        # Use minimal layers for testing
        num_layers = 1
471
472
473
474
475
476
477
478
479
480
        num_hidden_layers = (
            3
            if model_arch
            in (
                "Gemma3nForConditionalGeneration",
                "Gemma4ForCausalLM",
                "Gemma4ForConditionalGeneration",
            )
            else 1
        )
481

XuruiYang's avatar
XuruiYang committed
482
    update_dict = {
483
        "num_layers": num_layers,
484
485
        # For Gemma-3n
        "num_kv_shared_layers": 1,
XuruiYang's avatar
XuruiYang committed
486
487
    }

488
489
    _hf_config = hf_config

490
    class DummyConfig:
491
        hf_config = _hf_config
492
493
        hf_text_config = text_config

494
    model_arch_config = ModelConfig.get_model_arch_config(DummyConfig)
495
496
    # Only set MoE related config when the model has MoE layers.
    # Otherwise all models detected as MoE by _get_transformers_backend_cls.
497
    if model_arch_config.num_experts > 0:
498
499
500
        update_dict.update(
            {
                "num_experts": num_experts,
501
                "num_experts_per_tok": 2,
502
                # Kimi uses `num_experts_per_token`.
503
                "num_experts_per_token": 2,
504
505
506
507
508
509
510
                "num_local_experts": num_experts,
                # Otherwise there will not be any expert layers
                "first_k_dense_replace": 0,
                # To avoid OOM on DeepSeek-V3
                "n_routed_experts": num_experts,
            }
        )
511

XuruiYang's avatar
XuruiYang committed
512
    # Update num_hidden_layers for non-Longcat architectures
513
    if model_arch != "LongcatFlashForCausalLM" and model_arch != "LongCatFlashMTPModel":
XuruiYang's avatar
XuruiYang committed
514
515
516
        update_dict["num_hidden_layers"] = num_hidden_layers

    text_config.update(update_dict)
517
518

    if hasattr(hf_config, "vision_config"):
519
520
521
522
523
524
        hf_config.vision_config.update(
            {
                "num_layers": 1,
                "num_hidden_layers": 1,
            }
        )
525
526
527

    # e.g.: ibm-granite/granite-speech-3.3-2b
    if hasattr(hf_config, "encoder_config"):
528
529
530
531
532
533
        hf_config.encoder_config.update(
            {
                "num_layers": 1,
                "num_hidden_layers": 1,
            }
        )
534
535
536

    # e.g.: Qwen/Qwen2-Audio-7B-Instruct
    if hasattr(hf_config, "audio_config"):
537
538
539
540
541
542
543
        hf_config.audio_config.update(
            {
                "num_layers": 1,
                "num_hidden_layers": 1,
                "encoder_layers": 1,
            }
        )
544
545

    return hf_config
546
547


548
549
def check_transformers_version(
    model: str,
550
551
    min_transformers_version: str | None = None,
    max_transformers_version: str | None = None,
552
):
553
554
    from .registry import _HfExamplesInfo

555
556
557
558
559
    return _HfExamplesInfo(
        model,
        min_transformers_version=min_transformers_version,
        max_transformers_version=max_transformers_version,
    ).check_transformers_version(on_fail="skip")