Offline Inference Vision Language Multi Image#

Source vllm-project/vllm.

  1"""
  2This example shows how to use vLLM for running offline inference with
  3multi-image input on vision language models, using the chat template defined
  4by the model.
  5"""
  6from argparse import Namespace
  7from typing import List, NamedTuple, Optional
  8
  9from PIL.Image import Image
 10from transformers import AutoProcessor, AutoTokenizer
 11
 12from vllm import LLM, SamplingParams
 13from vllm.multimodal.utils import fetch_image
 14from vllm.utils import FlexibleArgumentParser
 15
 16QUESTION = "What is the content of each image?"
 17IMAGE_URLS = [
 18    "https://upload.wikimedia.org/wikipedia/commons/d/da/2015_Kaczka_krzy%C5%BCowka_w_wodzie_%28samiec%29.jpg",
 19    "https://upload.wikimedia.org/wikipedia/commons/7/77/002_The_lion_king_Snyggve_in_the_Serengeti_National_Park_Photo_by_Giles_Laurent.jpg",
 20]
 21
 22
 23class ModelRequestData(NamedTuple):
 24    llm: LLM
 25    prompt: str
 26    stop_token_ids: Optional[List[str]]
 27    image_data: List[Image]
 28    chat_template: Optional[str]
 29
 30
 31# NOTE: The default `max_num_seqs` and `max_model_len` may result in OOM on
 32# lower-end GPUs.
 33# Unless specified, these settings have been tested to work on a single L4.
 34
 35
 36def load_qwenvl_chat(question: str, image_urls: List[str]) -> ModelRequestData:
 37    model_name = "Qwen/Qwen-VL-Chat"
 38    llm = LLM(
 39        model=model_name,
 40        trust_remote_code=True,
 41        max_model_len=1024,
 42        max_num_seqs=2,
 43        limit_mm_per_prompt={"image": len(image_urls)},
 44    )
 45    placeholders = "".join(f"Picture {i}: <img></img>\n"
 46                           for i, _ in enumerate(image_urls, start=1))
 47
 48    # This model does not have a chat_template attribute on its tokenizer,
 49    # so we need to explicitly pass it. We use ChatML since it's used in the
 50    # generation utils of the model:
 51    # https://huggingface.co/Qwen/Qwen-VL-Chat/blob/main/qwen_generation_utils.py#L265
 52    tokenizer = AutoTokenizer.from_pretrained(model_name,
 53                                              trust_remote_code=True)
 54
 55    # Copied from: https://huggingface.co/docs/transformers/main/en/chat_templating
 56    chat_template = "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"  # noqa: E501
 57
 58    messages = [{'role': 'user', 'content': f"{placeholders}\n{question}"}]
 59    prompt = tokenizer.apply_chat_template(messages,
 60                                           tokenize=False,
 61                                           add_generation_prompt=True,
 62                                           chat_template=chat_template)
 63
 64    stop_tokens = ["<|endoftext|>", "<|im_start|>", "<|im_end|>"]
 65    stop_token_ids = [tokenizer.convert_tokens_to_ids(i) for i in stop_tokens]
 66    return ModelRequestData(
 67        llm=llm,
 68        prompt=prompt,
 69        stop_token_ids=stop_token_ids,
 70        image_data=[fetch_image(url) for url in image_urls],
 71        chat_template=chat_template,
 72    )
 73
 74
 75def load_phi3v(question: str, image_urls: List[str]) -> ModelRequestData:
 76    # num_crops is an override kwarg to the multimodal image processor;
 77    # For some models, e.g., Phi-3.5-vision-instruct, it is recommended
 78    # to use 16 for single frame scenarios, and 4 for multi-frame.
 79    #
 80    # Generally speaking, a larger value for num_crops results in more
 81    # tokens per image instance, because it may scale the image more in
 82    # the image preprocessing. Some references in the model docs and the
 83    # formula for image tokens after the preprocessing
 84    # transform can be found below.
 85    #
 86    # https://huggingface.co/microsoft/Phi-3.5-vision-instruct#loading-the-model-locally
 87    # https://huggingface.co/microsoft/Phi-3.5-vision-instruct/blob/main/processing_phi3_v.py#L194
 88    llm = LLM(
 89        model="microsoft/Phi-3.5-vision-instruct",
 90        trust_remote_code=True,
 91        max_model_len=4096,
 92        max_num_seqs=2,
 93        limit_mm_per_prompt={"image": len(image_urls)},
 94        mm_processor_kwargs={"num_crops": 4},
 95    )
 96    placeholders = "\n".join(f"<|image_{i}|>"
 97                             for i, _ in enumerate(image_urls, start=1))
 98    prompt = f"<|user|>\n{placeholders}\n{question}<|end|>\n<|assistant|>\n"
 99    stop_token_ids = None
