当前位置: 首页 > article >正文

使用transformers调用Qwen2-VL-7B-Instruct

安装

pip install transformers
pip install qwen-vl-utils

Demo

from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
from qwen_vl_utils import process_vision_info

# default: Load the model on the available device(s)
model = Qwen2VLForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2-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 = Qwen2VLForConditionalGeneration.from_pretrained(
#     "Qwen/Qwen2-VL-7B-Instruct",
#     torch_dtype=torch.bfloat16,
#     attn_implementation="flash_attention_2",
#     device_map="auto",
# )

# default processer
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-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 count range of 256-1280, to balance speed and memory usage.
# min_pixels = 256*28*28
# max_pixels = 1280*28*28
# processor = AutoProcessor.from_pretrained("Qwen/Qwen2-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("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)

图像分辨率可提高性能

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

除此之外,可以直接在message修改图像尺寸或pixel

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

这里的增强逻辑是先在message里指定pixel或者尺寸,
然后使用

image_inputs, video_inputs = process_vision_info(messages)

这行代码调整输入
再使用修改后的processor处理image_inputs

展示不同处理后的图像分辨率

原始的图像分辨率

image_inputs
[<PIL.Image.Image image mode=RGB size=308x168 at 0x7F7F1673BFA0>]

不进行增强,使用默认的图像分辨率

image_inputs
[<PIL.Image.Image image mode=RGB size=308x168 at 0x7F7F1673BFA0>]
inputs['pixel_values'].shape
torch.Size([264, 1176])

仅修改processor

image_inputs
[<PIL.Image.Image image mode=RGB size=308x168 at 0x7F5EBB346F50>]
inputs['pixel_values'].shape
torch.Size([1056, 1176])

修改processor且直接修改尺寸

image_inputs
[<PIL.Image.Image image mode=RGB size=420x280 at 0x7FBBEB1BEF50>]
inputs['pixel_values'].shape
torch.Size([1120, 1176])

修改processor且直接修改pixel

image_inputs
[<PIL.Image.Image image mode=RGB size=280x168 at 0x7F5AF53E6FB0>]
inputs['pixel_values'].shape
torch.Size([1092, 1176])

可以看到第三种inputs[‘pixel_values’].shape最大


http://www.kler.cn/news/324188.html

相关文章:

  • 【算法题】221. 最大正方形-力扣(LeetCode)
  • 【Verilog学习日常】—牛客网刷题—Verilog企业真题—VL66
  • 负载均衡--会话保持失败原因及解决方案(五)
  • 鸿蒙harmonyos next纯flutter开发环境搭建
  • HTML基础用法介绍二
  • Goland使用SSH远程Linux进行断点调试 (兼容私有库)
  • Leetcode基础算法篇|202409(4)贪心算法
  • MySQL数据库修改authentication_string字段为显示密码后无法登录
  • oracle 如何判断当前时间在27号到当月月底
  • [JavaEE] HTTP/HTTPS
  • 2024中国新能源汽车零部件交易会,开源网安展示了什么?
  • Tomcat安装和配置教程(图文详解,最简洁易懂)
  • 【优选算法】(第七篇)
  • Python 算法交易实验89 QTV200日常推进-模式思考
  • SQL:如果字段需要排除某个值但又有空值时,不能直接用“<>”或not in
  • 万字长文理解无界队列和有界队列和适用场景
  • 《自控》误差传递函数、稳态误差、0型、I型、II型系统
  • 从零开始Ubuntu24.04上Docker构建自动化部署(五)Docker安装jenkins
  • TypeScript 设计模式之【策略模式】
  • PHP Session扩展默认session数据储存在哪里
  • 3. 轴指令(omron 机器自动化控制器)——>MC_MoveFeed
  • IDEA开发SpringBoot项目基础入门教程。包括Spring Boot简介、IDEA创建相关工程及工程结构介绍、书写配置文件、Bean对象管理等内容
  • 【教学类-18-04】20240508《蒙德里安“黑白格子画” 七款图案挑选》
  • [大语言模型-论文精读] 词性对抗性攻击:文本到图像生成的实证研究
  • 基于VUE的在线手办交易平台购物网站前后端分离系统设计与实现
  • 在矩池云使用 Llama-3.2-11B-Vision 详细指南
  • vxe-table制作高亮刷新功能
  • C#源码安装ZedGraph组件,并且立即演示使用
  • 代码随想录训练营第46天|回文子序列
  • 高通Camx-内存池架构/ImageBuffer