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

import pytest
from transformers import AutoTokenizer

7
8
from vllm.multimodal.utils import rescale_image_size
from vllm.sequence import SampleLogprobs
9
10
from vllm.utils import is_cpu

11
from ..conftest import IMAGE_ASSETS, HfRunner, VllmRunner, _ImageAssets
12
from .utils import check_logprobs_close
13

14
pytestmark = pytest.mark.vlm
15

16
17
HF_IMAGE_PROMPTS = IMAGE_ASSETS.prompts({
    "stop_sign":
18
    "<|user|>\n<|image_1|>\nWhat's the content of the image?<|end|>\n<|assistant|>\n",  # noqa: E501
19
    "cherry_blossom":
20
21
22
    "<|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",
23
})
24

25
models = ["microsoft/Phi-3-vision-128k-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
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:]

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

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
53


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


54
55
56
57
def run_test(
    hf_runner: Type[HfRunner],
    vllm_runner: Type[VllmRunner],
    image_assets: _ImageAssets,
58
    model: str,
59
    *,
60
    size_factors: List[float],
61
62
    dtype: str,
    max_tokens: int,
63
    num_logprobs: int,
64
65
66
    tensor_parallel_size: int,
    distributed_executor_backend: Optional[str] = None,
):
67
68
69
70
    """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.
71
72
    For vllm runner, we provide MultiModalDataDict objects 
    and corresponding vision language config as input.
73
74
75
    Note, the text input is also adjusted to abide by vllm contract.
    The text output is sanitized to be able to compare with hf.
    """
76
77
78
79
80
81
    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)]
82

83
84
85
86
    # 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).
87

88
    # max_model_len should be greater than image_feature_size
89
    with vllm_runner(model,
90
                     max_model_len=4096,
91
                     max_num_seqs=1,
92
                     dtype=dtype,
93
94
                     tensor_parallel_size=tensor_parallel_size,
                     distributed_executor_backend=distributed_executor_backend,
95
                     enforce_eager=True) as vllm_model:
96
97
98
99
100
101
        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
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
109
110
111
112
113
114
115
116
        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
        ]
117

118
119
120
121
122
    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=[
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
    run_test(
        hf_runner,
        vllm_runner,
        image_assets,
156
        model,
157
        size_factors=size_factors,
158
159
        dtype=dtype,
        max_tokens=max_tokens,
160
        num_logprobs=num_logprobs,
161
162
        tensor_parallel_size=1,
    )