vision_language_multi_image.py 24.3 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
3
"""
This example shows how to use vLLM for running offline inference with
Cyrus Leung's avatar
Cyrus Leung committed
4
5
multi-image input on vision language models for text generation,
using the chat template defined by the model.
6
"""
7
import os
8
from argparse import Namespace
9
from dataclasses import asdict
10
from typing import NamedTuple, Optional
11

12
from huggingface_hub import snapshot_download
13
from PIL.Image import Image
14
from transformers import AutoProcessor, AutoTokenizer
15

16
from vllm import LLM, EngineArgs, SamplingParams
17
from vllm.lora.request import LoRARequest
18
19
20
21
22
23
24
25
26
27
from vllm.multimodal.utils import fetch_image
from vllm.utils import FlexibleArgumentParser

QUESTION = "What is the content of each image?"
IMAGE_URLS = [
    "https://upload.wikimedia.org/wikipedia/commons/d/da/2015_Kaczka_krzy%C5%BCowka_w_wodzie_%28samiec%29.jpg",
    "https://upload.wikimedia.org/wikipedia/commons/7/77/002_The_lion_king_Snyggve_in_the_Serengeti_National_Park_Photo_by_Giles_Laurent.jpg",
]


28
class ModelRequestData(NamedTuple):
29
    engine_args: EngineArgs
30
    prompt: str
31
    image_data: list[Image]
32
33
34
    stop_token_ids: Optional[list[int]] = None
    chat_template: Optional[str] = None
    lora_requests: Optional[list[LoRARequest]] = None
35
36


37
38
39
40
41
# NOTE: The default `max_num_seqs` and `max_model_len` may result in OOM on
# lower-end GPUs.
# Unless specified, these settings have been tested to work on a single L4.


42
def load_aria(question: str, image_urls: list[str]) -> ModelRequestData:
43
    model_name = "rhymes-ai/Aria"
44
45
46
47
48
49
50
    engine_args = EngineArgs(
        model=model_name,
        tokenizer_mode="slow",
        trust_remote_code=True,
        dtype="bfloat16",
        limit_mm_per_prompt={"image": len(image_urls)},
    )
51
52
53
54
    placeholders = "<fim_prefix><|img|><fim_suffix>\n" * len(image_urls)
    prompt = (f"<|im_start|>user\n{placeholders}{question}<|im_end|>\n"
              "<|im_start|>assistant\n")
    stop_token_ids = [93532, 93653, 944, 93421, 1019, 93653, 93519]
55

56
    return ModelRequestData(
57
        engine_args=engine_args,
58
59
60
        prompt=prompt,
        stop_token_ids=stop_token_ids,
        image_data=[fetch_image(url) for url in image_urls],
61
    )
62

63

Jennifer Zhao's avatar
Jennifer Zhao committed
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
def load_aya_vision(question: str, image_urls: list[str]) -> ModelRequestData:
    model_name = "CohereForAI/aya-vision-8b"

    engine_args = EngineArgs(
        model=model_name,
        max_num_seqs=2,
        limit_mm_per_prompt={"image": len(image_urls)},
    )

    placeholders = [{"type": "image", "image": url} for url in image_urls]
    messages = [{
        "role":
        "user",
        "content": [
            *placeholders,
            {
                "type": "text",
                "text": question
            },
        ],
    }]

    processor = AutoProcessor.from_pretrained(model_name)

    prompt = processor.apply_chat_template(messages,
                                           tokenize=False,
                                           add_generation_prompt=True)

    return ModelRequestData(
        engine_args=engine_args,
        prompt=prompt,
        image_data=[fetch_image(url) for url in image_urls],
    )


99
100
def load_deepseek_vl2(question: str,
                      image_urls: list[str]) -> ModelRequestData:
101
    model_name = "deepseek-ai/deepseek-vl2-tiny"
102

103
104
105
106
107
108
109
    engine_args = EngineArgs(
        model=model_name,
        max_model_len=4096,
        max_num_seqs=2,
        hf_overrides={"architectures": ["DeepseekVLV2ForCausalLM"]},
        limit_mm_per_prompt={"image": len(image_urls)},
    )
110
111
112
113
114
115

    placeholder = "".join(f"image_{i}:<image>\n"
                          for i, _ in enumerate(image_urls, start=1))
    prompt = f"<|User|>: {placeholder}{question}\n\n<|Assistant|>:"

    return ModelRequestData(
116
        engine_args=engine_args,
117
118
119
120
121
        prompt=prompt,
        image_data=[fetch_image(url) for url in image_urls],
    )


