Qwen2-VL环境搭建&推理测试

引子

2024年8月30号,阿里推出Qwen2-VL,开源了2B/7B模型,处理任意分辨率图像无需分割成块。之前写了一篇Qwen-VL的博客,感兴趣的童鞋请移步(Qwen-VL环境搭建&推理测试-CSDN博客),这么小的模型,显然我的机器是跑的起来的,OK,那就让我们开始吧。

一、模型介绍

Qwen2-VL 的一项关键架构改进是实现了动态分辨率支持(Naive Dynamic Resolution support)。与上一代模型 Qwen-VL 不同,Qwen2-VL 可以处理任意分辨率的图像,而无需将其分割成块,从而确保模型输入与图像固有信息之间的一致性。这种方法更接近地模仿人类的视觉感知,使模型能够处理任何清晰度或大小的图像。另一个关键架构增强是 Multimodal Rotary Position Embedding(M-ROPE)。通过将 original rotary embedding 分解为代表时间和空间(高度和宽度)信息的三个部分,M-ROPE 使 LLM 能够同时捕获和集成 1D 文本、2D 视觉和 3D 视频位置信息。这使 LLM 能够充当多模态处理器和推理器。

二、环境搭建

1、模型下载

https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct

2、环境安装

docker run -it --rm --gpus=all -v /datas/work/zzq:/workspace pytorch/pytorch:2.4.0-cuda12.4-cudnn9-devel bash

git clone GitHub - huggingface/transformers: 🤗 Transformers: State-of-the-art Machine Learning for Pytorch, TensorFlow, and JAX.

cd transformers

pip install .

pip install qwen-vl-utils -i Simple Index

pip install accelerate==0.26.0 -i Simple Index

三、推理测试

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"
# )
model = Qwen2VLForConditionalGeneration.from_pretrained(
    "models", 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")
processor = AutoProcessor.from_pretrained("models")
# 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)

python test.py

Qwen2是一个预训练的语言模型,通常用于大规模语言生成任务。如果你想对其进行微调训练,首先需要搭建一个支持大语言模型训练的环境。以下是基本步骤: 1. **安装依赖**: - 安装Python(建议使用Python 3.6以上版本) - 安装PyTorch或TensorFlow库(选择其中一个作为深度学习框架) - 可能还需要其他库如transformers(提供预训练模型加载)、torchtext(数据处理工具) 2. **下载模型**: - Qwen2的微调通常是在Hugging Face的Transformers库中进行,访问`https://huggingface.co/qwenerobot/qwen-xxb`下载适合微调的qwen2模型。 3. **准备数据**: - 准备一个文本格式的数据集,包含你需要让模型学习的任务相关的标注数据(例如,问答对、评论标签等) 4. **加载模型并微调**: - 使用`from transformers import AutoTokenizer, AutoModelForSequenceClassification`(或其他任务相关模型)加载模型和分词器 - 将数据集划分为训练集和验证集 - 编写一个训练循环,通过`model.train()`进行模型训练 5. **评估和保存**: - 训练过程中定期评估模型性能,可以使用`model.evaluate()`或`trainer.evaluate()` - 微调完成后,保存模型以便后续使用,可以使用`model.save_pretrained()` ```python # 示例代码片段 tokenizer = AutoTokenizer.from_pretrained("qwenerobot/qwen-xxb") model = AutoModelForSequenceClassification.from_pretrained("qwenerobot/qwen-xxb") train_dataset, val_dataset = ... # 加载数据集 optimizer = AdamW(model.parameters(), lr=...) trainer = Trainer( model=model, train_dataset=train_dataset, eval_dataset=val_dataset, optimizer=optimizer, # 其他训练参数... ) trainer.train() ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

要养家的程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值