多模态大模型Qwen2.5-vl本地部署指南
目录
多模态大模型Qwen2.5 vl本地部署指南
Qwen2.5-VL 是通义千问系列的最新多模态大模型,具备图文理解、视觉推理、文档解析等强大能力,广泛应用于智能搜索、内容生成、企业文档处理等领域。
🔹 主要功能
✅ 多模态问答:解析图片、图表、文档,回答问题,支持 OCR 识别。
✅ 复杂文档解析:提取发票、合同、PPT、表格等文件中的结构化信息。
✅ 高级视觉推理:理解图像中的关系,如因果推理、数据分析。
✅ 智能摘要与生成:自动生成图片描述、文档摘要,提高信息获取效率。
✅ 代码与 UI 解析:识别截图中的代码/UI 设计,生成可执行代码或交互说明。
一. 环境准备
机器:4090
python: 3.10
cuda: 12.2
# 网络不好,可能需要尝试几次
pip install git+https://github.com/huggingface/transformers accelerate
pip install qwen-vl-utils[decord]
# 跑代码时缺少包
pip install torchvision==0.19.0
二. 下载模型
from modelscope import snapshot_download
model_dir = snapshot_download('Qwen/Qwen2.5-VL-7B')
三. 推理代码封装
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info
import torch
class QwenVLModel:
def __init__(self, model_path="./Qwen2.5-VL-7B-Instruct", use_flash_attention=False):
"""
初始化Qwen VL模型
Args:
model_path: 模型路径
use_flash_attention: 是否使用flash attention加速
"""
# 加载模型
if use_flash_attention:
self.model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
device_map="auto",
)
else:
self.model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
model_path, torch_dtype="auto", device_map="auto"
)
# 初始化处理器
min_pixels = 256*28*28
max_pixels = 1280*28*28
self.processor = AutoProcessor.from_pretrained(
model_path,
min_pixels=min_pixels,
max_pixels=max_pixels,
use_fast=True
)
def process_image(self, image_path, prompt):
"""
处理图片并生成输出
Args:
image_path: 图片路径
prompt: 提示文本
Returns:
生成的文本输出
"""
messages = [
{
"role": "user",
"content": [
{
"type": "image",
"image": image_path,
},
{"type": "text", "text": prompt},
],
}
]
# 准备推理输入
text = self.processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = self.processor(
text=[text],
images=image_inputs,
videos=video_inputs,
padding=True,
return_tensors="pt",
)
inputs = inputs.to(self.model.device)
# 生成输出
generated_ids = self.model.generate(**inputs, max_new_tokens=512)
generated_ids_trimmed = [
out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text = self.processor.batch_decode(
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
return output_text
if __name__ == "__main__":
model = QwenVLModel()
img_path = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"
output_text = model.process_image(
img_path,
"请用中文描述一下这张图片"
)
print(f"输出信息: {output_text}")
四. 测试效果
图片
模型输出结果:
输出信息: ['这张图片展示了一位女士和一只狗在海滩上互动的场景。女士坐在沙滩上,穿着格子衬衫和黑色裤子,面带微笑,似乎在与狗进行友好互动。狗戴着彩色的项圈,正伸出前爪与女士的手相触碰,显得非常亲密和愉快。背景是广阔的海洋和天空,夕阳的余晖洒在沙滩上,营造出一种温馨和谐的氛围。整个画面给人一种轻松愉快的感觉。']