vision_language_embedding.py 5.7 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
Cyrus Leung's avatar
Cyrus Leung committed
3
4
5
6
7
8
9
"""
This example shows how to use vLLM for running offline inference with
the correct prompt format on vision language models for multimodal embedding.

For most models, the prompt format should follow corresponding examples
on HuggingFace model repository.
"""
10

Cyrus Leung's avatar
Cyrus Leung committed
11
from argparse import Namespace
12
from dataclasses import asdict
Cyrus Leung's avatar
Cyrus Leung committed
13
14
15
16
from typing import Literal, NamedTuple, Optional, TypedDict, Union, get_args

from PIL.Image import Image

17
from vllm import LLM, EngineArgs
Cyrus Leung's avatar
Cyrus Leung committed
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from vllm.multimodal.utils import fetch_image
from vllm.utils import FlexibleArgumentParser


class TextQuery(TypedDict):
    modality: Literal["text"]
    text: str


class ImageQuery(TypedDict):
    modality: Literal["image"]
    image: Image


class TextImageQuery(TypedDict):
    modality: Literal["text+image"]
    text: str
    image: Image


QueryModality = Literal["text", "image", "text+image"]
Query = Union[TextQuery, ImageQuery, TextImageQuery]


class ModelRequestData(NamedTuple):
43
    engine_args: EngineArgs
Cyrus Leung's avatar
Cyrus Leung committed
44
45
46
47
    prompt: str
    image: Optional[Image]


48
def run_e5_v(query: Query) -> ModelRequestData:
49
    llama3_template = "<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n \n"  # noqa: E501
Cyrus Leung's avatar
Cyrus Leung committed
50
51
52

    if query["modality"] == "text":
        text = query["text"]
53
        prompt = llama3_template.format(f"{text}\nSummary above sentence in one word: ")
Cyrus Leung's avatar
Cyrus Leung committed
54
55
        image = None
    elif query["modality"] == "image":
56
        prompt = llama3_template.format("<image>\nSummary above image in one word: ")
Cyrus Leung's avatar
Cyrus Leung committed
57
58
        image = query["image"]
    else:
59
        modality = query["modality"]
Cyrus Leung's avatar
Cyrus Leung committed
60
61
        raise ValueError(f"Unsupported query modality: '{modality}'")

62
    engine_args = EngineArgs(
Cyrus Leung's avatar
Cyrus Leung committed
63
        model="royokong/e5-v",
64
        task="embed",
Cyrus Leung's avatar
Cyrus Leung committed
65
        max_model_len=4096,
66
        limit_mm_per_prompt={"image": 1},
Cyrus Leung's avatar
Cyrus Leung committed
67
68
69
    )

    return ModelRequestData(
70
        engine_args=engine_args,
Cyrus Leung's avatar
Cyrus Leung committed
71
72
73
74
75
        prompt=prompt,
        image=image,
    )


76
def run_vlm2vec(query: Query) -> ModelRequestData:
Cyrus Leung's avatar
Cyrus Leung committed
77
78
79
80
81
82
83
84
85
    if query["modality"] == "text":
        text = query["text"]
        prompt = f"Find me an everyday image that matches the given caption: {text}"  # noqa: E501
        image = None
    elif query["modality"] == "image":
        prompt = "<|image_1|> Find a day-to-day image that looks similar to the provided image."  # noqa: E501
        image = query["image"]
    elif query["modality"] == "text+image":
        text = query["text"]
86
87
88
        prompt = (
            f"<|image_1|> Represent the given image with the following question: {text}"  # noqa: E501
        )
Cyrus Leung's avatar
Cyrus Leung committed
89
90
        image = query["image"]
    else:
91
        modality = query["modality"]
Cyrus Leung's avatar
Cyrus Leung committed
92
93
        raise ValueError(f"Unsupported query modality: '{modality}'")

94
    engine_args = EngineArgs(
Cyrus Leung's avatar
Cyrus Leung committed
95
        model="TIGER-Lab/VLM2Vec-Full",
96
        task="embed",
Cyrus Leung's avatar
Cyrus Leung committed
97
98
        trust_remote_code=True,
        mm_processor_kwargs={"num_crops": 4},
99
        limit_mm_per_prompt={"image": 1},
Cyrus Leung's avatar
Cyrus Leung committed
100
101
102
    )

    return ModelRequestData(
103
        engine_args=engine_args,
Cyrus Leung's avatar
Cyrus Leung committed
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
130
131
132
133
        prompt=prompt,
        image=image,
    )


def get_query(modality: QueryModality):
    if modality == "text":
        return TextQuery(modality="text", text="A dog sitting in the grass")

    if modality == "image":
        return ImageQuery(
            modality="image",
            image=fetch_image(
                "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/American_Eskimo_Dog.jpg/360px-American_Eskimo_Dog.jpg"  # noqa: E501
            ),
        )

    if modality == "text+image":
        return TextImageQuery(
            modality="text+image",
            text="A cat standing in the snow.",
            image=fetch_image(
                "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Felis_catus-cat_on_snow.jpg/179px-Felis_catus-cat_on_snow.jpg"  # noqa: E501
            ),
        )

    msg = f"Modality {modality} is not supported."
    raise ValueError(msg)


134
def run_encode(model: str, modality: QueryModality, seed: Optional[int]):
Cyrus Leung's avatar
Cyrus Leung committed
135
136
137
    query = get_query(modality)
    req_data = model_example_map[model](query)

138
139
140
    # Disable other modalities to save memory
    default_limits = {"image": 0, "video": 0, "audio": 0}
    req_data.engine_args.limit_mm_per_prompt = default_limits | dict(
141
142
        req_data.engine_args.limit_mm_per_prompt or {}
    )
143

144
145
146
    engine_args = asdict(req_data.engine_args) | {"seed": seed}
    llm = LLM(**engine_args)

Cyrus Leung's avatar
Cyrus Leung committed
147
148
149
150
    mm_data = {}
    if req_data.image is not None:
        mm_data["image"] = req_data.image

151
152
153
154
155
156
    outputs = llm.embed(
        {
            "prompt": req_data.prompt,
            "multi_modal_data": mm_data,
        }
    )
Cyrus Leung's avatar
Cyrus Leung committed
157

158
    print("-" * 50)
Cyrus Leung's avatar
Cyrus Leung committed
159
160
    for output in outputs:
        print(output.outputs.embedding)
161
        print("-" * 50)
Cyrus Leung's avatar
Cyrus Leung committed
162
163
164
165
166
167
168


model_example_map = {
    "e5_v": run_e5_v,
    "vlm2vec": run_vlm2vec,
}

169
170

def parse_args():
Cyrus Leung's avatar
Cyrus Leung committed
171
    parser = FlexibleArgumentParser(
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
        description="Demo on using vLLM for offline inference with "
        "vision language models for multimodal embedding"
    )
    parser.add_argument(
        "--model-name",
        "-m",
        type=str,
        default="vlm2vec",
        choices=model_example_map.keys(),
        help="The name of the embedding model.",
    )
    parser.add_argument(
        "--modality",
        type=str,
        default="image",
        choices=get_args(QueryModality),
        help="Modality of the input.",
    )
    parser.add_argument(
        "--seed",
        type=int,
        default=None,
        help="Set the seed when initializing `vllm.LLM`.",
    )
196
    return parser.parse_args()
197

198
199
200
201
202
203
204

def main(args: Namespace):
    run_encode(args.model_name, args.modality, args.seed)


if __name__ == "__main__":
    args = parse_args()
Cyrus Leung's avatar
Cyrus Leung committed
205
    main(args)