使用CLIP和LLM构建多模态RAG系统

本文涉及的产品
实时计算 Flink 版,5000CU*H 3个月
实时数仓Hologres,5000CU*H 100GB 3个月
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
简介: 在本文中我们将探讨使用开源大型语言多模态模型(Large Language Multi-Modal)构建检索增强生成(RAG)系统。本文的重点是在不依赖LangChain或LLlama index的情况下实现这一目标,这样可以避免更多的框架依赖。

什么是RAG

在人工智能领域,检索增强生成(retrieve - augmented Generation, RAG)作为一种变革性技术改进了大型语言模型(Large Language Models)的能力。从本质上讲,RAG通过允许模型从外部源动态检索实时信息来增强AI响应的特异性。

该体系结构将生成能力与动态检索过程无缝结合,使人工智能能够适应不同领域中不断变化的信息。与微调和再训练不同,RAG提供了一种经济高效的解决方案,允许人工智能在不改变整个模型的情况下能够得到最新和相关的信息。

RAG的作用

1、提高准确性和可靠性:

通过将大型语言模型(llm)重定向到权威的知识来源来解决它们的不可预测性。降低了提供虚假或过时信息的风险,确保更准确和可靠的反应。

2、增加透明度和信任:

像LLM这样的生成式人工智能模型往往缺乏透明度,这使得人们很难相信它们的输出。RAG通过允许组织对生成的文本输出有更大的控制,解决了对偏差、可靠性和遵从性的关注。

3、减轻幻觉:

LLM容易产生幻觉反应——连贯但不准确或捏造的信息。RAG通过确保响应以权威来源为基础,减少关键部门误导性建议的风险。

4、具有成本效益的适应性:

RAG提供了一种经济有效的方法来提高AI输出,而不需要广泛的再训练/微调。可以通过根据需要动态获取特定细节来保持最新和相关的信息,确保人工智能对不断变化的信息的适应性。

多模式模态模型

多模态涉及有多个输入,并将其结合成单个输出,以CLIP为例:CLIP的训练数据是文本-图像对,通过对比学习,模型能够学习到文本-图像对的匹配关系。

该模型为表示相同事物的不同输入生成相同(非常相似)的嵌入向量。

多模

态大型语言(multi-modal large language)

GPT4v和Gemini vision就是探索集成了各种数据类型(包括图像、文本、语言、音频等)的多模态语言模型(MLLM)。虽然像GPT-3、BERT和RoBERTa这样的大型语言模型(llm)在基于文本的任务中表现出色,但它们在理解和处理其他数据类型方面面临挑战。为了解决这一限制,多模态模型结合了不同的模态,从而能够更全面地理解不同的数据。

多模态大语言模型它超越了传统的基于文本的方法。以GPT-4为例,这些模型可以无缝地处理各种数据类型,包括图像和文本,从而更全面地理解信息。

与RAG相结合

这里我们将使用Clip嵌入图像和文本,将这些嵌入存储在ChromDB矢量数据库中。然后将利用大模型根据检索到的信息参与用户聊天会话。

我们将使用来自Kaggle的图片和维基百科的信息来创建一个花卉专家聊天机器人

首先我们安装软件包:

 ! pip install -q timm einops wikipedia chromadb open_clip_torch
 !pip install -q transformers==4.36.0
 !pip install -q bitsandbytes==0.41.3 accelerate==0.25.0

预处理数据的步骤很简单只是把图像和文本放在一个文件夹里

可以随意使用任何矢量数据库,这里我们使用ChromaDB。

 import chromadb

 from chromadb.utils.embedding_functions import OpenCLIPEmbeddingFunction
 from chromadb.utils.data_loaders import ImageLoader
 from chromadb.config import Settings


 client = chromadb.PersistentClient(path="DB")

 embedding_function = OpenCLIPEmbeddingFunction()
 image_loader = ImageLoader() # must be if you reads from URIs

ChromaDB需要自定义嵌入函数

 from chromadb import Documents, EmbeddingFunction, Embeddings

 class MyEmbeddingFunction(EmbeddingFunction):
     def __call__(self, input: Documents) -> Embeddings:
         # embed the documents somehow or images
         return embeddings

