开发环境、工具

windows10 专业版
idea2020.1.4、anaconda3、python3.11.10

机器配置

I5-1240P、16GRAM

模型名称

通义千问 Qwen/Qwen2-VL-2B-Instruct-GPTQ-Int8

代码调用示例

本机无cudn显卡,使用cpu推理调用

from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info
import torch

# 指定本地模型路径
model_dir = 'D:/work/program/pytorch_models/Qwen/Qwen2-VL-2B-Instruct-GPTQ-Int8'

# 加载模型
model = Qwen2VLForConditionalGeneration.from_pretrained(
    model_dir,
    torch_dtype=torch.float32,  # 使用 float32 数据类型
    device_map="cpu"  # 使用 CPU
)

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

# 输入消息
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "file://D:\\work\\code\\clark\\gitee\\py_llm\\output\\result2.png",
            },
            {"type": "text", "text": "描述一下这张图片"},
        ],
    }
]

# 准备推理
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",
)

# 将输入数据移动到 CPU
inputs = inputs.to("cpu")

# 推理:生成输出
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)

执行完成输出结果

生成结果

['这张图片展示了一辆红色的汽车在沙漠中行驶。背景是广阔的沙漠景观,地平线上有几座沙丘。天空呈现出淡黄色,表明可能是清晨或傍晚。汽车的尾灯和后视镜清晰可见,显示出它正在行驶。整个场景给人一种孤独和荒凉的感觉,仿佛汽车正在穿越一个无人的沙漠地带。']

工程代码

https://gitee.com/clark2020/py_llm.git

欢迎讨论交流

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