QwenVL系列多模态模型学习笔记-第3篇

第二代 Qwen2-VL 应用案例

模型下载 —— 基于魔塔社区

本次 Qwen2-VL 开源了两个尺寸的模型,Qwen2-VL-2B-InstructQwen2-VL-7B-Instruct,以及其 GPTQ 和 AWQ 的量化版本。

模型链接:

Qwen2-VL-2B-Instruct:https://www.modelscope.cn/models/qwen/Qwen2-VL-2B-Instruct

Qwen2-VL-7B-Instruct:https://www.modelscope.cn/models/qwen/Qwen2-VL-7B-Instruct

推荐使用 ModelScope CLI 下载模型

1
modelscope download --model=qwen/Qwen2-VL-7B-Instruct --local_dir ./Qwen2-VL-7B-Instruct

模型推理 —— 基于 transformers

安装依赖:

1
pip install git+https://github.com/huggingface/transformers
1
pip install qwen-vl-utils

单图推理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from PIL import Image
import torch
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
from qwen_vl_utils import process_vision_info
from modelscope import snapshot_download


model_dir = "/mnt/workspace/Qwen2-VL-2B-Instruct"
min_pixels = 256*28*28
max_pixels = 1280*28*28

# Load the model in half-precision on the available device(s)
model = Qwen2VLForConditionalGeneration.from_pretrained(
model_dir, device_map="auto", torch_dtype = torch.float16
)
# Load the processor
processor = AutoProcessor.from_pretrained(
model_dir, min_pixels=min_pixels, max_pixels=max_pixels
)

messages = [
{
"role": "user",
"content": [
{"type": "image", "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"},
{"type": "text", "text": "Describe this image."}
]
}
]

# Preparation for inference
text = processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
text=[text], images=image_inputs, videos=video_inputs,
padding=True, return_tensors="pt"
)
inputs = inputs.to('cuda')

# Inference: Generation of the output
generated_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids_trimmed = [
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]

output_text = processor.batch_decode(
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)

print(output_text)

把输入文本编程对话形式:输入文本被处理成对话模板的样式,图片或者视频暂时被 <|image_pad|> 这样的占位符替代。

1
2
3
4
5
 <|im_start|>system
You are a helpful assistant.<|im_end|>
<|im_start|>user
<|vision_start|><|image_pad|><|vision_end|>Describe this image.<|im_end|>
<|im_start|>assistant

多图推理

1
2
3
4
5
6
7
8
9
10
11
# Messages containing multiple images and a text query
messages = [
{
"role": "user",
"content": [
{"type": "image", "image": "file:///path/to/image1.jpg"},
{"type": "image", "image": "file:///path/to/image2.jpg"},
{"type": "text", "text": "Identify the similarities between these images."}
]
}
]

视频理解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Messages containing a video and a text query
messages = [
{
"role": "user",
"content": [
{
"type": "video",
"video": "file:///path/to/video1.mp4",
'max_pixels': 360*420,
'fps': 1.0
},
{"type": "text", "text": "Describe this video."}
]
}
]

模型推理 —— 基于 vllm

安装依赖

1
pip install git+https://github.com/fyabc/vllm.git@add_qwen2_vl_new

启动 OpenAI 接口服务

1
python -m vllm.entrypoints.openai.api_server --served-model-name Qwen2-VL-7B-Instruct --model model_path

调用服务

1
2
3
4
5
6
7
8
9
10
11
12
curl http://localhost:8000/v1/chat/completions \    
-H "Content-Type: application/json" \
-d '{
"model": "Qwen2-VL-7B-Instruct",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": "https://modelscope.oss-cn-beijing.aliyuncs.com/resource/qwen.png"}},
{"type": "text", "text": "What is the text in the illustrate?"}
]}
]
}'

调用服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from openai import OpenAI

# Set OpenAI's API key and API base to use vLLM's API server.
openai_api_key = "EMPTY"
openai_api_base = "http://localhost:8000/v1"

client = OpenAI(
api_key=openai_api_key, base_url=openai_api_base
)

chat_response = client.chat.completions.create(
model="Qwen2-7B-Instruct",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": "https://modelscope.oss-cn-beijing.aliyuncs.com/resource/qwen.png"}},
{"type": "text", "text": "What is the text in the illustrate?"},
]},
]
)

print("Chat response:", chat_response)

模型微调 —— 基于 swift

在开始微调之前,请确保您的环境已准备妥当。

1
git clone https://github.com/modelscope/swift.gitcd swift
1
pip install -e .[llm]
1
pip install pyav qwen_vl_utils

图像描述微调

1
2
3
4
5
6
7
8
9
# 默认会将 lora_target_modules 设置为 llm 的所有linear
CUDA_VISIBLE_DEVICES=0,1,2,3 NPROC_PER_NODE=4 swift sft \
--model_type qwen2-vl-7b-instruct \
--model_id_or_path qwen/Qwen2-VL-7B-Instruct \
--sft_type lora \
--dataset coco-en-mini#20000 \
--deepspeed default-zero2
--dataset train.jsonl \
--val_dataset val.jsonl \ # 自定义数据集

以下是自定义数据集的样例:

1
{"query": "<image>55555", "response": "66666", "images": ["image_path"]}
1
{"query": "eeeee<image>eeeee<image>eeeee", "response": "fffff", "history": [], "images": ["image_path1", "image_path2"]}
1
{"query": "EEEEE", "response": "FFFFF", "history": [["query1", "response2"], ["query2", "response2"]], "images": []}

微调后推理脚本如下:

1
2
3
4
CUDA_VISIBLE_DEVICES=0 swift infer \    
--ckpt_dir output/qwen2-vl-7b-instruct/vx-xxx/checkpoint-xxx \
--load_dataset_config true
--merge_lora true

图像 grounding 微调

1
2
3
4
5
6
7
# swift 跨模型通用格式
{
"query": "Find <bbox>",
"response": "<ref-object>",
"images": ["/coco2014/train2014/COCO_train2014_000000001507.jpg"],
"objects": "[{\"caption\": \"guy in red\", \"bbox\": [138, 136, 235, 359], \"bbox_type\": \"real\", \"image\": 0}]"
}
1
2
3
4
5
6
{
"query": "Find <ref-object>",
"response": "<bbox>",
"images": ["/coco2014/train2014/COCO_train2014_000000001507.jpg"],
"objects": "[{\"caption\": \"guy in red\", \"bbox\": [138, 136, 235, 359], \"bbox_type\": \"real\", \"image\": 0}]"
}
1
2
3
4
5
6
# qwen2-vl-chat 特定格式,注意特殊字符的存在
{
"query": "Find <|object_ref_start|>the man<|object_ref_end|>",
"response": "<|box_start|>(123,235),(324,546)<|box_end|>",
"images": ["/coco2014/train2014/COCO_train2014_000000001507.jpg"]
}

视频微调

1
2
3
4
5
6
NFRAMES=24 MAX_PIXELS=100352 CUDA_VISIBLE_DEVICES=0,1,2,3 NPROC_PER_NODE=4 swift sft \  
--model_type qwen2-vl-7b-instruct \
--model_id_or_path qwen/Qwen2-VL-7B-Instruct \
--sft_type lora \
--dataset video-chatgpt \
--deepspeed default-zero2

QwenVL系列多模态模型学习笔记-第3篇
http://example.com/2025/06/25/QwenVL系列多模态模型学习笔记-第3篇/
作者
Jinbiao Zhu
发布于
2025年6月25日
许可协议