【大模型】视觉语言模型:Qwen2.5-VL的使用

发布于:2025-04-02 ⋅ 阅读:(20) ⋅ 点赞:(0)

官方github地址:https://github.com/QwenLM/Qwen2.5-VL

目录

Qwen家族的最新成员:Qwen2.5-VL

主要增强功能

模型架构更新

快速开始

使用Transformers聊天

Docker



Qwen家族的最新成员:Qwen2.5-VL

主要增强功能

强大的文档解析功能:将文本识别升级为全文档解析,擅长处理多场景、多语言和各种内置(手写、表格、图表、化学式和乐谱)文档。

跨格式精确的对象基础:解锁在检测,指向和计数对象方面的提高准确性,为高级空间推理提供绝对坐标和JSON格式。

超长视频理解和细粒度视频基础:将原生动态分辨率扩展到时间维度,增强对持续数小时的视频的理解能力,同时在数秒内提取事件片段。

增强的计算机和移动设备代理功能:利用先进的推理和决策能力,通过智能手机和计算机上的高级代理功能来增强模型。

模型架构更新

视频理解的动态分辨率和帧率训练

通过采用动态FPS采样将动态分辨率扩展到时间维度,使模型能够在不同采样率下理解视频。因此,在时间维度上使用id和绝对时间对齐来更新mRoPE,使模型能够学习时间序列和速度,最终获得精确定位特定时刻的能力。

流线型和高效的视觉编码器

通过在ViT中战略性地实施窗口注意力来提高训练和推理速度。利用SwiGLU和RMSNorm对ViT架构进行进一步优化,使其与Qwen2.5 LLM的结构保持一致。

快速开始

下面,将提供简单的示例来展示如何将Qwen2.5-VL与ModelScope和Transformers一起使用。

Qwen2.5-VL的代码已经在最新的 Hugging face transformers中,建议使用命令从源代码构建:

pip install git+https://github.com/huggingface/transformers accelerate

安装依赖

pip install qwen-vl-util

使用Transformers聊天

这里展示了一个代码片段,展示如何使用聊天模型与transformers和qwen_vl_utils:

from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info

# default: Load the model on the available device(s)
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2.5-VL-7B-Instruct", torch_dtype="auto", device_map="auto"
)

# We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
# model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
#     "Qwen/Qwen2.5-VL-7B-Instruct",
#     torch_dtype=torch.bfloat16,
#     attn_implementation="flash_attention_2",
#     device_map="auto",
# )

# default processor
processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")

# The default range for the number of visual tokens per image in the model is 4-16384.
# You can set min_pixels and max_pixels according to your needs, such as a token range of 256-1280, to balance performance and cost.
# min_pixels = 256*28*28
# max_pixels = 1280*28*28
# processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", 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(model.device)

# 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)

更多使用提示

对于输入图像,支持本地文件、base64和url。对于视频,目前只支持本地文件。

# You can directly insert a local file path, a URL, or a base64-encoded image into the position where you want in the text.
## Local file path
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "image": "file:///path/to/your/image.jpg"},
            {"type": "text", "text": "Describe this image."},
        ],
    }
]
## Image URL
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "image": "http://path/to/your/image.jpg"},
            {"type": "text", "text": "Describe this image."},
        ],
    }
]
## Base64 encoded image
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "image": "data:image;base64,/9j/..."},
            {"type": "text", "text": "Describe this image."},
        ],
    }
]

提高性能的图像解决方法

该模型支持广泛的分辨率输入。默认情况下,它使用本机分辨率作为输入,但是更高的分辨率可以以更多的计算为代价来提高性能。用户可以设置最小和最大像素数,以实现满足其需求的最佳配置,例如token计数范围为256-1280,以平衡速度和内存使用。

min_pixels = 256 * 28 * 28
max_pixels = 1280 * 28 * 28
processor = AutoProcessor.from_pretrained(
    "Qwen/Qwen2.5-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels
)

此外,提供了两种方法对输入到模型的图像大小进行细粒度控制:

1.指定确切的尺寸:直接设置resized_height和resized_width。这些值将四舍五入到最接近28的倍数。

2.定义min_pixels和max_pixels:图像将被调整大小,以保持其宽高比在min_pixels和max_pixels的范围内。

# resized_height and resized_width
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "file:///path/to/your/image.jpg",
                "resized_height": 280,
                "resized_width": 420,
            },
            {"type": "text", "text": "Describe this image."},
        ],
    }
]
# min_pixels and max_pixels
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "file:///path/to/your/image.jpg",
                "min_pixels": 50176,
                "max_pixels": 50176,
            },
            {"type": "text", "text": "Describe this image."},
        ],
    }
]

为多个图像输入添加id

默认情况下,对话中直接包含图像和视频内容。在处理多个图像时,为图像和视频添加标签有助于更好地参考。用户可以通过以下设置控制此行为:

1.添加视觉id

Flash-Attention 2加速生成

首先,确保安装最新版本的Flash Attention 2

pip install -U flash-attn --no-build-isolation

此外,应该有一个与Flash-Attention 2兼容的硬件。在flash attention repository的官方文档中阅读更多信息。FlashAttention-2只能在模型加载到torch.float16 或者 torch.bfloat16

要使用Flash Attention-2加载和运行模型,只需在加载模型时添加attn_implementation="flash_attention_2",如下所示:

from transformers import Qwen2_5_VLForConditionalGeneration

model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2.5-VL-7B-Instruct", 
    torch_dtype=torch.bfloat16, 
    attn_implementation="flash_attention_2",
)

处理长文本

当前配置config.json设置的上下文长度最多为32,768个token。为了处理超过32,768个token的大量输入,使用 YaRN,这是一种增强模型长度外推的技术,确保在长文本上的最佳性能。

对于支持的框架,可以在config.json中添加以下内容来启用YaRN:

{
	...,
    "type": "yarn",
    "mrope_section": [
        16,
        24,
        24
    ],
    "factor": 4,
    "original_max_position_embeddings": 32768
}

然而,需要注意的是,这种方法对时间和空间定位任务的性能有很大的影响,因此不建议使用。

同时,对于长视频输入,由于MRoPE本身使用id更经济,因此可以直接将max_position_embeddings修改为更大的值,例如64k。

Docker

为了简化部署过程,提供了带有预构建环境的docker:qwenllm/qwenvl。只需要安装驱动程序并下载模型文件来启动演示。

docker run --gpus all --ipc=host --network=host --rm --name qwen2.5 -it qwenllm/qwenvl:2.5-cu121 bash


网站公告

今日签到

点亮在社区的每一天
去签到