视觉语言模型 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)
相关推荐
Thanks_ks33 分钟前
AI Agent 开发入门:用 Function Calling 让大模型学会 “动手干活”,附订单查询机器人实战
python·ai·大模型·openai·agent·通义千问·mcp
土豆12502 小时前
你只说要什么,它负责拆活交付:任务编排插件上手指南
人工智能·llm
GoldenSpider.AI4 小时前
讲透 Claude Code 的 Code Mode:原理、流程、用法与 24 轮实测
人工智能·ai编程·claude code
oak隔壁找我4 小时前
一款运行在 DSH(DeepSeek Harness)中的工作区文件管理插件
人工智能
江屿风4 小时前
AI Agent架构全解析:从规划到记忆的智能跃迁
人工智能·笔记·架构·agent·c/s·mcp工作流
ZONGYUAN-ROOT4 小时前
【API配额】多源 LLM API 配额池化实战:轮换调度、变化量监控、故障自愈一套方案(Python 完整实现)
人工智能
syso_稻草人4 小时前
qwen-image-2.1 高清放大拆解:Qwen21LatentUpscale 潜空间 2x + denoise 0.35 修细节,12 组场景实测
人工智能·stable diffusion·prompt·comfyui·qwen-image2.1
羲云网络5 小时前
GPT Image 2.6 动态表情怎么改:从情绪歧义到动作节奏验收
人工智能·gif·图像编辑
EatFan5 小时前
AI Agent 工程化元年:从单体智能到 Agent 集群的架构演进与落地路径
人工智能·架构·ai agent·autogen·crewai·agent集群·记忆工程