offline_inference_vision_language.py 14.2 KB
Newer Older
1
"""
Cyrus Leung's avatar
Cyrus Leung committed
2
3
This example shows how to use vLLM for running offline inference with
the correct prompt format on vision language models for text generation.
4
5
6
7
8
9
10
11

For most models, the prompt format should follow corresponding examples
on HuggingFace model repository.
"""
from transformers import AutoTokenizer

from vllm import LLM, SamplingParams
from vllm.assets.image import ImageAsset
12
from vllm.assets.video import VideoAsset
13
14
from vllm.utils import FlexibleArgumentParser

15
16
17
18
# 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.

19
20

# LLaVA-1.5
21
def run_llava(question: str, modality: str):
22
    assert modality == "image"
23
24
25

    prompt = f"USER: <image>\n{question}\nASSISTANT:"

26
    llm = LLM(model="llava-hf/llava-1.5-7b-hf", max_model_len=4096)
27
28
    stop_token_ids = None
    return llm, prompt, stop_token_ids
29
30
31


# LLaVA-1.6/LLaVA-NeXT
32
def run_llava_next(question: str, modality: str):
33
    assert modality == "image"
34
35

    prompt = f"[INST] <image>\n{question} [/INST]"
36
37
38
39
40
41
42
    llm = LLM(model="llava-hf/llava-v1.6-mistral-7b-hf", max_model_len=8192)
    stop_token_ids = None
    return llm, prompt, stop_token_ids


# LlaVA-NeXT-Video
# Currently only support for video input
43
def run_llava_next_video(question: str, modality: str):
44
45
    assert modality == "video"

46
47
    prompt = f"USER: <video>\n{question} ASSISTANT:"
    llm = LLM(model="llava-hf/LLaVA-NeXT-Video-7B-hf", max_model_len=8192)
48
49
    stop_token_ids = None
    return llm, prompt, stop_token_ids
50
51


52
# LLaVA-OneVision
53
def run_llava_onevision(question: str, modality: str):
54
55
56
57
58
59
60
61
62
63

    if modality == "video":
        prompt = f"<|im_start|>user <video>\n{question}<|im_end|> \
        <|im_start|>assistant\n"

    elif modality == "image":
        prompt = f"<|im_start|>user <image>\n{question}<|im_end|> \
        <|im_start|>assistant\n"

    llm = LLM(model="llava-hf/llava-onevision-qwen2-7b-ov-hf",
64
              max_model_len=16384)
65
66
67
68
    stop_token_ids = None
    return llm, prompt, stop_token_ids


69
# Fuyu
70
def run_fuyu(question: str, modality: str):
71
    assert modality == "image"
72
73

    prompt = f"{question}\n"
74
    llm = LLM(model="adept/fuyu-8b", max_model_len=2048, max_num_seqs=2)
75
76
    stop_token_ids = None
    return llm, prompt, stop_token_ids
77
78
79


# Phi-3-Vision
80
def run_phi3v(question: str, modality: str):
81
    assert modality == "image"
82
83
84
85
86
87
88
89

    prompt = f"<|user|>\n<|image_1|>\n{question}<|end|>\n<|assistant|>\n"  # noqa: E501
    # Note: The default setting of max_num_seqs (256) and
    # max_model_len (128k) for this model may cause OOM.
    # You may lower either to run this example on lower-end GPUs.

    # In this example, we override max_num_seqs to 5 while
    # keeping the original context length of 128k.
90
91
92
93
94
95
96
97
98
99
100
101
102

    # 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
103
104
105
    llm = LLM(
        model="microsoft/Phi-3-vision-128k-instruct",
        trust_remote_code=True,
106
107
        max_model_len=4096,
        max_num_seqs=2,
108
        # Note - mm_processor_kwargs can also be passed to generate/chat calls
109
        mm_processor_kwargs={"num_crops": 16},
110
    )
