Published on

图像搜索双方案解析:CLIP向量化与Qwen-VL内容描述技术实战

Authors
  • avatar
    Name
    Liant
    Twitter

背景介绍

需求场景是对图片的搜索,目前了解到的方案有两个:

  1. 一个是将图片向量化,然后进行向量搜索;
  2. 一个是对图片内容描述,使用文字搜索;

图片向量

模型地址 ViT-B-16

模型介绍

本项目为CLIP模型的中文版本,使用大规模中文数据进行训练(~2亿图文对),旨在帮助用户快速实现中文领域的图文特征&相似度计算、跨模态检索、零样本图片分类等任务。本项目代码基于open_clip project建设,并针对中文领域数据以及在中文数据上实现更好的效果做了优化。本项目提供了API、训练代码和测试代码,下文中将详细介绍细节。

模型使用

  1. 环境

    • python >= 3.6.4
    • pytorch >= 1.8.0 (with torchvision >= 0.9.0)
    • CUDA Version >= 10.2
  2. 安装

# 依赖项
pip install Pillow

# 1.通过pip安装
pip install cn_clip

# 2.或者从源代码安装
cd Chinese-CLIP
pip install -e .
  1. 使用
import torch 
from PIL import Image

from cn_clip.clip import load_from_name, available_models
print("Available models:", available_models())  
# Available models: ['ViT-B-16', 'ViT-L-14', 'ViT-L-14-336', 'ViT-H-14', 'RN50']

device = "cuda" if torch.cuda.is_available() else "cpu"
# download_root:需要指定模型下载目录
model, preprocess = load_from_name("ViT-B-16", device=device, download_root='./')
model.eval()

imageFD = Image.open('a.png')
image = preprocess(imageFD).unsqueeze(0).to(device)
image_features = model.encode_image(image)
embedding = image_features.tolist()[0]
print(embedding)

部署的主要问题是下载模型

图片描述

模型地址 Qwen-VL-Chat

模型介绍

Qwen-VL 是阿里云研发的大规模视觉语言模型(Large Vision Language Model, LVLM)。Qwen-VL 可以以图像、文本、检测框作为输入,并以文本和检测框作为输出。Qwen-VL 系列模型的特点包括:

模型使用

  1. 环境

    • python 3.8及以上版本
    • pytorch 1.12及以上版本,推荐2.0及以上版本
    • 建议使用CUDA 11.4及以上(GPU用户需考虑此选项)
  2. 安装

pip install modelscope -U
pip install transformers accelerate tiktoken -U
pip install einops transformers_stream_generator -U
pip install "pillow==9.*" -U
pip install torchvision
pip install matplotlib -U
  1. 使用
import json
import time
from datetime import datetime

from modelscope import (
    snapshot_download, AutoModelForCausalLM, AutoTokenizer, GenerationConfig
)
import torch
model_id = 'qwen/Qwen-VL-Chat'
revision = 'v1.1.0'

model_dir = snapshot_download(model_id, revision=revision)
torch.manual_seed(1234)

# 请注意:分词器默认行为已更改为默认关闭特殊token攻击防护。
tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)

# 打开fp16精度,V100、P100、T4等显卡建议启用以节省显存
model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", trust_remote_code=True, fp16=True).eval()

# 可指定不同的生成长度、top_p等相关超参
model.generation_config = GenerationConfig.from_pretrained(model_dir, trust_remote_code=True)

# 第一轮对话 1st dialogue turn
image_path = 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'
query = tokenizer.from_list_format([
    {'image': image_path},
    {'text': '这是什么'},
])
response, history = model.chat(tokenizer, query=query, history=None)
print(response)

使用的是modelscope社区引入,不会出现模型下载不了的问题.