AutoAI RAG実験をカスタム基盤モデルコーディングする
ガイドラインとコードサンプルを見て、 AutoAI RAG実験のコーディングとカスタム基盤モデル使用方法を学んでください。
カスタムモデルのデプロイメントでは、 watsonx.ai Python クライアントライブラリ (バージョン 1.3.12 以降)を使用します。
AutoAI RAG 実験でカスタム基盤モデル使用するには、以下の手順に従ってください。
ステップ1:カスタム基盤モデル デプロイメントための前提条件を準備する
モデルのスナップショットをダウンロードする。
from pathlib import Path from huggingface_hub import snapshot_download byom_cache_dir = Path("your", "model", "cache", "dir") if not byom_cache_dir.exists(): raise FileExistsError("Please use the path which exists.") if byom_cache_dir.is_file(): raise NotADirectoryError("Please use the path which points to a directory.") snapshot_download(HUGGING_FACE_MODEL_REPOSITORY, cache_dir=byom_cache_dir)
Cloud Object Storage への接続を作成する。
from ibm_watsonx_ai import APIClient, Credentials credentials = Credentials( api_key=<API_KEY>, url=<WML_ENDPOINT> ) client = APIClient(credentials=credentials, project_id=<PROJECT_ID>)
S3Bucket に接続する。
from ibm_watsonx_ai.helpers.connections import DataConnection, S3Location location = S3Location(bucket=BUCKET_NAME, path=BUCKET_MODEL_DIR_NAME) data_connection = DataConnection(location=location, connection_asset_id=DATASOURCE_CONNECTION_ASSET_ID) data_connection.set_client(api_client=client)
モデルファイルを S3Bucket にアップロードする。
model_files = byom_cache_dir / "model_dir_name" / "snapshots" / "snapshot_id" if not model_files.exists(): raise FileExistsError("Please use the snapshot path which exists.") if model_files.is_file(): raise NotADirectoryError("Please use the snapshot path which points to a directory.") for model_file in model_files.iterdir(): # avoid uploading unnecessary files if model_file.name.startswith("."): continue data_connection.write(data=str(model_file), remote_name=model_file.name)
ステップ 2: モデルのデプロイ
カスタム基盤モデルデプロイするには、 カスタムモデルのドキュメントの手順に従ってください。
ステップ3: グラウンディングデータの準備
RAG実験に使用するグラウンディング資料を準備し、接続する。 詳しくは、 プロジェクトのデータの取得と準備を参照してください。
- 対応フォーマットPDF、HTML、DOCX、Markdown、プレーンテキスト
- Cloud Object Storage バケット内のデータ、バケット内のフォルダ、または最大20個のファイルを指定して接続します。
- AutoAI 実験に使用するドキュメントのサンプル
例えば、 Cloud Object Storage バケットにドキュメントが保存されているときに、データ接続を作成する:
from ibm_watsonx_ai.helpers import DataConnection, S3Location
conn_meta_props= {
client.connections.ConfigurationMetaNames.NAME: f"Connection to input data - {datasource_name} ",
client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_id_by_name(datasource_name),
client.connections.ConfigurationMetaNames.DESCRIPTION: "ibm-watsonx-ai SDK documentation",
client.connections.ConfigurationMetaNames.PROPERTIES: {
'bucket': <BUCKET_NAME>,
'access_key': <ACCESS_KEY>,
'secret_key': <SECRET_ACCESS_KEY>,
'iam_url': 'https://iam.cloud.ibm.com/identity/token',
'url': <ENDPOINT_URL>
}
}
conn_details = client.connections.create(meta_props=conn_meta_props)
cos_connection_id = client.connections.get_id(conn_details)
input_data_references = [DataConnection(
connection_asset_id=cos_connection_id,
location=S3Location(
bucket=<BACKET_NAME>,
path=<BACKET_PATH>
)
)]
次の例では、プロジェクトで作成された(またはスペースに昇格された) データ資産使用する方法を示します。
core_api.html
は、サンプルノートブックで使用されているグラウンディング文書ファイルの例です。
import os, wget
input_data_filename = "core_api.html"
input_data_path = f"https://ibm.github.io/watsonx-ai-python-sdk/{input_data_filename}"
if not os.path.isfile(input_data_filename):
wget.download(input_data_path, out=input_data_filename)
asset_details = client.data_assets.create(input_data_filename, input_data_filename)
asset_id = client.data_assets.get_id(asset_details)
input_data_references = [DataConnection(data_asset_id=asset_id)]
input_data_references
は最大20の インスタンスをサポートしている。 DataConnection
ステップ4:評価データの準備
granite_code_models.pdf
資料をダウンロードする。import wget data_url = "https://arxiv.org/pdf/2405.04324" byom_input_filename = "granite_code_models.pdf" wget.download(data_url, byom_input_filename)
評価データを準備する。
correct_answer_document_ids
の場合は、ダウンロードしたファイル名を入力してください。import json local_benchmark_json_filename = "benchmark.json" benchmarking_data = [ { "question": "What are the two main variants of Granite Code models?", "correct_answer": "The two main variants are Granite Code Base and Granite Code Instruct.", "correct_answer_document_ids": [byom_input_filename] }, { "question": "What is the purpose of Granite Code Instruct models?", "correct_answer": "Granite Code Instruct models are finetuned for instruction-following tasks using datasets like CommitPack, OASST, HelpSteer, and synthetic code instruction datasets, aiming to improve reasoning and instruction-following capabilities.", "correct_answer_document_ids": [byom_input_filename] }, { "question": "What is the licensing model for Granite Code models?", "correct_answer": "Granite Code models are released under the Apache 2.0 license, ensuring permissive and enterprise-friendly usage.", "correct_answer_document_ids": [byom_input_filename] }, ] with open(local_benchmark_json_filename, mode="w", encoding="utf-8") as fp: json.dump(benchmarking_data, fp, indent=4)
評価ファイルを Cloud Object Storage バケットにアップロードします。
documents_dir_location = S3Location(bucket=BUCKET_NAME, path=byom_input_filename) documents_dir_data_connection = DataConnection(location=documents_dir_location, connection_asset_id=DATASOURCE_CONNECTION_ASSET_ID) documents_dir_data_connection.set_client(api_client=client) documents_dir_data_connection.write(data=byom_input_filename, remote_name=byom_input_filename) benchmark_file_location = S3Location(bucket=BUCKET_NAME, path=BUCKET_BENCHMARK_JSON_FILE_PATH) benchmark_file_data_connection = DataConnection(location=benchmark_file_location, connection_asset_id=DATASOURCE_CONNECTION_ASSET_ID) benchmark_file_data_connection.set_client(api_client=client) benchmark_file_data_connection.write(data=local_benchmark_json_filename)
ステップ5:カスタム基盤モデル AutoAI RAG実験を実行する
Python SDKで実験を実行する。 deployment_id
には、デプロイされたカスタム・ 基盤モデル ID を指定します。
from ibm_watsonx_ai import Credentials
from ibm_watsonx_ai.experiment import AutoAI
from ibm_watsonx_ai.helpers.connections import ContainerLocation
from ibm_watsonx_ai.foundation_models.schema import (
AutoAIRAGCustomModelConfig,
AutoAIRAGModelParams
)
credentials = Credentials(
api_key=<API_KEY>,
url=<WML_ENDPOINT>
)
experiment = AutoAI(credentials, project_id=<PROJECT_ID>)
deployment_id = <DEPLOYMENT_ID> # custom foundation model deployment id
deployment_project_id = <DEPLOYMENT_PROJECT_ID> # project ID where your custom foundation model has been deployed
custom_prompt_template_text = "Answer my question {question} related to these documents {reference_documents}."
custom_context_template_text = "My document {document}"
parameters = AutoAIRAGModelParams(max_sequence_length=32_000)
custom_foundation_model_config = AutoAIRAGCustomModelConfig(
deployment_id=deployment_id,
project_id=deployment_project_id,
prompt_template_text=custom_prompt_template_text,
context_template_text=custom_context_template_text,
parameters=parameters
)
rag_optimizer = experiment.rag_optimizer(
name='AutoAI RAG - Custom foundation model experiment',
description = "AutoAI RAG experiment with custom foundation model.",
max_number_of_rag_patterns=4,
optimization_metrics=['faithfulness'],
foundation_models=[custom_foundation_model_config],
)
container_data_location = DataConnection(
type="container",
location=ContainerLocation(
path="autorag/results"
),
)
container_data_location.set_client(api_client=client)
rag_optimizer.run(
test_data_references=[benchmark_file_data_connection],
input_data_references=[documents_dir_data_connection],
results_reference=container_data_location,
)
ジョブ詳細はこちら:
rag_optimizer.get_details()
ステータスが完了したら、次のステップに進むことができます。
ステップ6:パターンを見直し、最適なものを選ぶ
AutoAI RAG実験が成功裏に終了したら、パターンを見直すことができる。 summary
メソッドを使用して、完成したパターンと評価メトリクス情報を Pandas DataFrame の形式でリストアップし、最適化されたメトリクスに対するパフォーマンスに従ってランク付けされたパターンをレビューできるようにします。
summary = rag_optimizer.summary()
summary
例えば、パターン結果はこのように表示される:
パターン | 平均正答率 | 平均忠実度 | 平均文脈正しさ | chunking.chunk_size | embeddings.model_id | vector_store.distance_metric | retrieval.method | retrieval.number_of_chunks | generation.deployment_id |
---|---|---|---|---|---|---|---|---|---|
Pattern1 | 0.6802 | 0.5407 | 1.0000 | 512 | ibm/slate-125m-english-rtrvr | ユークリッド | ウィンドウ | 5 | 38aeef16-c69c-4858-ba69-42f97d965abc |
Pattern2 | 0.7172 | 0.5950 | 1.0000 | 1024 | intfloat/multilingual-e5-large | ユークリッド | ウィンドウ | 5 | 38aeef16-c69c-4858-ba69-42f97d965abc |
Pattern3 | 0.6543 | 0.5144 | 1.0000 | 1024 | intfloat/multilingual-e5-large | ユークリッド | シンプル | 5 | 38aeef16-c69c-4858-ba69-42f97d965abc |
Pattern4 | 0.6216 | 0.5030 | 1.0000 | 1024 | intfloat/multilingual-e5-large | コサイン | ウィンドウ | 5 | 38aeef16-c69c-4858-ba69-42f97d965abc |
Pattern5 | 0.7369 | 0.5630 | 1.0000 | 1024 | intfloat/multilingual-e5-large | コサイン | ウィンドウ | 3 | 38aeef16-c69c-4858-ba69-42f97d965abc |
ローカルでテストするパターンを選択する
パターンを選択してローカルでテストする前に、文書インデックスを再作成する。
ヒント:以下のコードサンプルでは、
core_api.html
とfm_embeddings.html
の文書でインデックスを構築しています。from langchain_community.document_loaders import WebBaseLoader best_pattern = rag_optimizer.get_pattern() urls = [ "https://ibm.github.io/watsonx-ai-python-sdk/core_api.html", "https://ibm.github.io/watsonx-ai-python-sdk/fm_embeddings.html", ] docs_list = WebBaseLoader(urls).load() doc_splits = best_pattern.chunker.split_documents(docs_list) best_pattern.indexing_function(doc_splits)
RAGパターンをローカルにクエリー。
payload = { client.deployments.ScoringMetaNames.INPUT_DATA: [ { "values": ["How to use new approach of providing credentials to APIClient?"], } ] } best_pattern.query(payload)
モデルの反応はこうだ:
According to the document, the new approach to provide credentials to APIClient is by using the Credentials class. Here's an example:
from ibm_watsonx_ai import APIClient
from ibm_watsonx_ai import Credentials
credentials = Credentials(
url = "https://us-south.ml.cloud.ibm.com",
token = "***********",
)
client = APIClient(credentials)
This replaces the old approach of passing a dictionary with credentials to the APIClient constructor.
特定のパターンを検索するには、パターン番号を rag_optimizer.get_pattern()
に渡します。
で実験結果をレビューする。 Cloud Object Storage
実験の最終ステータスが失敗またはエラーであった場合、 rag_optimizer.get_logs()
、または実験結果を参照し、何が問題であったかを理解する。 実験結果とログは、お客様のアカウントにリンクされているデフォルトの Cloud Object Storage インスタンスに保存されます。 デフォルトでは、結果は default_autoai_rag_out
ディレクトリに保存される。
結果はパターン別に整理されている。 例:
|-- Pattern1
| | -- evaluation_results.json
| | -- indexing_inference_notebook.ipynb (Chroma)
|-- Pattern2
| ...
|-- training_status.json
各パターンはこれらの結果を含んでいる:
evaluation_results.json
ファイルには、各ベンチマーク問題の評価結果が含まれています。indexing_inference_notebook.ipynb
には、ベクトルデータベースのインデックスを構築するための python コードと、検索および生成関数を構築するための python コードが含まれています。 このノートブックでは、データの取得、チャンキング、埋め込み作成、チャンクの取得、プロンプトの作成、回答の生成などのコマンドを紹介している。
結果ノートブック indexing_notebook.ipynb
には、ドキュメントの埋め込みとインデックス作成のためのコードが含まれている。 vector_store.add_documents()
を vector_store.add_documents_async()
に変更することで、文書のインデックス作成作業を高速化することができます。
推論と索引のノートブックを入手
指定した推論ノートブックをダウンロードするには、 get_inference_notebook()
. pattern_name
を空のままにしておくと、このメソッドは最もよく計算されたパターンのノートブックをダウンロードする。
rag_optimizer.get_inference_notebook(pattern_name='Pattern3')
詳細とコードサンプルについては、 AutoAI RAGとカスタム・ 基盤モデル ノートブックの使用 を参照してください。