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

import pytest
Huy Do's avatar
Huy Do committed
5
6
import transformers
from packaging import version
7
8
from transformers import AutoModel

9
10
11
12
13
from vllm.entrypoints.chat_utils import (
    ChatCompletionContentPartImageEmbedsParam,
    ChatCompletionContentPartImageParam,
    ChatCompletionContentPartTextParam,
)
14
from vllm.entrypoints.pooling.scoring.typing import ScoreMultiModalParam
15
16
17

from ....conftest import HfRunner, VllmRunner

18
19
20
21
22
pytestmark = pytest.mark.skip(
    reason="jinaai/jina-reranker-m0 custom code is incompatible with "
    "transformers v5 (missing all_tied_weights_keys)"
)

23
MODELS = ["jinaai/jina-reranker-m0"]
24

25
MM_PROCESSOR_KWARGS = {
26
27
28
29
    "min_pixels": 3136,
    "max_pixels": 602112,
}

30
LIMIT_MM_PER_PROMPT = {"image": 2}
31

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
CHECKPOINT_TO_HF_MAPPER = {
    "visual.": "model.visual.",
    "model.": "model.language_model.",
}

# Shared long text for test data
LONG_TEXT_DOC = """We present ReaderLM-v2, a compact 1.5 billion parameter language model designed for efficient
web content extraction. Our model processes documents up to 512K tokens, transforming messy HTML
into clean Markdown or JSON formats with high accuracy -- making it an ideal tool for grounding
large language models. The models effectiveness results from two key innovations: (1) a three-stage
data synthesis pipeline that generates high quality, diverse training data by iteratively drafting,
refining, and critiquing web content extraction; and (2) a unified training framework combining
continuous pre-training with multi-objective optimization. Intensive evaluation demonstrates that
ReaderLM-v2 outperforms GPT-4o-2024-08-06 and other larger models by 15-20% on carefully curated
benchmarks, particularly excelling at documents exceeding 100K tokens, while maintaining significantly
lower computational requirements."""  # noqa: E501

# Test data for different scenarios
TEXT_IMAGE_TEST_DATA = {
    "query": [{"text": "slm markdown"}],
    "documents": [
        {
            "image": "https://raw.githubusercontent.com/jina-ai/multimodal-reranker-test/main/handelsblatt-preview.png"
        },
        {
            "image": "https://raw.githubusercontent.com/jina-ai/multimodal-reranker-test/main/paper-11.png"
        },
    ],
}

TEXT_TEXT_TEST_DATA = {
    "query": [{"text": "slm markdown"}],
    "documents": [
        {"text": LONG_TEXT_DOC},
        {"text": "数据提取么?为什么不用正则啊,你用正则不就全解决了么?"},
    ],
}

IMAGE_TEXT_TEST_DATA = {
    "query": [
        {
            "image": "https://raw.githubusercontent.com/jina-ai/multimodal-reranker-test/main/paper-11.png"
        }
    ],
    "documents": [
        {"text": LONG_TEXT_DOC},
        {"text": "数据提取么?为什么不用正则啊,你用正则不就全解决了么?"},
    ],
}

IMAGE_IMAGE_TEST_DATA = {
    "query": [
        {
            "image": "https://raw.githubusercontent.com/jina-ai/multimodal-reranker-test/main/paper-11.png"
        }
    ],
    "documents": [
        {
            "image": "https://raw.githubusercontent.com/jina-ai/multimodal-reranker-test/main/handelsblatt-preview.png"
        },
        {
            "image": "https://raw.githubusercontent.com/jina-ai/multimodal-reranker-test/main/paper-11.png"
        },
    ],
}
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
TEXT_MIXED_DOCS_TEST_DATA = {
    "query": [{"text": "slm markdown"}],
    "documents": [
        {"text": LONG_TEXT_DOC},
        {
            "image": "https://raw.githubusercontent.com/jina-ai/multimodal-reranker-test/main/paper-11.png"
        },
        {"text": "数据提取么?为什么不用正则啊,你用正则不就全解决了么?"},
        {
            "image": "https://raw.githubusercontent.com/jina-ai/multimodal-reranker-test/main/handelsblatt-preview.png"
        },
    ],
}