这里将创建2个集合,一个用于文本,另一个用于图像

 collection_images = client.create_collection(
     name='multimodal_collection_images', 
     embedding_function=embedding_function, 
     data_loader=image_loader)

 collection_text = client.create_collection(
     name='multimodal_collection_text', 
     embedding_function=embedding_function, 
     )

 # Get the Images
 IMAGE_FOLDER = '/kaggle/working/all_data'


 image_uris = sorted([os.path.join(IMAGE_FOLDER, image_name) for image_name in os.listdir(IMAGE_FOLDER) if not image_name.endswith('.txt')])
 ids = [str(i) for i in range(len(image_uris))]

 collection_images.add(ids=ids, uris=image_uris) #now we have the images collection

对于Clip,我们可以像这样使用文本检索图像

 from matplotlib import pyplot as plt

 retrieved = collection_images.query(query_texts=["tulip"], include=['data'], n_results=3)
 for img in retrieved['data'][0]:
     plt.imshow(img)
     plt.axis("off")
     plt.show()

也可以使用图像检索相关的图像

文本集合如下所示

 # now the text DB
 from chromadb.utils import embedding_functions
 default_ef = embedding_functions.DefaultEmbeddingFunction()

 text_pth = sorted([os.path.join(IMAGE_FOLDER, image_name) for image_name in os.listdir(IMAGE_FOLDER) if image_name.endswith('.txt')])

 list_of_text = []
 for text in text_pth:
     with open(text, 'r') as f:
         text = f.read()
         list_of_text.append(text)

 ids_txt_list = ['id'+str(i) for i in range(len(list_of_text))]
 ids_txt_list

 collection_text.add(
     documents = list_of_text,
     ids =ids_txt_list
 )

然后使用上面的文本集合获取嵌入

 results = collection_text.query(
     query_texts=["What is the bellflower?"],
     n_results=1
 )

 results

结果如下:

 {'ids': [['id0']],
  'distances': [[0.6072186183744086]],
  'metadatas': [[None]],
  'embeddings': None,
  'documents': [['Campanula () is the type genus of the Campanulaceae family of flowering plants. Campanula are commonly known as bellflowers and take both their common and scientific names from the bell-shaped flowers—campanula is Latin for "little bell".\nThe genus includes over 500 species and several subspecies, distributed across the temperate and subtropical regions of the Northern Hemisphere, with centers of diversity in the Mediterranean region, Balkans, Caucasus and mountains of western Asia. The range also extends into mountains in tropical regions of Asia and Africa.\nThe species include annual, biennial and perennial plants, and vary in habit from dwarf arctic and alpine species under 5 cm high, to large temperate grassland and woodland species growing to 2 metres (6 ft 7 in) tall.']],
  'uris': None,
  'data': None}

或使用图片获取文本

 query_image = '/kaggle/input/flowers/flowers/rose/00f6e89a2f949f8165d5222955a5a37d.jpg'
 raw_image = Image.open(query_image)

 doc = collection_text.query(
     query_embeddings=embedding_function(query_image),

     n_results=1,

 )['documents'][0][0]

上图的结果如下:

 A rose is either a woody perennial flowering plant of the genus Rosa (), in the family Rosaceae (), or the flower it bears. There are over three hundred species and tens of thousands of cultivars. They form a group  of plants that can be erect shrubs, climbing, or trailing, with stems  that are often armed with sharp prickles. Their flowers vary in size and shape and are usually large and showy, in colours ranging from white  through yellows and reds. Most species are native to Asia, with smaller  numbers native to Europe, North America, and northwestern Africa.  Species, cultivars and hybrids are all widely grown for their beauty and often are fragrant. Roses have acquired cultural significance in many  societies. Rose plants range in size from compact, miniature roses, to  climbers that can reach seven meters in height. Different species  hybridize easily, and this has been used in the development of the wide  range of garden roses.

