Commit ·
8ce189e
1
Parent(s): 1cabc3e
Upload 3 files
Browse filesFiles changed (3)
- compute_metrics.pyAdded+213
- data.zipAdded+3
- inference.pyAdded+179
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213import numpy as npimport jsonimport pandas as pd
QUES_TYPES = ['MCQ','MCQ(multiple)','Integer','Numeric']
models = [ "Random", "GPT3_normal", "GPT3.5_normal", "GPT4_normal", "GPT4_CoT", 'GPT4_CoT_self_refine', "GPT4_CoT+OneShot", "GPT4_CoT+SC@8"]
def get_aggregate(answers, question_type, single_threshold=None, multiple_threshold=None): # Pass optional \tau_{single} and \tau_{multiple} parameters if needed for evaluation under risk. if question_type == 'MCQ(multiple)' or question_type == 'MCQ': letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'None': 4} idx_to_letter = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'None'} abcd = [0,0,0,0,0] for ans in answers: if ans == 'None': abcd[letter_to_idx[ans]] += 1 else: for c in ans: abcd[letter_to_idx[c]] += 1 if question_type == 'MCQ': abcd = abcd[:-1] answer = idx_to_letter[np.argmax(abcd)] if single_threshold is not None: answer = answer if abcd[np.argmax(abcd)]/len(answers) >= single_threshold else "None" else: if multiple_threshold is not None: options_selected = [idx_to_letter[x] for x in range(len(abcd)) if abcd[x] >= len(answers)*multiple_threshold and idx_to_letter[x] != 'None'] else: options_selected = [idx_to_letter[x] for x in range(len(abcd)) if abcd[x] >= len(answers)/2 and idx_to_letter[x] != 'None'] if len(options_selected) == 0: answer = "None" else: answer = ''.join(sorted(options_selected)) else: # For integer and numeric answers, choose the most common response(other than None) while "None" in answers: answers.remove("None") if len(answers) == 0: answers = ["None"] unique, counts = np.unique(answers, return_counts=True) answer = unique[np.argmax(counts)] return answer
def compute_score(gold, resp, question_type, year): assert question_type in QUES_TYPES if question_type == 'MCQ(multiple)': gold = set([c for c in ['A', 'B', 'C', 'D'] if c in gold]) resp = set([c for c in ['A', 'B', 'C', 'D'] if c in resp]) if resp == gold : return 1.0 else: if len(resp-gold) == 0: return 0.25*len(resp) return 0.0 # If response contains something not in the gold set, give 0 elif question_type == 'MCQ': gold = set([c for c in ['A', 'B', 'C', 'D'] if c in gold]) resp = set([c for c in ['A', 'B', 'C', 'D'] if c in resp]) return int(gold == resp) else: if resp == "None": return 0.0 g, r = float(gold), float(resp) return int(abs(g-r) <= 0.01)
def construct_responses_table(): responses = {} for model in models: if "SC@" in model: pass elif "Random" == model: pass else: responses[model] = json.load(open(f"data/responses/{model}_responses/responses.json")) dataset = json.load(open('data/dataset.json')) extracts = { "Type": [], "Index": [], "Description": [], "Subject": [], "Gold": [], } for model in models: if "Random" == model: continue else: extracts[f'{model}'] = []
for i, q in enumerate(dataset): extracts['Type'].append(q['type']) extracts['Index'].append(q['index']) extracts['Description'].append(q['description']) extracts['Subject'].append(q['subject']) extracts['Gold'].append(q['gold']) for model in models: if "SC@" in model: continue elif "Random" == model: continue else: try: assert q['question'] == responses[model][i]['question'] except:
print(q['question']) breakpoint() print(responses[model][i]['question']) breakpoint() try: extracts[f'{model}'].append(responses[model][i]['extract']) except: print(extracts) if "GPT4_CoT+SC" in model: num_responses = int(model.split("@")[1]) for i, q in enumerate(dataset): sc_responses = json.load(open('data/responses/GPT4_CoT+SC_responses/responses.json')) resp = sc_responses[i] answers = [resp['GPT4_CoT+SC_response']['choices'][k]['extract'] for k in range(num_responses)] answer = get_aggregate(answers, resp['type']) extracts[f'{model}'].append(answer) pd.DataFrame(extracts).to_csv('results/extracts.csv', index=False) return pd.read_csv('results/extracts.csv',dtype=str)
responses = construct_responses_table()output = []for i, response in responses.iterrows(): out = {} out["Type"] = response["Type"] out["Index"] = response["Index"] out["Description"] = response["Description"] out["Subject"] = response["Subject"] gold = response["Gold"] out["Gold"] = gold if response["Type"] == "MCQ": out["Random"] = 0.25 elif response["Type"] == "MCQ(multiple)": num_ans = len(gold) if num_ans == 1: out["Random"] = 0.0625 elif num_ans == 2: out["Random"] = 0.09375 elif num_ans == 3: out["Random"] = 0.203125 elif num_ans == 4: out["Random"] = 0.5 else: out["Random"] = 0 for model in models: if model == "Random": continue resp = response[f"{model}"] if not isinstance(resp, str): resp = "None" out[f"{model}"] = resp out[f'{model}'] = compute_score(gold,resp,out["Type"],out["Description"]) out[f'Max'] = 1 output.append(out)
df = pd.DataFrame()df['Type'] = [x['Type'] for x in output]df['Index'] = [x['Index'] for x in output]df['Description'] = [x['Description'] for x in output]df['Subject'] = [x['Subject'] for x in output]df['Gold'] = [x['Gold'] for x in output]df['Random'] = [x['Random'] for x in output]for model in models: df[f"{model}"] = [ x.get(f"{model}", "None") for x in output] df[f"{model}"] = [x.get(f"{model}", 0) for x in output]
df.to_csv(f"results/scores.csv", index=False)
modes = ['overall', 'type_wise', 'subject_wise']for mode in modes: col_dict = {} for model in models: col_dict[f'{model}'] = ['mean']
if mode != 'overall': col_dict[f'{models[0]}'].insert(0,'count') if mode == 'overall': grouped_multiple = df.agg(col_dict) elif mode == 'type_wise': grouped_multiple = df.groupby(['Type']).agg(col_dict) elif mode == 'subject_wise': grouped_multiple = df.groupby(['Subject']).agg(col_dict)
if mode != 'overall': grouped_multiple.columns = ['count'] + models grouped_multiple = grouped_multiple.reset_index() grouped_multiple = grouped_multiple.round(3) grouped_multiple.to_csv(f"results/aggregated_scores_{mode}.csv", index=False)print("Done!")123version https://git-lfs.github.com/spec/v1oid sha256:9db3aa734a3e5b7e02cead16c17b6687ff363d8a4d1015395f04f28ace33a07asize 8069293123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179import osfrom tqdm import tqdmimport jsonimport osimport openaifrom tqdm import tqdmimport argparseimport multiprocessing from copy import deepcopyfrom functools import partial
prompt_library = { "MCQ": "In this problem, only one option will be correct. Give a detailed solution and end the solution with the final answer.", "MCQ(multiple)": "In this problem, multiple options can be correct. Give a detailed solution and end the solution with the final answer.", "Integer": "In this problem, the final answer will be a non-negative integer. Give a detailed solution and end the solution with the final answer.", "Numeric": "In this problem, the final will be a numeric value. Give the numerical answer correct upto the 2nd decimal digit. Give a detailed solution and end the solution with the final answer.",}
few_shot_examples = json.load(open('data/few_shot_examples.json'))
def write_in_file(response_file, response_dict, question, mode, model_nickname): if os.path.exists(response_file): with open(response_file, 'r') as infile: responses = json.load(infile) else: responses = []
found = False for i, old_resp in enumerate(responses): if old_resp['description'] == question['description'] and old_resp['index'] == question['index']: responses[i][f"{model_nickname}_{mode}_response" ] = response_dict[f"{model_nickname}_{mode}_response"] found = True break
if not found: responses.append(response_dict) json.dump(sorted(responses, key=lambda elem: (elem['description'], elem['index'])), open(response_file, 'w'), indent=4) print(f"####UPDATED {response_file}, Current size : {len(responses)}####")
def get_response(question,model, model_nickname, mode, response_file, lock):
response_dict = deepcopy(question) prefix_prompt = prompt_library[question['type']] suffix_prompt = ""
if mode in ['CoT', 'CoT+SC', 'CoT+Exam'] : suffix_prompt = "Let's think step by step.\n"
ques = question["question"] stripped_ques = ques.replace("\n\n", "\n").strip() if mode in ['CoT+OneShot', 'CoT', 'CoT+SC', 'CoT+Exam']: if mode == 'CoT+Exam': if response_dict['type'] in ['MCQ', 'MCQ(multiple)']: if response_dict['type'] == 'MCQ': exam_prompt = "If the answer is wrong, you'll be given -1 marks. If the answer is correct, you'll be given +3 marks. If you're unsure of the answer, you can skip the question, and you'll be given 0 marks." else: exam_prompt = "If any of the options in the final answer is wrong, you'll be given -2 marks. If all the options are correct, you'll be given +4 marks. If some of the options are correct, you'll be given +1 for each correct option. If you're unsure of the answer, you can skip the question, and you'll be given 0 marks." prompt = prefix_prompt + " " + exam_prompt + "\n\n" + "Problem: " + stripped_ques + "\nSolution: " + suffix_prompt else: print("No point doing this for Numeric/Integer questions since there is no negative marking...") breakpoint() else: if mode == 'CoT+OneShot': ex = few_shot_examples[question['subject']][question['type']] prompt = prefix_prompt + "\n\n" + "Problem: " + ex['problem'] + "\nSolution: " + ex['solution'] + "\n\n" + "Problem: " + stripped_ques + "\nSolution: " else: prompt = prefix_prompt + "\n\n" + "Problem: " + stripped_ques + "\nSolution: " + suffix_prompt else: prompt = prefix_prompt + "\n\n" + "Problem: " + stripped_ques + suffix_prompt prompt = prompt.strip() response_dict[f"prompt"] = prompt num_retries = 0 print(f'Question: {question["description"]}, Index: {question["index"]}, Model: {model_nickname}, Mode: {mode}, query begins') while True: try: if model in ["text-davinci-003", "text-davinci-002", 'davinci-002']: response = openai.Completion.create( model=model, prompt=prompt, max_tokens=2048, temperature=0 if mode in ['CoT', 'normal', 'CoT+Exam'] else 0.5, n=1 if mode in ['CoT', 'normal', 'CoT+Exam'] else 3 ) else: response = openai.ChatCompletion.create( model=model, messages=[ {"role": "system", "content": ""}, {"role": "user", "content": prompt} ], max_tokens=2048, temperature=0 if mode in ['CoT+OneShot', 'CoT', 'normal', 'CoT+Exam'] else 0.5, n=1 if mode in ['CoT+OneShot', 'CoT', 'normal', 'CoT+Exam'] else 8 ) lock.acquire() response_dict[f"{model_nickname}_{mode}_response"] = response write_in_file(response_file, response_dict, question, mode, model_nickname) lock.release() break except Exception as e: num_retries += 1 print("Failure!", e) return
def main(): ''' The code can restart from the already done questions in case there is a failure midpoint. ''' args = argparse.ArgumentParser() args.add_argument('--model', default='gpt-3.5-turbo') args.add_argument('--data', default='data/dataset.json') args.add_argument('--mode', default='normal') args.add_argument('--num_procs', default=1, type=int) args.add_argument('--max_questions', default=1, type=int) args = args.parse_args()
openai.organization = os.getenv("OPENAI_ORG") openai.api_key = os.getenv("OPENAI_API_KEY") model_nickname = { "davinci-002": "davinci-002", "text-davinci-003": "GPT3", "gpt-3.5-turbo": "GPT3.5", "gpt-4-0613": "GPT4_0613", "gpt-4-0314": "GPT4" } assert args.model in model_nickname.keys() assert args.mode in ['normal', 'CoT', 'CoT+OneShot', 'CoT+Exam', 'CoT+SC'] out_file_dir = f'responses/{model_nickname[args.model]}_{args.mode}_responses' out_file = os.path.join(out_file_dir, 'responses.json') questions = json.load(open(args.data))
rem_ques = [] if os.path.exists(out_file):
for question in tqdm(questions[:args.max_questions]): if os.path.exists(out_file): with open(out_file, 'r') as infile: responses = json.load(infile) found = False
for i, old_resp in enumerate(responses): if question['type'] in ['Numeric', 'Integer'] and args.mode == 'CoT+Exam': found = True if old_resp['description'] == question['description'] and old_resp['index'] == question['index']: found = all([old_resp.get( f"{model_nickname[args.model]}_{args.mode}_response", False) for model in [args.model]]) if found: print("This question has already been done") else: rem_ques.append(question) else: os.makedirs(out_file_dir, exist_ok=True) if args.mode == 'CoT+Exam': rem_ques = [] for q in questions: if q['type'] in ['MCQ', 'MCQ(multiple)']: rem_ques.append(q) else: rem_ques = questions[:args.max_questions] print(f"There are {len(rem_ques)} problems remaining") manager = multiprocessing.Manager() lock = manager.Lock() pool = multiprocessing.Pool(args.num_procs) f = partial(get_response, model=args.model, model_nickname=model_nickname[args.model], mode=args.mode, response_file=out_file, lock=lock) pool.map(f, rem_ques)
if __name__ == '__main__': main()compute_metrics.pyAdded+213
data.zipAdded+3
inference.pyAdded+179