视觉语言模型 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)
相关推荐
Work(沉淀版)34 分钟前
DAY 40
人工智能·深度学习·机器学习
蓦然回首却已人去楼空2 小时前
Build a Large Language Model (From Scratch) 序章
人工智能·语言模型·自然语言处理
CM莫问2 小时前
<论文>(微软)WINA:用于加速大语言模型推理的权重感知神经元激活
人工智能·算法·语言模型·自然语言处理·大模型·推理加速
拾忆-eleven2 小时前
NLP学习路线图(二十六):自注意力机制
人工智能·深度学习
MYH5163 小时前
在NLP文本处理中,将字符映射到阿拉伯数字(构建词汇表vocab)的核心目的和意义
人工智能·深度学习·自然语言处理
要努力啊啊啊3 小时前
KV Cache:大语言模型推理加速的核心机制详解
人工智能·语言模型·自然语言处理
mzlogin5 小时前
DIY|Mac 搭建 ESP-IDF 开发环境及编译小智 AI
人工智能
归去_来兮5 小时前
知识图谱技术概述
大数据·人工智能·知识图谱
就是有点傻5 小时前
VM图像处理之图像二值化
图像处理·人工智能·计算机视觉
行云流水剑5 小时前
【学习记录】深入解析 AI 交互中的五大核心概念:Prompt、Agent、MCP、Function Calling 与 Tools
人工智能·学习·交互