Qwen2-VL 全链路模型体验、下载、推理、微调实战!

简介: 经过了一年的不懈努力,今天通义千问团队对 Qwen-VL 模型进行重大更新——推出 Qwen2-VL。那么Qwen2-VL 有什么新功能呢?一起来看一下吧

引言

经过了一年的不懈努力,今天通义千问团队对 Qwen-VL 模型进行重大更新——推出 Qwen2-VL。

Qwen2-VL 有什么新功能?

· 增强的图像理解能力:Qwen2-VL显著提高了模型理解和解释视觉信息的能力,为关键性能指标设定了新的基准

· 高级视频理解能力:Qwen2-VL具有卓越的在线流媒体功能,能够以很高的精度实时分析动态视频内容

· 集成的可视化agent功能:Qwen2-VL 现在无缝整合了复杂的系统集成,将 Qwen2-VL 转变为能够进行复杂推理和决策的强大可视化代理

· 扩展的多语言支持:Qwen2-VL 扩展了语言能力,以更好地服务于多样化的全球用户群,使 Qwen2-VL 在不同语言环境中更易于访问和有效

模型结构

  • Qwen2-VL 的一项关键架构改进是实现了动态分辨率支持(Naive Dynamic Resolution support)。与上一代模型Qwen-VL不同,Qwen2-VL 可以处理任意分辨率的图像,而无需将其分割成块,从而确保模型输入与图像固有信息之间的一致性。这种方法更接近地模仿人类的视觉感知,使模型能够处理任何清晰度或大小的图像。

image.png

  • 另一个关键的架构增强是Multimodal Rotary Position Embedding (M-ROPE) 的创新。通过将original rotary embedding分解为代表时间和空间(高度和宽度)信息的三个部分,M-ROPE 使 LLM 能够同时捕获和集成 1D 文本、2D视觉和 3D 视频位置信息。这使 LLM 能够充当强大的多模态处理器和推理器。

image.png

模型效果

在 7B 规模下,Qwen2-VL-7B成功保留了对图像、多图像和视频输入的支持,以更具成本效益的模型大小提供具有竞争力的性能。具体而言,Qwen2-VL-7B在文档理解任务(例如 DocVQA)和通过 MTVQA 评估的图像多语言文本理解方面表现出色,建立了非常优秀的性能。

image.png

本次Qwen2-VL推出一款更小的 2B 模型,该模型针对潜在的移动部署进行了优化。尽管参数量只有2B,但该模型在图像、视频和多语言理解方面表现出色。与其他类似规模的模型相比,它在视频相关任务、文档理解和一般场景问答方面表现尤为出色。

image.png

模型下载

本次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下载模型

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

模型体验

效果体验:

1 游戏视频理解:

image.png

2 数学几何求解:

image.png

3 OCR识别:

image.png

模型推理

transformers推理

安装依赖:

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

模型推理代码-单图推理

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"
# Load the model in half-precision on the available device(s)
model = Qwen2VLForConditionalGeneration.from_pretrained(model_dir, device_map="auto", torch_dtype = torch.float16)
min_pixels = 256*28*28
max_pixels = 1280*28*28
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)

模型推理代码-多图推理

# 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."}]}]
# 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
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)

模型推理代码-视频理解

# 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."}]}]
# 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
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)

vLLM推理

安装依赖

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

启动OpenAI接口服务

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

调用服务-https

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?"}
    ]}
    ]
    }'

调用服务-sdk

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对qwen2-vl-7b-instruct进行微调。swift是魔搭社区官方提供的大模型与多模态大模型微调推理框架。

swift开源地址:

https://github.com/modelscope/swift

通常,多模态大模型微调会使用自定义数据集进行微调。在这里,我们将展示可直接运行的demo。

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

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

图像描述微调

我们使用 coco-en-mini 数据集进行微调,该数据集的任务是对图片内容进行描述。您可以在 modelscope 上找到该数据集:https://modelscope.cn/datasets/modelscope/coco_2014_caption/summary

# 默认会将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 \

自定义数据集支持json和jsonl样式,以下是自定义数据集的样例:

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

显存占用:

image.png

训练损失图(时间原因,只训练了200个step):

image.png

微调后推理脚本如下:

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

微调后模型对验证集进行推理的示例:

image.png

图像grounding微调

我们使用refcoco-unofficial-grounding数据集进行grounding微调,您可以在 modelscope 上找到该数据集:https://modelscope.cn/datasets/swift/refcoco

# 支持使用zero3进行微调
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 refcoco-unofficial-grounding#20000 \
  --deepspeed default-zero3

用户可以使用如下自定义数据集格式:

# 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}]" }
{"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}]" }
# 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"]}

视频微调

我们使用 video-chatgpt 数据集进行微调,该数据集的任务是对视频内容进行描述。您可以在 modelscope 上找到该数据集:https://modelscope.cn/datasets/swift/VideoChatGPT

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

自定义数据集支持json和jsonl样式,以下是自定义数据集的样例:

{"query": "<video>55555", "response": "66666", "videos": ["video_path"]}
{"query": "eeeee<video>eeeee<video>eeeee", "response": "fffff", "history": [], "videos": ["video_path1", "video_path2"]}
{"query": "EEEEE", "response": "FFFFF", "history": [["query1", "response2"], ["query2", "response2"]], "videos": []}

显存占用:

image.png

微调后推理脚本如下:

