|
import re |
|
import argparse |
|
import json |
|
import time |
|
import copy |
|
import traceback |
|
import random |
|
import requests |
|
import numpy as np |
|
import language_evaluation |
|
from multiprocessing import Pool |
|
import openai |
|
from huggingface_hub import HfApi, hf_hub_download |
|
import ast |
|
|
|
USE_INTERNAL = True |
|
|
|
GROUND_TRUTH = "ground_truth/drivelm_val.json" |
|
FORMAT = "json" |
|
|
|
|
|
MAXIMUM_L2_Error = 100 |
|
|
|
"""Error handling code""" |
|
TEAM_MESSAGE_TEMPLATE = "The team name in your submission is [<TEAM_NAME>].\n" |
|
def update_teamname_to_submission_comment(params, team_name): |
|
hfapi = HfApi() |
|
team_info_in_repo = "submission_info/{}.json".format(params.team_id) |
|
team_info_file = hf_hub_download( |
|
repo_id=params.competition_id, |
|
filename=team_info_in_repo, |
|
token=params.token, |
|
repo_type="dataset", |
|
) |
|
team_info = json.load(open(team_info_file, "r")) |
|
|
|
for sub_info in team_info["submissions"]: |
|
if sub_info["submission_id"] == params.submission_id: |
|
sub_info["submission_comment"] = TEAM_MESSAGE_TEMPLATE.replace("<TEAM_NAME>", team_name) + sub_info["submission_comment"] |
|
break |
|
|
|
with open(team_info_file, "w") as f: |
|
json.dump(team_info, f, indent=4) |
|
|
|
hfapi.upload_file( |
|
path_or_fileobj=team_info_file, |
|
path_in_repo=team_info_in_repo, |
|
repo_id=params.competition_id, |
|
repo_type="dataset", |
|
token=params.token, |
|
) |
|
return |
|
|
|
ERROR_MESSAGE_TEMPLATE = "[ERROR] [<ERROR_MESSAGE>]\n" |
|
def update_error_message_to_submission_comment(params, error_message): |
|
hfapi = HfApi() |
|
team_info_in_repo = "submission_info/{}.json".format(params.team_id) |
|
team_info_file = hf_hub_download( |
|
repo_id=params.competition_id, |
|
filename=team_info_in_repo, |
|
token=params.token, |
|
repo_type="dataset", |
|
) |
|
team_info = json.load(open(team_info_file, "r")) |
|
|
|
for sub_info in team_info["submissions"]: |
|
if sub_info["submission_id"] == params.submission_id: |
|
sub_info["submission_comment"] = ERROR_MESSAGE_TEMPLATE.replace("[<ERROR_MESSAGE>]", error_message) + sub_info["submission_comment"] |
|
break |
|
|
|
with open(team_info_file, "w") as f: |
|
json.dump(team_info, f, indent=4) |
|
|
|
hfapi.upload_file( |
|
path_or_fileobj=team_info_file, |
|
path_in_repo=team_info_in_repo, |
|
repo_id=params.competition_id, |
|
repo_type="dataset", |
|
token=params.token, |
|
) |
|
return |
|
|
|
def exception_handler_decorator(func): |
|
def wrapper(params): |
|
try: |
|
return func(params) |
|
except Exception as e: |
|
hfapi = HfApi() |
|
team_info_in_repo = "submission_info/{}.json".format(params.team_id) |
|
team_info_file = hf_hub_download( |
|
repo_id=params.competition_id, |
|
filename=team_info_in_repo, |
|
token=params.token, |
|
repo_type="dataset", |
|
) |
|
team_info = json.load(open(team_info_file, "r")) |
|
|
|
for sub_info in team_info["submissions"]: |
|
if sub_info["submission_id"] == params.submission_id: |
|
sub_info["error_message"] = str(e) + '\n\n' + traceback.format_exc() |
|
break |
|
|
|
with open(team_info_file.replace('.json', '_error.json'), "w") as f: |
|
json.dump(sub_info, f, indent=4) |
|
|
|
hfapi.upload_file( |
|
path_or_fileobj=team_info_file.replace('.json', '_error.json'), |
|
path_in_repo=f'submission_error/{params.submission_id}.json', |
|
repo_id=params.competition_id, |
|
repo_type="dataset", |
|
token=params.token, |
|
) |
|
raise e |
|
return wrapper |
|
|
|
"""DriveLM Specific""" |
|
|
|
|
|
API_KEYS = [ |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
'sk-wrFnTE0zlU1UngGmE8Dd1eC4880142Cd99A3CeB33eAe8d1e', |
|
'sk-DLon77JND74AgaCLKZoS0kZAdmUb3jU3oTzSvHfclS40flhS', |
|
'sk-sXnrftCjtiduDy40ecIT3h0Xu0H8YM8dWATM06TLH7Lt0zpv', |
|
] |
|
|
|
class KeyManager: |
|
def __init__(self): |
|
self.keys = API_KEYS |
|
|
|
self.status = ['unused' for _ in API_KEYS] |
|
|
|
def get_key(self): |
|
|
|
unused_indices = [i for i, s in enumerate(self.status) if s == 'unused'] |
|
if unused_indices: |
|
index = random.choice(unused_indices) |
|
self.status[index] = 'using' |
|
return self.keys[index], index |
|
|
|
print("No unused key available! Assigning a key currently in use.") |
|
|
|
using_indices = [i for i, s in enumerate(self.status) if s == 'using'] |
|
if using_indices: |
|
index = random.choice(using_indices) |
|
return self.keys[index], index |
|
|
|
|
|
raise Exception("No available key left!") |
|
|
|
def set_fail(self, index): |
|
if 0 <= index < len(self.keys): |
|
self.status[index] = 'fail' |
|
else: |
|
raise Exception("Error: Index out of bounds") |
|
|
|
def __str__(self): |
|
return "\n".join(f"{self.keys[i]}: {self.status[i]}" for i in range(len(self.keys))) |
|
|
|
key_manager = KeyManager() |
|
|
|
|
|
class GPTEvaluation: |
|
def __init__(self, api_keys): |
|
self.api_keys = api_keys |
|
self._key_use = random.randint(0, len(self.api_keys)-1) |
|
self._switch_key() |
|
|
|
def _switch_key(self): |
|
self._key_use = (self._key_use + 1) % len(self.api_keys) |
|
openai.api_key = self.api_keys[self._key_use] |
|
print("Switched to key: ", self._key_use) |
|
|
|
|
|
def call_chatgpt(self, chatgpt_messages, max_tokens=40, model="gpt-3.5-turbo"): |
|
response = openai.chat.completions.create( |
|
model=model, messages=chatgpt_messages, temperature=0.6, max_tokens=max_tokens |
|
) |
|
reply = response.choices[0].message.content |
|
total_tokens = response.usage.total_tokens |
|
return reply, total_tokens |
|
|
|
def prepare_chatgpt_message(self, prompt): |
|
system_message = "an evaluator who rates my answer based on the correct answer" |
|
messages = [{"role": "system", "content": system_message}] |
|
messages.append({"role": "user", "content": "{}".format(prompt)}) |
|
|
|
return messages |
|
|
|
def forward(self, data): |
|
answer, GT = data |
|
prompts = "Rate my answer based on the correct answer out of 100, with higher scores indicating that the answer is closer to the correct answer, and you should be accurate to single digits like 62, 78, 41,etc. Output the number only, no need for explanation. " |
|
prompts = prompts + "This is the correct answer: " + GT + ". This is my answer: " + answer |
|
|
|
output = "" |
|
messages = self.prepare_chatgpt_message(prompts) |
|
reply, total_tokens = self.call_chatgpt(messages, max_tokens=3000) |
|
|
|
time.sleep(2) |
|
|
|
output += reply |
|
output += "\n\n" |
|
|
|
output = output[:-2] |
|
|
|
return output |
|
|
|
class GPTEvaluationInternal: |
|
def __init__(self): |
|
self.api_key, self.key_idx = key_manager.get_key() |
|
print("Initial key id: ", self.key_idx) |
|
self.query_count = 0 |
|
|
|
|
|
self.prompts_p1 = ["Rate my answer based on the correct answer out of 100, ", "Please score my answer out of 100 compared with correct answer, "] |
|
self.prompts_p2 = ["with higher scores indicating that the answer is closer to the correct answer, ", "higher is better, ", ""] |
|
self.prompts_p3 = ["you should be accurate to single digits like 62, 78, 41, etc. ", "be accurate to integer value. ", ""] |
|
self.prompts_p4 = ["Output the number only, no need for explanation. ", "Please respond the number only. ", "Please answer the score only. "] |
|
|
|
def call_chatgpt(self, chatgpt_messages, max_tokens=40, model="gpt-3.5-turbo"): |
|
while True: |
|
try: |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Baseurl = "https://api.claudeshop.top" |
|
url = Baseurl + "/v1/chat/completions" |
|
|
|
headers = { |
|
'Accept': 'application/json', |
|
'Authorization': f'Bearer {self.api_key}', |
|
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)', |
|
'Content-Type': 'application/json' |
|
} |
|
|
|
payload = json.dumps({ |
|
"model": model, |
|
"messages": [ |
|
{ |
|
"role": "system", |
|
"content": chatgpt_messages[0]["content"] |
|
}, |
|
{ |
|
"role": "user", |
|
"content": chatgpt_messages[1]["content"] |
|
} |
|
], |
|
"temperature": 0.6, |
|
"max_tokens": max_tokens, |
|
}) |
|
|
|
response = requests.request("POST", url, headers=headers, data=payload) |
|
content = response.json() |
|
|
|
except Exception as e: |
|
print("Failed prompt: ", chatgpt_messages) |
|
print("Key id ", self.key_idx, " fail with error after querying ", self.query_count, " times: ", e) |
|
print(type(e)) |
|
if ("We've encountered an issue with repetitive patterns in your prompt." in str(e)): |
|
return '00', 0 |
|
key_manager.set_fail(self.key_idx) |
|
self.api_key, self.key_idx = key_manager.get_key() |
|
self.query_count = 0 |
|
continue |
|
break |
|
|
|
self.query_count += 1 |
|
|
|
|
|
|
|
|
|
|
|
|
|
print(content) |
|
reply = content['choices'][0]['message']['content'] |
|
total_tokens = content['usage']['total_tokens'] |
|
|
|
return reply, total_tokens |
|
|
|
def prepare_chatgpt_message(self, prompt): |
|
system_message = "an evaluator who rates my answer based on the correct answer" |
|
messages = [{"role": "system", "content": system_message}] |
|
messages.append({"role": "user", "content": "{}".format(prompt)}) |
|
|
|
return messages |
|
|
|
def forward(self, chunk_data): |
|
|
|
outputs = [] |
|
for data in chunk_data: |
|
answer, GT = data |
|
|
|
prompts = "Rate my answer based on the correct answer out of 100, with higher scores indicating that the answer is closer to the correct answer, and you should be accurate to single digits like 62, 78, 41,etc. Output the number only, no need for explanation. " |
|
prompts = prompts + "This is the correct answer: " + GT + ". This is my answer: " + answer |
|
|
|
output = "" |
|
messages = self.prepare_chatgpt_message(prompts) |
|
reply, total_tokens = self.call_chatgpt(messages, max_tokens=3000) |
|
|
|
time.sleep(0.5) |
|
|
|
output += reply |
|
output += "\n\n" |
|
|
|
output = output[:-2] |
|
|
|
outputs.append(output) |
|
return outputs |
|
|
|
|
|
class evaluation_suit(): |
|
def __init__(self): |
|
self.language_eval = language_evaluation.CocoEvaluator(coco_types=["BLEU", "ROUGE_L", "CIDEr"]) |
|
self.num_process = 3 |
|
|
|
if USE_INTERNAL: |
|
self.chatgpt_eval = [] |
|
for i in range(self.num_process): |
|
self.chatgpt_eval.append(GPTEvaluationInternal()) |
|
else: |
|
|
|
|
|
self.chatgpt_eval = GPTEvaluation(API_KEYS) |
|
self.GPT = [] |
|
self.accuracy = {"answer": [], "GT": []} |
|
self.language = {"answer": [], "GT": []} |
|
self.language_score_keys = [] |
|
self.match = {"match": {"answer": [], "GT": []}, "GPT": []} |
|
self.traj_L2 = {"answer": [], "GT": []} |
|
|
|
def eval_acc(self): |
|
scores = [] |
|
for i in range(len(self.accuracy["answer"])): |
|
answer = self.accuracy["answer"][i] |
|
GT = self.accuracy["GT"][i] |
|
if answer == GT: |
|
scores.append(1.0) |
|
else: |
|
scores.append(0.0) |
|
|
|
scores = sum(scores) / len(scores) |
|
return scores |
|
|
|
def extract_traj_from_response(self, response): |
|
response = response.split('[', 1)[1].split(']')[0] |
|
response = response.split(', ') |
|
coordinates = [list(ast.literal_eval(s)) for s in response] |
|
|
|
coordinates = np.array(coordinates) |
|
return coordinates |
|
|
|
def eval_traj_L2(self): |
|
ADEs = [] |
|
for i in range(len(self.traj_L2["answer"])): |
|
answer = self.traj_L2["answer"][i] |
|
GT = self.traj_L2["GT"][i] |
|
try: |
|
|
|
answer_traj = self.extract_traj_from_response(answer) |
|
GT_traj = self.extract_traj_from_response(GT) |
|
|
|
ADE = np.linalg.norm(answer_traj - GT_traj) |
|
except Exception as e: |
|
print(answer) |
|
print(GT) |
|
print("Can not extract traj from the response. Return default MAXIMUM_L2_Error.") |
|
ADE = MAXIMUM_L2_Error |
|
ADEs.append(ADE) |
|
mean_ADE = sum(ADEs) / len(ADEs) |
|
return mean_ADE |
|
|
|
def eval_long_tail_behavior_planning_gpt_score(self, data): |
|
|
|
|
|
scores = [] |
|
for item in data: |
|
answer, GT = item |
|
|
|
answer = answer.split(", and its 3-second future trajectory")[0] |
|
GT = GT.split("The autonomous vehicle's 3-second future trajectory is")[0] |
|
item = (answer, GT) |
|
|
|
score = 50 |
|
scores.append(float(score)) |
|
|
|
scores = sum(scores) / len(scores) |
|
return scores |
|
|
|
def eval_chatGPT(self, data): |
|
remain_attempts = len(self.chatgpt_eval.api_keys) |
|
while remain_attempts > 0: |
|
try: |
|
with Pool(3) as p: |
|
scores = p.map(self.chatgpt_eval.forward, data) |
|
scores = list(map(float, scores)) |
|
except Exception as e: |
|
print("This key fail with error: ", e) |
|
remain_attempts -= 1 |
|
if remain_attempts == 0: |
|
print("All keys failed!") |
|
raise e |
|
else: |
|
self.chatgpt_eval._switch_key() |
|
continue |
|
break |
|
|
|
scores = sum(scores) / len(scores) |
|
return scores |
|
|
|
def apply_function(self, task): |
|
func, chunk = task |
|
return func(chunk) |
|
|
|
def eval_chatGPT_internal(self, data): |
|
|
|
chunk_size = len(data) // self.num_process |
|
tasks = [(self.chatgpt_eval[i].forward, data[i * chunk_size : (i+1) * chunk_size]) for i in range(self.num_process)] |
|
|
|
with Pool(self.num_process) as p: |
|
scores_chunked = p.map(self.apply_function, tasks) |
|
scores = [score for chunk in scores_chunked for score in chunk] |
|
scores = list(map(float, scores)) |
|
|
|
scores = sum(scores) / len(scores) |
|
return scores |
|
|
|
def eval_language(self): |
|
""" |
|
return the dict evaluation results |
|
""" |
|
answer = self.language["answer"] |
|
GT = self.language["GT"] |
|
results_gen = self.language_eval.run_evaluation(answer, GT) |
|
results_gen_dict = { |
|
f"language/{k}": v for k, v in results_gen.items() |
|
} |
|
self.language_score_keys = list(results_gen_dict.keys()) |
|
return results_gen_dict |
|
|
|
def eval_match(self): |
|
outs1 = [] |
|
for i in range(len(self.match["match"]["answer"])): |
|
answer = self.match["match"]["answer"][i] |
|
GT = self.match["match"]["GT"][i] |
|
_, F1_score = self.match_result(answer, GT) |
|
outs1.append(F1_score * 100) |
|
|
|
outs1 = sum(outs1) / len(outs1) |
|
if USE_INTERNAL: |
|
outs2 = self.eval_chatGPT_internal(self.match["GPT"]) |
|
else: |
|
outs2 = self.eval_chatGPT(self.match["GPT"]) |
|
scores = (outs1 + outs2) / 2.0 |
|
return scores |
|
|
|
def eval_graph(self, question): |
|
|
|
question_nums = re.findall(r'\d+\.\d+', question) |
|
question_nums = np.array([list(map(float, x.split()))[0] for x in question_nums]).reshape(-1, 2) |
|
question_nums = [list(i) for i in question_nums] |
|
for q in question_nums: |
|
if q not in self.graph: |
|
return False |
|
return True |
|
|
|
def match_result(self, answer, GT): |
|
""" |
|
answer: [[1.,2.], [2., 3.]] |
|
GT: [[1., 2.], [2., 3.]] |
|
""" |
|
answer_nums = re.findall(r'\d+\.\d+', answer) |
|
GT_nums = re.findall(r'\d+\.\d+', GT) |
|
|
|
if len(answer_nums) % 2 != 0: |
|
answer_nums = answer_nums[:-1] |
|
answer_nums = np.array([list(map(float, x.split()))[0] for x in answer_nums]).reshape(-1, 2) |
|
GT_nums = np.array([list(map(float, x.split()))[0] for x in GT_nums]).reshape(-1, 2) |
|
length = len(GT_nums) |
|
|
|
matched_out = [] |
|
true_positives = 0 |
|
false_positives = 0 |
|
false_negatives = 0 |
|
for pred in answer_nums: |
|
closest_distance = float('inf') |
|
closest_gt = None |
|
closest_id = None |
|
for i, gt in enumerate(GT_nums): |
|
distance = np.sum(np.abs(pred - gt)) |
|
if distance < closest_distance: |
|
closest_distance = distance |
|
closest_gt = gt |
|
closest_id = i |
|
|
|
if closest_distance < 16: |
|
true_positives += 1 |
|
matched_out.append(closest_gt) |
|
GT_nums = np.delete(GT_nums, closest_id, axis=0) |
|
else: |
|
false_positives += 1 |
|
|
|
false_negatives = length - true_positives |
|
precision = true_positives / (true_positives + false_positives + 1e-8) |
|
recall = true_positives / (true_positives + false_negatives + 1e-8) |
|
F1 = 2 * precision * recall / (precision + recall + 1e-8) |
|
|
|
return matched_out, F1 |
|
|
|
def set_graph(self, answer, GT): |
|
self.graph, _ = self.match_result(answer, GT) |
|
self.graph = [list(i) for i in self.graph] |
|
|
|
def forward(self, tag, answer, GT): |
|
if 0 in tag: |
|
self.accuracy["answer"].append(answer) |
|
self.accuracy["GT"].append(GT) |
|
if 1 in tag: |
|
self.GPT.append((answer, GT)) |
|
if 2 in tag: |
|
self.language["GT"].append(GT) |
|
self.language["answer"].append(answer) |
|
if 3 in tag: |
|
self.match["match"]["GT"].append(GT) |
|
self.match["match"]["answer"].append(answer) |
|
self.match["GPT"].append((answer, GT)) |
|
if 4 in tag: |
|
self.traj_L2["GT"].append(GT) |
|
self.traj_L2["answer"].append(answer) |
|
|
|
|
|
def evaluation(self): |
|
print("evaluation start!") |
|
scores = {} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
scores["traj_l2"] = self.eval_traj_L2() |
|
scores["chatgpt_longtail_behavior"] = self.eval_long_tail_behavior_planning_gpt_score(self.GPT) |
|
|
|
return scores |
|
|
|
|
|
@exception_handler_decorator |
|
def compute(params, quiet=True): |
|
try: |
|
print("Team name is: ", params.team_id) |
|
|
|
|
|
|
|
submission_filename = "submissions/{}-{}.{}".format(params.team_id, params.submission_id, FORMAT) |
|
print(submission_filename) |
|
|
|
submission = hf_hub_download( |
|
repo_id=params.competition_id, |
|
filename=submission_filename, |
|
token=params.token, |
|
repo_type="dataset", |
|
) |
|
except Exception as e: |
|
error_message = "submission.json not found in the repository, or it cannot be loaded." |
|
update_error_message_to_submission_comment(params, error_message) |
|
raise e |
|
|
|
with open(submission, 'r') as f : |
|
pred_file = json.load(f) |
|
team_name = pred_file.get('team', None) |
|
pred_file = pred_file["results"] |
|
pred_file = {pred_file[i]["id"]: pred_file[i] for i in range(len(pred_file))} |
|
|
|
if team_name is not None: |
|
update_teamname_to_submission_comment(params, team_name) |
|
else: |
|
update_error_message_to_submission_comment(params, "Team name not found in the submission file.") |
|
|
|
ground_truth = hf_hub_download( |
|
repo_id=params.competition_id, |
|
filename=GROUND_TRUTH, |
|
token=params.token, |
|
repo_type="dataset", |
|
) |
|
|
|
with open(ground_truth, 'r') as f: |
|
test_file = json.load(f) |
|
|
|
print("Submission and Ground Truth downloaded.") |
|
print("Evaluating...") |
|
|
|
try: |
|
evaluation = evaluation_suit() |
|
output = {"chatgpt": [], "traj_l2": []} |
|
for scene_id in test_file.keys(): |
|
scene_data = test_file[scene_id]['key_frames'] |
|
|
|
for frame_id in scene_data.keys(): |
|
frame_data_qa = scene_data[frame_id]['QA'] |
|
if 'long_tail_behavior_planning' not in frame_data_qa: |
|
continue |
|
for i, qa in enumerate(frame_data_qa["long_tail_behavior_planning"]): |
|
question = qa['Q'] |
|
GT = qa['A'] |
|
tag = [1,4] |
|
idx = scene_id + "_" + frame_id + "_lt_" + str(i) |
|
predict = pred_file[idx]["answer"] |
|
evaluation.forward(tag, predict, GT) |
|
|
|
output = evaluation.evaluation() |
|
print("chatgpt score: ", output["chatgpt_longtail_behavior"]) |
|
print("traj score: ", output["traj_l2"]) |
|
for key in evaluation.language_score_keys: |
|
print(key, output[key]) |
|
|
|
|
|
scores = [] |
|
weights = [0.4, 0.2, 0.2, 0.2] |
|
|
|
|
|
score = output["chatgpt_longtail_behavior"] / 100. |
|
scores.append(score) |
|
|
|
|
|
|
|
output["final_score"] = score |
|
|
|
except Exception as e: |
|
error_message = "Evaluation failed. " + str(e) |
|
update_error_message_to_submission_comment(params, error_message) |
|
raise e |
|
|
|
evaluation = { |
|
"public_score": output, |
|
"private_score": output |
|
} |
|
|
|
return evaluation |
|
|