zeju-0727 commited on
Commit
5df59cd
·
verified ·
1 Parent(s): 03f06f4

Upload dyve_tts/eval/math/modeling/evaluate_gpt3.py with huggingface_hub

Browse files
dyve_tts/eval/math/modeling/evaluate_gpt3.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import openai
3
+ import numpy as np
4
+ import operator
5
+ import json
6
+ from dataset.util import clean_numbers, last_boxed_only, last_boxed_only_string
7
+ from math_equivalence import is_equiv
8
+
9
+ openai.api_key = PUT_KEY_HERE
10
+
11
+ def call_engine(train_prompt, problem, engine="davinci"):
12
+ '''
13
+ Given a problem, returns the most likely answer determined by the GPT engine
14
+ '''
15
+ test_question = "\n" + problem + "\n" + "Answer: $"
16
+ prompt = train_prompt + test_question
17
+ # print(len(prompt))
18
+ num_tokens = 20
19
+ c = openai.Completion.create(
20
+ engine=engine,
21
+ prompt=prompt,
22
+ max_tokens=num_tokens,
23
+ logprobs=100,
24
+ temperature=0,
25
+ echo=True
26
+ )
27
+ tokens = c["choices"][0]["logprobs"]["tokens"]
28
+ startindex = -1 * num_tokens
29
+ endindex = -1 * num_tokens + 1
30
+ for token in tokens[startindex + 1:]:
31
+ if token == "$" or token == "###" or token == "\n":
32
+ break
33
+ else:
34
+ endindex += 1
35
+ final_answer = ""
36
+ for i in range(startindex, endindex):
37
+ all_answers = c["choices"][0]["logprobs"]["top_logprobs"][i]
38
+ best_answer = max(all_answers.items(), key=operator.itemgetter(1))[0]
39
+ final_answer += best_answer
40
+ return final_answer
41
+
42
+ def remove_boxed(s):
43
+ left = "\\boxed{"
44
+ try:
45
+ assert s[:len(left)] == left
46
+ assert s[-1] == "}"
47
+ return s[len(left):-1]
48
+ except:
49
+ return None
50
+
51
+ train_prompt = "Given a mathematics problem, determine the answer. Simplify your answer as much as possible." + "\n" + "Problem: What is $\left(\\frac{7}{8}\\right)^3 \cdot \left(\\frac{7}{8}\\right)^{-3}$?" + "\n" + "Answer: $1$"
52
+ train_prompt += "\n" + "###" + "\n" + "Problem: In how many ways can 4 books be selected from a shelf of 6 books if the order in which the books are selected does not matter?" + "\n" +"Answer: $15$"
53
+ train_prompt += "\n" +"###" + "\n" + "Problem: Find the distance between the points $(2,1,-4)$ and $(5,8,-3).$" + "\n" + "Answer: $\sqrt{59}$"
54
+ train_prompt += "\n" + "###" + "\n" + "Problem: The faces of an octahedral die are labeled with digits $1$ through $8$. What is the probability, expressed as a common fraction, of rolling a sum of $15$ with a pair of such octahedral dice?" + "\n" + "Answer: $\\frac{1}{32}$"
55
+ train_prompt += "\n" + "###" + "\n" + "Problem: The first three terms of an arithmetic sequence are 1, 10 and 19, respectively. What is the value of the 21st term?" + "\n" + "Answer: $181$"
56
+ train_prompt += "\n" + "###" + "\n" + "Problem: Calculate $6 \\cdot 8\\frac{1}{3}" + "\n" + "Answer: $50$"
57
+ train_prompt += "\n" + "###" + "\n" + "Problem: When the binary number $100101110010_2$ is divided by 4, what is the remainder (give your answer in base 10)?" + "\n" + "Answer: $2$"
58
+ train_prompt += "\n" + "###" + "\n" + "Problem: How many zeros are at the end of the product 25 $\\times$ 240?" + "\n" + "Answer: $3$" + "\n" + "###"
59
+
60
+ rootdir = "../modeling/MATH/data/test"
61
+
62
+
63
+ def run(engine="davinci", max=-1):
64
+ outputs = []
65
+ answers = []
66
+ types = []
67
+ levels = []
68
+
69
+ fnames_list = []
70
+
71
+ cors = {}
72
+ subject_cors = {}
73
+ level_cors = {}
74
+ correct = 0
75
+ total = 0
76
+ for subdir, dirs, files in os.walk(rootdir):
77
+ for file in files:
78
+ fnames_list.append(os.path.join(subdir, file))
79
+ with open(os.path.join(subdir, file), 'r') as fp:
80
+ try:
81
+ problem_data = json.load(fp)
82
+ except Exception as e:
83
+ print(f"Error loading JSON from {file}", e)
84
+ raise e
85
+ prob_level = problem_data["level"]
86
+ prob_type = problem_data["type"]
87
+ try:
88
+ prob_level = int(prob_level.split("Level ")[1])
89
+ except:
90
+ prob_level = None
91
+ model_output = call_engine(train_prompt, problem_data["problem"], engine=engine)
92
+ answer = remove_boxed(last_boxed_only_string(problem_data["solution"]))
93
+
94
+ levels.append(prob_level)
95
+ types.append(prob_type)
96
+ outputs.append(model_output)
97
+ answers.append(answer)
98
+
99
+ print("Model output:")
100
+ print(model_output)
101
+ print("Correct answer:")
102
+ print(answer)
103
+ print("--------------------------------------------")
104
+
105
+ try:
106
+ equiv = is_equiv(model_output, answer)
107
+ except:
108
+ equiv = False
109
+ if (prob_level, prob_type) in cors:
110
+ cors[(prob_level, prob_type)].append(equiv)
111
+ else:
112
+ cors[(prob_level, prob_type)] = [equiv]
113
+ if prob_level in level_cors:
114
+ level_cors[prob_level].append(equiv)
115
+ else:
116
+ if prob_level is not None:
117
+ level_cors[prob_level] = [equiv]
118
+ if prob_type in subject_cors:
119
+ subject_cors[prob_type].append(equiv)
120
+ else:
121
+ if prob_type is not None:
122
+ subject_cors[prob_type] = [equiv]
123
+ if equiv:
124
+ correct += 1
125
+ total += 1
126
+
127
+ print(str(correct) + "/" + str(total))
128
+
129
+ if max > 0 and total > max:
130
+ break
131
+ if max > 0 and total > max:
132
+ break
133
+
134
+ with open("outputs_answers_gpt3_{}.txt".format(engine), "w+") as f:
135
+ for k, (output, answer, prob_type, prob_level, fname) in enumerate(zip(outputs, answers, types, levels, fnames_list)):
136
+ f.write("{} TYPE: {} | LEVEL: {} | OUTPUT: {} | ANSWER: {} | FNAME: {}\n".format(k, prob_type, prob_level, output, answer, fname))
137
+
138
+ f.write("#####################\n")
139
+ # also get accuracies for each
140
+ for subject in ['Prealgebra', 'Algebra', 'Number Theory', 'Counting & Probability', 'Geometry', 'Intermediate Algebra', 'Precalculus']:
141
+ for level in range(1, 6):
142
+ key = (level, subject)
143
+ if key not in cors.keys():
144
+ print("Skipping", key)
145
+ continue
146
+ cors_list = cors[key]
147
+ print("{} Level {} Accuracy = {}/{} = {:.3f}".format(subject, level, np.sum(cors_list), len(cors_list), np.mean(cors_list)))
148
+ f.write("{} Level {} Accuracy = {}/{} = {:.3f}\n".format(subject, level, np.sum(cors_list), len(cors_list), np.mean(cors_list)))
149
+ print("#####################")
150
+ f.write("#####################\n")
151
+ for level in sorted(level_cors):
152
+ if level not in level_cors.keys():
153
+ print("Skipping", level)
154
+ continue
155
+ cors_list = level_cors[level]
156
+ print("Level {} Accuracy = {}/{} = {:.3f}".format(level, np.sum(cors_list), len(cors_list), np.mean(cors_list)))
157
+ f.write("Level {} Accuracy = {}/{} = {:.3f}\n".format(level, np.sum(cors_list), len(cors_list), np.mean(cors_list)))
158
+ print("#####################")
159
+ f.write("#####################\n")
160
+ for subject in ['Prealgebra', 'Algebra', 'Number Theory', 'Counting & Probability', 'Geometry', 'Intermediate Algebra', 'Precalculus']:
161
+ if subject not in subject_cors.keys():
162
+ print("Skipping", subject)
163
+ continue
164
+ cors_list = subject_cors[subject]
165
+ print("{} Accuracy = {}/{} = {:.3f}".format(subject, np.sum(cors_list), len(cors_list), np.mean(cors_list)))
166
+ f.write("{} Accuracy = {}/{} = {:.3f}\n".format(subject, np.sum(cors_list), len(cors_list), np.mean(cors_list)))
167
+ print("#####################")
168
+ f.write("#####################\n")
169
+ print("Overall Accuracy = {}/{} = {:.3f}".format(correct, total, correct/total))
170
+ f.write("Overall Accuracy = {}/{} = {:.3f}\n".format(correct, total, correct/total))
171
+
172
+ if __name__ == "__main__":
173
+ engines = ["davinci", "curie", "babbage", "ada"][::-1]
174
+ for engine in engines:
175
+ run(engine)
176
+
177
+ # for testing:
178
+ # for engine in ["ada"]:
179
+ # run(engine, max=10)