离线推理 视觉语言 多图像#
源代码 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
237model_example_map = {
238 "phi3_v": load_phi3v,
239 "internvl_chat": load_internvl,
240 "NVLM_D": load_nvlm_d,
241 "qwen2_vl": load_qwen2_vl,
242 "qwen_vl_chat": load_qwenvl_chat,
243}
244
245
246def run_generate(model, question: str, image_urls: List[str]):
247 req_data = model_example_map[model](question, image_urls)
248
249 sampling_params = SamplingParams(temperature=0.0,
250 max_tokens=128,
251 stop_token_ids=req_data.stop_token_ids)
252
253 outputs = req_data.llm.generate(
254 {
255 "prompt": req_data.prompt,
256 "multi_modal_data": {
257 "image": req_data.image_data
258 },
259 },
260 sampling_params=sampling_params)
261
262 for o in outputs:
263 generated_text = o.outputs[0].text
264 print(generated_text)
265
266
267def run_chat(model: str, question: str, image_urls: List[str]):
268 req_data = model_example_map[model](question, image_urls)
269
270 sampling_params = SamplingParams(temperature=0.0,
271 max_tokens=128,
272 stop_token_ids=req_data.stop_token_ids)
273 outputs = req_data.llm.chat(
274 [{
275 "role":
276 "user",
277 "content": [
278 {
279 "type": "text",
280 "text": question,
281 },
282 *({
283 "type": "image_url",
284 "image_url": {
285 "url": image_url
286 },
287 } for image_url in image_urls),
288 ],
289 }],
290 sampling_params=sampling_params,
291 chat_template=req_data.chat_template,
292 )
293
294 for o in outputs:
295 generated_text = o.outputs[0].text
296 print(generated_text)
297
298
299def main(args: Namespace):
300 model = args.model_type
301 method = args.method
302
303 if method == "generate":
304 run_generate(model, QUESTION, IMAGE_URLS)
305 elif method == "chat":
306 run_chat(model, QUESTION, IMAGE_URLS)
307 else:
308 raise ValueError(f"Invalid method: {method}")
309
310
311if __name__ == "__main__":
312 parser = FlexibleArgumentParser(
313 description='Demo on using vLLM for offline inference with '
314 'vision language models that support multi-image input')
315 parser.add_argument('--model-type',
316 '-m',
317 type=str,
318 default="phi3_v",
319 choices=model_example_map.keys(),
320 help='Huggingface "model_type".')
321 parser.add_argument("--method",
322 type=str,
323 default="generate",
324 choices=["generate", "chat"],
325 help="The method to run in `vllm.LLM`.")
326
327 args = parser.parse_args()
328 main(args)