test_phi3v.py 10.4 KB
Newer Older
1
import os
2
import re
3
from typing import List, Optional, Tuple, Type
4
5

import pytest
6
from PIL import Image
7
8
from transformers import AutoTokenizer

9
10
from vllm.multimodal.utils import rescale_image_size
from vllm.sequence import SampleLogprobs
11
from vllm.utils import is_cpu, is_hip
12

13
from ..conftest import IMAGE_ASSETS, HfRunner, VllmRunner
14
from .utils import check_logprobs_close
15

16
pytestmark = pytest.mark.vlm
17

18
19
HF_IMAGE_PROMPTS = IMAGE_ASSETS.prompts({
    "stop_sign":
20
    "<|user|>\n<|image_1|>\nWhat's the content of the image?<|end|>\n<|assistant|>\n",  # noqa: E501
21
    "cherry_blossom":
22
    "<|user|>\n<|image_1|>\nWhat is the season?<|end|>\n<|assistant|>\n",
23
})
24
HF_MULTIIMAGE_IMAGE_PROMPT = "<|user|>\n<|image_1|>\n<|image_2|>\nDescribe these images.<|end|>\n<|assistant|>\n"  # noqa: E501
25

26
models = ["microsoft/Phi-3.5-vision-instruct"]
27
28


29
30
def vllm_to_hf_output(vllm_output: Tuple[List[int], str,
                                         Optional[SampleLogprobs]],
31
32
33
                      model: str):
    """Sanitize vllm output to be comparable with hf output."""
    _, output_str, out_logprobs = vllm_output
34

35
36
37
38
    output_str_without_image = re.sub(r"(<\|image_\d+\|>)+", "", output_str)
    assert output_str_without_image[0] == " "
    output_str_without_image = output_str_without_image[1:]

39
    hf_output_str = output_str_without_image + "<|end|><|endoftext|>"
40

41
    tokenizer = AutoTokenizer.from_pretrained(model)
42
43
44
45
46
    hf_output_ids = tokenizer.encode(output_str_without_image)
    assert hf_output_ids[0] == 1
    hf_output_ids = hf_output_ids[1:]

    return hf_output_ids, hf_output_str, out_logprobs
47
48
49
50
51
52


target_dtype = "half"
if is_cpu():
    target_dtype = "bfloat16"

53
54
55
56
57
58
# ROCm Triton FA can run into shared memory issues with these models,
# use other backends in the meantime
# FIXME (mattwong, gshtrasb, hongxiayan)
if is_hip():
    os.environ["VLLM_USE_TRITON_FLASH_ATTN"] = "0"

59

60
61
62
def run_test(
    hf_runner: Type[HfRunner],
    vllm_runner: Type[VllmRunner],
63
    images: List[Image.Image],
64
    model: str,
65
    *,
66
    size_factors: List[float],
67
68
    dtype: str,
    max_tokens: int,
69
    num_logprobs: int,
70
71
72
    tensor_parallel_size: int,
    distributed_executor_backend: Optional[str] = None,
):
73
74
75
76
    """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.
77
    For vllm runner, we provide MultiModalDataDict objects 
78
    and corresponding MultiModalConfig as input.
79
80
81
    Note, the text input is also adjusted to abide by vllm contract.
    The text output is sanitized to be able to compare with hf.
    """
82
83
    inputs_per_image = [(
        [prompt for _ in size_factors],
84
85
86
87
        [
            rescale_image_size(image, factor, transpose=idx)
            for idx, factor in enumerate(size_factors)
        ],
88
    ) for image, prompt in zip(images, HF_IMAGE_PROMPTS)]
89

90
91
92
93
    # 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).
94

95
    # max_model_len should be greater than image_feature_size
96
    with vllm_runner(model,
97
                     max_model_len=4096,
98
                     max_num_seqs=1,
99
                     dtype=dtype,
100
101
                     tensor_parallel_size=tensor_parallel_size,
                     distributed_executor_backend=distributed_executor_backend,
102
                     enforce_eager=True) as vllm_model:
103
104
105
106
        vllm_outputs_per_image = [
            vllm_model.generate_greedy_logprobs(prompts,
                                                max_tokens,
                                                num_logprobs=num_logprobs,
107
108
                                                images=images)
            for prompts, images in inputs_per_image
109
110
111
112
        ]

    # use eager mode for hf runner, since phi3_v didn't work with flash_attn
    hf_model_kwargs = {"_attn_implementation": "eager"}
113
    with hf_runner(model, dtype=dtype,
114
                   model_kwargs=hf_model_kwargs) as hf_model:
