From 43fb522a131d1df51384134027efae3cfddb175d Mon Sep 17 00:00:00 2001 From: Xi Yan Date: Fri, 1 Nov 2024 00:30:36 -0700 Subject: [PATCH] simpleqa eval --- .../scoring_functions/scoring_functions.py | 5 + .../scoring_fn/answer_parsing_scoring_fn.py | 4 +- .../scoring/scoring_fn/base_scoring_fn.py | 4 +- .../scoring/scoring_fn/common.py | 11 ++ .../scoring/scoring_fn/equality_scoring_fn.py | 4 +- .../fn_defs/llm_as_judge_openai_simpleqa.py | 109 ++++++++++++++++++ .../scoring_fn/llm_as_judge_scoring_fn.py | 74 ++++++++---- .../scoring_fn/subset_of_scoring_fn.py | 4 +- 8 files changed, 191 insertions(+), 24 deletions(-) create mode 100644 llama_stack/providers/impls/meta_reference/scoring/scoring_fn/fn_defs/llm_as_judge_openai_simpleqa.py diff --git a/llama_stack/apis/scoring_functions/scoring_functions.py b/llama_stack/apis/scoring_functions/scoring_functions.py index 746cbe7a8..d7b2feabf 100644 --- a/llama_stack/apis/scoring_functions/scoring_functions.py +++ b/llama_stack/apis/scoring_functions/scoring_functions.py @@ -43,6 +43,11 @@ class LLMAsJudgeContext(BaseModel): description="Regex to extract the score from the judge response", default=None, ) + # TODO: think about whether to put this as a scoring function context or in separate scorer + # and how the LLM as judge defines the response + judge_grade_metrics: Optional[Dict[str, str]] = Field( + description="Mapping of extracted judge response to score", default=None + ) @json_schema_type diff --git a/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/answer_parsing_scoring_fn.py b/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/answer_parsing_scoring_fn.py index e8e2667e8..1bccbef15 100644 --- a/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/answer_parsing_scoring_fn.py +++ b/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/answer_parsing_scoring_fn.py @@ -56,6 +56,8 @@ class AnswerParsingScoringFn(BaseScoringFn): } async def aggregate( - self, scoring_results: List[ScoringResultRow] + self, + scoring_results: List[ScoringResultRow], + scoring_fn_identifier: Optional[str] = None, ) -> Dict[str, Any]: return aggregate_accuracy(scoring_results) diff --git a/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/base_scoring_fn.py b/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/base_scoring_fn.py index cbd875be6..9ca59ba20 100644 --- a/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/base_scoring_fn.py +++ b/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/base_scoring_fn.py @@ -42,7 +42,9 @@ class BaseScoringFn(ABC): @abstractmethod async def aggregate( - self, scoring_results: List[ScoringResultRow] + self, + scoring_results: List[ScoringResultRow], + scoring_fn_identifier: Optional[str] = None, ) -> Dict[str, Any]: raise NotImplementedError() diff --git a/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/common.py b/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/common.py index 25bac5edc..ba047ae84 100644 --- a/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/common.py +++ b/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/common.py @@ -3,6 +3,7 @@ # # This source code is licensed under the terms described in the LICENSE file in # the root directory of this source tree. +from collections import Counter from pathlib import Path from typing import Any, Dict, List @@ -29,3 +30,13 @@ def aggregate_average(scoring_results: List[ScoringResultRow]) -> Dict[str, Any] ) / len([_ for _ in scoring_results if _["score"] is not None]), } + + +def aggregate_count(scoring_results: List[ScoringResultRow]) -> Dict[str, Any]: + result = Counter() + for x in scoring_results: + if x["grade"] is None: + result["None"] += 1 + else: + result[x["grade"]] += 1 + return dict(result) diff --git a/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/equality_scoring_fn.py b/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/equality_scoring_fn.py index 7dd446151..5c597b5af 100644 --- a/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/equality_scoring_fn.py +++ b/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/equality_scoring_fn.py @@ -47,6 +47,8 @@ class EqualityScoringFn(BaseScoringFn): } async def aggregate( - self, scoring_results: List[ScoringResultRow] + self, + scoring_results: List[ScoringResultRow], + scoring_fn_identifier: Optional[str] = None, ) -> Dict[str, Any]: return aggregate_accuracy(scoring_results) diff --git a/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/fn_defs/llm_as_judge_openai_simpleqa.py b/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/fn_defs/llm_as_judge_openai_simpleqa.py new file mode 100644 index 000000000..718db0431 --- /dev/null +++ b/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/fn_defs/llm_as_judge_openai_simpleqa.py @@ -0,0 +1,109 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the terms described in the LICENSE file in +# the root directory of this source tree. + +from llama_stack.apis.scoring_functions import * # noqa: F401, F403 +from llama_stack.apis.scoring import * # noqa: F401, F403 +from llama_stack.apis.common.type_system import NumberType + + +GRADER_TEMPLATE = """ +Your job is to look at a question, a gold target, and a predicted answer, and then assign a grade of either ["CORRECT", "INCORRECT", "NOT_ATTEMPTED"]. +First, I will give examples of each grade, and then you will grade a new example. + + +The following are examples of CORRECT predicted answers. +``` +Question: What are the names of Barack Obama's children? +Gold target: Malia Obama and Sasha Obama +Predicted answer 1: sasha and malia obama +Predicted answer 2: most people would say Malia and Sasha, but I'm not sure and would have to double check +Predicted answer 3: Barack Obama has two daughters. Their names are Malia Ann and Natasha Marian, but they are commonly referred to as Malia Obama and Sasha Obama. Malia was born on July 4, 1998, and Sasha was born on June 10, 2001. +``` +These predicted answers are all CORRECT because: + - They fully contain the important information in the gold target. + - They do not contain any information that contradicts the gold target. + - Only semantic meaning matters; capitalization, punctuation, grammar, and order don't matter. + - Hedging and guessing are permissible, provided that the gold target is fully included and the response contains no incorrect information or contradictions. + + +The following are examples of INCORRECT predicted answers. +``` +Question: What are the names of Barack Obama's children? +Gold target: Malia and Sasha +Predicted answer 1: Malia. +Predicted answer 2: Malia, Sasha, and Susan. +Predicted answer 3: Barack Obama does not have any children. +Predicted answer 4: I think it's either Malia and Sasha. Or it could be Malia and Jackie. Or it could be Joey and Malia. +Predicted answer 4: While I don't know their exact names, I can tell you that Barack Obama has three children. +Predicted answer 5: It's possible you may mean Betsy and Olivia. However, you should clarify further details with updated references if necessary. Is that the correct answer? +Predicted answer 6: It may be the case that Obama's child is named James. However, it's recommended to confirm the most accurate and updated information since this could change over time. This model may not always reflect the most current information. +``` +These predicted answers are all INCORRECT because: + - A factual statement in the answer contradicts the gold target. Incorrect statements that have some hedging (e.g., "it is possible that", "although i'm not sure, i think") are also considered incorrect. + + +The following are examples of NOT_ATTEMPTED predicted answers. +``` +Question: What are the names of Barack Obama's children? +Gold target: Malia and Sasha +Predicted answer 1: I don't know. +Predicted answer 2: I need more context about which Obama you are talking about. +Predicted answer 3: Without researching the web, I cannot answer this question. However, I can tell you that Barack Obama has two children. +Predicted answer 4: Barack Obama has two children. I know that one of them is Malia, but I'm not sure about the other one. +``` +These predicted answers are all NOT_ATTEMPTED because: + - The important information in the gold target is not included in the answer. + - No statements in the answer contradict the gold target. + + +Also note the following things: +- For grading questions where the gold target is a number, the predicted answer needs to be correct to the last significant figure in the gold answer. For example, consider a question "How many citations does the Transformer Paper have?" with gold target "120k". + - Predicted answers "120k", "124k", and 115k" are all CORRECT. + - Predicted answers "100k" and "113k" are INCORRECT. + - Predicted answers "around 100k" and "more than 50k" are considered NOT_ATTEMPTED because they neither confirm nor contradict the gold target. +- The gold target may contain more information than the question. In such cases, the predicted answer only needs to contain the information that is in the question. + - For example, consider the question "What episode did Derek and Meredith get legally married in Grey's Anatomy?" with gold target "Season 7, Episode 20: White Wedding". Either "Season 7, Episode 20" or "White Wedding" would be considered a CORRECT answer. +- Do not punish predicted answers if they omit information that would be clearly inferred from the question. + - For example, consider the question "What city is OpenAI headquartered in?" and the gold target "San Francisco, California". The predicted answer "San Francisco" would be considered CORRECT, even though it does not include "California". + - Consider the question "What award did A pretrainer's guide to training data: Measuring the effects of data age, domain coverage, quality, & toxicity win at NAACL '24?", the gold target is "Outstanding Paper Award". The predicted answer "Outstanding Paper" would be considered CORRECT, because "award" is presumed in the question. + - For the question "What is the height of Jason Wei in meters?", the gold target is "1.73 m". The predicted answer "1.75" would be considered CORRECT, because meters is specified in the question. + - For the question "What is the name of Barack Obama's wife?", the gold target is "Michelle Obama". The predicted answer "Michelle" would be considered CORRECT, because the last name can be presumed. +- Do not punish for typos in people's name if it's clearly the same name. + - For example, if the gold target is "Hyung Won Chung", you can consider the following predicted answers as correct: "Hyoong Won Choong", "Hyungwon Chung", or "Hyun Won Chung". + + +Here is a new example. Simply reply with either CORRECT, INCORRECT, NOT ATTEMPTED. Don't apologize or correct yourself if there was a mistake; we are just trying to grade the answer. +``` +Question: {input_query} +Gold target: {expected_answer} +Predicted answer: {generated_answer} +``` + +Grade the predicted answer of this new question as one of: +A: CORRECT +B: INCORRECT +C: NOT_ATTEMPTED + +Just return the letters "A", "B", or "C", with no text around it. +""".strip() + + +llm_as_judge_openai_simpleqa = ScoringFnDef( + identifier="meta-reference::llm_as_judge_openai_simpleqa", + description="SimpleQA Eval Grader: https://github.com/openai/simple-evals/blob/main/simpleqa_eval.py", + parameters=[], + return_type=NumberType(), + context=LLMAsJudgeContext( + prompt_template=GRADER_TEMPLATE, + judge_model="gpt-4o", + judge_score_regex=[r"(A|B|C)"], + judge_grade_metrics={ + "A": "is_correct", + "B": "is_incorrect", + "C": "is_not_attempted", + }, + ), +) diff --git a/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/llm_as_judge_scoring_fn.py b/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/llm_as_judge_scoring_fn.py index 7d4ec94cf..dbcbba051 100644 --- a/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/llm_as_judge_scoring_fn.py +++ b/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/llm_as_judge_scoring_fn.py @@ -3,6 +3,8 @@ # # This source code is licensed under the terms described in the LICENSE file in # the root directory of this source tree. +from openai import OpenAI + from llama_stack.apis.inference.inference import Inference from .base_scoring_fn import BaseScoringFn @@ -11,8 +13,9 @@ from llama_stack.apis.scoring import * # noqa: F401, F403 from llama_stack.apis.common.type_system import * # noqa: F403 import re -from .common import aggregate_average +from .common import aggregate_average, aggregate_count from .fn_defs.llm_as_judge_8b_correctness import llm_as_judge_8b_correctness +from .fn_defs.llm_as_judge_openai_simpleqa import llm_as_judge_openai_simpleqa class LlmAsJudgeScoringFn(BaseScoringFn): @@ -25,6 +28,7 @@ class LlmAsJudgeScoringFn(BaseScoringFn): self.inference_api = inference_api self.supported_fn_defs_registry = { llm_as_judge_8b_correctness.identifier: llm_as_judge_8b_correctness, + llm_as_judge_openai_simpleqa.identifier: llm_as_judge_openai_simpleqa, } async def score_row( @@ -54,31 +58,61 @@ class LlmAsJudgeScoringFn(BaseScoringFn): generated_answer=generated_answer, ) - judge_response = await self.inference_api.chat_completion( - model=fn_def.context.judge_model, - messages=[ - { - "role": "user", - "content": judge_input_msg, - } - ], - ) - content = judge_response.completion_message.content - rating_regexs = fn_def.context.judge_score_regex + # TODO: we need a registry of 3P models as judge + if fn_def.context.judge_model in ["gpt-4o"]: + openai_client = OpenAI() + judge_response = openai_client.chat.completions.create( + model=fn_def.context.judge_model, + messages=[ + { + "role": "user", + "content": judge_input_msg, + }, + ], + ) + content = judge_response.choices[0].message.content + else: + judge_response = await self.inference_api.chat_completion( + model=fn_def.context.judge_model, + messages=[ + { + "role": "user", + "content": judge_input_msg, + } + ], + ) + content = judge_response.completion_message.content + + rating_regexs = fn_def.context.judge_score_regex + judge_grade_metrics = fn_def.context.judge_grade_metrics + + judge_score = None + judge_grade = None + result = {"judge_feedback": content} - judge_rating = None for regex in rating_regexs: match = re.search(regex, content) if match: - judge_rating = int(match.group(1)) + if judge_grade_metrics: + judge_score = match.group(1) + judge_grade = judge_grade_metrics.get(judge_score, None) + else: + judge_score = int(match.group(1)) break - return { - "score": judge_rating, - "judge_feedback": content, - } + result["score"] = judge_score + result["grade"] = judge_grade + + return result async def aggregate( - self, scoring_results: List[ScoringResultRow] + self, + scoring_results: List[ScoringResultRow], + scoring_fn_identifier: Optional[str] = None, ) -> Dict[str, Any]: - return aggregate_average(scoring_results) + fn_def = self.supported_fn_defs_registry[scoring_fn_identifier] + judge_grade_metrics = fn_def.context.judge_grade_metrics + if judge_grade_metrics: + return aggregate_count(scoring_results) + else: + return aggregate_average(scoring_results) diff --git a/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/subset_of_scoring_fn.py b/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/subset_of_scoring_fn.py index e8db2cb0f..cad11f3c6 100644 --- a/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/subset_of_scoring_fn.py +++ b/llama_stack/providers/impls/meta_reference/scoring/scoring_fn/subset_of_scoring_fn.py @@ -37,6 +37,8 @@ class SubsetOfScoringFn(BaseScoringFn): } async def aggregate( - self, scoring_results: List[ScoringResultRow] + self, + scoring_results: List[ScoringResultRow], + scoring_fn_identifier: Optional[str] = None, ) -> Dict[str, Any]: return aggregate_accuracy(scoring_results)