찾다
기술 주변기기일체 포함다중 모드 RAG 시스템 구축 방법: CLIP 및 LLM 사용

오픈소스 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으로 문의하시기 바랍니다. 삭제
LLM에서 도구 호출LLM에서 도구 호출Apr 14, 2025 am 11:28 AM

대형 언어 모델 (LLM)은 인기가 높아졌으며, 도구 전달 기능은 단순한 텍스트 생성을 넘어 기능을 극적으로 확장했습니다. 이제 LLM은 동적 UI 생성 및 자율적 인 A와 같은 복잡한 자동화 작업을 처리 할 수 ​​있습니다.

ADHD 게임, 건강 도구 및 AI 챗봇이 글로벌 건강을 변화시키는 방법ADHD 게임, 건강 도구 및 AI 챗봇이 글로벌 건강을 변화시키는 방법Apr 14, 2025 am 11:27 AM

비디오 게임이 불안을 완화하거나 집중하거나 ADHD를 가진 어린이를 지원할 수 있습니까? 건강 관리 도전이 전 세계적으로 급증함에 따라, 특히 청소년들 사이에서 혁신가들은 비디오 게임 인 가능성이없는 도구로 전환하고 있습니다. 이제 세계 최대의 엔터테인먼트 인더스 중 하나입니다

AI에 대한 UN 입력 : 우승자, 패자 및 기회AI에 대한 UN 입력 : 우승자, 패자 및 기회Apr 14, 2025 am 11:25 AM

UNCTAD의 사무 총장 인 Rebeca Grynspan은“역사는 기술 진보가 경제 성장을 유발하거나 공평한 소득 분배를 보장하거나 포용적인 인간 발전을 촉진하지는 않습니다.

생성 AI를 통한 협상 기술 ​​학습생성 AI를 통한 협상 기술 ​​학습Apr 14, 2025 am 11:23 AM

쉽게 생성 AI를 협상 교사 및 스파링 파트너로 사용하십시오. 그것에 대해 이야기합시다. 혁신적인 AI 혁신에 대한이 분석은 AI의 최신 Forbes 열 범위의 일부입니다.

Ted는 Openai, Google, 메타가 법정으로 공개됩니다.Ted는 Openai, Google, 메타가 법정으로 공개됩니다.Apr 14, 2025 am 11:22 AM

밴쿠버에서 개최 된 TED2025 컨퍼런스는 어제 4 월 11 일 36 번째 판을 마무리했습니다. Sam Altman, Eric Schmidt 및 Palmer Luckey를 포함한 60 개 이상의 국가에서 80 명의 스피커를 선보였습니다. 테드의 주제 인“인류를 다시 상상했다”는 재단사가 만들어졌다

Joseph Stiglitz는 AI 독점권 속에서 임시 불평등을 경고합니다.Joseph Stiglitz는 AI 독점권 속에서 임시 불평등을 경고합니다.Apr 14, 2025 am 11:21 AM

Joseph Stiglitz는 2001 년에 유명한 경제학자이자 노벨 경제학상을 수상했습니다. Stiglitz는 AI가 기존의 불평등과 통합 된 권력을 몇몇 지배적 인 기업의 손에 악화시킬 수 있으며 궁극적으로 경제를 훼손 할 수 있다고 주장합니다.

그래프 데이터베이스 란 무엇입니까?그래프 데이터베이스 란 무엇입니까?Apr 14, 2025 am 11:19 AM

그래프 데이터베이스 : 관계를 통한 데이터 관리 혁명 데이터가 확장되고 그 특성이 다양한 필드에서 발전함에 따라 그래프 데이터베이스는 상호 연결된 데이터를 관리하기위한 변환 솔루션으로 떠오르고 있습니다. 전통적인 것과는 달리

LLM 라우팅 : 전략, 기술 및 파이썬 구현LLM 라우팅 : 전략, 기술 및 파이썬 구현Apr 14, 2025 am 11:14 AM

대형 언어 모델 (LLM) 라우팅 : 지능형 작업 분포를 통한 성능 최적화 LLM의 빠르게 진화하는 환경은 각각 독특한 강점과 약점을 가진 다양한 모델을 제시합니다. 일부는 Creative Content Gen에서 탁월합니다

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구