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

import pytest
from transformers import AutoTokenizer

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

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

15
pytestmark = pytest.mark.vlm
16

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

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


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

34
35
36
37
    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:]

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

40
    tokenizer = AutoTokenizer.from_pretrained(model)
41
42
43
44
45
    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
46
47
48
49
50
51


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

52
53
54
55
56
57
# 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"

58

59
60
61
def run_test(
    hf_runner: Type[HfRunner],
    vllm_runner: Type[VllmRunner],
62
    inputs: List[Tuple[List[str], PromptImageInput]],
63
    model: str,
64
65
66
    *,
    dtype: str,
    max_tokens: int,
67
    num_logprobs: int,
68
    mm_limit: int,
69
70
71
    tensor_parallel_size: int,
    distributed_executor_backend: Optional[str] = None,
):
72
73
74
75
    """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.
76
    For vllm runner, we provide MultiModalDataDict objects 
77
    and corresponding MultiModalConfig as input.
78
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
84
85
    # 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).
86

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

    # use eager mode for hf runner, since phi3_v didn't work with flash_attn
    hf_model_kwargs = {"_attn_implementation": "eager"}
106
    with hf_runner(model, dtype=dtype,
107
                   model_kwargs=hf_model_kwargs) as hf_model:
108
        eos_token_id = hf_model.processor.tokenizer.eos_token_id
109
        hf_outputs_per_case = [
110
111
112
            hf_model.generate_greedy_logprobs_limit(prompts,
                                                    max_tokens,
                                                    num_logprobs=num_logprobs,
113
                                                    images=images,
114
                                                    eos_token_id=eos_token_id)
115
            for prompts, images in inputs
116
        ]
117

118
119
    for hf_outputs, vllm_outputs in zip(hf_outputs_per_case,
                                        vllm_outputs_per_case):
120
121
122
        check_logprobs_close(
            outputs_0_lst=hf_outputs,
            outputs_1_lst=[
123
                vllm_to_hf_output(vllm_output, model)
124
125
126
127
128
129
130
131
132
                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.
133
@pytest.mark.parametrize("model", models)
134
135
136
137
138
139
140
141
142
143
144
145
146
@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],
    ],
)
147
148
@pytest.mark.parametrize("dtype", [target_dtype])
@pytest.mark.parametrize("max_tokens", [128])
149
@pytest.mark.parametrize("num_logprobs", [10])
150
151
def test_models(hf_runner, vllm_runner, image_assets, model, size_factors,
                dtype: str, max_tokens: int, num_logprobs: int) -> None:
152
153
154
155
156
157
158
    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)]

159
160
161
    run_test(
        hf_runner,
        vllm_runner,
162
        inputs_per_image,
163
        model,
164
165
        dtype=dtype,
        max_tokens=max_tokens,
166
        num_logprobs=num_logprobs,
167
        mm_limit=1,
168
169
        tensor_parallel_size=1,
    )
170
171
172
173
174
175


@pytest.mark.parametrize("model", models)
@pytest.mark.parametrize("dtype", [target_dtype])
def test_regression_7840(hf_runner, vllm_runner, image_assets, model,
                         dtype) -> None:
176
177
178
179
180
181
    images = [asset.pil_image for asset in image_assets]

    inputs_regresion_7840 = [
        ([prompt], [image]) for image, prompt in zip(images, HF_IMAGE_PROMPTS)
    ]

182
183
184
185
    # Regression test for #7840.
    run_test(
        hf_runner,
        vllm_runner,
186
        inputs_regresion_7840,
187
188
189
190
        model,
        dtype=dtype,
        max_tokens=128,
        num_logprobs=10,
191
        mm_limit=1,
192
193
        tensor_parallel_size=1,
    )
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211


@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])
212
@pytest.mark.parametrize("num_logprobs", [10])
213
214
215
def test_multi_images_models(hf_runner, vllm_runner, image_assets, model,
                             size_factors, dtype: str, max_tokens: int,
                             num_logprobs: int) -> None:
216
217
218
219
220
221
222
223
224
    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(
225
226
        hf_runner,
        vllm_runner,
227
        inputs_per_case,
228
229
230
231
        model,
        dtype=dtype,
        max_tokens=max_tokens,
        num_logprobs=num_logprobs,
232
        mm_limit=2,
233
234
        tensor_parallel_size=1,
    )