这样我们就完成了文本和图像的匹配工作,其实这里都是CLIP的工作,下面我们开始加入LLM。

 from huggingface_hub import hf_hub_download

 hf_hub_download(repo_id="visheratin/LLaVA-3b", filename="configuration_llava.py", local_dir="./", force_download=True)
 hf_hub_download(repo_id="visheratin/LLaVA-3b", filename="configuration_phi.py", local_dir="./", force_download=True)
 hf_hub_download(repo_id="visheratin/LLaVA-3b", filename="modeling_llava.py", local_dir="./", force_download=True)
 hf_hub_download(repo_id="visheratin/LLaVA-3b", filename="modeling_phi.py", local_dir="./", force_download=True)
 hf_hub_download(repo_id="visheratin/LLaVA-3b", filename="processing_llava.py", local_dir="./", force_download=True)

我们是用visheratin/LLaVA-3b

 from modeling_llava import LlavaForConditionalGeneration
 import torch

 model = LlavaForConditionalGeneration.from_pretrained("visheratin/LLaVA-3b")
 model = model.to("cuda")

加载tokenizer

 from transformers import AutoTokenizer

 tokenizer = AutoTokenizer.from_pretrained("visheratin/LLaVA-3b")

然后定义处理器,方便我们以后调用

 from processing_llava import LlavaProcessor, OpenCLIPImageProcessor

 image_processor = OpenCLIPImageProcessor(model.config.preprocess_config)
 processor = LlavaProcessor(image_processor, tokenizer)

下面就可以直接使用了

 question = 'Answer with organized answers: What type of rose is in the picture? Mention some of its characteristics and how to take care of it ?'

 query_image = '/kaggle/input/flowers/flowers/rose/00f6e89a2f949f8165d5222955a5a37d.jpg'
 raw_image = Image.open(query_image)

 doc = collection_text.query(
     query_embeddings=embedding_function(query_image),

     n_results=1,

 )['documents'][0][0]

 plt.imshow(raw_image)
 plt.show()
 imgs = collection_images.query(query_uris=query_image, include=['data'], n_results=3)
 for img in imgs['data'][0][1:]:
     plt.imshow(img)
     plt.axis("off")
     plt.show()

得到的结果如下:

结果还包含了我们需要的大部分信息

这样我们整合就完成了,最后就是创建聊天模板,

 prompt = """<|im_start|>system
 A chat between a curious human and an artificial intelligence assistant.
 The assistant is an exprt in flowers , and gives helpful, detailed, and polite answers to the human's questions.
 The assistant does not hallucinate and pays very close attention to the details.<|im_end|>
 <|im_start|>user
 <image>
 {question} Use the following article as an answer source. Do not write outside its scope unless you find your answer better {article} if you thin your answer is better add it after document.<|im_end|>
 <|im_start|>assistant
 """.format(question='question', article=doc)

如何创建聊天过程我们这里就不详细介绍了,完整代码在这里:

https://avoid.overfit.cn/post/c2d8059cc5c145a48acb5ecb8890dc0e

作者:Ahmed Haytham