100
101    return ModelRequestData(
102        llm=llm,
103        prompt=prompt,
104        stop_token_ids=stop_token_ids,
105        image_data=[fetch_image(url) for url in image_urls],
106        chat_template=None,
107    )
108
109
110def load_internvl(question: str, image_urls: List[str]) -> ModelRequestData:
111    model_name = "OpenGVLab/InternVL2-2B"
112
113    llm = LLM(
114        model=model_name,
115        trust_remote_code=True,
116        max_model_len=4096,
117        limit_mm_per_prompt={"image": len(image_urls)},
118        mm_processor_kwargs={"max_dynamic_patch": 4},
119    )
120
121    placeholders = "\n".join(f"Image-{i}: <image>\n"
122                             for i, _ in enumerate(image_urls, start=1))
123    messages = [{'role': 'user', 'content': f"{placeholders}\n{question}"}]
124
125    tokenizer = AutoTokenizer.from_pretrained(model_name,
126                                              trust_remote_code=True)
127    prompt = tokenizer.apply_chat_template(messages,
128                                           tokenize=False,
129                                           add_generation_prompt=True)
130
131    # Stop tokens for InternVL
132    # models variants may have different stop tokens
133    # please refer to the model card for the correct "stop words":
134    # https://huggingface.co/OpenGVLab/InternVL2-2B#service
135    stop_tokens = ["<|endoftext|>", "<|im_start|>", "<|im_end|>", "<|end|>"]
136    stop_token_ids = [tokenizer.convert_tokens_to_ids(i) for i in stop_tokens]
137
138    return ModelRequestData(
139        llm=llm,
140        prompt=prompt,
141        stop_token_ids=stop_token_ids,
142        image_data=[fetch_image(url) for url in image_urls],
143        chat_template=None,
144    )
145
146
147def load_qwen2_vl(question, image_urls: List[str]) -> ModelRequestData:
148    try:
149        from qwen_vl_utils import process_vision_info
150    except ModuleNotFoundError:
151        print('WARNING: `qwen-vl-utils` not installed, input images will not '
152              'be automatically resized. You can enable this functionality by '
153              '`pip install qwen-vl-utils`.')
154        process_vision_info = None
155
156    model_name = "Qwen/Qwen2-VL-7B-Instruct"
157
158    # Tested on L40
159    llm = LLM(
160        model=model_name,
161        max_model_len=32768 if process_vision_info is None else 4096,
162        max_num_seqs=5,
163        limit_mm_per_prompt={"image": len(image_urls)},
164    )
165
166    placeholders = [{"type": "image", "image": url} for url in image_urls]
167    messages = [{
168        "role": "system",
169        "content": "You are a helpful assistant."
170    }, {
171        "role":
172        "user",
173        "content": [
174            *placeholders,
175            {
176                "type": "text",
177                "text": question
178            },
179        ],
180    }]
181
182    processor = AutoProcessor.from_pretrained(model_name)
183
184    prompt = processor.apply_chat_template(messages,
185                                           tokenize=False,
186                                           add_generation_prompt=True)
187
188    stop_token_ids = None
189
190    if process_vision_info is None:
191        image_data = [fetch_image(url) for url in image_urls]
192    else:
193        image_data, _ = process_vision_info(messages)
194
195    return ModelRequestData(
196        llm=llm,
197        prompt=prompt,
198        stop_token_ids=stop_token_ids,
199        image_data=image_data,
200        chat_template=None,
201    )
202
203
204model_example_map = {
205    "phi3_v": load_phi3v,
206    "internvl_chat": load_internvl,
207    "qwen2_vl": load_qwen2_vl,
208    "qwen_vl_chat": load_qwenvl_chat,
209}
210
211
212def run_generate(model, question: str, image_urls: List[str]):
213    req_data = model_example_map[model](question, image_urls)
214
215    sampling_params = SamplingParams(temperature=0.0,
216                                     max_tokens=128,
217                                     stop_token_ids=req_data.stop_token_ids)
218
219    outputs = req_data.llm.generate(
220        {
221            "prompt": req_data.prompt,
222            "multi_modal_data": {
223                "image": req_data.image_data
224            },
225        },
226        sampling_params=sampling_params)
227
228    for o in outputs:
229        generated_text = o.outputs[0].text
230        print(generated_text)
231
232
233def run_chat(model: str, question: str, image_urls: List[str]):
234    req_data = model_example_map[model](question, image_urls)
235
236    sampling_params = SamplingParams(temperature=0.0,
237                                     max_tokens=128,
238                                     stop_token_ids=req_data.stop_token_ids)
239    outputs = req_data.llm.chat(
240        [{
241            "role":
242            "user",
243            "content": [
244                {
245                    "type": "text",
246                    "text": question,
247                },
248                *({
249                    "type": "image_url",
250                    "image_url": {
251                        "url": image_url
252                    },
253                } for image_url in image_urls),
254            ],
255        }],
256        sampling_params=sampling_params,
257        chat_template=req_data.chat_template,
258    )
259
260    for o in outputs:
261        generated_text = o.outputs[0].text
262        print(generated_text)
263
264
265def main(args: Namespace):
266    model = args.model_type
267    method = args.method
268
269    if method == "generate":
270        run_generate(model, QUESTION, IMAGE_URLS)
271    elif method == "chat":
272        run_chat(model, QUESTION, IMAGE_URLS)
273    else:
274        raise ValueError(f"Invalid method: {method}")
275
276
277if __name__ == "__main__":
278    parser = FlexibleArgumentParser(
279        description='Demo on using vLLM for offline inference with '
280        'vision language models that support multi-image input')
281    parser.add_argument('--model-type',
282                        '-m',
283                        type=str,
284                        default="phi3_v",
285                        choices=model_example_map.keys(),
286                        help='Huggingface "model_type".')
287    parser.add_argument("--method",
288                        type=str,
289                        default="generate",
290                        choices=["generate", "chat"],
291                        help="The method to run in `vllm.LLM`.")
292
293    args = parser.parse_args()
294    main(args)