122
def load_gemma3(question: str, image_urls: list[str]) -> ModelRequestData:
123
124
    model_name = "google/gemma-3-4b-it"

125
    engine_args = EngineArgs(
126
127
128
129
130
        model=model_name,
        max_model_len=8192,
        max_num_seqs=2,
        limit_mm_per_prompt={"image": len(image_urls)},
    )
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151

    placeholders = [{"type": "image", "image": url} for url in image_urls]
    messages = [{
        "role":
        "user",
        "content": [
            *placeholders,
            {
                "type": "text",
                "text": question
            },
        ],
    }]

    processor = AutoProcessor.from_pretrained(model_name)

    prompt = processor.apply_chat_template(messages,
                                           tokenize=False,
                                           add_generation_prompt=True)

    return ModelRequestData(
152
        engine_args=engine_args,
153
154
155
156
157
        prompt=prompt,
        image_data=[fetch_image(url) for url in image_urls],
    )


158
def load_h2ovl(question: str, image_urls: list[str]) -> ModelRequestData:
159
    model_name = "h2oai/h2ovl-mississippi-800m"
160

161
    engine_args = EngineArgs(
162
163
164
165
        model=model_name,
        trust_remote_code=True,
        max_model_len=8192,
        limit_mm_per_prompt={"image": len(image_urls)},
166
        mm_processor_kwargs={"max_dynamic_patch": 4},
167
168
169
170
171
172
173
174
175
176
177
178
179
    )

    placeholders = "\n".join(f"Image-{i}: <image>\n"
                             for i, _ in enumerate(image_urls, start=1))
    messages = [{'role': 'user', 'content': f"{placeholders}\n{question}"}]

    tokenizer = AutoTokenizer.from_pretrained(model_name,
                                              trust_remote_code=True)
    prompt = tokenizer.apply_chat_template(messages,
                                           tokenize=False,
                                           add_generation_prompt=True)

    # Stop tokens for H2OVL-Mississippi
180
    # https://huggingface.co/h2oai/h2ovl-mississippi-800m
181
182
183
    stop_token_ids = [tokenizer.eos_token_id]

    return ModelRequestData(
184
        engine_args=engine_args,
185
186
187
188
189
190
        prompt=prompt,
        stop_token_ids=stop_token_ids,
        image_data=[fetch_image(url) for url in image_urls],
    )


191
def load_idefics3(question: str, image_urls: list[str]) -> ModelRequestData:
192
193
194
    model_name = "HuggingFaceM4/Idefics3-8B-Llama3"

    # The configuration below has been confirmed to launch on a single L40 GPU.
195
    engine_args = EngineArgs(
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
        model=model_name,
        max_model_len=8192,
        max_num_seqs=16,
        enforce_eager=True,
        limit_mm_per_prompt={"image": len(image_urls)},
        # if you are running out of memory, you can reduce the "longest_edge".
        # see: https://huggingface.co/HuggingFaceM4/Idefics3-8B-Llama3#model-optimizations
        mm_processor_kwargs={
            "size": {
                "longest_edge": 2 * 364
            },
        },
    )

    placeholders = "\n".join(f"Image-{i}: <image>\n"
                             for i, _ in enumerate(image_urls, start=1))
    prompt = f"<|begin_of_text|>User:{placeholders}\n{question}<end_of_utterance>\nAssistant:"  # noqa: E501
    return ModelRequestData(
214
        engine_args=engine_args,
215
216
217
218
219
        prompt=prompt,
        image_data=[fetch_image(url) for url in image_urls],
    )


220
def load_internvl(question: str, image_urls: list[str]) -> ModelRequestData:
221
222
    model_name = "OpenGVLab/InternVL2-2B"

223
    engine_args = EngineArgs(
224
225
226
227
        model=model_name,
        trust_remote_code=True,
        max_model_len=4096,
        limit_mm_per_prompt={"image": len(image_urls)},
228
        mm_processor_kwargs={"max_dynamic_patch": 4},
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
    )

    placeholders = "\n".join(f"Image-{i}: <image>\n"
                             for i, _ in enumerate(image_urls, start=1))
    messages = [{'role': 'user', 'content': f"{placeholders}\n{question}"}]

    tokenizer = AutoTokenizer.from_pretrained(model_name,
                                              trust_remote_code=True)
    prompt = tokenizer.apply_chat_template(messages,
                                           tokenize=False,
                                           add_generation_prompt=True)

    # Stop tokens for InternVL
    # models variants may have different stop tokens
    # please refer to the model card for the correct "stop words":
