File size: 15,214 Bytes
dd4cef8 |
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 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 |
# This code is modified from the original work available at:
# https://github.com/TIGER-AI-Lab/MMLU-Pro
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Changes made:
# - Updated `eval.py` logic for our dataset.
import os
import json
from tqdm import tqdm
import time
from datasets import load_dataset
import argparse
import pandas as pd
import base64
from PIL import Image
from io import BytesIO
import ast
OPENAI_API_KEY = ""
GEMINI_API_KEY = ""
# The 5-shot examples are taken from MMLU Maths and Physics questions.
ms_prompt="""
Diberikan contoh-contoh berikut:
Soalan: Glukosa diangkut ke dalam sel otot:
Pilihan:
A. melalui pengangkut protein yang dipanggil GLUT4.
B. hanya dengan kehadiran insulin.
C. melalui hexokinase.
D. melalui pengangkut asid monokarbilik.
Jawapan: A
Soalan: Jika sebuah pentagon P dengan bucu-bucu di (–2, –4), (–4, 1), (–1, 4), (2, 4), dan (3, 0) dipantulkan merentasi garis y = x untuk mendapatkan pentagon baru, P’, maka salah satu bucu P’ ialah
Pilihan:
A. (0, –3)
B. (4, 1)
C. (2, 2)
D. (–4, –2)
Jawapan: D
Soalan: John membahagikan pin topi cenderamatanya kepada dua timbunan. Kedua-dua timbunan mempunyai bilangan pin yang sama. Dia memberikan kepada abangnya separuh daripada satu pertiga salah satu timbunan. John mempunyai 66 pin yang tinggal. Berapakah bilangan pin yang John miliki pada asalnya?
Pilihan:
A. 396
B. 72
C. 66
D. 36
Jawapan: B
Soalan: Sebuah sfera pejal (I = 0.06 kg·m^2) berputar bebas mengelilingi paksi melalui pusatnya pada kelajuan sudut 20 rad/s. Dikehendaki menghentikan sfera tersebut dengan menggunakan daya geseran sebesar 2.0 N di permukaan luar sfera, pada jarak 0.30 m dari pusat sfera. Berapa lamakah masa yang diambil untuk menghentikan sfera tersebut?
Pilihan:
A. 4 s
B. 2 s
C. 0.06 s
D. 0.03 s
Jawapan: B
Soalan: Cahaya ultraviolet mempunyai panjang gelombang sekitar 6 × 10^-8 m. Apakah frekuensi cahaya ini?
Pilihan:
A. 5 × 10^15 Hz
B. 0.5 Hz
C. 2 Hz
D. 20 Hz
Jawapan: A
Berikut adalah soalan pilihan berganda. Pilih jawapan yang betul daripada pilihan 'A', 'B', 'C', atau 'D'.
Jawab dengan hanya huruf pilihan yang betul. Jangan berikan sebarang penjelasan atau teks tambahan.
Jawapan hendaklah hanya salah satu daripada ini: 'A', 'B', 'C', 'D'.\n\n
"""
en_prompt = """
Given the examples:
Question: Glucose is transported into the muscle cell:
Choices:
A. via protein transporters called GLUT4.
B. only in the presence of insulin.
C. via hexokinase.
D. via monocarbylic acid transporters.
Answer: A
Question: If a pentagon P with vertices at (– 2, – 4), (– 4, 1), (–1, 4), (2, 4), and (3, 0) is reflected across the line y = x to get a new pentagon, P’, then one of the vertices of P’ is
Choices:
A. (0, – 3)
B. (4, 1)
C. (2, 2)
D. (– 4, –2)
Answer: D
Question: John divided his souvenir hat pins into two piles. The two piles had an equal number of pins. He gave his brother one-half of one-third of one pile. John had 66 pins left. How many pins did John originally have?
Choices:
A. 396
B. 72
C. 66
D. 36
Answer: B
Question: A solid sphere (I = 0.06 kg·m^2) spins freely around an axis through its center at an angular speed of 20 rad/s. It is desired to bring the sphere to rest by applying a friction force of magnitude 2.0 N to the sphere’s outer surface, a distance of 0.30 m from the sphere’s center. How much time will it take the sphere to come to rest?
Choices:
A. 4 s
B. 2 s
C. 0.06 s
D. 0.03 s
Answer: B
Question: Ultraviolet light has a wavelength of about 6 × 10^-8 m. What is the frequency of this light?
Choices:
A. 5 × 10^15 Hz
B. 0.5 Hz
C. 2 Hz
D. 20 Hz
Answer: A
The following are multiple choice questions. Choose the correct answer from the options 'A', 'B', 'C', or 'D'.
Answer with only the letter of the correct option. Do not provide any extra explanation or text.
The answer should only be one of these: 'A', 'B', 'C', 'D'.\n\n
"""
def get_client():
if args.model_name in ["gpt-4o-mini", "gpt-4o"]:
import openai
openai.api_key = OPENAI_API_KEY
client = openai
elif args.model_name in ["gemini-2.0-flash-exp", "gemini-1.5-flash"]:
import google.generativeai as genai
genai.configure(api_key=GEMINI_API_KEY)
generation_config = {
"temperature": 0.0,
"top_p": 0.1,
"max_output_tokens": 1,
"response_mime_type": "text/plain",
}
client = genai.GenerativeModel(
model_name=args.model_name,
generation_config=generation_config,
)
else:
client = None
print("For other model API calls, please implement the client definition method yourself.")
return client
def call_api(client, instruction, inputs):
start = time.time()
if args.model_name in ["gpt-4o-mini", "gpt-4o"]:
message_text = [{"role": "user", "content": instruction + inputs}]
completion = client.chat.completions.create(
model=args.model_name,
messages=message_text,
temperature=0,
max_tokens=1,
top_p=0.1,
)
result = completion.choices[0].message.content
elif args.model_name in ["gemini-2.0-flash-exp", "gemini-1.5-flash"]:
response = client.generate_content([instruction, inputs])
result = response.text
else:
print("For other model API calls, please implement the request method yourself.")
result = None
print("cost time", time.time() - start)
return result
def call_api_figures(client, instruction, inputs, figures):
start = time.time()
if args.model_name in ["gpt-4o-mini", "gpt-4o"]:
content = [{"type": "text", "text": instruction + inputs}]
for figure in figures:
content.append({
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{encode_image(figure)}"}
})
message_text = [{"role": "user", "content": content}]
completion = client.chat.completions.create(
model=args.model_name,
messages=message_text,
temperature=0,
max_tokens=1,
top_p=0.1
)
result = completion.choices[0].message.content
elif args.model_name in ["gemini-2.0-flash-exp", "gemini-1.5-flash"]:
content = [instruction, inputs]
for figure in figures:
content.append(figure)
response = client.generate_content(content)
result = response.text
else:
print("For other model API calls, please implement the request method yourself.")
result = None
print("cost time", time.time() - start)
return result
# Function to encode the image to base64
def encode_image(image):
# Check if the image is in RGBA mode and convert it to RGB
if image.mode == "RGBA":
image = image.convert("RGB")
buffered = BytesIO()
image.save(buffered, format="JPEG") # Save image as JPEG
return base64.b64encode(buffered.getvalue()).decode("utf-8") # Return base64 string
def format_question(question_text, options_str, language):
# Parse the string into a Python list
options = ast.literal_eval(options_str)
if language == 'en':
question = f"Question: {question_text}\nOptions:\n"
for opt in options:
question += f"{opt}\n"
question += "Answer: "
elif language == 'ms':
question = f"Soalan: {question_text}\nPilihan:\n"
for opt in options:
question += f"{opt}\n"
question += "Jawapan: "
return question
def single_request(client, single_question, with_figure, language):
question = single_question["Questions"]
options = single_question["Options"]
if language == 'en':
prompt = en_prompt
elif language == 'ms':
prompt = ms_prompt
input_text = format_question(question, options, language)
retries = 5
delay = 15
attempt = 0
if with_figure:
figures_data = single_question["Label"]
pairs = [entry.strip() for item in figures_data for entry in item.split(",")]
figure_labels = [{"label": label.strip(), "path": path.strip()} for label, path in [pair.split(":") for pair in pairs]]
figures = single_question["Figures"]
prompt += "".join([f"Figure {index}: {figure['label']}\n" for index, figure in enumerate(figure_labels)])
while attempt < retries:
try:
response = call_api_figures(client, prompt, input_text, figures)
if response:
response = response.replace('**', '')
return response, response
except Exception as e:
print(f"Error: {e}")
attempt += 1
if attempt < retries:
print(f"Retrying in {delay:.2f} seconds...")
time.sleep(delay)
return None, f"Failed after {retries} retries."
else:
while attempt < retries:
try:
response = call_api(client, prompt, input_text)
if response:
response = response.replace('**', '')
return response, response
except Exception as e:
print(f"Error: {e}")
attempt += 1
if attempt < retries:
print(f"Retrying in {delay:.2f} seconds...")
time.sleep(delay)
return None, f"Failed after {retries} retries."
def evaluate(language, with_figure=False):
client = get_client()
# Load dataset from Hugging Face
dataset_name = "Supa-AI/STEM-en-ms"
dataset = load_dataset(dataset_name, name=f"data_{language}", split="eval")
# Convert to pandas DataFrame
data = pd.DataFrame(dataset)
# Split the dataset into two parts: with figures and without figures
data_with_figures = data[data["Figures"].apply(lambda x: isinstance(x, list) and len(x) > 0)]
data_without_figures = data[data["Figures"].apply(lambda x: isinstance(x, list) and len(x) == 0)]
if with_figure:
test_data = data_with_figures
suffix = f"{args.model_name}_{language}_wfigures".split("/", 1)[-1]
else:
test_data = data_without_figures
suffix = f"{args.model_name}_{language}_wofigures".split("/", 1)[-1]
output_res_path = os.path.join(args.output_dir, suffix + "_result.json")
total_questions = len(test_data) # Total includes all questions
# Load existing results if available
if os.path.exists(output_res_path):
with open(output_res_path, "r", encoding="utf-8") as f:
existing_results = json.load(f)
processed_ids = {entry["FileName"] for entry in existing_results}
# Count correct predictions from existing results
correct_predictions_existing = sum(1 for entry in existing_results if entry.get("pred") == entry.get("Answers"))
else:
existing_results = []
processed_ids = set()
correct_predictions_existing = 0
# Filter out already processed entries
test_data = test_data[~test_data["FileName"].isin(processed_ids)]
res = existing_results
correct_predictions_new = 0
for _, each in tqdm(test_data.iterrows(), total=len(test_data)):
label = each["Answers"]
# if len(each["Figures"]) > 1: continue
pred, response = single_request(client, each, with_figure, language)
if response is not None:
each["pred"] = pred
each["model_outputs"] = response
if pred is not None and pred == label:
correct_predictions_new += 1
res.append(each.to_dict())
save_res(res, output_res_path) # Save results incrementally
print(f"FileName: {each["FileName"]}, Answer: {each["Answers"]}, Prediction: {each["pred"]}")
# Calculate accuracy
correct_predictions_total = correct_predictions_existing + correct_predictions_new
print("Total Question: ", total_questions)
print("Correct Predictions Exist: ", correct_predictions_existing)
print("Correct Predictions New: ", correct_predictions_new)
accuracy = correct_predictions_total / total_questions if total_questions > 0 else 0
print(f"Accuracy: {accuracy:.2%}")
def remove_images_from_res(res):
"""Recursively removes image objects from the result dictionary."""
if isinstance(res, dict):
for key, value in res.items():
if isinstance(value, Image.Image):
res[key] = "Image is not saved" # Replace image objects with a placeholder
elif isinstance(value, (dict, list)):
remove_images_from_res(value) # Recursively process nested structures
elif isinstance(res, list):
for i in range(len(res)):
if isinstance(res[i], Image.Image):
res[i] = "Image is not saved" # Replace image objects with a placeholder
elif isinstance(res[i], (dict, list)):
remove_images_from_res(res[i]) # Recursively process nested structures
return res
def save_res(res, output_res_path):
"""Save the result to a file, excluding images."""
os.makedirs(os.path.dirname(output_res_path), exist_ok=True)
res = remove_images_from_res(res) # Remove images from the result
with open(output_res_path, "w", encoding="utf-8") as fo:
fo.write(json.dumps(res, indent=4, ensure_ascii=False))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--output_dir", "-o", type=str, default="eval_results/")
parser.add_argument("--model_name", "-m", type=str, default="gpt-4o",
choices=["gpt-4o-mini", "gpt-4o", # OPENAI
"gemini-2.0-flash-exp", "gemini-1.5-flash", # GEMINI
])
parser.add_argument("--language", "-l", type=str, default="en")
parser.add_argument("--with_figures", "-f", type=bool, default=False)
args = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
evaluate(args.language, args.with_figures) |