"vllm/vscode:/vscode.git/clone" did not exist on "aeb37c2a725554791ff6f258b1e18830867a3ab9"
test_phi3v.py 6.69 KB
Newer Older
1
import re
2
from typing import List, Optional, Tuple, Type
3
4
5
6
7

import pytest
from transformers import AutoTokenizer

from vllm.config import VisionLanguageConfig
8
9
from vllm.multimodal.utils import rescale_image_size
from vllm.sequence import SampleLogprobs
10
11
from vllm.utils import is_cpu

12
from ..conftest import IMAGE_ASSETS, HfRunner, VllmRunner, _ImageAssets
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
22
23
    "<|user|>\n<|image_1|>\nWhat is the season?<|end|>\n<|assistant|>\n",
    "boardwalk":
    "<|user|>\n<|image_1|>\nWhat's in this image?<|end|>\n<|assistant|>\n",
24
})
25
26
27


def iter_phi3v_configs(model_name: str):
28
    # Need to use the max possible feature size for profile_run
29
    image_hw_to_feature_size = {
30
        (1008, 1344): 2653,
31
32
33
    }

    for (h, w), f in image_hw_to_feature_size.items():
34
35
36
37
38
        input_shape = (1, 3, h, w)
        yield (model_name,
               VisionLanguageConfig(image_feature_size=f,
                                    image_token_id=32044,
                                    image_input_shape=input_shape))
39
40
41
42
43
44
45


model_and_vl_config = [
    *iter_phi3v_configs("microsoft/Phi-3-vision-128k-instruct"),
]


46
47
def vllm_to_hf_output(vllm_output: Tuple[List[int], str,
                                         Optional[SampleLogprobs]],
48
49
50
51
52
53
                      vlm_config: VisionLanguageConfig, model_id: str):
    """Sanitize vllm output to be comparable with hf output.
    The function reduces `input_ids` from 1, 32000, 32000, ..., 32000,
    x1, x2, x3 ... to 1, 32000, x1, x2, x3 ...
    It also reduces `output_str` from "<image><image>bla" to "bla".
    """
54
    output_ids, output_str, out_logprobs = vllm_output
55

56
57
58
59
60
    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:]

    hf_output_str = output_str_without_image.replace("<|user|>", "") \
61
62
        .replace("<|end|>\n<|assistant|>", " ")

63
64
65
66
67
68
    tokenizer = AutoTokenizer.from_pretrained(model_id)
    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
69
70
71
72
73
74
75


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


76
77
78
79
80
81
def run_test(
    hf_runner: Type[HfRunner],
    vllm_runner: Type[VllmRunner],
    image_assets: _ImageAssets,
    model_and_config: Tuple[str, VisionLanguageConfig],
    *,
82
    size_factors: List[float],
83
84
    dtype: str,
    max_tokens: int,
85
    num_logprobs: int,
86
87
88
    tensor_parallel_size: int,
    distributed_executor_backend: Optional[str] = None,
):
89
90
91
92
    """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.
93
94
    For vllm runner, we provide MultiModalDataDict objects 
    and corresponding vision language config as input.
95
96
97
98
    Note, the text input is also adjusted to abide by vllm contract.
    The text output is sanitized to be able to compare with hf.
    """
    model_id, vlm_config = model_and_config
99
100
101
102
103
104
    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)]
105

106
107
108
109
    # 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).
110

111
    # max_model_len should be greater than image_feature_size
112
    with vllm_runner(model_id,
113
                     max_model_len=4096,
114
                     dtype=dtype,
115
116
                     tensor_parallel_size=tensor_parallel_size,
                     distributed_executor_backend=distributed_executor_backend,
117
                     enforce_eager=True,
118
                     **vlm_config.as_cli_args_dict()) as vllm_model:
119
120
121
122
123
124
        vllm_outputs_per_image = [
            vllm_model.generate_greedy_logprobs(prompts,
                                                max_tokens,
                                                num_logprobs=num_logprobs,
                                                images=vllm_images)
            for prompts, vllm_images in inputs_per_image
125
126
127
128
129
130
        ]

    # use eager mode for hf runner, since phi3_v didn't work with flash_attn
    hf_model_kwargs = {"_attn_implementation": "eager"}
    with hf_runner(model_id, dtype=dtype,
                   model_kwargs=hf_model_kwargs) as hf_model:
131
132
133
134
135
136
137
138
139
        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,
                                                    images=hf_images,
                                                    eos_token_id=eos_token_id)
            for prompts, hf_images in inputs_per_image
        ]
140

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
    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=[
                vllm_to_hf_output(vllm_output, vlm_config, model_id)
                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.
156
@pytest.mark.parametrize("model_and_config", model_and_vl_config)
157
158
159
160
161
162
163
164
165
166
167
168
169
@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],
    ],
)
170
171
@pytest.mark.parametrize("dtype", [target_dtype])
@pytest.mark.parametrize("max_tokens", [128])
172
@pytest.mark.parametrize("num_logprobs", [10])
173
def test_models(hf_runner, vllm_runner, image_assets, model_and_config,
174
175
                size_factors, dtype: str, max_tokens: int,
                num_logprobs: int) -> None:
176
177
178
179
180
    run_test(
        hf_runner,
        vllm_runner,
        image_assets,
        model_and_config,
181
        size_factors=size_factors,
182
183
        dtype=dtype,
        max_tokens=max_tokens,
184
        num_logprobs=num_logprobs,
185
186
        tensor_parallel_size=1,
    )