-
Notifications
You must be signed in to change notification settings - Fork 2k
Add AI2ARC dataset #8502
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
TomeHirata
wants to merge
3
commits into
stanfordnlp:main
Choose a base branch
from
TomeHirata:datasets/arc
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add AI2ARC dataset #8502
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,147 @@ | ||
import re | ||
from typing import Literal | ||
|
||
import tqdm | ||
|
||
import dspy | ||
|
||
|
||
class AI2ARC: | ||
"""AI2 Reasoning Challenge (ARC) Dataset. | ||
|
||
The ARC dataset contains multiple-choice science questions at a grade-school level. | ||
It consists of two subsets: ARC-Challenge (harder questions) and ARC-Easy (easier questions). | ||
|
||
Args: | ||
subset: Either "challenge" or "easy" to specify which subset to load | ||
""" | ||
|
||
def __init__(self, subset: Literal["challenge", "easy"] = "challenge"): | ||
if subset not in ["challenge", "easy"]: | ||
raise ValueError("subset must be either 'challenge' or 'easy'") | ||
|
||
self.subset = subset | ||
|
||
from datasets import load_dataset | ||
|
||
dataset_name = "allenai/ai2_arc" | ||
config_name = f"ARC-{subset.title()}" | ||
|
||
try: | ||
hf_dataset = load_dataset(dataset_name, config_name) | ||
except Exception as e: | ||
raise RuntimeError(f"Failed to load {config_name} from {dataset_name}: {e}") | ||
|
||
official_train = self._process_split(hf_dataset["train"]) if "train" in hf_dataset else [] | ||
TomeHirata marked this conversation as resolved.
Show resolved
Hide resolved
|
||
official_dev = self._process_split(hf_dataset["validation"]) if "validation" in hf_dataset else [] | ||
official_test = self._process_split(hf_dataset["test"]) if "test" in hf_dataset else [] | ||
|
||
self.train = [dspy.Example(**x).with_inputs("question", "choices") for x in official_train] | ||
self.dev = [dspy.Example(**x).with_inputs("question", "choices") for x in official_dev] | ||
self.test = [dspy.Example(**x).with_inputs("question", "choices") for x in official_test] | ||
|
||
def _process_split(self, split_data): | ||
"""Process a data split and convert to DSPy format.""" | ||
processed_data = [] | ||
|
||
for example in tqdm.tqdm(split_data, desc=f"Processing {self.subset} split"): | ||
TomeHirata marked this conversation as resolved.
Show resolved
Hide resolved
|
||
choices_text = [] | ||
choice_labels = example["choices"]["label"] | ||
choice_texts = example["choices"]["text"] | ||
|
||
for label, text in zip(choice_labels, choice_texts, strict=False): | ||
choices_text.append(f"({label}) {text}") | ||
|
||
processed_example = { | ||
"id": example["id"], | ||
"question": example["question"], | ||
"choices": "\n".join(choices_text), | ||
"choices_list": choice_texts, | ||
"choice_labels": choice_labels, | ||
"answer": example["answerKey"], | ||
"answer_text": self._get_answer_text(example) | ||
} | ||
|
||
processed_data.append(processed_example) | ||
|
||
return processed_data | ||
|
||
def _get_answer_text(self, example): | ||
"""Extract the answer text corresponding to the correct answer key.""" | ||
answer_key = example["answerKey"] | ||
choice_labels = example["choices"]["label"] | ||
choice_texts = example["choices"]["text"] | ||
|
||
try: | ||
answer_index = choice_labels.index(answer_key) | ||
return choice_texts[answer_index] | ||
except ValueError: | ||
# If answer key not found in labels, return the key itself | ||
return answer_key | ||
|
||
|
||
def ai2_arc_metric(gold, pred, trace=None): | ||
"""Metric function for AI2 ARC dataset. | ||
|
||
Args: | ||
gold: Gold example with 'answer' field | ||
pred: Predicted example with 'answer' field | ||
trace: Optional trace (unused) | ||
|
||
Returns: | ||
bool: True if prediction matches gold answer | ||
""" | ||
pred_answer = str(pred.answer).strip().upper() | ||
TomeHirata marked this conversation as resolved.
Show resolved
Hide resolved
|
||
gold_answer = str(gold.answer).strip().upper() | ||
|
||
if len(pred_answer) == 1 and pred_answer in ["A", "B", "C", "D"]: | ||
return pred_answer == gold_answer | ||
|
||
for letter in ["A", "B", "C", "D"]: | ||
if f"({letter})" in pred_answer or f"{letter})" in pred_answer: | ||
return letter == gold_answer | ||
|
||
return False | ||
|
||
|
||
def parse_arc_answer(answer_text): | ||
"""Parse answer from model output to extract the letter choice. | ||
|
||
Args: | ||
answer_text: Raw model output | ||
|
||
Returns: | ||
str: Extracted answer letter (A, B, C, or D), or the original text if not found | ||
""" | ||
answer_text = str(answer_text).strip() | ||
|
||
patterns = [ | ||
r"\(([ABCD])\)", # (A), (B), etc. | ||
r"([ABCD])\)", # A), B), etc. | ||
r"^([ABCD])$", # Just A, B, C, D at start of line | ||
r"answer is ([ABCD])", # "answer is A" | ||
r"choice ([ABCD])", # "choice A" | ||
] | ||
|
||
for pattern in patterns: | ||
match = re.search(pattern, answer_text.upper()) | ||
if match: | ||
return match.group(1) | ||
|
||
# If no pattern found, return the first letter if it's A, B, C, or D | ||
first_char = answer_text.upper()[0] if answer_text else "" | ||
if first_char in ["A", "B", "C", "D"]: | ||
return first_char | ||
|
||
return answer_text | ||
|
||
|
||
# Convenience functions for loading specific subsets | ||
def ARC_Challenge(): | ||
TomeHirata marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""Load the ARC-Challenge subset.""" | ||
return AI2ARC(subset="challenge") | ||
|
||
|
||
def ARC_Easy(): | ||
"""Load the ARC-Easy subset.""" | ||
return AI2ARC(subset="easy") |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.