244
    # https://huggingface.co/OpenGVLab/InternVL2-2B/blob/main/conversation.py
245
246
    stop_tokens = ["<|endoftext|>", "<|im_start|>", "<|im_end|>", "<|end|>"]
    stop_token_ids = [tokenizer.convert_tokens_to_ids(i) for i in stop_tokens]
247

248
    return ModelRequestData(
249
        engine_args=engine_args,
250
251
252
253
        prompt=prompt,
        stop_token_ids=stop_token_ids,
        image_data=[fetch_image(url) for url in image_urls],
    )
254
255


256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def load_llama4(question: str, image_urls: list[str]) -> ModelRequestData:
    model_name = "meta-llama/Llama-4-Scout-17B-16E-Instruct"

    engine_args = EngineArgs(
        model=model_name,
        max_model_len=8192,
        max_num_seqs=4,
        tensor_parallel_size=8,
        limit_mm_per_prompt={"image": len(image_urls)},
    )

    placeholders = [{"type": "image", "image": url} for url in image_urls]
    messages = [{
        "role":
        "user",
        "content": [
            *placeholders,
            {
                "type": "text",
                "text": question
            },
        ],
    }]

    processor = AutoProcessor.from_pretrained(model_name)

    prompt = processor.apply_chat_template(messages,
                                           tokenize=False,
                                           add_generation_prompt=True)

    return ModelRequestData(
        engine_args=engine_args,
        prompt=prompt,
        image_data=[fetch_image(url) for url in image_urls],
    )


293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def load_mistral3(question: str, image_urls: list[str]) -> ModelRequestData:
    model_name = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"

    # Adjust this as necessary to fit in GPU
    engine_args = EngineArgs(
        model=model_name,
        max_model_len=8192,
        max_num_seqs=2,
        tensor_parallel_size=2,
        limit_mm_per_prompt={"image": len(image_urls)},
    )

    placeholders = "[IMG]" * len(image_urls)
    prompt = f"<s>[INST]{question}\n{placeholders}[/INST]"

    return ModelRequestData(
        engine_args=engine_args,
        prompt=prompt,
        image_data=[fetch_image(url) for url in image_urls],
    )


315
def load_mllama(question: str, image_urls: list[str]) -> ModelRequestData:
316
317
318
    model_name = "meta-llama/Llama-3.2-11B-Vision-Instruct"

    # The configuration below has been confirmed to launch on a single L40 GPU.
319
    engine_args = EngineArgs(
320
        model=model_name,
321
322
        max_model_len=8192,
        max_num_seqs=2,
323
324
325
        limit_mm_per_prompt={"image": len(image_urls)},
    )

326
327
    img_prompt = "Given the first image <|image|> and the second image<|image|>"
    prompt = f"<|begin_of_text|>{img_prompt}, {question}?"
328
    return ModelRequestData(
329
        engine_args=engine_args,
330
331
332
333
334
        prompt=prompt,
        image_data=[fetch_image(url) for url in image_urls],
    )


335
def load_nvlm_d(question: str, image_urls: list[str]) -> ModelRequestData:
336
337
338
    model_name = "nvidia/NVLM-D-72B"

    # Adjust this as necessary to fit in GPU
339
    engine_args = EngineArgs(
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
        model=model_name,
        trust_remote_code=True,
        max_model_len=8192,
        tensor_parallel_size=4,
        limit_mm_per_prompt={"image": len(image_urls)},
        mm_processor_kwargs={"max_dynamic_patch": 4},
    )

    placeholders = "\n".join(f"Image-{i}: <image>\n"
                             for i, _ in enumerate(image_urls, start=1))
    messages = [{'role': 'user', 'content': f"{placeholders}\n{question}"}]

    tokenizer = AutoTokenizer.from_pretrained(model_name,
                                              trust_remote_code=True)
    prompt = tokenizer.apply_chat_template(messages,
                                           tokenize=False,
                                           add_generation_prompt=True)

    return ModelRequestData(
359
        engine_args=engine_args,
360
361
362
363
364
        prompt=prompt,
        image_data=[fetch_image(url) for url in image_urls],
    )


365
def load_pixtral_hf(question: str, image_urls: list[str]) -> ModelRequestData:
366
367
368
    model_name = "mistral-community/pixtral-12b"

    # Adjust this as necessary to fit in GPU
