test_online_vision.py 5.9 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
5
import json

6
7
import pytest
import requests
pansicheng's avatar
pansicheng committed
8
from transformers import AutoProcessor
9

10
from tests.utils import VLLM_PATH, RemoteOpenAIServer
11
from vllm.entrypoints.pooling.embed.protocol import EmbeddingResponse
12
from vllm.multimodal.media import MediaWithBytes
13
from vllm.multimodal.utils import encode_image_url, fetch_image
14
15
16
17

MODEL_NAME = "TIGER-Lab/VLM2Vec-Full"
MAXIMUM_IMAGES = 2

18
vlm2vec_jinja_path = VLLM_PATH / "examples/pooling/embed/template/vlm2vec_phi3v.jinja"
19
20
assert vlm2vec_jinja_path.exists()

21
# Test different image extensions (JPG/PNG) and formats (gray/RGB/RGBA)
22
TEST_IMAGE_ASSETS = [
23
24
25
26
    "2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",  # "https://vllm-public-assets.s3.us-west-2.amazonaws.com/vision_model_images/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
    "Grayscale_8bits_palette_sample_image.png",  # "https://vllm-public-assets.s3.us-west-2.amazonaws.com/vision_model_images/Grayscale_8bits_palette_sample_image.png",
    "1280px-Venn_diagram_rgb.svg.png",  # "https://vllm-public-assets.s3.us-west-2.amazonaws.com/vision_model_images/1280px-Venn_diagram_rgb.svg.png",
    "RGBA_comp.png",  # "https://vllm-public-assets.s3.us-west-2.amazonaws.com/vision_model_images/RGBA_comp.png",
27
28
]

29
30
31
32
input_text = "The best thing about vLLM is that it supports many different models"
image_url = "https://vllm-public-assets.s3.us-west-2.amazonaws.com/multimodal_asset/cat_snow.jpg"
image_base64 = {"url": encode_image_url(fetch_image(image_url))}

33
34
35
36

@pytest.fixture(scope="module")
def server():
    args = [
37
38
        "--runner",
        "pooling",
39
40
41
42
43
44
45
        "--max-model-len",
        "2048",
        "--max-num-seqs",
        "5",
        "--enforce-eager",
        "--trust-remote-code",
        "--limit-mm-per-prompt",
46
        json.dumps({"image": MAXIMUM_IMAGES}),
47
48
        "--chat-template",
        str(vlm2vec_jinja_path),
49
50
51
52
53
54
    ]

    with RemoteOpenAIServer(MODEL_NAME, args) as remote_server:
        yield remote_server


55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
@pytest.mark.parametrize("model_name", [MODEL_NAME])
def test_chat_text_request(server: RemoteOpenAIServer, model_name: str):
    messages = [
        {
            "role": "user",
            "content": input_text,
        },
    ]

    # note: vlm2vec_phi3v.jinja
    # Embedding models should only embed one message at a time.

    response = requests.post(
        server.url_for("v1/embeddings"),
        json={"model": model_name, "messages": messages},
    )
    response.raise_for_status()

    output = EmbeddingResponse.model_validate(response.json())
    assert len(output.data) == 1
    assert output.model == MODEL_NAME
    assert len(output.data[0].embedding) == 3072
    assert output.usage.prompt_tokens == 14


@pytest.mark.parametrize("model_name", [MODEL_NAME])
def test_chat_image_url_request(server: RemoteOpenAIServer, model_name: str):
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Represent the user's input."},
                {"type": "image_url", "image_url": {"url": image_url}},
            ],
        }
    ]

    response = requests.post(
        server.url_for("v1/embeddings"),
        json={"model": model_name, "messages": messages},
    )
    response.raise_for_status()

    output = EmbeddingResponse.model_validate(response.json())
    assert len(output.data) == 1
    assert output.model == MODEL_NAME
    assert len(output.data[0].embedding) == 3072
    assert output.usage.prompt_tokens == 767


@pytest.mark.parametrize("model_name", [MODEL_NAME])
def test_chat_image_base64_request(server: RemoteOpenAIServer, model_name: str):
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Represent the user's input."},
                {"type": "image_url", "image_url": image_base64},
            ],
        }
    ]

    response = requests.post(
        server.url_for("v1/embeddings"),
        json={"model": model_name, "messages": messages},
    )
    response.raise_for_status()

    output = EmbeddingResponse.model_validate(response.json())
    assert len(output.data) == 1
    assert output.model == MODEL_NAME
    assert len(output.data[0].embedding) == 3072
    assert output.usage.prompt_tokens == 767


pansicheng's avatar
pansicheng committed
130
def get_hf_prompt_tokens(model_name, content, image_url):
131
132
133
    processor = AutoProcessor.from_pretrained(
        model_name, trust_remote_code=True, num_crops=4
    )
pansicheng's avatar
pansicheng committed
134
135
136

    placeholder = "<|image_1|> "
    prompt = f"{placeholder}{content}"
137
138
139
140
141
    image = fetch_image(image_url)
    # Unwrap MediaWithBytes if present
    if isinstance(image, MediaWithBytes):
        image = image.media
    images = [image]
pansicheng's avatar
pansicheng committed
142
143
144
145
    inputs = processor(prompt, images, return_tensors="pt")
    return inputs.input_ids.shape[1]


146
147
@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
148
@pytest.mark.parametrize("image_url", TEST_IMAGE_ASSETS, indirect=True)
149
150
151
async def test_image_embedding(
    server: RemoteOpenAIServer, model_name: str, image_url: str
):
pansicheng's avatar
pansicheng committed
152
    content_text = "Represent the given image."
153
154
155
156
157
158
159
160
161
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "image_url", "image_url": {"url": image_url}},
                {"type": "text", "text": content_text},
            ],
        }
    ]
162

163
164
    response = requests.post(
        server.url_for("v1/embeddings"),
165
        json={"model": model_name, "messages": messages, "encoding_format": "float"},
166
    )
167
    response.raise_for_status()
168
169
    embeddings = EmbeddingResponse.model_validate(response.json())

170
    hf_prompt_tokens = get_hf_prompt_tokens(model_name, content_text, image_url)
pansicheng's avatar
pansicheng committed
171

172
173
174
175
    assert embeddings.id is not None
    assert len(embeddings.data) == 1
    assert len(embeddings.data[0].embedding) == 3072
    assert embeddings.usage.completion_tokens == 0
pansicheng's avatar
pansicheng committed
176
177
    assert embeddings.usage.prompt_tokens == hf_prompt_tokens
    assert embeddings.usage.total_tokens == hf_prompt_tokens