사용자 지정 파운데이션 모델을 사용하여 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, 마크다운, 일반 텍스트
- 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
메서드를 사용하여 완성된 패턴과 평가 지표 정보를 판다( 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 | 유클리디안 | Windows | 5 | 38aeef16-c69c-4858-ba69-42f97d965abc |
Pattern2 | 0.7172 | 0.5950 | 1.0000 | 1024자입니다. | intfloat/multilingual-e5-large | 유클리디안 | Windows | 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 | 코사인 | Windows | 5 | 38aeef16-c69c-4858-ba69-42f97d965abc |
Pattern5 | 0.7369 | 0.5630 | 1.0000 | 1024자입니다. | intfloat/multilingual-e5-large | 코사인 | Windows | 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
에는 벡터 데이터베이스 인덱스 구축과 검색 및 생성 기능을 구축하기 위한 파이썬 코드가 포함되어 있습니다. 이 노트북에는 데이터 검색, 청크 생성, 임베딩 생성은 물론 청크 검색, 프롬프트 작성, 답변 생성을 위한 명령어가 소개되어 있습니다.
결과 노트북 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 사용하기를 참조하세요.
상위 주제: AutoAI SDK로 RAG 패턴 자동화하기