test_minicpmv.py 6.79 KB
Newer Older
1
from typing import List, Optional, Tuple, Type, Union
2
3
4
5

import pytest
import torch
import torch.types
6
from PIL import Image
7
from transformers import BatchEncoding
8
9
10
11

from vllm.multimodal.utils import rescale_image_size
from vllm.sequence import SampleLogprobs

12
from ..conftest import IMAGE_ASSETS, HfRunner, VllmRunner
13
14
15
16
17
18
19
20
21
22
23
24
25
from .utils import check_logprobs_close

pytestmark = pytest.mark.vlm

# The image token is placed before "user" on purpose so that the test can pass
HF_IMAGE_PROMPTS = IMAGE_ASSETS.prompts({
    "stop_sign":
        "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n" \
        "(<image>./</image>)\nWhat's the content of the image?<|eot_id|>" \
        "<|start_header_id|>assistant<|end_header_id|>\n\n",  # noqa: E501
    "cherry_blossom":
        "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n" \
        "(<image>./</image>)\nWhat is the season?<|eot_id|>" \
26
        "<|start_header_id|>assistant<|end_header_id|>\n\n",
27
})
28
29
30
31
32
HF_MULTIIMAGE_IMAGE_PROMPT = \
    "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n" \
    "(<image>./</image>)\n(<image>./</image>)\n" \
    "Describe these images.<|eot_id|>" \
    "<|start_header_id|>assistant<|end_header_id|>\n\n"
33
34
35
36

models = ["openbmb/MiniCPM-Llama3-V-2_5"]


37
38
39
40
def _wrap_inputs(hf_inputs: BatchEncoding) -> BatchEncoding:
    return BatchEncoding({"model_inputs": hf_inputs})


41
42
43
44
45
46
47
48
49
50
51
52
53
54
def trunc_hf_output(hf_output: Tuple[List[int], str,
                                     Optional[SampleLogprobs]]):
    output_ids, output_str, out_logprobs = hf_output
    if output_str.endswith("<|eot_id|>"):
        output_str = output_str.split("<|eot_id|>")[0]
    return output_ids, output_str, out_logprobs


target_dtype = "half"


def run_test(
    hf_runner: Type[HfRunner],
    vllm_runner: Type[VllmRunner],
55
56
    inputs: List[Tuple[List[str], Union[List[Image.Image],
                                        List[List[Image.Image]]]]],
57
58
59
60
61
    model: str,
    *,
    dtype: str,
    max_tokens: int,
    num_logprobs: int,
62
    mm_limit: int,
63
64
65
66
67
68
69
70
    tensor_parallel_size: int,
    distributed_executor_backend: Optional[str] = None,
):
    """Inference result should be the same between hf and vllm.

    All the image fixtures for the test is under tests/images.
    For huggingface runner, we provide the PIL images as input.
    For vllm runner, we provide MultiModalDataDict objects 
71
    and corresponding MultiModalConfig as input.
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    Note, the text input is also adjusted to abide by vllm contract.
    The text output is sanitized to be able to compare with hf.
    """

    # NOTE: take care of the order. run vLLM first, and then run HF.
    # vLLM needs a fresh new process without cuda initialization.
    # if we run HF first, the cuda initialization will be done and it
    # will hurt multiprocessing backend with fork method (the default method).

    # max_model_len should be greater than image_feature_size
    with vllm_runner(model,
                     max_model_len=4096,
                     max_num_seqs=1,
                     dtype=dtype,
86
                     limit_mm_per_prompt={"image": mm_limit},
87
88
89
90
91
92
93
94
95
                     tensor_parallel_size=tensor_parallel_size,
                     distributed_executor_backend=distributed_executor_backend,
                     enforce_eager=True) as vllm_model:
        tokenizer = vllm_model.model.get_tokenizer()
        stop_token_ids = [tokenizer.eos_id, tokenizer.eot_id]
        vllm_outputs_per_image = [
            vllm_model.generate_greedy_logprobs(prompts,
                                                max_tokens,
                                                num_logprobs=num_logprobs,
96
                                                images=images,
97
                                                stop_token_ids=stop_token_ids)
98
            for prompts, images in inputs
99
100
        ]

101
102
    hf_model = hf_runner(model, dtype=dtype, postprocess_inputs=_wrap_inputs)
    with hf_model, torch.no_grad():
103
104
105
106
        hf_outputs_per_image = [
            hf_model.generate_greedy_logprobs_limit(prompts,
                                                    max_tokens,
                                                    num_logprobs=num_logprobs,
107
                                                    images=images,
108
                                                    tokenizer=tokenizer)
109
            for prompts, images in inputs
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
        ]

    for hf_outputs, vllm_outputs in zip(hf_outputs_per_image,
                                        vllm_outputs_per_image):
        check_logprobs_close(
            outputs_0_lst=[
                trunc_hf_output(hf_output) for hf_output in hf_outputs
            ],
            outputs_1_lst=vllm_outputs,
            name_0="hf",
            name_1="vllm",
        )


@pytest.mark.parametrize("model", models)
@pytest.mark.parametrize(
    "size_factors",
    [
        # No image
        [],
        # Single-scale
        [1.0],
        # Single-scale, batched
        [1.0, 1.0, 1.0],
        # Multi-scale
        [0.25, 0.5, 1.0],
    ],
)
@pytest.mark.parametrize("dtype", [target_dtype])
@pytest.mark.parametrize("max_tokens", [128])
@pytest.mark.parametrize("num_logprobs", [5])
def test_models(hf_runner, vllm_runner, image_assets, model, size_factors,
                dtype: str, max_tokens: int, num_logprobs: int) -> None:
143
144
145
146
147
148
149
    images = [asset.pil_image for asset in image_assets]

    inputs_per_image = [(
        [prompt for _ in size_factors],
        [rescale_image_size(image, factor) for factor in size_factors],
    ) for image, prompt in zip(images, HF_IMAGE_PROMPTS)]

150
151
152
    run_test(
        hf_runner,
        vllm_runner,
153
        inputs_per_image,
154
155
156
157
        model,
        dtype=dtype,
        max_tokens=max_tokens,
        num_logprobs=num_logprobs,
158
        mm_limit=1,
159
160
        tensor_parallel_size=1,
    )
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182


@pytest.mark.parametrize("model", models)
@pytest.mark.parametrize(
    "size_factors",
    [
        # No image
        [],
        # Single-scale
        [1.0],
        # Single-scale, batched
        [1.0, 1.0, 1.0],
        # Multi-scale
        [0.25, 0.5, 1.0],
    ],
)
@pytest.mark.parametrize("dtype", [target_dtype])
@pytest.mark.parametrize("max_tokens", [128])
@pytest.mark.parametrize("num_logprobs", [5])
def test_multi_images_models(hf_runner, vllm_runner, image_assets, model,
                             size_factors, dtype: str, max_tokens: int,
                             num_logprobs: int) -> None:
183
184
185
186
187
188
189
190
191
    images = [asset.pil_image for asset in image_assets]

    inputs_per_case = [
        ([HF_MULTIIMAGE_IMAGE_PROMPT for _ in size_factors],
         [[rescale_image_size(image, factor) for image in images]
          for factor in size_factors])
    ]

    run_test(
192
193
        hf_runner,
        vllm_runner,
194
        inputs_per_case,
195
196
197
198
        model,
        dtype=dtype,
        max_tokens=max_tokens,
        num_logprobs=num_logprobs,
199
        mm_limit=2,
200
201
        tensor_parallel_size=1,
    )