369
    engine_args = EngineArgs(
370
371
372
373
374
375
376
377
378
379
380
        model=model_name,
        max_model_len=8192,
        max_num_seqs=2,
        tensor_parallel_size=2,
        limit_mm_per_prompt={"image": len(image_urls)},
    )

    placeholders = "[IMG]" * len(image_urls)
    prompt = f"<s>[INST]{question}\n{placeholders}[/INST]"

    return ModelRequestData(
381
        engine_args=engine_args,
382
383
384
385
386
        prompt=prompt,
        image_data=[fetch_image(url) for url in image_urls],
    )


387
def load_phi3v(question: str, image_urls: list[str]) -> ModelRequestData:
388
389
390
391
392
393
394
395
396
397
398
399
    # num_crops is an override kwarg to the multimodal image processor;
    # For some models, e.g., Phi-3.5-vision-instruct, it is recommended
    # to use 16 for single frame scenarios, and 4 for multi-frame.
    #
    # Generally speaking, a larger value for num_crops results in more
    # tokens per image instance, because it may scale the image more in
    # the image preprocessing. Some references in the model docs and the
    # formula for image tokens after the preprocessing
    # transform can be found below.
    #
    # https://huggingface.co/microsoft/Phi-3.5-vision-instruct#loading-the-model-locally
    # https://huggingface.co/microsoft/Phi-3.5-vision-instruct/blob/main/processing_phi3_v.py#L194
400
    engine_args = EngineArgs(
401
402
403
404
405
406
407
408
409
410
411
412
        model="microsoft/Phi-3.5-vision-instruct",
        trust_remote_code=True,
        max_model_len=4096,
        max_num_seqs=2,
        limit_mm_per_prompt={"image": len(image_urls)},
        mm_processor_kwargs={"num_crops": 4},
    )
    placeholders = "\n".join(f"<|image_{i}|>"
                             for i, _ in enumerate(image_urls, start=1))
    prompt = f"<|user|>\n{placeholders}\n{question}<|end|>\n<|assistant|>\n"

    return ModelRequestData(
413
        engine_args=engine_args,
414
415
416
417
418
        prompt=prompt,
        image_data=[fetch_image(url) for url in image_urls],
    )


419
420
421
422
423
424
425
426
427
428
def load_phi4mm(question: str, image_urls: list[str]) -> ModelRequestData:
    """
    Phi-4-multimodal-instruct supports both image and audio inputs. Here, we
    show how to process multi images inputs.
    """

    model_path = snapshot_download("microsoft/Phi-4-multimodal-instruct")
    # Since the vision-lora and speech-lora co-exist with the base model,
    # we have to manually specify the path of the lora weights.
    vision_lora_path = os.path.join(model_path, "vision-lora")
429
    engine_args = EngineArgs(
430
431
432
433
434
435
436
437
438
439
440
441
442
443
        model=model_path,
        trust_remote_code=True,
        max_model_len=10000,
        max_num_seqs=2,
        limit_mm_per_prompt={"image": len(image_urls)},
        enable_lora=True,
        max_lora_rank=320,
    )

    placeholders = "".join(f"<|image_{i}|>"
                           for i, _ in enumerate(image_urls, start=1))
    prompt = f"<|user|>{placeholders}{question}<|end|><|assistant|>"

    return ModelRequestData(
444
        engine_args=engine_args,
445
446
        prompt=prompt,
        image_data=[fetch_image(url) for url in image_urls],
447
        lora_requests=[LoRARequest("vision", 1, vision_lora_path)],
448
449
450
    )


451
def load_qwen_vl_chat(question: str,
452
                      image_urls: list[str]) -> ModelRequestData:
453
    model_name = "Qwen/Qwen-VL-Chat"
454
    engine_args = EngineArgs(
455
456
457
458
        model=model_name,
        trust_remote_code=True,
        max_model_len=1024,
        max_num_seqs=2,
459
        hf_overrides={"architectures": ["QwenVLForConditionalGeneration"]},
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
        limit_mm_per_prompt={"image": len(image_urls)},
    )
    placeholders = "".join(f"Picture {i}: <img></img>\n"
                           for i, _ in enumerate(image_urls, start=1))

    # This model does not have a chat_template attribute on its tokenizer,
    # so we need to explicitly pass it. We use ChatML since it's used in the
    # generation utils of the model:
    # https://huggingface.co/Qwen/Qwen-VL-Chat/blob/main/qwen_generation_utils.py#L265
    tokenizer = AutoTokenizer.from_pretrained(model_name,
                                              trust_remote_code=True)

    # Copied from: https://huggingface.co/docs/transformers/main/en/chat_templating
    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

    messages = [{'role': 'user', 'content': f"{placeholders}\n{question}"}]
    prompt = tokenizer.apply_chat_template(messages,
                                           tokenize=False,
                                           add_generation_prompt=True,
                                           chat_template=chat_template)

    stop_tokens = ["<|endoftext|>", "<|im_start|>", "<|im_end|>"]
    stop_token_ids = [tokenizer.convert_tokens_to_ids(i) for i in stop_tokens]
