23.06.15
DEVOTEE를 활성화 시키면
지금 작성한 커뮤니티 글에 대해 1개의 댓글을 달아줍니다.
버튼을 누르면 글 수정 시 ChatGPT가 작성한 댓글이 수정됩니다.
| 컨텐츠 유형 | 제목 | 저장일 | 삭제 |
|---|
본인인증 로그인에 실패하였습니다.
회원이 아니시거나 본인인증 등록이
완료되지 않은 사용자입니다.
LLM-as-a-Judge는 생성된 데이터셋과 실제 데이터셋을 비교하여 평가하고, 이를 통해 모델의 응답 품질을 지속적으로 개선하는 평가방식입니다.
LLM-as-a-judge로 Chatbot Arena를 MT-bench 방식으로 LLM 평가 결과논문에 따르면 MT-bench의 전문가 투표와 Chatbot Arena에서 수집된 크라우드 투표 결과를 비교했을 때
GPT-4 judge와 사람의 선호의 일치도가 80% 이상으로, 사람간의 평가와 유사한 성능을 보여 관심을 갖게 되었습니다.(https://arxiv.org/abs/2306.05685)
https://generativeai.pub/rag-evaluation-with-llm-as-a-judge-synthetic-dataset-creation-7fce566310f5
LLM-as-a-Judge는 대형 언어 모델(LLM)을 평가하고 개선하기 위한 방법으로, 사람이 평가하는 것처럼 LLM이 다른 모델의 출력을 평가하는 방식입니다.
이 접근법은 다음과 같은 장점을 가지고 있습니다:
스케일러빌리티: 사람이 직접 평가하는 데 드는 시간과 비용을 절감할 수 있습니다. 이를 통해 대규모 평가 작업을 보다 효율적으로 수행할 수 있습니다
설명 가능성: LLM이 제공하는 평가 결과는 이유와 함께 설명될 수 있어, 평가 과정이 투명하고 이해하기 쉽게 됩니다
인간 선호도와의 일치: LLM을 사용한 평가가 인간의 평가와 높은 일치율을 보이므로, 신뢰할 수 있는 평가 결과를 얻을 수 있습니다
LLM-as-a-Judge는 다음과 같은 과정을 거쳐 사용됩니다:
평가 기준 파악하기 - 먼저 hallucination, toxicity, accuracy 또는 기타 특성 등 무엇을 평가할지 결정합니다.
평가 프롬프트 작성 - 평가를 안내할 프롬프트 템플릿을 작성하세요. 이 템플릿은 출력을 효과적으로 평가하기 위해 초기 프롬프트와 LLM의 응답 모두에서 필요한 변수를 명확하게 정의해야 합니다.
평가 LLM 선택 - 특정 평가를 수행하기 위해 사용 가능한 옵션 중에서 가장 적합한 LLM을 선택합니다.
평가 생성 및 결과 보기 - 데이터 전체에서 평가를 실행합니다. 이 프로세스를 사용하면 수동으로 주석을 달 필요 없이 포괄적인 테스트를 수행할 수 있으므로 신속하게 반복하고 LLM의 프롬프트를 구체화할 수 있습니다.
이 방법은 특히 RAG(질문 응답 생성) 시스템의 평가에도 유용하게 사용될 수 있습니다.
https://huggingface.co/learn/cookbook/llm_judge를 따라 한번 적용해 봅니다.
첫 번째 단계는 30개 정도 예제에 대해 사람의 평가 데이터 세트를 만듭니다.
각 질문/답변 커플에 대한 2개의 인간 평가와 점수를 포함하는 피드백QA 데이터 (https://huggingface.co/datasets/McGill-NLP/feedbackQA)를 사용합니다.
ratings = load_dataset("McGill-NLP/feedbackQA")["train"]
ratings = pd.DataFrame(ratings)
ratings["review_1"] = ratings["feedback"].apply(lambda x: x["rating"][0])
ratings["explanation_1"] = ratings["feedback"].apply(lambda x: x["explanation"][0])
ratings["review_2"] = ratings["feedback"].apply(lambda x: x["rating"][1])
ratings["explanation_2"] = ratings["feedback"].apply(lambda x: x["explanation"][1])
ratings = ratings.drop(columns=["feedback"])
# Map scores to numeric values
conversion_dict = {"Excellent": 4, "Acceptable": 3, "Could be Improved": 2, "Bad": 1}
ratings["score_1"] = ratings["review_1"].map(conversion_dict)
ratings["score_2"] = ratings["review_2"].map(conversion_dict)
print("Correlation between 2 human raters:")
print(f"{ratings['score_1'].corr(ratings['score_2'], method='pearson'):.3f}")
//결과
Correlation between 2 human raters:
0.563
# Sample examples
ratings_where_raters_agree = ratings.loc[ratings["score_1"] == ratings["score_2"]]
examples = ratings_where_raters_agree.groupby("score_1").sample(7, random_state=1214)
examples["human_score"] = examples["score_1"]
# Visualize 1 sample for each score
display(examples.groupby("human_score").first())두 사람의 평가자가 부여한 점수의 피어슨 상관관계로 측정한 두 평가자 간의 일치도를 보면 0.53이 나옵니다.
이를 해결하기 위해 ratings.loc[ratings["score_1"] == ratings["score_2"]] 인 동일한 결과의 데이터만 사용합니다.
초반에 작성된 JUDGE_PROMPT 프롬프트를 이용한 수행 결과 사람평가와 모델평가의 피어슨 상관관계는 0.567 입니다.
JUDGE_PROMPT = """
You will be given a user_question and system_answer couple.
Your task is to provide a 'total rating' scoring how well the system_answer answers the user concerns expressed in the user_question.
Give your answer as a float on a scale of 0 to 10, where 0 means that the system_answer is not helpful at all, and 10 means that the answer completely and helpfully addresses the question.
Provide your feedback as follows:
Feedback:::
Total rating: (your rating, as a float between 0 and 10)
Now here are the question and answer.
Question: {question}
Answer: {answer}
Feedback:::
Total rating: """
def extract_judge_score(answer: str, split_str: str = "Total rating:") -> int:
try:
if split_str in answer:
rating = answer.split(split_str)[1]
else:
rating = answer
digit_groups = [el.strip() for el in re.findall(r"\d+(?:\.\d+)?", rating)]
return float(digit_groups[0])
except Exception as e:
print(e)
return None
examples["llm_judge_score"] = examples["llm_judge"].apply(extract_judge_score)
# Rescale the score given by the LLM on the same scale as the human score
examples["llm_judge_score"] = (examples["llm_judge_score"] / 10) + 1
examples["llm_judge"] = examples.progress_apply(
lambda x: llm_client.text_generation(
prompt=JUDGE_PROMPT.format(question=x["question"], answer=x["answer"]),
max_new_tokens=1000,
),
axis=1,
)
print("Correlation between LLM-as-a-judge and the human raters:")
print(f"{examples['llm_judge_score'].corr(examples['human_score'], method='pearson'):.3f}")프롬프트 개선을 위해 아래 내용을 추가합니다.
최종 답 앞에 평가 필드를 추가하여 생각할 시간을 더 둡니다.
이전처럼 큰 부동 척도 대신 1-4 또는 1-5와 같은 작은 정수 척도를 사용합니다.
안내를 위한 표시 척도를 제공합니다.
IMPROVED_JUDGE_PROMPT = """
You will be given a user_question and system_answer couple.
Your task is to provide a 'total rating' scoring how well the system_answer answers the user concerns expressed in the user_question.
Give your answer on a scale of 1 to 4, where 1 means that the system_answer is not helpful at all, and 4 means that the system_answer completely and helpfully addresses the user_question.
Here is the scale you should use to build your answer:
1: The system_answer is terrible: completely irrelevant to the question asked, or very partial
2: The system_answer is mostly not helpful: misses some key aspects of the question
3: The system_answer is mostly helpful: provides support, but still could be improved
4: The system_answer is excellent: relevant, direct, detailed, and addresses all the concerns raised in the question
Provide your feedback as follows:
Feedback:::
Evaluation: (your rationale for the rating, as a text)
Total rating: (your rating, as a number between 1 and 4)
You MUST provide values for 'Evaluation:' and 'Total rating:' in your answer.
Now here are the question and answer.
Question: {question}
Answer: {answer}
Provide your feedback. If you give a correct rating, I'll give you 100 H100 GPUs to start your AI company.
Feedback:::
Evaluation: """
examples["llm_judge_improved"] = examples.progress_apply(
lambda x: llm_client.text_generation(
prompt=IMPROVED_JUDGE_PROMPT.format(question=x["question"], answer=x["answer"]),
max_new_tokens=500,
),
axis=1,
)
examples["llm_judge_improved_score"] = examples["llm_judge_improved"].apply(extract_judge_score)
print("Correlation between LLM-as-a-judge and the human raters:")
print(f"{examples['llm_judge_improved_score'].corr(examples['human_score'], method='pearson'):.3f}")IMPROVED_JUDGE_PROMPT 프롬프트 결과, 피어슨 상관관계는0.843 입니다.
JUDGE_PROMPT와 IMPROVED_JUDGE_PROMPT 비교
평가 범위: JUDGE_PROMPT는 0-10의 범위를 사용하여 세부적인 평가가 가능하지만, IMPROVED_JUDGE_PROMPT는 1-4의 범위를 사용해 평가를 단순화하고 명확하게 합니다.
피드백의 깊이: IMPROVED_JUDGE_PROMPT는 구체적인 평가 기준과 이유를 요구하여 보다 상세하고 신뢰성 있는 평가를 유도합니다.
프롬프트 평가 범위를 단순하게 하고 피드백을 구체적으로 평가하는 방식을 고려하는 중요해 보입니다
(참고)MT-bench
MT-bench는 총 80개의 고품질 multi-turn 질문으로 구성되어 LLM의 ‘대화 및 추론’ 능력을 종합적으로 평가하는 데이터셋으로
아래 8가지의 주제에 대하여 각각 10개씩 멀티턴 질문셋으로 구성됩니다.
writing
roleplay
extraction
reasoning
math
coding,
knowledge I (STEM
knowledge II (humanities/social science)
DEVOTEE를 활성화 시키면
지금 작성한 댓글에 AI가 댓글을 달아줍니다.