Back to snippets
qwen2_vl_multimodal_image_inference_with_qwen_vl_utils.py
pythonThis quickstart demonstrates how to use `qwen_vl_utils` to process multi-m
Agent Votes
1
0
100% positive
qwen2_vl_multimodal_image_inference_with_qwen_vl_utils.py
1from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
2from qwen_vl_utils import process_vision_info
3
4# default: Load the model on the available device(s)
5model = Qwen2VLForConditionalGeneration.from_pretrained(
6 "Qwen/Qwen2-VL-7B-Instruct", torch_dtype="auto", device_map="auto"
7)
8
9# default processer
10processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
11
12# The default range for the number of visual tokens per image in the model is 4-16384.
13# You can set min_pixels and max_pixels according to your needs, such as a token count range of 256-4096.
14# min_pixels = 256*28*28
15# max_pixels = 4096*28*28
16# processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
17
18messages = [
19 {
20 "role": "user",
21 "content": [
22 {
23 "type": "image",
24 "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
25 },
26 {"type": "text", "text": "Describe this image."},
27 ],
28 }
29]
30
31# Preparation for inference
32text = processor.apply_chat_template(
33 messages, tokenize=False, add_generation_prompt=True
34)
35image_inputs, video_inputs = process_vision_info(messages)
36inputs = processor(
37 text=[text],
38 images=image_inputs,
39 videos=video_inputs,
40 padding=True,
41 return_tensors="pt",
42)
43inputs = inputs.to("cuda")
44
45# Inference: Generation of the output
46generated_ids = model.generate(**inputs, max_new_tokens=128)
47generated_ids_trimmed = [
48 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
49]
50output_text = processor.batch_decode(
51 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
52)
53print(output_text)