ホームページ  >  記事  >  テクノロジー周辺機器  >  マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する

WBOY
WBOY転載
2024-01-13 22:24:12718ブラウズ

オープンソースの大規模言語マルチモーダルを使用して、検索拡張生成 (RAG) システムを構築する方法について説明します。私たちの焦点は、フレームワークの依存関係の追加を避けるために、LangChain や LLlama インデックスに依存せずにこれを達成することです。

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する

RAGとは

人工知能の分野で、検索拡張世代の出現RAG テクノロジーの導入により、大規模言語モデル (Large Language Model) に革命的な改善がもたらされました。 RAG の本質は、モデルが外部ソースからリアルタイム情報を動的に取得できるようにすることで、人工知能の応答性を向上させることです。この技術の導入により、AIがユーザーのニーズによりきめ細かく対応できるようになります。外部ソースから情報を取得して融合することで、RAG はより正確で包括的な回答を生成し、より価値のあるコンテンツをユーザーに提供できます。この機能の向上により、インテリジェントな顧客サービス、インテリジェントな検索、知識の質問と回答システムなど、人工知能の応用分野に幅広い展望がもたらされました。 RAG の出現は、言語モデルのさらなる開発を示し、人工知能をもたらします

このアーキテクチャは、動的検索プロセスと生成機能をシームレスに組み合わせ、人工知能が常に変化する情報のさまざまな分野に適応できるようにします。 。微調整や再トレーニングとは異なり、RAG は、AI がモデル全体を変更せずに最新の関連情報を取得できる、コスト効率の高いソリューションを提供します。この機能の組み合わせにより、RAG は急速に変化する情報環境に対応する際の利点が得られます。

RAG の役割

1. 精度と信頼性の向上:

大きな言語でモデル (LLM) は信頼できる情報源を直接導き、その予測不可能性の問題を解決し、誤った情報や古い情報を提供するリスクを軽減し、応答の正確性と信頼性を高めます。

2. 透明性と信頼性の向上:

LLM のような生成 AI モデルは透明性に欠けていることが多く、人々が信頼することが困難になります。出力。 RAG は、より優れた制御を提供することで、バイアス、信頼性、コンプライアンスに関する懸念に対処します。

3. 幻覚を減らす:

LLM は幻覚反応を起こしやすく、一貫性はあるが不正確または捏造された情報を提供します。 RAG は、信頼できる情報源に依存して対応力を確保することで、主要部門への誤解を招くアドバイスのリスクを軽減します。

4. 費用対効果の高い適応性:

RAG は、大規模な再トレーニングや罰金を必要とせずに AI 出力を向上させる費用対効果の高い方法を提供します。 -チューニング。必要に応じて特定の詳細を動的に取得することで、情報を最新かつ関連性の高い状態に保つことができ、変化する情報に対する AI の適応性を確保します。

マルチモーダル モーダル モデル

マルチモーダルには、CLIP を例として、複数の入力があり、それらを 1 つの出力に結合することが含まれます。 CLIP はテキストと画像のペアであり、モデルは比較学習を通じてテキストと画像のペアの一致関係を学習できます。

このモデルは、同じものを表す異なる入力に対して同じ (非常に類似した) 埋め込みベクトルを生成します。

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する


##マルチモード

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する

マルチモーダル大規模言語

GPT4v と Gemini ビジョンは、さまざまなデータ型 (画像、テキスト、言語、音声など) を統合するマルチモーダル大規模言語を探索します。 モーダル言語モデル (MLLM)。 GPT-3、BERT、RoBERTa などの大規模言語モデル (LLM) はテキストベースのタスクではうまく機能しますが、他のデータ型の理解と処理では課題に直面しています。この制限に対処するために、マルチモーダル モデルはさまざまなモダリティを組み合わせて、さまざまなデータをより包括的に理解できるようにします。

マルチモーダル大規模言語モデル 従来のテキストベースの方法を超えています。 GPT-4 を例に挙げると、これらのモデルは、画像やテキストなどのさまざまなデータ タイプをシームレスに処理して、情報をより包括的に理解できます。

RAG と組み合わせる

ここでは、Clip を使用して画像とテキストを埋め込み、これらの埋め込みを ChromDB ベクター データベースに保存します。大規模なモデルは、取得された情報に基づいてユーザー チャット セッションに参加するために利用されます。

マルチモーダル RAG システムを構築する方法: CLIP と LLM を使用する


Kaggle の画像と Wikipedia の情報を使用して、花の専門家チャットボットを作成します

最初にソフトウェア パッケージをインストールします:

! 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事は51cto.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。