视觉语言模型 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)
相关推荐
Psycho_MrZhang几秒前
Agent 测评、缺陷分级与发布流程
人工智能
朝朝辞暮i3 分钟前
VLA 系统学习第 17 课:正式进入 ACT——为什么需要 CVAE、潜变量 z 和 KL Loss?
人工智能·深度学习·神经网络·transformer·vla
小宋102114 分钟前
Agent轨迹级评测实战:工具选择、预算超限与回归门禁
android·网络·人工智能·回归
larance20 分钟前
[菜鸟教程] 机器学习教程九课-常用数据类型
人工智能·机器学习
宋哥转AI33 分钟前
我的创作纪念日:成为创作者的第 128 天
人工智能·ai
AI编程教父35 分钟前
WorkBuddy企业培训怎么选?腾讯云公开课程与红烁AI内训对比
大数据·人工智能
深蓝AI44 分钟前
AI Agent 点了发布却超时:一条回执丢失,为什么能造成两篇文章?
人工智能·python
怪奇云呼军1 小时前
教育试听预约后没到课,闪电智能 Voice Agent 如何做分层回访?
人工智能·python·算法·云计算·音视频
ajassi20001 小时前
AI语音智能体开发日记(十八)智能体服务器xiaozhi-esp32-server源码部署指南
运维·服务器·人工智能·ai·ai编程
云淡风轻~窗明几净1 小时前
角谷猜想的进展之三 移动了群山/沸騰的群山 2026-10-10
人工智能·算法·dubbo·图论