111
112
    stop_token_ids = None
    return llm, prompt, stop_token_ids
113
114
115


# PaliGemma
116
def run_paligemma(question: str, modality: str):
117
    assert modality == "image"
118

119
120
    # PaliGemma has special prompt format for VQA
    prompt = "caption en"
121
    llm = LLM(model="google/paligemma-3b-mix-224")
122
123
    stop_token_ids = None
    return llm, prompt, stop_token_ids
124
125
126


# Chameleon
127
def run_chameleon(question: str, modality: str):
128
    assert modality == "image"
129
130

    prompt = f"{question}<image>"
131
    llm = LLM(model="facebook/chameleon-7b", max_model_len=4096)
132
133
    stop_token_ids = None
    return llm, prompt, stop_token_ids
134
135
136


# MiniCPM-V
137
def run_minicpmv(question: str, modality: str):
138
    assert modality == "image"
139
140
141
142
143
144
145

    # 2.0
    # The official repo doesn't work yet, so we need to use a fork for now
    # For more details, please see: See: https://github.com/vllm-project/vllm/pull/4087#issuecomment-2250397630 # noqa
    # model_name = "HwwwH/MiniCPM-V-2"

    # 2.5
146
147
148
149
    # model_name = "openbmb/MiniCPM-Llama3-V-2_5"

    #2.6
    model_name = "openbmb/MiniCPM-V-2_6"
150
151
152
153
    tokenizer = AutoTokenizer.from_pretrained(model_name,
                                              trust_remote_code=True)
    llm = LLM(
        model=model_name,
154
155
        max_model_len=4096,
        max_num_seqs=2,
156
157
        trust_remote_code=True,
    )
158
159
160
161
162
163
164
165
166
167
    # NOTE The stop_token_ids are different for various versions of MiniCPM-V
    # 2.0
    # stop_token_ids = [tokenizer.eos_id]

    # 2.5
    # stop_token_ids = [tokenizer.eos_id, tokenizer.eot_id]

    # 2.6
    stop_tokens = ['<|im_end|>', '<|endoftext|>']
    stop_token_ids = [tokenizer.convert_tokens_to_ids(i) for i in stop_tokens]
168
169
170
171
172
173
174
175

    messages = [{
        'role': 'user',
        'content': f'(<image>./</image>)\n{question}'
    }]
    prompt = tokenizer.apply_chat_template(messages,
                                           tokenize=False,
                                           add_generation_prompt=True)
176
    return llm, prompt, stop_token_ids
177
178


179
# InternVL
180
def run_internvl(question: str, modality: str):
181
182
    assert modality == "image"

183
184
    model_name = "OpenGVLab/InternVL2-2B"

185
    llm = LLM(
186
        model=model_name,
187
        trust_remote_code=True,
188
        max_model_len=4096,
189
    )
190
191
192
193
194
195
196
197
198
199
200
201
202
203

    tokenizer = AutoTokenizer.from_pretrained(model_name,
                                              trust_remote_code=True)
    messages = [{'role': 'user', 'content': f"<image>\n{question}"}]
    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":
    # https://huggingface.co/OpenGVLab/InternVL2-2B#service
    stop_tokens = ["<|endoftext|>", "<|im_start|>", "<|im_end|>", "<|end|>"]
    stop_token_ids = [tokenizer.convert_tokens_to_ids(i) for i in stop_tokens]
204
    return llm, prompt, stop_token_ids
205
206


207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# NVLM-D
def run_nvlm_d(question: str, modality: str):
    assert modality == "image"

    model_name = "nvidia/NVLM-D-72B"

    # Adjust this as necessary to fit in GPU
    llm = LLM(
        model=model_name,
        trust_remote_code=True,
        max_model_len=4096,
        tensor_parallel_size=4,
    )

    tokenizer = AutoTokenizer.from_pretrained(model_name,
                                              trust_remote_code=True)
    messages = [{'role': 'user', 'content': f"<image>\n{question}"}]
    prompt = tokenizer.apply_chat_template(messages,
                                           tokenize=False,
                                           add_generation_prompt=True)
    stop_token_ids = None
    return llm, prompt, stop_token_ids