def _normalize_image(image_val: str) -> str:
    """Normalize image value to proper format for HF model."""
    return (
        image_val
        if image_val.startswith(("http://", "https://"))
        else f"data:image/png;base64,{image_val}"
    )


def create_score_multimodal_param(
    content_parts: list[dict],
124
) -> list[ScoreMultiModalParam]:
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
    """
    Create a ScoreMultiModalParam from a list of content dictionaries.

    Each dict supports the following formats:
    - Text: {'text': 'content'}
    - Image URL: {'image': 'https://...'}
    - Image Base64: {'image': 'base64_str'}
    """
    formatted_content = []

    for part in content_parts:
        if "text" in part:
            formatted_content.append(
                ChatCompletionContentPartTextParam(
                    type="text",
                    text=part["text"],
                )
            )
        elif "image" in part:
            image_val = part["image"]
            if image_val.startswith(("http://", "https://")):
                formatted_content.append(
                    ChatCompletionContentPartImageParam(
                        type="image_url",
                        image_url={"url": image_val},
                    )
                )
            else:
                formatted_content.append(
                    ChatCompletionContentPartImageEmbedsParam(
                        type="image_embeds", image_embeds=image_val
                    )
                )

159
    return [ScoreMultiModalParam(content=[content]) for content in formatted_content]
160
161
162


def _run_vllm(
163
    vllm_runner: type[VllmRunner],
164
    model: str,
165
    dtype: str,
166
167
168
169
170
171
    query_strs: list[dict[str, str]],
    document_strs: list[dict[str, str]],
) -> list[float]:
    """Run vLLM reranker and return scores."""
    query = create_score_multimodal_param(query_strs)
    documents = create_score_multimodal_param(document_strs)
172
173

    with vllm_runner(
174
        model,
175
176
177
178
        runner="pooling",
        dtype=dtype,
        max_num_seqs=2,
        max_model_len=2048,
179
180
        mm_processor_kwargs=MM_PROCESSOR_KWARGS,
        limit_mm_per_prompt=LIMIT_MM_PER_PROMPT,
181
    ) as vllm_model:
182
        outputs = vllm_model.llm.score(query, documents)
183
184
185
186

    return [output.outputs.score for output in outputs]


187
def _run_hf(
188
    hf_runner: type[HfRunner],
189
    model: str,
190
    dtype: str,
191
192
193
194
195
196
197
198
199
200
201
202
203
204
    query_strs: list[dict[str, str]],
    document_strs: list[dict[str, str]],
) -> list[float]:
    """Run HuggingFace reranker and return scores."""
    query = query_strs[0]
    if "text" in query:
        query_type = "text"
        query_data = query["text"]
    elif "image" in query:
        query_type = "image"
        query_data = _normalize_image(query["image"])
    else:
        raise ValueError("Unsupported query format")

205
    scores: list[float] = []
206

207
    with hf_runner(
208
        model,
209
210
211
        dtype=dtype,
        trust_remote_code=True,
        auto_cls=AutoModel,
212
        model_kwargs={"key_mapping": CHECKPOINT_TO_HF_MAPPER},
213
    ) as hf_model:
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
        for doc in document_strs:
            if "text" in doc:
                score = hf_model.model.compute_score(
                    [[query_data, doc["text"]]],
                    max_length=2048,
                    query_type=query_type,
                    doc_type="text",
                )
                scores.append(score)
            elif "image" in doc:
                score = hf_model.model.compute_score(
                    [[query_data, doc["image"]]],
                    max_length=2048,
                    query_type=query_type,
                    doc_type="image",
                )
                scores.append(score)
    return scores
232
233


234
235
236
237
238
239
240
241
242
243
244
245
246
def _run_test(
    hf_runner: type[HfRunner],
    vllm_runner: type[VllmRunner],
    model: str,
    dtype: str,
    query_strs: list[dict[str, str]],
    document_strs: list[dict[str, str]],
) -> None:
    """Run comparison test between vLLM and HuggingFace implementations."""
    # 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).
247

248
249
250
251
252
253
    vllm_outputs = _run_vllm(vllm_runner, model, dtype, query_strs, document_strs)
    hf_outputs = _run_hf(hf_runner, model, dtype, query_strs, document_strs)

    # Compare outputs
    assert len(hf_outputs) == len(vllm_outputs), (
        f"Output length mismatch: HF={len(hf_outputs)}, vLLM={len(vllm_outputs)}"
254
    )
