thomasrantian's picture
test
1b71ca0
raw
history blame
26.5 kB
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"
# Deafult traj_L2 error
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-NuE4a50TeXtSPVom099111B600C9435eAdCc445fE3FfFa72"] # need openai.api_base = "https://api.chatweb.plus/v1"
API_KEYS = [
# "sk-proj-s8DmEUz3c0fMsXNvoK2eT3BlbkFJgxqZ2ZN35VfGbf6pz32K", # batch 7
# "sk-proj-WJA3qO4cTryRDhOEpB4QT3BlbkFJTxgvO3xyMOEoWsga3iIj",
# "sk-proj-UXLnPZ54GqsFt8PUSUcfT3BlbkFJbcBmGdsnkUxKv9DMUUCv",
# "sk-proj-STphQ681iiXwW3ooY0sKT3BlbkFJYlqJFZr3lVqRNVdFh87a",
# "sk-proj-TnvZchmH06y3cKzixZ8XT3BlbkFJfMog1yTeQn1sX1kgLDw7",
# "sk-proj-GBuvgZ7HbVcrgXWMx7poT3BlbkFJBPq7Wjl3DC7WCizEgO1y",
# "sk-proj-iNV3Na6hlyFAVcDRAasiT3BlbkFJJavS6Od5RdDFyefuBRwq", # batch 8
# "sk-proj-DKvaprWQ8QSuV3Dd2LUmT3BlbkFJueAfFMUp1LZOeRoes1vD",
# "sk-proj-HHziJI12Spjjj0UeFc4ET3BlbkFJ9DjK4XKuLtBPCj88kMsq",
# "sk-proj-zImCrO7m5gjswwZhbMpOT3BlbkFJthf6TsqCiphXB4DtQxUG",
# "sk-proj-KWKBI0kUMINMetoYwJWST3BlbkFJ3EdKYkLUkm4tzXcV8dbl",
# "sk-proj-kv1aJThY7iupJ6qXdZpXT3BlbkFJSVIN1D2oJk7n60DXKngX",
# "sk-proj-wtVxu5lh9rKbl1FUBXwOT3BlbkFJ2mF0RsqOEzfUpaKGVQ45",
# "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", # batch 9
# "sk-wrFnTE0zlU1UngGmE8Dd1eC4880142Cd99A3CeB33eAe8d1e", # need openai.api_base = "https://api.claudeshop.top/"
# "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",
# "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",
# "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",
# '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',
# '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',
# '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',
# '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',
######################### new api key ##############################
'sk-wrFnTE0zlU1UngGmE8Dd1eC4880142Cd99A3CeB33eAe8d1e',
'sk-DLon77JND74AgaCLKZoS0kZAdmUb3jU3oTzSvHfclS40flhS',
'sk-sXnrftCjtiduDy40ecIT3h0Xu0H8YM8dWATM06TLH7Lt0zpv',
]
class KeyManager:
def __init__(self):
self.keys = API_KEYS
# Initialize all keys as "unused"
self.status = ['unused' for _ in API_KEYS]
def get_key(self):
# Try to find an unused key first
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.")
# If no unused key is available, try a 'using' key
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
# No suitable key is left
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)
# openai.api_base = "https://api.claudeshop.top/"
def call_chatgpt(self, chatgpt_messages, max_tokens=40, model="gpt-3.5-turbo"): # default 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) # default 1
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.client = openai.Client(api_key=api_key)
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"): # default model: gpt-3.5-turbo
while True:
try:
# old
# client = openai.Client(api_key=self.api_key)
# response = client.chat.completions.create(
# model=model, messages=chatgpt_messages, temperature=0.6, max_tokens=max_tokens
# )
# new
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
# old
# reply = response.choices[0].message.content
# total_tokens = response.usage.total_tokens
# new
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):
# self.client = client
outputs = []
for data in chunk_data:
answer, GT = data
# prompts = random.choice(self.prompts_p1) + random.choice(self.prompts_p2) + random.choice(self.prompts_p3) + random.choice(self.prompts_p4)
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) # default 0.25
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 # default: 32
if USE_INTERNAL:
self.chatgpt_eval = []
for i in range(self.num_process):
self.chatgpt_eval.append(GPTEvaluationInternal())
else:
# API_KEYS = API_KEYS_FAST
# API_KEYS.extend(API_KEYS_SLOW)
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]
# convert to tensor
coordinates = np.array(coordinates) # 6 x 2
return coordinates # 6 x 2
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:
# Compute the ADE of the traj
answer_traj = self.extract_traj_from_response(answer)
GT_traj = self.extract_traj_from_response(GT)
# Compute the L2 betwween the two trajectories
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):
# with Pool(32) as p: # Change the number based on your CPU cores
# scores = p.map(self.chatgpt_eval.forward, data)
scores = []
for item in data:
answer, GT = item
# Remove the traj from the answer and GT
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 = self.chatgpt_eval.forward(item)
score = 50
scores.append(float(score))
#scores = list(map(float, scores))
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: # Change the number based on your CPU cores
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):
# check if answer in self.graph
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)
# transform string into float
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["accuracy"] = self.eval_acc()
# print("USE_INTERNAL: ", USE_INTERNAL)
# if USE_INTERNAL:
# scores["chatgpt"] = self.eval_chatGPT_internal(self.GPT)
# else:
# scores["chatgpt"] = self.eval_chatGPT(self.GPT)
# scores.update(self.eval_language())
# scores["match"] = self.eval_match()
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)
# if "29857a24" in params.team_id:
# global USE_INTERNAL
# USE_INTERNAL = True
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])
# Normalize to 0-1 and combine the scores: chatgpt, language, match, accuracy
scores = []
weights = [0.4, 0.2, 0.2, 0.2]
# chatGPT
score = output["chatgpt_longtail_behavior"] / 100.
scores.append(score)
# language
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