231
# BLIP-2
232
def run_blip2(question: str, modality: str):
233
    assert modality == "image"
234
235
236
237
238

    # BLIP-2 prompt format is inaccurate on HuggingFace model repository.
    # See https://huggingface.co/Salesforce/blip2-opt-2.7b/discussions/15#64ff02f3f8cf9e4f5b038262 #noqa
    prompt = f"Question: {question} Answer:"
    llm = LLM(model="Salesforce/blip2-opt-2.7b")
239
240
    stop_token_ids = None
    return llm, prompt, stop_token_ids
241
242


243
# Qwen
244
def run_qwen_vl(question: str, modality: str):
245
    assert modality == "image"
246
247
248
249

    llm = LLM(
        model="Qwen/Qwen-VL",
        trust_remote_code=True,
250
251
        max_model_len=1024,
        max_num_seqs=2,
252
253
254
255
256
257
258
    )

    prompt = f"{question}Picture 1: <img></img>\n"
    stop_token_ids = None
    return llm, prompt, stop_token_ids


259
# Qwen2-VL
260
def run_qwen2_vl(question: str, modality: str):
261
262
    assert modality == "image"

263
264
265
266
    model_name = "Qwen/Qwen2-VL-7B-Instruct"

    llm = LLM(
        model=model_name,
267
        max_model_len=4096,
268
        max_num_seqs=5,
269
270
271
272
273
        # Note - mm_processor_kwargs can also be passed to generate/chat calls
        mm_processor_kwargs={
            "min_pixels": 28 * 28,
            "max_pixels": 1280 * 28 * 28,
        },
274
275
276
277
278
279
280
281
282
283
    )

    prompt = ("<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n"
              "<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>"
              f"{question}<|im_end|>\n"
              "<|im_start|>assistant\n")
    stop_token_ids = None
    return llm, prompt, stop_token_ids


284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# Pixtral HF-format
def run_pixtral_hf(question: str, modality: str):
    assert modality == "image"

    model_name = "mistral-community/pixtral-12b"

    llm = LLM(
        model=model_name,
        max_model_len=8192,
    )

    prompt = f"<s>[INST]{question}\n[IMG][/INST]"
    stop_token_ids = None
    return llm, prompt, stop_token_ids


300
301
# LLama 3.2
def run_mllama(question: str, modality: str):
302
303
304
305
306
307
308
309
    assert modality == "image"

    model_name = "meta-llama/Llama-3.2-11B-Vision-Instruct"

    # Note: The default setting of max_num_seqs (256) and
    # max_model_len (131072) for this model may cause OOM.
    # You may lower either to run this example on lower-end GPUs.

310
    # The configuration below has been confirmed to launch on a single L40 GPU.
311
312
    llm = LLM(
        model=model_name,
313
        max_model_len=4096,
314
315
316
317
318
319
320
321
322
        max_num_seqs=16,
        enforce_eager=True,
    )

    prompt = f"<|image|><|begin_of_text|>{question}"
    stop_token_ids = None
    return llm, prompt, stop_token_ids


323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# Molmo
def run_molmo(question, modality):
    assert modality == "image"

    model_name = "allenai/Molmo-7B-D-0924"

    llm = LLM(
        model=model_name,
        trust_remote_code=True,
        dtype="bfloat16",
    )

    prompt = question
    stop_token_ids = None
    return llm, prompt, stop_token_ids


340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# GLM-4v
def run_glm4v(question: str, modality: str):
    assert modality == "image"
    model_name = "THUDM/glm-4v-9b"

    llm = LLM(model=model_name,
              max_model_len=2048,
              max_num_seqs=2,
              trust_remote_code=True,
              enforce_eager=True)
    prompt = question
    stop_token_ids = [151329, 151336, 151338]
    return llm, prompt, stop_token_ids


