视觉语言模型 Qwen2-VL

视觉语言模型 Qwen2-VL

flyfish

py 复制代码
from PIL import Image
import requests
import torch
from torchvision import io
from typing import Dict
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
from modelscope import snapshot_download

# 下载模型快照并指定保存目录
model_dir = snapshot_download("qwen/Qwen2-VL-7B-Instruct")

# 加载模型到可用设备(CPU或GPU),并使用自动精度(根据设备自动选择)
model = Qwen2VLForConditionalGeneration.from_pretrained(
    model_dir, torch_dtype="auto", device_map="auto"
)

# 加载图像处理器
processor = AutoProcessor.from_pretrained(model_dir)

# 图像的URL
url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"

# 从给定的URL加载图像
image = Image.open(requests.get(url, stream=True).raw)

# 定义对话历史,包括用户输入的文本和图像
conversation = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
            },
            {"type": "text", "text": "Describe this image."},
        ],
    }
]

# 使用处理器应用聊天模板,并添加生成提示
text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)

# 预处理输入数据,将文本和图像转换为模型可以接受的格式
inputs = processor(
    text=[text_prompt], images=[image], padding=True, return_tensors="pt"
)

# 将输入数据移动到CUDA设备上(如果可用的话)
inputs = inputs.to("cuda")

# 推理:生成输出文本
output_ids = model.generate(**inputs, max_new_tokens=128)  # 最大新生成token数量为128

# 提取生成的token ID,去掉输入的原始token ID
generated_ids = [
    output_ids[len(input_ids) :]
    for input_ids, output_ids in zip(inputs.input_ids, output_ids)
]

# 解码生成的token ID为人类可读的文本
output_text = processor.batch_decode(
    generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
)

# 打印生成的描述文本
print(output_text)
相关推荐
XM_jhxx3 小时前
±0.03mm的精度怎么保证?翌东塑胶用AI赋能质量管控升级
人工智能
阿正的梦工坊3 小时前
深入理解 PyTorch 中的 unsqueeze 操作
人工智能·pytorch·python
秦歌6665 小时前
DeepAgents框架详解和文件后端
人工智能·langchain
测试员周周6 小时前
【Appium 系列】第06节-页面对象实现 — LoginPage 实战
开发语言·前端·人工智能·python·功能测试·appium·测试用例
霸道流氓气质6 小时前
基于 Milvus Lite 的 Spring AI RAG 向量库实践方案与示例
人工智能·spring·milvus
ar01236 小时前
AR巡检平台:构筑智能巡检新模式的数字化引擎
人工智能·ar
语音之家6 小时前
【预讲会征集】ACL 2026 论文预讲会
人工智能·论文·acl
碳基硅坊6 小时前
电商场景下的商品自动识别与辅助上架
人工智能
熊猫钓鱼>_>7 小时前
强化学习与决策优化:从理论到工程落地的完整指南
人工智能·llm·强化学习·rl·马尔可夫·mdp·决策过程