483

484
    return ModelRequestData(
485
        engine_args=engine_args,
486
487
488
489
490
491
492
        prompt=prompt,
        stop_token_ids=stop_token_ids,
        image_data=[fetch_image(url) for url in image_urls],
        chat_template=chat_template,
    )


493
def load_qwen2_vl(question: str, image_urls: list[str]) -> ModelRequestData:
494
495
496
497
498
499
500
501
502
503
    try:
        from qwen_vl_utils import process_vision_info
    except ModuleNotFoundError:
        print('WARNING: `qwen-vl-utils` not installed, input images will not '
              'be automatically resized. You can enable this functionality by '
              '`pip install qwen-vl-utils`.')
        process_vision_info = None

    model_name = "Qwen/Qwen2-VL-7B-Instruct"

504
    # Tested on L40
505
    engine_args = EngineArgs(
506
507
        model=model_name,
        max_model_len=32768 if process_vision_info is None else 4096,
508
        max_num_seqs=5,
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
        limit_mm_per_prompt={"image": len(image_urls)},
    )

    placeholders = [{"type": "image", "image": url} for url in image_urls]
    messages = [{
        "role": "system",
        "content": "You are a helpful assistant."
    }, {
        "role":
        "user",
        "content": [
            *placeholders,
            {
                "type": "text",
                "text": question
            },
        ],
    }]

    processor = AutoProcessor.from_pretrained(model_name)

    prompt = processor.apply_chat_template(messages,
                                           tokenize=False,
                                           add_generation_prompt=True)

    if process_vision_info is None:
        image_data = [fetch_image(url) for url in image_urls]
    else:
        image_data, _ = process_vision_info(messages)

539
    return ModelRequestData(
540
        engine_args=engine_args,
541
542
543
        prompt=prompt,
        image_data=image_data,
    )
544
545


546
def load_qwen2_5_vl(question: str, image_urls: list[str]) -> ModelRequestData:
Roger Wang's avatar
Roger Wang committed
547
548
549
550
551
552
553
554
555
556
    try:
        from qwen_vl_utils import process_vision_info
    except ModuleNotFoundError:
        print('WARNING: `qwen-vl-utils` not installed, input images will not '
              'be automatically resized. You can enable this functionality by '
              '`pip install qwen-vl-utils`.')
        process_vision_info = None

    model_name = "Qwen/Qwen2.5-VL-3B-Instruct"

557
    engine_args = EngineArgs(
Roger Wang's avatar
Roger Wang committed
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
        model=model_name,
        max_model_len=32768 if process_vision_info is None else 4096,
        max_num_seqs=5,
        limit_mm_per_prompt={"image": len(image_urls)},
    )

    placeholders = [{"type": "image", "image": url} for url in image_urls]
    messages = [{
        "role": "system",
        "content": "You are a helpful assistant."
    }, {
        "role":
        "user",
        "content": [
            *placeholders,
            {
                "type": "text",
                "text": question
            },
        ],
    }]

    processor = AutoProcessor.from_pretrained(model_name)

    prompt = processor.apply_chat_template(messages,
                                           tokenize=False,
                                           add_generation_prompt=True)

    if process_vision_info is None:
        image_data = [fetch_image(url) for url in image_urls]
    else:
        image_data, _ = process_vision_info(messages,
590
                                            return_video_kwargs=False)
Roger Wang's avatar
Roger Wang committed
591
592

    return ModelRequestData(
593
        engine_args=engine_args,
Roger Wang's avatar
Roger Wang committed
594
595
596
597
598
        prompt=prompt,
        image_data=image_data,
    )