355
356
357
model_example_map = {
    "llava": run_llava,
    "llava-next": run_llava_next,
358
    "llava-next-video": run_llava_next_video,
359
    "llava-onevision": run_llava_onevision,
360
361
362
363
364
    "fuyu": run_fuyu,
    "phi3_v": run_phi3v,
    "paligemma": run_paligemma,
    "chameleon": run_chameleon,
    "minicpmv": run_minicpmv,
365
    "blip-2": run_blip2,
366
    "internvl_chat": run_internvl,
367
    "NVLM_D": run_nvlm_d,
368
    "qwen_vl": run_qwen_vl,
369
    "qwen2_vl": run_qwen2_vl,
370
    "pixtral_hf": run_pixtral_hf,
371
    "mllama": run_mllama,
372
    "molmo": run_molmo,
373
    "glm4v": run_glm4v,
374
375
376
}


377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
def get_multi_modal_input(args):
    """
    return {
        "data": image or video,
        "question": question,
    }
    """
    if args.modality == "image":
        # Input image and question
        image = ImageAsset("cherry_blossom") \
            .pil_image.convert("RGB")
        img_question = "What is the content of this image?"

        return {
            "data": image,
            "question": img_question,
        }

    if args.modality == "video":
        # Input video and question
        video = VideoAsset(name="sample_demo_1.mp4",
                           num_frames=args.num_frames).np_ndarrays
        vid_question = "Why is this video funny?"

        return {
            "data": video,
            "question": vid_question,
        }

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


410
411
412
413
414
def main(args):
    model = args.model_type
    if model not in model_example_map:
        raise ValueError(f"Model type {model} is not supported.")

415
416
417
418
419
    modality = args.modality
    mm_input = get_multi_modal_input(args)
    data = mm_input["data"]
    question = mm_input["question"]

420
    llm, prompt, stop_token_ids = model_example_map[model](question, modality)
421
422
423

    # We set temperature to 0.2 so that outputs can be different
    # even when all prompts are identical when running batch inference.
424
425
426
    sampling_params = SamplingParams(temperature=0.2,
                                     max_tokens=64,
                                     stop_token_ids=stop_token_ids)
427
428
429
430
431
432
433

    assert args.num_prompts > 0
    if args.num_prompts == 1:
        # Single inference
        inputs = {
            "prompt": prompt,
            "multi_modal_data": {
434
                modality: data
435
436
437
438
439
440
441
442
            },
        }

    else:
        # Batch inference
        inputs = [{
            "prompt": prompt,
            "multi_modal_data": {
443
                modality: data
444
445
446
447
448
449
450
451
452
453
454
455
456
            },
        } for _ in range(args.num_prompts)]

    outputs = llm.generate(inputs, sampling_params=sampling_params)

    for o in outputs:
        generated_text = o.outputs[0].text
        print(generated_text)


if __name__ == "__main__":
    parser = FlexibleArgumentParser(
        description='Demo on using vLLM for offline inference with '
Cyrus Leung's avatar
Cyrus Leung committed
457
        'vision language models for text generation')
458
459
460
461
462
463
464
465
    parser.add_argument('--model-type',
                        '-m',
                        type=str,
                        default="llava",
                        choices=model_example_map.keys(),
                        help='Huggingface "model_type".')
    parser.add_argument('--num-prompts',
                        type=int,
466
                        default=4,
467
                        help='Number of prompts to run.')
468
469
470
    parser.add_argument('--modality',
                        type=str,
                        default="image",
471
                        choices=['image', 'video'],
472
473
474
475
476
                        help='Modality of the input.')
    parser.add_argument('--num-frames',
                        type=int,
                        default=16,
                        help='Number of frames to extract from the video.')
477
478
    args = parser.parse_args()
    main(args)