File size: 5,874 Bytes
235c967 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | import re
import string
from typing import Dict, Any, Optional, List, Tuple, Callable
############################Tool Fuctions############################
def normalize_text(text: str) -> str:
"""Normalize text by removing whitespace, punctuation, and converting to lowercase."""
text = text.lower()
text = re.sub(r'\s+', '', text)
text = text.translate(str.maketrans('', '', string.punctuation))
return text
def extract_answer_from_text(text: str) -> str:
"""Extract answer from text with various patterns."""
patterns = [
r"The answer is:?\s*(.*?)(?:\n|$)",
r"Answer:?\s*(.*?)(?:\n|$)",
r"Final answer:?\s*(.*?)(?:\n|$)",
r"Therefore,\s*(.*?)(?:\n|$)",
r"Thus,\s*(.*?)(?:\n|$)",
]
for pattern in patterns:
match = re.search(pattern, text, re.DOTALL)
if match:
return match.group(1).strip()
# If no pattern matches, return the last line as a fallback
lines = text.strip().split('\n')
return lines[-1].strip()
# ====== Dataset Processors ======
def process_metamathqa(item: Dict[str, Any]) -> Tuple[str, str]:
"""Process MetaMathQA dataset item."""
question = item["query"]
answer = extract_answer_from_text(item["response"])
return question, answer
def process_gsm8k(item: Dict[str, Any]) -> Tuple[str, str]:
"""Process GSM8K dataset item."""
question = item["question"]
answer = item["answer"]
answer=answer.split("####")[1].strip().lower()
return question, answer
def process_theoremqa(item: Dict[str, Any]) -> Tuple[str, str]:
"""Process TheoremQA dataset item."""
question = item["Question"]
answer = str(item["Answer"])
return question, answer
def process_mmlu(item: Dict[str, Any]) -> Tuple[str, str]:
"""Process MMLU dataset with multiple choice format."""
question = item['question']
choices = [item['choices'][i] for i in range(len(item['choices']))]
formatted_question = question + "\n" + "\n".join([f"{chr(65+i)}. {choice}" for i, choice in enumerate(choices)])
answer = chr(65 + item['answer']) # Convert to A, B, C, D format
return formatted_question, answer
def process_gpqa(item: Dict[str, Any]) -> Tuple[str, str]:
"""Process GPQA dataset item."""
question = item["Question"]
answer = extract_answer_from_text(item["Correct Answer"])
return question, answer
# ====== Scoring Functions ======
def compute_score_exact_match(prediction: str, label: str) -> Dict[str, Any]:
"""Basic exact match after normalization."""
norm_pred = normalize_text(prediction)
norm_label = normalize_text(label)
is_correct = norm_pred == norm_label
is_valid = len(norm_pred) > 0 # Simple validity check
return {
"is_correct": is_correct,
"is_valid": is_valid,
"normalized_prediction": norm_pred,
"normalized_label": norm_label
}
def compute_score_numeric(prediction: str, label: str) -> Dict[str, Any]:
"""Extract numeric values and compare them."""
# Extract the first numeric value from both prediction and label
pred_match = re.search(r'(\d+(?:\.\d+)?)', prediction)
label_match = re.search(r'(\d+(?:\.\d+)?)', label)
is_valid = pred_match is not None
if pred_match and label_match:
pred_answer = pred_match.group(0)
label_answer = label_match.group(0)
try:
is_correct = float(pred_answer) == float(label_answer)
except ValueError:
is_correct = False
else:
is_correct = False
# Also try text match as fallback
text_match = normalize_text(prediction) == normalize_text(label)
is_correct = is_correct or text_match
return {
"is_correct": is_correct,
"is_valid": is_valid,
"numeric_match": is_correct and not text_match,
"text_match": text_match
}
def compute_score_multiple_choice(prediction: str, label: str) -> Dict[str, Any]:
"""Score multiple choice answers (A, B, C, D)."""
pred_match = re.search(r'([A-D])', prediction.upper())
label_match = re.search(r'([A-D])', label.upper())
is_valid = pred_match is not None
if pred_match and label_match:
pred_choice = pred_match.group(0)
label_choice = label_match.group(0)
is_correct = pred_choice == label_choice
else:
# Fallback to text comparison
is_correct = normalize_text(prediction) == normalize_text(label)
return {
"is_correct": is_correct,
"is_valid": is_valid,
"extracted_prediction": pred_match.group(0) if pred_match else None,
"extracted_label": label_match.group(0) if label_match else None
}
##########################registration###########################
REGISTERD_STATIC_ENV = {
"metamathqa": {
"config": {
"path": "meta-math/MetaMathQA",
},
"processor": process_metamathqa,
"compute_score": compute_score_exact_match
},
"gsm8k": {
"config": {
"path": "openai/gsm8k",
"name":"main"
},
"processor": process_gsm8k,
"compute_score": compute_score_numeric
},
# "theoremqa": {
# "config": {
# "path": "TIGER-Lab/TheoremQA",
# },
# "processor": process_theoremqa,
# "compute_score": compute_score_numeric
# },
"mmlu": {
"config": {
"path": "cais/mmlu",
"name": "abstract_algebra",
},
"processor": process_mmlu,
"compute_score": compute_score_multiple_choice
},
# "gpqa":{
# "config": {
# "path": "Idavidrein/gpqa",
# "name": "gpqa_main",
# },
# "processor": process_gpqa,
# "compute_score": compute_score_exact_match
# }
} |