255

256
257
258
259
    for i, (hf_score, vllm_score) in enumerate(zip(hf_outputs, vllm_outputs)):
        assert hf_score == pytest.approx(vllm_score, rel=0.02), (
            f"Score mismatch at index {i}: HF={hf_score}, vLLM={vllm_score}"
        )
260
261


262
@pytest.mark.parametrize("model", MODELS)
263
@pytest.mark.parametrize("dtype", ["half"])
Huy Do's avatar
Huy Do committed
264
265
266
267
@pytest.mark.skipif(
    version.parse(transformers.__version__) == version.parse("4.57.5"),
    reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
)
268
269
270
271
272
273
274
275
276
277
278
279
280
281
def test_model_text_image(
    hf_runner,
    vllm_runner,
    model: str,
    dtype: str,
) -> None:
    """Visual Documents Reranking"""
    _run_test(
        hf_runner,
        vllm_runner,
        model,
        dtype,
        TEXT_IMAGE_TEST_DATA["query"],
        TEXT_IMAGE_TEST_DATA["documents"],
282
    )
283

284
285
286

@pytest.mark.parametrize("model", MODELS)
@pytest.mark.parametrize("dtype", ["half"])
Huy Do's avatar
Huy Do committed
287
288
289
290
@pytest.mark.skipif(
    version.parse(transformers.__version__) == version.parse("4.57.5"),
    reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
)
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def test_model_text_text(
    hf_runner,
    vllm_runner,
    model: str,
    dtype: str,
) -> None:
    """Textual Documents Reranking"""
    _run_test(
        hf_runner,
        vllm_runner,
        model,
        dtype,
        TEXT_TEXT_TEST_DATA["query"],
        TEXT_TEXT_TEST_DATA["documents"],
    )
306
307


308
@pytest.mark.parametrize("model", MODELS)
309
@pytest.mark.parametrize("dtype", ["half"])
Huy Do's avatar
Huy Do committed
310
311
312
313
@pytest.mark.skipif(
    version.parse(transformers.__version__) == version.parse("4.57.5"),
    reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
)
314
315
316
317
318
319
320
321
322
323
324
325
326
327
def test_model_image_text(
    hf_runner,
    vllm_runner,
    model: str,
    dtype: str,
) -> None:
    """Image Querying for Textual Documents"""
    _run_test(
        hf_runner,
        vllm_runner,
        model,
        dtype,
        IMAGE_TEXT_TEST_DATA["query"],
        IMAGE_TEXT_TEST_DATA["documents"],
328
    )
329
330
331
332


@pytest.mark.parametrize("model", MODELS)
@pytest.mark.parametrize("dtype", ["half"])
Huy Do's avatar
Huy Do committed
333
334
335
336
@pytest.mark.skipif(
    version.parse(transformers.__version__) == version.parse("4.57.5"),
    reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
)
337
338
339
340
341
342
343
344
345
346
347
348
349
350
def test_model_image_image(
    hf_runner,
    vllm_runner,
    model: str,
    dtype: str,
) -> None:
    """Image Querying for Image Documents"""
    _run_test(
        hf_runner,
        vllm_runner,
        model,
        dtype,
        IMAGE_IMAGE_TEST_DATA["query"],
        IMAGE_IMAGE_TEST_DATA["documents"],
351
    )
352

353
354
355

@pytest.mark.parametrize("model", MODELS)
@pytest.mark.parametrize("dtype", ["half"])
Huy Do's avatar
Huy Do committed
356
357
358
359
@pytest.mark.skipif(
    version.parse(transformers.__version__) == version.parse("4.57.5"),
    reason="Skipped for transformers==4.57.5, https://github.com/huggingface/transformers/issues/43295",
)
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
def test_model_text_mixed_documents(
    hf_runner,
    vllm_runner,
    model: str,
    dtype: str,
) -> None:
    """Text Query for Mixed Text and Image Documents"""
    _run_test(
        hf_runner,
        vllm_runner,
        model,
        dtype,
        TEXT_MIXED_DOCS_TEST_DATA["query"],
        TEXT_MIXED_DOCS_TEST_DATA["documents"],
    )