다중 모드 RAG 시스템 구축 방법: CLIP 및 LLM 사용

WBOY
풀어 주다: 2024-01-13 22:24:12
앞으로
773명이 탐색했습니다.

오픈소스 Large Language Multi-Modal을 활용하여 RAG(Retrieval Augmented Generation) 시스템을 구축하는 방법에 대해 논의하겠습니다. 우리의 초점은 더 많은 프레임워크 종속성을 추가하지 않기 위해 LangChain 또는 LLlama 인덱스에 의존하지 않고 이를 달성하는 것입니다.

다중 모드 RAG 시스템 구축 방법: CLIP 및 LLM 사용

RAG란 무엇입니까

인공지능 분야에서 RAG(Recovery-Augmented Generation) 기술의 등장은 대규모 언어 모델(Large Language Models)에 혁명적인 발전을 가져왔습니다. RAG의 핵심은 모델이 외부 소스로부터 실시간 정보를 동적으로 검색할 수 있도록 하여 인공지능의 반응성을 높이는 것입니다. 이 기술의 도입으로 AI는 사용자 요구에 보다 구체적으로 대응할 수 있게 됐다. RAG는 ​​외부 소스에서 정보를 검색하고 융합함으로써 보다 정확하고 포괄적인 답변을 생성하여 사용자에게 보다 가치 있는 콘텐츠를 제공할 수 있습니다. 이러한 기능 향상으로 지능형 고객 서비스, 지능형 검색, 지식 질의응답 시스템 등 인공지능 응용 분야에 대한 전망이 더욱 넓어졌습니다. RAG의 출현은 언어 모델의 추가 개발을 의미하며

을 인공 지능에 도입합니다. 이 아키텍처는 동적 검색 프로세스와 생성 기능을 원활하게 결합하여 인공 지능이 다양한 분야에서 변화하는 정보에 적응할 수 있도록 합니다. 미세 조정 및 재훈련과 달리 RAG는 AI가 전체 모델을 변경하지 않고도 최신 관련 정보를 얻을 수 있는 비용 효율적인 솔루션을 제공합니다. 이러한 기능의 조합은 RAG가 급변하는 정보 환경에 대응하는 데 있어 이점을 제공합니다.

RAG의 역할

1. 정확성과 신뢰성 향상:

LLM을 신뢰할 수 있는 지식 소스로 전달하여 예측 불가능성 문제를 해결합니다. 허위이거나 오래된 정보는 응답을 더욱 정확하고 신뢰할 수 있게 만듭니다.

2. 투명성과 신뢰도 향상:

LLM과 같은 생성형 AI 모델은 투명성이 부족한 경우가 많아 사람들이 결과물을 신뢰하기 어렵습니다. RAG는 ​​더 강력한 제어 기능을 제공하여 편향, 신뢰성 및 규정 준수에 대한 우려를 해결합니다.

3. 환각 감소:

LLM은 환각 반응을 일으키기 쉽습니다. 즉, 일관되지만 부정확하거나 조작된 정보를 제공합니다. RAG는 ​​대응을 보장하기 위해 권위 있는 소스에 의존함으로써 주요 부문에 대한 오해의 소지가 있는 조언의 위험을 줄입니다.

4. 비용 효율적인 적응성:

RAG는 광범위한 재교육/미세 조정 없이 AI 출력을 향상시킬 수 있는 비용 효율적인 방법을 제공합니다. 필요에 따라 특정 세부 정보를 동적으로 검색하여 정보를 최신 상태로 유지하고 변화하는 정보에 대한 AI 적응성을 보장할 수 있습니다.

멀티모달 모달 모델

멀티모달은 여러 입력을 갖고 이를 단일 출력으로 결합하는 것을 포함하며 CLIP을 예로 들어 보겠습니다. CLIP의 학습 데이터는 텍스트-이미지 쌍이며 대조 학습을 통해 모델은 텍스트-이미지 쌍 간의 일치 관계를 학습합니다.

이 모델은 동일한 것을 나타내는 다양한 입력에 대해 동일한(매우 유사한) 임베딩 벡터를 생성합니다. multi-modal

다중 모드 RAG 시스템 구축 방법: CLIP 및 LLM 사용


모달 대형 언어 (멀티 모달 큰 언어)

GPT4V 및 Gemini Vision은 다양한 데이터 유형 (이미지, 텍스트, 포함 포함)을 탐색하고 통합합니다. 언어, 오디오 등) MLLM(다중 모드 언어 모델). GPT-3, BERT, RoBERTa와 같은 대규모 언어 모델(LLM)은 텍스트 기반 작업에서는 잘 수행되지만 다른 데이터 유형을 이해하고 처리하는 데 어려움을 겪습니다. 이러한 한계를 해결하기 위해 다중 모드 모델은 다양한 양식을 결합하여 다양한 데이터를 보다 포괄적으로 이해할 수 있도록 합니다.

다중 모드 RAG 시스템 구축 방법: CLIP 및 LLM 사용

다중 모드 대형 언어 모델 전통적인 텍스트 기반 방법을 뛰어넘습니다. GPT-4를 예로 들면, 이러한 모델은 이미지와 텍스트를 포함한 다양한 데이터 유형을 원활하게 처리하여 정보를 보다 완벽하게 이해할 수 있습니다.

RAG

여기에서는 Clip을 사용하여 이미지와 텍스트를 삽입하고 이러한 삽입을 ChromDB 벡터 데이터베이스에 저장합니다. 그런 다음 대규모 모델을 활용하여 검색된 정보를 기반으로 사용자 채팅 세션에 참여합니다.

Kaggle의 이미지와 Wikipedia의 정보를 사용하여 꽃 전문가 챗봇을 만듭니다.

다중 모드 RAG 시스템 구축 방법: CLIP 및 LLM 사용먼저 패키지를 설치합니다.

! 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
로그인 후 복사

데이터 전처리 단계는 매우 간단합니다. 그냥 폴더에 이미지와 텍스트를 넣으세요

다중 모드 RAG 시스템 구축 방법: CLIP 및 LLM 사용

可以随意使用任何矢量数据库,这里我们使用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 imagesreturn embeddings
로그인 후 복사

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

collection_images = client.create_collection(name='multimodal_collection_images', embedding_functinotallow=embedding_function, data_loader=image_loader)  collection_text = client.create_collection(name='multimodal_collection_text', embedding_functinotallow=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()
로그인 후 복사

다중 모드 RAG 시스템 구축 방법: CLIP 및 LLM 사용

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

다중 모드 RAG 시스템 구축 방법: CLIP 및 LLM 사용

文本集合如下所示

# 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]
로그인 후 복사

다중 모드 RAG 시스템 구축 방법: CLIP 및 LLM 사용

上图的结果如下:

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_, filename="configuration_llava.py", local_dir="./", force_download=True) hf_hub_download(repo_, filename="configuration_phi.py", local_dir="./", force_download=True) hf_hub_download(repo_, filename="modeling_llava.py", local_dir="./", force_download=True) hf_hub_download(repo_, filename="modeling_phi.py", local_dir="./", force_download=True) hf_hub_download(repo_, 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()
로그인 후 복사

得到的结果如下:

다중 모드 RAG 시스템 구축 방법: CLIP 및 LLM 사용

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

다중 모드 RAG 시스템 구축 방법: CLIP 및 LLM 사용

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

prompt = """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. 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. assistant """.format(questinotallow='question', article=doc)</image>
로그인 후 복사

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

https://www.php.cn/link/71eee742e4c6e094e6af364597af3f05

위 내용은 다중 모드 RAG 시스템 구축 방법: CLIP 및 LLM 사용의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:51cto.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!