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_nvlm_d(question: str, image_urls: List[str]):
148    model_name = "nvidia/NVLM-D-72B"
149
150    # Adjust this as necessary to fit in GPU
151    llm = LLM(
152        model=model_name,
153        trust_remote_code=True,
154        max_model_len=8192,
155        tensor_parallel_size=4,
156        limit_mm_per_prompt={"image": len(image_urls)},
157        mm_processor_kwargs={"max_dynamic_patch": 4},
158    )
159
160    placeholders = "\n".join(f"Image-{i}: <image>\n"
161                             for i, _ in enumerate(image_urls, start=1))
162    messages = [{'role': 'user', 'content': f"{placeholders}\n{question}"}]
163
164    tokenizer = AutoTokenizer.from_pretrained(model_name,
165                                              trust_remote_code=True)
166    prompt = tokenizer.apply_chat_template(messages,
167                                           tokenize=False,
168                                           add_generation_prompt=True)
169    stop_token_ids = None
170
171    return ModelRequestData(
172        llm=llm,
173        prompt=prompt,
174        stop_token_ids=stop_token_ids,
175        image_data=[fetch_image(url) for url in image_urls],
176        chat_template=None,
177    )
178
179
180def load_qwen2_vl(question, image_urls: List[str]) -> ModelRequestData:
181    try:
182        from qwen_vl_utils import process_vision_info
183    except ModuleNotFoundError:
184        print('WARNING: `qwen-vl-utils` not installed, input images will not '
185              'be automatically resized. You can enable this functionality by '
186              '`pip install qwen-vl-utils`.')
187        process_vision_info = None
188
189    model_name = "Qwen/Qwen2-VL-7B-Instruct"
190
191    # Tested on L40
192    llm = LLM(
193        model=model_name,
194        max_model_len=32768 if process_vision_info is None else 4096,
195        max_num_seqs=5,
196        limit_mm_per_prompt={"image": len(image_urls)},
197    )
198
199    placeholders = [{"type": "image", "image": url} for url in image_urls]
200    messages = [{
201        "role": "system",
202        "content": "You are a helpful assistant."
203    }, {
204        "role":
205        "user",
206        "content": [
207            *placeholders,
208            {
209                "type": "text",
210                "text": question
211            },
212        ],
213    }]
214
215    processor = AutoProcessor.from_pretrained(model_name)
216
217    prompt = processor.apply_chat_template(messages,
218                                           tokenize=False,
219                                           add_generation_prompt=True)
220
221    stop_token_ids = None
222
223    if process_vision_info is None:
224        image_data = [fetch_image(url) for url in image_urls]
225    else:
226        image_data, _ = process_vision_info(messages)
227
228    return ModelRequestData(
229        llm=llm,
230        prompt=prompt,
231        stop_token_ids=stop_token_ids,
232        image_data=image_data,
233        chat_template=None,
234    )
235
236
237def load_mllama(question, image_urls: List[str]) -> ModelRequestData:
238    model_name = "meta-llama/Llama-3.2-11B-Vision-Instruct"
239
240    # The configuration below has been confirmed to launch on a single L40 GPU.
241    llm = LLM(
242        model=model_name,
243        max_model_len=4096,
244        max_num_seqs=16,
245        enforce_eager=True,
246        limit_mm_per_prompt={"image": len(image_urls)},
247    )
248
249    prompt = f"<|image|><|image|><|begin_of_text|>{question}"
250    return ModelRequestData(
251        llm=llm,
252        prompt=prompt,
253        stop_token_ids=None,
254        image_data=[fetch_image(url) for url in image_urls],
255        chat_template=None,
256    )
257
258
259model_example_map = {
260    "phi3_v": load_phi3v,
261    "internvl_chat": load_internvl,
262    "NVLM_D": load_nvlm_d,
263    "qwen2_vl": load_qwen2_vl,
264    "qwen_vl_chat": load_qwenvl_chat,
265    "mllama": load_mllama,
266}
267
268
269def run_generate(model, question: str, image_urls: List[str]):
270    req_data = model_example_map[model](question, image_urls)
271
272    sampling_params = SamplingParams(temperature=0.0,
273                                     max_tokens=128,
274                                     stop_token_ids=req_data.stop_token_ids)
275
276    outputs = req_data.llm.generate(
277        {
278            "prompt": req_data.prompt,
279            "multi_modal_data": {
280                "image": req_data.image_data
281            },
282        },
283        sampling_params=sampling_params)
284
285    for o in outputs:
286        generated_text = o.outputs[0].text
287        print(generated_text)
288
289
290def run_chat(model: str, question: str, image_urls: List[str]):
291    req_data = model_example_map[model](question, image_urls)
292
293    sampling_params = SamplingParams(temperature=0.0,
294                                     max_tokens=128,
295                                     stop_token_ids=req_data.stop_token_ids)
296    outputs = req_data.llm.chat(
297        [{
298            "role":
299            "user",
300            "content": [
301                {
302                    "type": "text",
303                    "text": question,
304                },
305                *({
306                    "type": "image_url",
307                    "image_url": {
308                        "url": image_url
309                    },
310                } for image_url in image_urls),
311            ],
312        }],
313        sampling_params=sampling_params,
314        chat_template=req_data.chat_template,
315    )
316
317    for o in outputs:
318        generated_text = o.outputs[0].text
319        print(generated_text)
320
321
322def main(args: Namespace):
323    model = args.model_type
324    method = args.method
325
326    if method == "generate":
327        run_generate(model, QUESTION, IMAGE_URLS)
328    elif method == "chat":
329        run_chat(model, QUESTION, IMAGE_URLS)
330    else:
331        raise ValueError(f"Invalid method: {method}")
332
333
334if __name__ == "__main__":
335    parser = FlexibleArgumentParser(
336        description='Demo on using vLLM for offline inference with '
337        'vision language models that support multi-image input')
338    parser.add_argument('--model-type',
339                        '-m',
340                        type=str,
341                        default="phi3_v",
342                        choices=model_example_map.keys(),
343                        help='Huggingface "model_type".')
344    parser.add_argument("--method",
345                        type=str,
346                        default="generate",
347                        choices=["generate", "chat"],
348                        help="The method to run in `vllm.LLM`.")
349
350    args = parser.parse_args()
351    main(args)