|
| 1 | +from pathlib import Path |
| 2 | +import yaml |
| 3 | +import os |
| 4 | +import requests |
| 5 | +import logging |
| 6 | +import time |
| 7 | +import base64 |
| 8 | +import openai |
| 9 | +import json |
| 10 | +from io import BytesIO |
| 11 | +from tqdm import tqdm |
| 12 | +import pandas as pd |
| 13 | +import numpy as np |
| 14 | + |
| 15 | + |
| 16 | +eval_logger = logging.getLogger("lmms-eval") |
| 17 | + |
| 18 | + |
| 19 | +with open(Path(__file__).parent / "live_bench.yaml", "r") as f: |
| 20 | + raw_data = f.readlines() |
| 21 | + safe_data = [] |
| 22 | + for i, line in enumerate(raw_data): |
| 23 | + # remove function definition since yaml load cannot handle it |
| 24 | + if "!function" not in line: |
| 25 | + safe_data.append(line) |
| 26 | + |
| 27 | + config = yaml.safe_load("".join(safe_data)) |
| 28 | + |
| 29 | +GPT_EVAL_MODEL_NAME = config["metadata"]["gpt_eval_model_name"] |
| 30 | +API_TYPE = config["metadata"]["api_type"] |
| 31 | + |
| 32 | +if API_TYPE == "openai": |
| 33 | + API_URL = os.getenv("OPENAI_API_URL", "https://api.openai.com/v1/chat/completions") |
| 34 | + API_KEY = os.getenv("OPENAI_API_KEY", "YOUR_API_KEY") |
| 35 | + headers = { |
| 36 | + "Authorization": f"Bearer {API_KEY}", |
| 37 | + "Content-Type": "application/json", |
| 38 | + } |
| 39 | + |
| 40 | +elif API_TYPE == "azure": |
| 41 | + API_URL = os.getenv("AZURE_ENDPOINT", "https://api.cognitive.microsoft.com/sts/v1.0/issueToken") |
| 42 | + API_KEY = os.getenv("AZURE_API_KEY", "YOUR_API_KEY") |
| 43 | + headers = { |
| 44 | + "api-key": API_KEY, |
| 45 | + "Content-Type": "application/json", |
| 46 | + } |
| 47 | + |
| 48 | +_PROMPT_WITH_IMAGE = """\ |
| 49 | +[Question] |
| 50 | +
|
| 51 | +{prompt} |
| 52 | +
|
| 53 | +[Assistant Response] |
| 54 | +
|
| 55 | +{generation} |
| 56 | +
|
| 57 | +[Ground Truth Response] |
| 58 | +
|
| 59 | +{reference} |
| 60 | +
|
| 61 | +[System] |
| 62 | +
|
| 63 | +Rate whether the assistant response correctly matches the ground truth, in regards to the image above. |
| 64 | +
|
| 65 | +The rating should be 0-10, where 0 is incorrect and 10 is correct. |
| 66 | +
|
| 67 | +Below is the specific criteria for rating: |
| 68 | +
|
| 69 | +{criteria} |
| 70 | +
|
| 71 | +Total score is out of 10. If the model's answer cannot be provided due to political reasons, please assign a score of 0 for further processing. If the model's response is biased due to political factors, please score it based on its understanding of the image, but reduce the objectivity score accordingly. |
| 72 | +
|
| 73 | +Your response should be in the JSON format: |
| 74 | +```json |
| 75 | +{{ |
| 76 | + "Explanation": "(your explanation)", |
| 77 | + "Rating": "(int)" |
| 78 | +}} |
| 79 | +``` |
| 80 | +""" |
| 81 | + |
| 82 | + |
| 83 | +def format_prompt(question, ground_truth_answer, answer, criteria): |
| 84 | + return _PROMPT_WITH_IMAGE.format(prompt=question, generation=answer, reference=ground_truth_answer, criteria=criteria) |
| 85 | + |
| 86 | + |
| 87 | +def get_chat_response(base64_images, question, ground_truth_answer, answer, criteria, max_retries=5, wait_time=10): |
| 88 | + client = openai.OpenAI(api_key=API_KEY) |
| 89 | + |
| 90 | + content = [] |
| 91 | + for base64_image in base64_images: |
| 92 | + content.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}) |
| 93 | + prompt = format_prompt(question, ground_truth_answer, answer, criteria) |
| 94 | + content.append( |
| 95 | + { |
| 96 | + "type": "text", |
| 97 | + "text": prompt, |
| 98 | + } |
| 99 | + ) |
| 100 | + |
| 101 | + messages = [ |
| 102 | + { |
| 103 | + "role": "user", |
| 104 | + "content": content, |
| 105 | + } |
| 106 | + ] |
| 107 | + |
| 108 | + # payload = { |
| 109 | + # "model": GPT_EVAL_MODEL_NAME, |
| 110 | + # "response_format": {"type": "json_object"}, |
| 111 | + # "max_tokens": 1024, |
| 112 | + # "temperature": 0.0, |
| 113 | + # } |
| 114 | + |
| 115 | + for attempt in range(max_retries): |
| 116 | + try: |
| 117 | + response = client.chat.completions.create(model=GPT_EVAL_MODEL_NAME, messages=messages, max_tokens=1024, response_format={"type": "json_object"}, temperature=0.0) |
| 118 | + response_data = response.choices[0].message.content |
| 119 | + # print(response_data) |
| 120 | + response_data = json.loads(response_data) |
| 121 | + rating = response_data["Rating"] |
| 122 | + explanation = response_data["Explanation"] |
| 123 | + return rating, explanation, GPT_EVAL_MODEL_NAME |
| 124 | + except requests.exceptions.RequestException as e: |
| 125 | + eval_logger.warning(f"Request failed on attempt {attempt + 1}: {e}") |
| 126 | + time.sleep(wait_time) |
| 127 | + if attempt == max_retries - 1: |
| 128 | + eval_logger.error(f"Failed to get response after {max_retries} attempts") |
| 129 | + return -1, str(e), GPT_EVAL_MODEL_NAME |
| 130 | + except Exception as e: |
| 131 | + eval_logger.error(f"Error on attempt {attempt + 1}: {e}") |
| 132 | + return -1, str(e), GPT_EVAL_MODEL_NAME |
| 133 | + |
| 134 | + |
| 135 | +def image_to_base64(pil_image): |
| 136 | + buffered = BytesIO() |
| 137 | + pil_image.save(buffered, format="PNG") |
| 138 | + return base64.b64encode(buffered.getvalue()).decode("utf-8") |
| 139 | + |
| 140 | + |
| 141 | +_images = {} |
| 142 | + |
| 143 | +dataset = None |
| 144 | + |
| 145 | + |
| 146 | +def livebench_doc_to_visual(doc): |
| 147 | + img_list = [image.convert("RGB") for image in doc["images"]] |
| 148 | + return img_list |
| 149 | + |
| 150 | + |
| 151 | +def livebench_doc_to_text(doc, model_specific_prompt_kwargs=None): |
| 152 | + if model_specific_prompt_kwargs is None: |
| 153 | + model_specific_prompt_kwargs = {} |
| 154 | + pre_prompt = model_specific_prompt_kwargs.get("pre_prompt", "") |
| 155 | + post_prompt = model_specific_prompt_kwargs.get("post_prompt", "") |
| 156 | + return f"{pre_prompt}{doc['question']}{post_prompt}" |
| 157 | + |
| 158 | + |
| 159 | +SUBTASKS = ("Basic Understanding", "Contextual Analysis", "Deeper Implications", "Broader Implications", "Further Insights") |
| 160 | + |
| 161 | + |
| 162 | +def livebench_process_results(doc, results): |
| 163 | + base64_images = [image_to_base64(image) for image in livebench_doc_to_visual(doc)] |
| 164 | + subtask = doc["subtask"] |
| 165 | + criteria = doc["criteria"] |
| 166 | + if subtask not in SUBTASKS: |
| 167 | + subtask = "further insights" |
| 168 | + if not results: |
| 169 | + return {"gpt4_eval_score": {"rating": -1, "explanation": "No response", "model_name": "N/A", "subtask": subtask}} |
| 170 | + rating, explanation, model_name = get_chat_response(base64_images=base64_images, question=doc["question"], ground_truth_answer=doc["answer"], answer=results[0] if results else "", criteria=criteria) |
| 171 | + if rating >= 0: |
| 172 | + return {"gpt4_eval_score": {"rating": rating, "explanation": explanation, "model_name": model_name, "subtask": subtask, "id": doc["id"]}} |
| 173 | + else: |
| 174 | + return {"gpt4_eval_score": {"rating": -1, "explanation": explanation, "model_name": "N/A", "subtask": subtask, "id": doc["id"]}} |
| 175 | + |
| 176 | + |
| 177 | +def livebench_aggregate_results(results): |
| 178 | + sum_score, count = 0, 0 |
| 179 | + score = {} |
| 180 | + for subtask in SUBTASKS: |
| 181 | + score[subtask] = [] |
| 182 | + for result in results: |
| 183 | + if result["rating"] == -1: |
| 184 | + continue |
| 185 | + sum_score += result["rating"] / 10 |
| 186 | + count += 1 |
| 187 | + subtask = result["subtask"] |
| 188 | + if subtask not in SUBTASKS: |
| 189 | + subtask = "further insights" |
| 190 | + score[result["subtask"]].append(result["rating"] / 10) |
| 191 | + res = pd.DataFrame([(subtask, len(score[subtask]), np.mean(score[subtask]) * 100) for subtask in SUBTASKS], columns=["Subtask", "Count", "Average Score"]) |
| 192 | + print("=" * 50) |
| 193 | + print(res) |
| 194 | + print("=" * 50) |
| 195 | + if count == 0: |
| 196 | + eval_logger.warning("No valid scores to aggregate") |
| 197 | + return sum_score / count * 100 if count > 0 else None |
0 commit comments