目录
相关文章
|
8天前
|
人工智能 语音技术
首个可保留情感的音频LLM!Meta重磅开源7B-Spirit LM,一网打尽音频+文本多模态任务
Meta AI 研究团队提出了一种名为 SpiRit-LM 的新型多模态语言模型,该模型能够处理文本和音频,实现两者无缝融合。SpiRit-LM 通过“交织”方法训练,具备多模态融合、情感保留和多任务学习能力,在自动语音识别、文本转语音等任务上表现出色。它有 Base 和 Expressive 两个版本,后者能更好地捕捉情感表达。研究团队在多个基准上测试了其性能,并探索了其在语音助手、内容创作、教育和音频编辑等领域的应用前景。
18 1
|
10天前
|
人工智能
RAG没有银弹!四级难度,最新综述覆盖数据集、解决方案,教你LLM+外部数据的正确使用姿势
在人工智能领域,大型语言模型(LLM)结合外部数据展现出强大能力,尤其检索增强生成(RAG)和微调技术备受关注。然而,不同专业领域的有效部署仍面临挑战,如准确检索数据、理解用户意图等。综述文章《Retrieval Augmented Generation (RAG) and Beyond》提出RAG任务分类方法,将用户查询分为四个级别,并探讨了外部数据集成的三种形式:上下文、小型模型和微调。文章提供了宝贵见解和实用指导,帮助更好地利用LLM潜力解决实际问题。论文链接:https://arxiv.org/abs/2409.14924
45 6
|
13天前
|
机器学习/深度学习 人工智能 计算机视觉
MILS:无需对LLM进行额外训练就能处理多模态任务,Meta AI提出零样本生成多模态描述方法
MILS 是 Meta AI 推出的零样本生成高质量多模态描述方法,支持图像、视频和音频的描述生成,无需额外训练。
102 34
MILS:无需对LLM进行额外训练就能处理多模态任务,Meta AI提出零样本生成多模态描述方法
|
1月前
|
人工智能 数据可视化 开发者
FlowiseAI:34K Star!集成多种模型和100+组件的 LLM 应用低代码开发平台,拖拽组件轻松构建程序
FlowiseAI 是一款开源的低代码工具,通过拖拽可视化组件,用户可以快速构建自定义的 LLM 应用程序,支持多模型集成和记忆功能。
117 14
FlowiseAI:34K Star!集成多种模型和100+组件的 LLM 应用低代码开发平台,拖拽组件轻松构建程序
|
1月前
|
自然语言处理 人机交互 数据库
TransferTOD:利用LLM解决TOD系统在域外场景槽位难以泛化的问题
任务型对话系统旨在高效处理任务导向的对话,如何利用任务型对话系统准确、高效、合理地完成信息采集的工作一直是一项关键且具有挑战性的任务。
|
2月前
|
弹性计算 自然语言处理 数据库
通过阿里云Milvus和LangChain快速构建LLM问答系统
本文介绍如何通过整合阿里云Milvus、阿里云DashScope Embedding模型与阿里云PAI(EAS)模型服务,构建一个由LLM(大型语言模型)驱动的问题解答应用,并着重演示了如何搭建基于这些技术的RAG对话系统。
|
2月前
|
开发框架 人工智能 安全
Promptic:轻量级 LLM 应用开发框架,提供完善的底层功能,使开发者更专注于构建上层功能
Promptic 是一个轻量级的 LLM 应用开发框架,支持通过一行代码切换不同的 LLM 服务提供商。它提供了类型安全的输出、流式支持、内置对话记忆、错误处理和重试等功能,帮助开发者专注于构建功能,而不是底层的复杂性。
92 6
Promptic:轻量级 LLM 应用开发框架,提供完善的底层功能,使开发者更专注于构建上层功能
|
2月前
|
人工智能 算法
图像伪造照妖镜!北大发布多模态LLM图像篡改检测定位框架FakeShield
北京大学研究团队提出了一种名为FakeShield的多模态框架,旨在解决图像伪造检测与定位(IFDL)中的黑箱问题及泛化能力不足。FakeShield不仅能评估图像真实性,生成篡改区域的掩码,还能提供像素级和图像级的篡改线索及详细文本描述,增强检测的可解释性。通过使用GPT-4o增强现有数据集,创建多模态篡改描述数据集(MMTD-Set),并引入领域标签引导的可解释伪造检测模块(DTE-FDM)和多模态伪造定位模块(MFLM),FakeShield在多种篡改技术的检测与定位上表现优异,为图像真实性维护提供了有力工具。
120 14
|
3月前
|
自然语言处理 算法
RAG真能提升LLM推理能力?人大最新研究:数据有噪声,RAG性能不升反降
随着大型语言模型(LLM)在自然语言处理领域的广泛应用,检索增强生成(RAG)技术因能引入新知识和减少幻觉而受到关注。然而,RAG对LLM推理能力的实际提升效果仍存争议。中国人民大学的一项研究表明,RAG虽能辅助LLM推理,但在处理含噪信息和深度推理时面临挑战。为此,研究团队提出了DPrompt tuning方法,旨在解决噪声问题并提升RAG性能。
85 12
|
3月前
|
数据采集 人工智能 自然语言处理
万字干货|复杂表格多Agent方案:从LLM洞察、系统性 思考到实践经验总结
笔者结合实践经验以近期在负责的复杂表格智能问答为切入点,结合大模型的哲学三问(“是谁、从哪里来、到哪里去”),穿插阐述自己对大模型的一些理解与判断,以及面向公共云LLM的建设模式思考,并分享软件设计+模型算法结合的一些研发实践经验。