115
116
117
118
119
        eos_token_id = hf_model.processor.tokenizer.eos_token_id
        hf_outputs_per_image = [
            hf_model.generate_greedy_logprobs_limit(prompts,
                                                    max_tokens,
                                                    num_logprobs=num_logprobs,
120
                                                    images=images,
121
                                                    eos_token_id=eos_token_id)
122
            for prompts, images in inputs_per_image
123
        ]
124

125
126
127
128
129
    for hf_outputs, vllm_outputs in zip(hf_outputs_per_image,
                                        vllm_outputs_per_image):
        check_logprobs_close(
            outputs_0_lst=hf_outputs,
            outputs_1_lst=[
130
                vllm_to_hf_output(vllm_output, model)
131
132
133
134
135
136
137
138
139
                for vllm_output in vllm_outputs
            ],
            name_0="hf",
            name_1="vllm",
        )


# Since we use _attn_implementation="eager" for hf_runner, there is more
# significant numerical difference. The basic `logprobs=5` fails to pass.
140
@pytest.mark.parametrize("model", models)
141
142
143
144
145
146
147
148
149
150
151
152
153
@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],
    ],
)
154
155
@pytest.mark.parametrize("dtype", [target_dtype])
@pytest.mark.parametrize("max_tokens", [128])
156
@pytest.mark.parametrize("num_logprobs", [10])
157
158
def test_models(hf_runner, vllm_runner, image_assets, model, size_factors,
                dtype: str, max_tokens: int, num_logprobs: int) -> None:
159
160
161
    run_test(
        hf_runner,
        vllm_runner,
162
        [asset.pil_image for asset in image_assets],
163
        model,
164
        size_factors=size_factors,
165
166
        dtype=dtype,
        max_tokens=max_tokens,
167
        num_logprobs=num_logprobs,
168
169
        tensor_parallel_size=1,
    )
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187


@pytest.mark.parametrize("model", models)
@pytest.mark.parametrize("dtype", [target_dtype])
def test_regression_7840(hf_runner, vllm_runner, image_assets, model,
                         dtype) -> None:
    # Regression test for #7840.
    run_test(
        hf_runner,
        vllm_runner,
        [image_assets[0].pil_image.resize((465, 226))],
        model,
        size_factors=[1.0],
        dtype=dtype,
        max_tokens=128,
        num_logprobs=10,
        tensor_parallel_size=1,
    )
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
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
289
290
291
292
293
294
295
296
297


def run_multi_image_test(
    hf_runner: Type[HfRunner],
    vllm_runner: Type[VllmRunner],
    images: List[Image.Image],
    model: str,
    *,
    size_factors: List[float],
    dtype: str,
    max_tokens: int,
    num_logprobs: int,
    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 
    and corresponding MultiModalConfig as input.
    Note, the text input is also adjusted to abide by vllm contract.
    The text output is sanitized to be able to compare with hf.
    """

    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])
    ]

    # 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,
                     limit_mm_per_prompt={"image": len(images)},
                     dtype=dtype,
                     tensor_parallel_size=tensor_parallel_size,
                     distributed_executor_backend=distributed_executor_backend,
                     enforce_eager=True) as vllm_model:
        vllm_outputs_per_case = [
            vllm_model.generate_greedy_logprobs(prompts,
                                                max_tokens,
                                                num_logprobs=num_logprobs,
                                                images=images)
            for prompts, images in inputs_per_case
        ]

    hf_model_kwargs = {"_attn_implementation": "eager"}
    with hf_runner(model, dtype=dtype,
                   model_kwargs=hf_model_kwargs) as hf_model:
        eos_token_id = hf_model.processor.tokenizer.eos_token_id
        hf_outputs_per_case = [
            hf_model.generate_greedy_logprobs_limit(prompts,
                                                    max_tokens,
                                                    num_logprobs=num_logprobs,
                                                    images=images,
                                                    eos_token_id=eos_token_id)
            for prompts, images in inputs_per_case
        ]

    for hf_outputs, vllm_outputs in zip(hf_outputs_per_case,
                                        vllm_outputs_per_case):
        check_logprobs_close(
            outputs_0_lst=hf_outputs,
            outputs_1_lst=[
                vllm_to_hf_output(vllm_output, model)
                for vllm_output in 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_multi_images_models(hf_runner, vllm_runner, image_assets, model,
                             size_factors, dtype: str, max_tokens: int,
                             num_logprobs: int) -> None:
    run_multi_image_test(
        hf_runner,
        vllm_runner,
        [asset.pil_image for asset in image_assets],
        model,
        size_factors=size_factors,
        dtype=dtype,
        max_tokens=max_tokens,
        num_logprobs=num_logprobs,
        tensor_parallel_size=1,
    )