Skip to content

Commit c6ecad9

Browse files
vballolihusseinmozannar
authored andcommitted
Add QA support to Evals (microsoft#210)
Co-authored-by: Hussein Mozannar <hssein.mzannar@gmail.com> Co-authored-by: Hussein Mozannar <hmozannar@microsoft.com>
1 parent 5e6429e commit c6ecad9

16 files changed

Lines changed: 673 additions & 25 deletions

File tree

experiments/endpoint_configs/config_template.yaml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@ coder_client: *client_4o_openai
1111
web_surfer_client: *client_4o_openai
1212
file_surfer_client: *client_4o_openai
1313
action_guard_client: *client_4o_openai
14-
user_proxy_client: *client_4o_openai
14+
user_proxy_client: *client_4o_openai
15+
model_client: *client_4o_openai

experiments/eval/run.py

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from typing import Optional, Dict, Any, Callable
77
from magentic_ui.eval.core import run_evaluate_benchmark_func, evaluate_benchmark_func
88
from systems.magentic_ui_sim_user_system import MagenticUISimUserSystem
9+
from magentic_ui.eval.systems import LLMSystem
910
from magentic_ui.eval.benchmarks import WebVoyagerBenchmark
1011
from magentic_ui.eval.benchmark import Benchmark
1112
from autogen_core.models import ChatCompletionClient
@@ -157,19 +158,26 @@ def run_system_sim_user(args: argparse.Namespace, system_name: str) -> None:
157158
"""
158159
config = load_config(args.config)
159160

160-
system = MagenticUISimUserSystem(
161-
simulated_user_type=args.simulated_user_type,
162-
endpoint_config_orch=config.get("orchestrator_client") if config else None,
163-
endpoint_config_websurfer=config.get("web_surfer_client") if config else None,
164-
endpoint_config_coder=config.get("coder_client") if config else None,
165-
endpoint_config_file_surfer=config.get("file_surfer_client")
166-
if config
167-
else None,
168-
endpoint_config_user_proxy=config.get("user_proxy_client") if config else None,
169-
web_surfer_only=args.web_surfer_only,
170-
how_helpful_user_proxy=args.how_helpful_user_proxy,
171-
dataset_name=args.dataset,
172-
)
161+
if system_name == "LLM":
162+
# Use LLMSystem for LLM-based evaluations
163+
system = LLMSystem(
164+
system_name=system_name,
165+
endpoint_config=config.get("model_client") if config else None,
166+
)
167+
else:
168+
system = MagenticUISimUserSystem(
169+
simulated_user_type=args.simulated_user_type,
170+
endpoint_config_orch=config.get("orchestrator_client") if config else None,
171+
endpoint_config_websurfer=config.get("web_surfer_client") if config else None,
172+
endpoint_config_coder=config.get("coder_client") if config else None,
173+
endpoint_config_file_surfer=config.get("file_surfer_client")
174+
if config
175+
else None,
176+
endpoint_config_user_proxy=config.get("user_proxy_client") if config else None,
177+
web_surfer_only=args.web_surfer_only,
178+
how_helpful_user_proxy=args.how_helpful_user_proxy,
179+
dataset_name=args.dataset,
180+
)
173181

174182
run_system_evaluation(args, system, system_name, config)
175183

@@ -229,8 +237,8 @@ def main() -> None:
229237
parser.add_argument(
230238
"--system-type",
231239
type=str,
232-
default="magentic-ui",
233-
choices=["magentic-ui", "magentic-ui-sim-user"],
240+
default="MagenticUI",
241+
choices=["MagenticUI", "magentic-ui-sim-user", "LLM"],
234242
help="Type of system to run",
235243
)
236244
parser.add_argument(
@@ -250,7 +258,8 @@ def main() -> None:
250258

251259
# Determine system name based on arguments
252260

253-
system_name = "MagenticUI"
261+
system_name = args.system_type
262+
254263
if args.simulated_user_type != "none":
255264
system_name += f"_{args.simulated_user_type}_{args.how_helpful_user_proxy}"
256265
if args.web_surfer_only:

src/magentic_ui/eval/benchmarks/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
from .webvoyager.webvoyager import WebVoyagerBenchmark
55
from .bearcubs.bearcubs import BearcubsBenchmark
66
from .webgames.webgames import WebGamesBenchmark
7+
from .simpleqa.simpleqa import SimpleQABenchmark
8+
from .gpqa.gpqa import GPQABenchmark
79

810
__all__ = [
911
"AssistantBenchBenchmark",
@@ -12,4 +14,6 @@
1214
"WebVoyagerBenchmark",
1315
"BearcubsBenchmark",
1416
"WebGamesBenchmark",
17+
"SimpleQABenchmark",
18+
"GPQABenchmark",
1519
]
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import Union, Optional, Dict
2+
from ..benchmark import Benchmark
3+
from ..models import AllTaskTypes
4+
5+
6+
class BaseQABenchmark(Benchmark):
7+
"""Base class for Question-Answering benchmarks."""
8+
9+
def __init__(
10+
self,
11+
name: str,
12+
data_dir: Union[str, None] = None,
13+
tasks: Optional[Dict[str, AllTaskTypes]] = None,
14+
num_instances: Optional[int] = None,
15+
):
16+
super().__init__(name, data_dir, tasks)
17+
18+
self.num_instances = num_instances
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# GPQA Eval
2+
3+
Run instructions:
4+
5+
```python
6+
python experiments/eval/run.py --current-dir . --dataset GPQA --split main --run-id 0 --simulated-user-type none --parallel 1 --config experiments/endpoint_configs/config_template.yaml --mode run --system-type LLM
7+
```
8+
9+
```
10+
@inproceedings{rein2024gpqa,
11+
title={{GPQA}: A Graduate-Level Google-Proof Q\&A Benchmark},
12+
author={David Rein and Betty Li Hou and Asa Cooper Stickland and Jackson Petty and Richard Yuanzhe Pang and Julien Dirani and Julian Michael and Samuel R. Bowman},
13+
booktitle={First Conference on Language Modeling},
14+
year={2024},
15+
url={https://openreview.net/forum?id=Ti67584b98}
16+
}
17+
```

src/magentic_ui/eval/benchmarks/gpqa/__init__.py

Whitespace-only changes.
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
import re
2+
import os
3+
import logging
4+
import pandas as pd
5+
from ..baseqa import BaseQABenchmark
6+
from ...models import (
7+
GPQACandidate,
8+
GPQATask,
9+
GPQAEvalResult,
10+
AllTaskTypes,
11+
)
12+
from typing import Dict, List, Union, Optional
13+
14+
from huggingface_hub import snapshot_download # type: ignore
15+
16+
17+
class GPQABenchmark(BaseQABenchmark):
18+
DATASET_URL = "hf://datasets/Idavidrein/gpqa/"
19+
DATASET_REPO_ID = "Idavidrein/gpqa"
20+
SPLITS = ["diamond", "extended", "main"]
21+
SYSTEM_INSTRUCTION = (
22+
"You are a helpful assistant that answers multiple-choice questions. "
23+
"Return your answer in the format: Answer: X, where X is a single uppercase letter (A, B, C, or D)."
24+
)
25+
26+
def __init__(
27+
self,
28+
name: str,
29+
data_dir: Union[str, None] = None,
30+
tasks: Optional[Dict[str, AllTaskTypes]] = None,
31+
num_instances: Optional[int] = None,
32+
system_instruction: str = SYSTEM_INSTRUCTION,
33+
):
34+
super().__init__(name, data_dir, tasks, num_instances)
35+
36+
self.system_instruction = system_instruction
37+
38+
def download_dataset(self) -> None:
39+
"""
40+
Download the dataset into self.data_dir using huggingface_hub.snapshot_download().
41+
"""
42+
assert self.data_dir is not None, "data_dir must be provided for GPQABenchmark"
43+
if not os.path.exists(self.data_dir):
44+
os.makedirs(self.data_dir, exist_ok=True)
45+
46+
logging.info(f"[GPQABenchmark] Downloading dataset into '{self.data_dir}'...")
47+
snapshot_download(
48+
repo_id=self.DATASET_REPO_ID,
49+
repo_type="dataset",
50+
local_dir=self.data_dir,
51+
local_dir_use_symlinks=True,
52+
)
53+
logging.info("[GPQABenchmark] Dataset downloaded.")
54+
55+
def load_dataset(self) -> None:
56+
"""
57+
Read all the split csvs from the dataset
58+
"""
59+
60+
split_paths = { # type: ignore
61+
split: os.path.join(self.data_dir, f"gpqa_{split}.csv") # type: ignore
62+
for split in self.SPLITS
63+
}
64+
65+
for split_name, split_path in split_paths.items(): # type: ignore
66+
if not os.path.exists(split_path): # type: ignore
67+
raise FileNotFoundError(f"Dataset file {split_path} does not exist.")
68+
69+
df = pd.read_csv(split_path) # type: ignore
70+
for _, row in df.iterrows():
71+
self.tasks[row["Record ID"]] = GPQATask( # type: ignore
72+
id=row["Record ID"], # type: ignore
73+
question=row["Question"], # type: ignore
74+
ground_truth=row["Correct Answer"], # type: ignore
75+
options=[ # type: ignore
76+
row["Correct Answer"],
77+
row["Incorrect Answer 1"],
78+
row["Incorrect Answer 2"],
79+
row["Incorrect Answer 3"],
80+
],
81+
set=split_name,
82+
metadata=row.to_dict(), # type: ignore
83+
system_instruction=self.system_instruction, # type: ignore
84+
)
85+
86+
logging.info(
87+
f"[GPQABenchmark] Loaded {len(self.tasks)} tasks from {self.SPLITS} splits from the dataset."
88+
)
89+
90+
def get_split_tasks(self, split: str) -> List[str]:
91+
assert (
92+
split in self.SPLITS
93+
), f"Invalid split: {split}. Must be one of {self.SPLITS}."
94+
return [task.id for task in self.tasks.values() if task.set == split]
95+
96+
def evaluator(self, task: GPQATask, candidate: GPQACandidate) -> GPQAEvalResult: # type: ignore
97+
if isinstance(task, Dict):
98+
task = GPQATask(**task) # type: ignore
99+
if isinstance(candidate, Dict):
100+
candidate = GPQACandidate(**candidate) # type: ignore
101+
102+
answer_search_by_format = re.search(
103+
r"(?i)Answer[ \t]*:[ \t]*\$?([A-D])\$?", candidate.answer
104+
)
105+
extracted_answer = (
106+
answer_search_by_format.group(1) if answer_search_by_format else None
107+
)
108+
109+
# Find the correct letter (A/B/C/D) for the ground truth answer
110+
options = task.options
111+
ground_truth = task.ground_truth
112+
try:
113+
correct_index = options.index(ground_truth)
114+
correct_letter = "ABCD"[correct_index]
115+
except (ValueError, IndexError):
116+
correct_letter = None
117+
raise ValueError(
118+
f"Ground truth answer {ground_truth} not found in options {options}"
119+
)
120+
121+
score = correct_letter == extracted_answer # type: ignore
122+
return GPQAEvalResult( # type: ignore
123+
score=score, # type: ignore
124+
metadata={
125+
"ground_truth_answer": task.ground_truth,
126+
"extracted_answer": extracted_answer,
127+
"llm_response": candidate.answer,
128+
"task_id": task.id,
129+
},
130+
)
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# SimpleQA Eval
2+
3+
SimpleQA: Measuring short-form factuality in large language models
4+
Authors: Jason Wei, Nguyen Karina, Hyung Won Chung, Yunxin Joy Jiao, Spencer Papay, Amelia Glaese, John Schulman, William Fedus
5+
https://cdn.openai.com/papers/simpleqa.pdf
6+
7+
8+
Run instructions:
9+
10+
```python
11+
python experiments/eval/run.py --current-dir . --dataset SimpleQA --split main --run-id 0 --simulated-user-type none --parallel 1 --config experiments/endpoint_configs/config_template.yaml --mode run --system-type LLM
12+
```
13+
14+
```
15+
@article{wei2024measuring,
16+
title={Measuring short-form factuality in large language models},
17+
author={Wei, Jason and Karina, Nguyen and Chung, Hyung Won and Jiao, Yunxin Joy and Papay, Spencer and Glaese, Amelia and Schulman, John and Fedus, William},
18+
journal={arXiv preprint arXiv:2411.04368},
19+
year={2024}
20+
}
21+
```

src/magentic_ui/eval/benchmarks/simpleqa/__init__.py

Whitespace-only changes.
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# Credit: The prompt is taken from OpenAI simple-evals: https://github.com/openai/simple-evals/blob/3ec4e9b5ae3931a1858580e2fd3ce80c7fcbe1d9/simpleqa_eval.py#L13
2+
EVALUATOR_INSTRUCTION: str = """
3+
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"].
4+
First, I will give examples of each grade, and then you will grade a new example.
5+
6+
7+
The following are examples of CORRECT predicted answers.
8+
```
9+
Question: What are the names of Barack Obama's children?
10+
Gold target: Malia Obama and Sasha Obama
11+
Predicted answer 1: sasha and malia obama
12+
Predicted answer 2: most people would say Malia and Sasha, but I'm not sure and would have to double check
13+
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.
14+
```
15+
These predicted answers are all CORRECT because:
16+
- They fully contain the important information in the gold target.
17+
- They do not contain any information that contradicts the gold target.
18+
- Only semantic meaning matters; capitalization, punctuation, grammar, and order don't matter.
19+
- Hedging and guessing are permissible, provided that the gold target is fully included and the response contains no incorrect information or contradictions.
20+
21+
22+
The following are examples of INCORRECT predicted answers.
23+
```
24+
Question: What are the names of Barack Obama's children?
25+
Gold target: Malia and Sasha
26+
Predicted answer 1: Malia.
27+
Predicted answer 2: Malia, Sasha, and Susan.
28+
Predicted answer 3: Barack Obama does not have any children.
29+
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.
30+
Predicted answer 4: While I don't know their exact names, I can tell you that Barack Obama has three children.
31+
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?
32+
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.
33+
```
34+
These predicted answers are all INCORRECT because:
35+
- 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.
36+
37+
38+
The following are examples of NOT_ATTEMPTED predicted answers.
39+
```
40+
Question: What are the names of Barack Obama's children?
41+
Gold target: Malia and Sasha
42+
Predicted answer 1: I don't know.
43+
Predicted answer 2: I need more context about which Obama you are talking about.
44+
Predicted answer 3: Without researching the web, I cannot answer this question. However, I can tell you that Barack Obama has two children.
45+
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.
46+
```
47+
These predicted answers are all NOT_ATTEMPTED because:
48+
- The important information in the gold target is not included in the answer.
49+
- No statements in the answer contradict the gold target.
50+
51+
52+
Also note the following things:
53+
- 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".
54+
- Predicted answers "120k", "124k", and 115k" are all CORRECT.
55+
- Predicted answers "100k" and "113k" are INCORRECT.
56+
- Predicted answers "around 100k" and "more than 50k" are considered NOT_ATTEMPTED because they neither confirm nor contradict the gold target.
57+
- 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.
58+
- 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.
59+
- Do not punish predicted answers if they omit information that would be clearly inferred from the question.
60+
- 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".
61+
- 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.
62+
- 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.
63+
- 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.
64+
- Do not punish for typos in people's name if it's clearly the same name.
65+
- 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".
66+
67+
68+
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.
69+
```
70+
Question: {question}
71+
Gold target: {target}
72+
Predicted answer: {answer}
73+
```
74+
75+
Grade the predicted answer of this new question as one of:
76+
A: CORRECT
77+
B: INCORRECT
78+
C: NOT_ATTEMPTED
79+
80+
Just return the letters "A", "B", or "C", with no text around it.
81+
""".strip()

0 commit comments

Comments
 (0)