LLM 평가기를 인간 판단과 정렬하기
LLM 평가기를 인간 판단과 정렬하기 (Aligning LLM Evaluators with Human Judgment)
이 튜토리얼은 Ragas와 함께 Vertex AI 모델을 사용하는 3부작 시리즈의 일부예요. Getting Started: Ragas with Vertex AI를 먼저 보는 것을 권장하지만, 보지 않았어도 쉽게 따라할 수 있어요. 모델 비교 튜토리얼은 링크로 이동하면 돼요.
출처: 문서
본문
이 튜토리얼에서는 Ragas를 사용해서 자신만의 커스텀 LLM 기반 메트릭을 훈련하고 정렬하는 방법을 배워요. LLM 기반 평가기는 AI 애플리케이션을 채점하는 강력한 수단을 제공하지만, 스타일·컨텍스트·미묘한 뉘앙스의 차이로 인해 인간의 기대와 다른 판단을 내릴 때가 있어요. 이 가이드를 따라 하면 메트릭이 인간 판단을 더 정확히 반영하도록 다듬을 수 있어요.
이 튜토리얼에서 할 일:
- Ragas로 모델 기반 메트릭 정의
- HHH 데이터셋의 "helpful" 하위 집합에서 EvaluationDataset 구성
- 초기 평가를 실행해 메트릭 성능 벤치마킹
- 15~20개 평가 예제 검토 및 주석
- 주석 데이터로 메트릭 훈련
- 인간 판단과의 정렬 개선을 관찰하기 위해 메트릭 재평가
시작하기
의존성 설치
%pip install --upgrade --user --quiet langchain-core langchain-google-vertexai langchain ragas
런타임 재시작
이 Jupyter 런타임에서 새로 설치한 패키지를 사용하려면 런타임을 재시작해야 해요. 아래 셀을 실행해서 현재 커널을 재시작하면 돼요.
재시작은 1분 이상 걸릴 수 있어요. 재시작 후 다음 단계로 계속해요.
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
노트북 환경 인증 (Colab 전용)
Google Colab에서 이 노트북을 실행한다면 아래 셀을 실행해서 환경을 인증해요.
import sys
if "google.colab" in sys.modules:
from google.colab import auth
auth.authenticate_user()
Google Cloud 프로젝트 정보 설정 및 Vertex AI SDK 초기화
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
LOCATION = "us-central1" # @param {type:"string"}
if not PROJECT_ID or PROJECT_ID == "[your-project-id]":
raise ValueError("Please set your PROJECT_ID")
import vertexai
vertexai.init(project=PROJECT_ID, location=LOCATION)
평가 메트릭 설정
LLM 기반 메트릭은 엄청난 잠재력이 있지만 인간 평가자와 비교해 응답을 잘못 판단할 때가 있어요. 이 격차를 메우기 위해 피드백 루프로 모델 기반 메트릭을 인간 판단과 정렬해요.
evaluator_llm 정의
필요한 wrapper를 임포트하고 평가기 LLM과 임베더를 정의해요.
from ragas.llms import LangchainLLMWrapper
from ragas.embeddings import LangchainEmbeddingsWrapper
from langchain_google_vertexai import VertexAI, VertexAIEmbeddings
evaluator_llm = LangchainLLMWrapper(VertexAI(model_name="gemini-2.0-flash-001"))
evaluator_embeddings = LangchainEmbeddingsWrapper(VertexAIEmbeddings(model_name="text-embedding-004"))
Ragas 메트릭
Ragas는 인간 평가자와 정렬되도록 파인튜닝할 수 있는 다양한 모델 기반 메트릭을 제공해요. 데모를 위해 Aspect Critic 메트릭(사용자 정의 이진 메트릭)을 사용할게요. 자세한 내용은 Aspect Critic 문서를 참고해요.
from ragas.metrics import AspectCritic
helpfulness_critic = AspectCritic(
name="helpfulness",
definition="Evaluate how helpful the assistant's response is to the user's query.",
llm=evaluator_llm
)
정렬 전에 LLM에 전달될 프롬프트를 미리 볼 수 있어요.
print(helpfulness_critic.get_prompts()["single_turn_aspect_critic_prompt"].instruction)
출력
Evaluate the Input based on the criterial defined. Use only 'Yes' (1) and 'No' (0) as verdict.
Criteria Definition: Evaluate how helpful the assistant's response is to the user's query.
정렬 점수 정의
이진 메트릭을 사용하므로 F1-score로 정렬을 측정할게요. 하지만 정렬하는 메트릭에 따라 이 함수를 수정해서 다른 방법으로 정렬을 측정할 수도 있어요.
from typing import List
from sklearn.metrics import f1_score
def alignment_score(human_score: List[float], llm_score: List[float]) -> float:
"""
F1-score 메트릭으로 인간 주석 이진 점수와 LLM 생성 이진 점수 사이의 정렬 계산.
Args:
human_score (List[int]): 인간 평가의 이진 라벨 (0 또는 1).
llm_score (List[int]): LLM 예측의 이진 라벨 (0 또는 1).
Returns:
float: 정렬을 측정하는 F1-score.
"""
return f1_score(human_score, llm_score)
데이터셋 준비
process_hhh_dataset 함수는 HHH 데이터셋의 데이터를 LLM 평가기의 훈련과 정렬에 사용하기 위해 준비해요. 각 예제에 0과 1 점수(1은 유용함, 0은 유용하지 않음)를 번갈아 할당해서 선호하는 응답을 나타내요.
import numpy as np
from datasets import load_dataset
from ragas import EvaluationDataset
def process_hhh_dataset(split: str = "helpful", total_count: int = 50):
dataset = load_dataset("HuggingFaceH4/hhh_alignment",split, split=f"test[:{total_count}]")
data = []
expert_scores = []
for idx, entry in enumerate(dataset):
# 입력과 타겟 세부 정보 추출
user_input = entry['input']
choices = entry['targets']['choices']
labels = entry['targets']['labels']
# 인덱스가 짝수인지 홀수인지에 따라 타겟 선택
if idx % 2 == 0:
target_label = 1
score = 1
else:
target_label = 0
score = 0
label_index = labels.index(target_label)
response = choices[label_index]
data.append({
'user_input': user_input,
'response': response,
})
expert_scores.append(score)
return EvaluationDataset.from_list(data), expert_scores
eval_dataset, expert_scores = process_hhh_dataset()
평가 실행
평가 데이터셋과 helpfulness 메트릭이 정의됐으니 이제 평가를 실행할 수 있어요.
from ragas import evaluate
results = evaluate(eval_dataset, metrics=[helpfulness_critic])
Evaluating: 100%|██████████| 50/50 [00:00<?, ?it/s]
이 초기 실행은 LLM 기반 평가기에 존재하는 정렬 불일치 수준을 보여주는데, 이후 훈련에서 다룰 거예요.
다음으로 메트릭 성능을 전문가 점수와 벤치마킹해요.
human_score = expert_scores
llm_score = results.to_pandas()["helpfulness"].values
initial_score = alignment_score(human_score, llm_score)
initial_score
출력
0.8076923076923077
검토 및 주석
이제 평가 결과를 얻었으니 검토하고 주석을 달 차례예요. Aligning LLM as judge with human evaluators 블로그에서 논의했듯이 상세한 피드백 수집은 LLM 기반 평가와 인간 평가 사이의 격차를 메우는 데 필수적이에요. 메트릭이 잘못 정렬될 수 있는 다양한 시나리오를 포착하기 위해 최소 15~20개 예제에 주석을 달아요.
다음은 위 예제에 대한 샘플 주석이에요. 다운로드해서 사용할 수 있어요.
훈련 및 정렬
다음 단계는 주석이 달린 예제로 메트릭을 훈련하는 것이에요. 이 훈련 프로세스는 주석 피드백을 바탕으로 지침과 few-shot 데모를 모두 조정하는 gradient-free 프롬프트 최적화 접근 방식을 활용해요.
from ragas.config import InstructionConfig, DemonstrationConfig
demo_config = DemonstrationConfig(embedding=evaluator_embeddings)
inst_config = InstructionConfig(llm=evaluator_llm)
helpfulness_critic.train(
path="annotated_data.json",
instruction_config=inst_config,
demonstration_config=demo_config,
)
Overall Progress: 100%|██████████| 170/170 [00:00<?, ?it/s]
Few-shot examples [single_turn_aspect_critic_prompt]: 100%|██████████| 16/16 [00:00<?, ?it/s]
훈련 후 메트릭에 최적화된 업데이트된 지침을 검토해요.
print(helpfulness_critic.get_prompts()["single_turn_aspect_critic_prompt"].instruction)
출력
You are provided with a user input and an assistant/model response. Your task is to evaluate the quality of the response based on how well it addresses the user input, considering all requests and constraints. Assign a score/verdict of 1 if the response is helpful, appropriate, and effective, and 0 if it is not. A good response should be accurate, complete, relevant, and provide a tangible improvement or solution, without omitting key information. Provide a brief explanation for your score/verdict.
재평가
이제 메트릭이 인간 피드백과 정렬되었으니 데이터셋에서 평가를 다시 실행해요. 이 단계는 개선을 벤치마킹하고 정렬 프로세스가 메트릭의 신뢰성을 얼마나 향상시켰는지 정량화할 수 있게 해줘요.
from ragas.llms import LangchainLLMWrapper
from ragas.embeddings import LangchainEmbeddingsWrapper
from langchain_google_vertexai import VertexAI, VertexAIEmbeddings
evaluator_llm = LangchainLLMWrapper(VertexAI(model_name="gemini-pro"))
evaluator_embeddings = LangchainEmbeddingsWrapper(VertexAIEmbeddings(model_name="text-embedding-004"))
from ragas import evaluate
results2 = evaluate(eval_dataset, metrics=[helpfulness_critic])
Evaluating: 100%|██████████| 50/50 [00:00<?, ?it/s]
업데이트된 결과를 전문가 점수와 벤치마킹해요.
human_score = expert_scores
llm_score = results2.to_pandas()["helpfulness"].values
new_score = alignment_score(human_score, llm_score)
new_score
출력
0.8444444444444444
이 시리즈의 다른 튜토리얼도 확인해요:
- Ragas with Vertex AI: Vertex AI 모델을 Ragas와 함께 사용해서 LLM 워크플로우를 평가하는 방법 학습.
- Model Comparison: Ragas 메트릭으로 VertexAI가 제공하는 모델을 RAG 기반 Q&A 작업에서 비교.