NFRAMES=24 MAX_PIXELS=100352 CUDA_VISIBLE_DEVICES=0 swift infer \
    --ckpt_dir output/qwen2-vl-7b-instruct/vx-xxx/checkpoint-xxx \
    --load_dataset_config true --merge_lora true

微调后模型对验证集进行推理的示例(时间原因,只训练了50个step):

image.png

点击链接👇,即可跳转模型~

https://www.modelscope.cn/models/qwen/Qwen2-VL-2B-Instruct?from=alizishequ__text

相关文章
|
16天前
|
分布式计算 测试技术 Spark
科大讯飞开源星火化学大模型、文生音效模型
近期,科大讯飞在魔搭社区(ModelScope)和Gitcode上开源两款模型:讯飞星火化学大模型Spark Chemistry-X1-13B、讯飞文生音频模型AudioFly,助力前沿化学技术研究,以及声音生成技术和应用的探索。
115 2
|
16天前
|
人工智能 Java API
AI 超级智能体全栈项目阶段一:AI大模型概述、选型、项目初始化以及基于阿里云灵积模型 Qwen-Plus实现模型接入四种方式(SDK/HTTP/SpringAI/langchain4j)
本文介绍AI大模型的核心概念、分类及开发者学习路径,重点讲解如何选择与接入大模型。项目基于Spring Boot,使用阿里云灵积模型(Qwen-Plus),对比SDK、HTTP、Spring AI和LangChain4j四种接入方式,助力开发者高效构建AI应用。
618 122
AI 超级智能体全栈项目阶段一:AI大模型概述、选型、项目初始化以及基于阿里云灵积模型 Qwen-Plus实现模型接入四种方式(SDK/HTTP/SpringAI/langchain4j)
|
19天前
|
机器学习/深度学习 人工智能 自然语言处理
AI Compass前沿速览:Qwen3-Max、Mixboard、Qwen3-VL、Audio2Face、Vidu Q2 AI视频生成模型、Qwen3-LiveTranslate-全模态同传大模型
AI Compass前沿速览:Qwen3-Max、Mixboard、Qwen3-VL、Audio2Face、Vidu Q2 AI视频生成模型、Qwen3-LiveTranslate-全模态同传大模型
235 13
AI Compass前沿速览:Qwen3-Max、Mixboard、Qwen3-VL、Audio2Face、Vidu Q2 AI视频生成模型、Qwen3-LiveTranslate-全模态同传大模型
|
15天前
|
自然语言处理 机器人 图形学
腾讯混元图像3.0正式开源发布!80B,首个工业级原生多模态生图模型
腾讯混元图像3.0,真的来了——开源,免费开放使用。 正式介绍一下:混元图像3.0(HunyuanImage 3.0),是首个工业级原生多模态生图模型,参数规模80B,也是目前测评效果最好、参数量最大的开源生图模型,效果可对…
330 2
腾讯混元图像3.0正式开源发布!80B,首个工业级原生多模态生图模型
|
14天前
|
机器学习/深度学习 存储 人工智能
大模型微调:从理论到实践的全面指南
🌟蒋星熠Jaxonic:AI探索者,专注大模型微调技术。从LoRA到RLHF,实践医疗、法律等垂直领域模型优化,分享深度学习的科学与艺术,共赴二进制星河的极客征程。
大模型微调:从理论到实践的全面指南
|
12天前
|
存储 数据采集 自然语言处理
56_大模型微调:全参数与参数高效方法对比
随着大型语言模型(LLM)规模的不断增长,从数百亿到数千亿参数,传统的全参数微调方法面临着计算资源消耗巨大、训练效率低下等挑战。2025年,大模型微调技术已经从早期的全参数微调发展到如今以LoRA、QLoRA为代表的参数高效微调方法,以及多种技术融合的复杂策略。本文将深入对比全参数微调和参数高效微调的技术原理、适用场景、性能表现和工程实践,为研究者和工程师提供全面的技术参考。
156 0
|
12天前
|
存储 机器学习/深度学习 人工智能
54_模型优化:大模型的压缩与量化
随着大型语言模型(LLM)的快速发展,模型规模呈指数级增长,从最初的数亿参数到如今的数千亿甚至万亿参数。这种规模扩张带来了惊人的能源消耗和训练成本,同时也给部署和推理带来了巨大挑战。2025年,大模型的"瘦身"已成为行业发展的必然趋势。本文将深入剖析大模型压缩与量化的核心技术、最新进展及工程实践,探讨如何通过创新技术让大模型在保持高性能的同时实现轻量化部署,为企业和开发者提供全面的技术指导。
|
12天前
|
机器学习/深度学习 人工智能 自然语言处理
38_多模态模型:CLIP的视觉-语言对齐_深度解析
想象一下,当你看到一张小狗在草地上奔跑的图片时,你的大脑立刻就能将视觉信息与"小狗"、"草地"、"奔跑"等概念联系起来。这种跨模态的理解能力对于人类来说似乎是理所当然的,但对于人工智能系统而言,实现这种能力却经历了长期的技术挑战。多模态学习的出现,标志着AI从单一模态处理向更接近人类认知方式的综合信息处理迈出了关键一步。
299 0
|
1月前
|
人工智能 自然语言处理 IDE
模型微调不再被代码难住!PAI和Qwen3-Coder加速AI开发新体验
通义千问 AI 编程大模型 Qwen3-Coder 正式开源,阿里云人工智能平台 PAI 支持云上一键部署 Qwen3-Coder 模型,并可在交互式建模环境中使用 Qwen3-Coder 模型。
402 109

热门文章

最新文章