599
model_example_map = {
600
    "aria": load_aria,
Jennifer Zhao's avatar
Jennifer Zhao committed
601
    "aya_vision": load_aya_vision,
602
    "deepseek_vl_v2": load_deepseek_vl2,
603
    "gemma3": load_gemma3,
604
    "h2ovl_chat": load_h2ovl,
605
    "idefics3": load_idefics3,
606
    "internvl_chat": load_internvl,
607
    "llama4": load_llama4,
608
    "mistral3": load_mistral3,
609
    "mllama": load_mllama,
610
    "NVLM_D": load_nvlm_d,
611
    "phi3_v": load_phi3v,
612
    "phi4_mm": load_phi4mm,
613
614
    "pixtral_hf": load_pixtral_hf,
    "qwen_vl_chat": load_qwen_vl_chat,
615
    "qwen2_vl": load_qwen2_vl,
Roger Wang's avatar
Roger Wang committed
616
    "qwen2_5_vl": load_qwen2_5_vl,
617
618
619
}


620
621
def run_generate(model, question: str, image_urls: list[str],
                 seed: Optional[int]):
622
    req_data = model_example_map[model](question, image_urls)
623

624
625
626
627
628
629
630
631
632
633
    engine_args = asdict(req_data.engine_args) | {"seed": args.seed}
    llm = LLM(**engine_args)

    # To maintain code compatibility in this script, we add LoRA here.
    # You can also add LoRA using:
    # llm.generate(prompts, lora_request=lora_request,...)
    if req_data.lora_requests:
        for lora_request in req_data.lora_requests:
            llm.llm_engine.add_lora(lora_request=lora_request)

634
635
    sampling_params = SamplingParams(temperature=0.0,
                                     max_tokens=128,
636
                                     stop_token_ids=req_data.stop_token_ids)
637

638
    outputs = llm.generate(
639
        {
640
            "prompt": req_data.prompt,
641
            "multi_modal_data": {
642
                "image": req_data.image_data
643
            },
644
        },
645
        sampling_params=sampling_params)
646

647
    print("-" * 50)
648
649
650
    for o in outputs:
        generated_text = o.outputs[0].text
        print(generated_text)
651
        print("-" * 50)
652
653


654
655
def run_chat(model: str, question: str, image_urls: list[str],
             seed: Optional[int]):
656
    req_data = model_example_map[model](question, image_urls)
657

658
659
660
661
662
663
664
665
666
667
    engine_args = asdict(req_data.engine_args) | {"seed": seed}
    llm = LLM(**engine_args)

    # To maintain code compatibility in this script, we add LoRA here.
    # You can also add LoRA using:
    # llm.generate(prompts, lora_request=lora_request,...)
    if req_data.lora_requests:
        for lora_request in req_data.lora_requests:
            llm.llm_engine.add_lora(lora_request=lora_request)

668
669
    sampling_params = SamplingParams(temperature=0.0,
                                     max_tokens=128,
670
                                     stop_token_ids=req_data.stop_token_ids)
671
    outputs = llm.chat(
672
673
674
675
676
677
678
        [{
            "role":
            "user",
            "content": [
                {
                    "type": "text",
                    "text": question,
679
                },
680
681
682
683
684
685
686
687
688
                *({
                    "type": "image_url",
                    "image_url": {
                        "url": image_url
                    },
                } for image_url in image_urls),
            ],
        }],
        sampling_params=sampling_params,
689
        chat_template=req_data.chat_template,
690
    )
691

692
    print("-" * 50)
693
694
695
    for o in outputs:
        generated_text = o.outputs[0].text
        print(generated_text)
696
        print("-" * 50)
697
698
699


def main(args: Namespace):
700
    model = args.model_type
701
    method = args.method
702
    seed = args.seed
703
704

    if method == "generate":
705
        run_generate(model, QUESTION, IMAGE_URLS, seed)
706
    elif method == "chat":
707
        run_chat(model, QUESTION, IMAGE_URLS, seed)
708
709
710
711
712
713
714
    else:
        raise ValueError(f"Invalid method: {method}")


if __name__ == "__main__":
    parser = FlexibleArgumentParser(
        description='Demo on using vLLM for offline inference with '
Cyrus Leung's avatar
Cyrus Leung committed
715
716
        'vision language models that support multi-image input for text '
        'generation')
717
718
719
720
721
722
    parser.add_argument('--model-type',
                        '-m',
                        type=str,
                        default="phi3_v",
                        choices=model_example_map.keys(),
                        help='Huggingface "model_type".')
723
724
725
726
727
    parser.add_argument("--method",
                        type=str,
                        default="generate",
                        choices=["generate", "chat"],
                        help="The method to run in `vllm.LLM`.")
728
729
730
731
    parser.add_argument("--seed",
                        type=int,
                        default=None,
                        help="Set the seed when initializing `vllm.LLM`.")
732
733
734

    args = parser.parse_args()
    main(args)