File size: 10,902 Bytes
466916b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import json
import random
import csv
from io import StringIO
from contextlib import redirect_stdout
from openai import OpenAI
from tqdm import tqdm


client = OpenAI(
  organization='org-GOLjWTjRYGCBi47VKNk0jhMm',
  project='proj_YotrLJgFnsq9wXOXBYaLjnO4',
  api_key='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'
)


program_data = []

PROMPT_DICT = {
    "prompt_new_parameter_value": (
        "Here is a math question with the parameter and parameter values. Please perturb the value of parameters into different values. Output five kinds of new values in the same format as the given parameters in five lines without index.\n\n"
        "Question:\n{question}\n\nParameters:\n{parameters}\n\n"
    ),
	"prompt_rewrite_question": (
		"Here is a math question with old parameter values, and five kinds of new parameter values. Please rewrite the question five times to update all the parameters from old value to each corresponding new value in five lines without index.\n\n"
		"Question: :\n{question}\n\nOld Parameters:\n{parameters}\n\nNew Parameters:\n{new_parameters}\n\nNew Question:"
	),
	"prompt_answer_question": (
		"Answer the math question below. Only output the answer without units.\n\n"
		"Question:\n{question}\n\nAnswer:"
	),
	"prompt_answer_question_few_shot_cot": (
		"Q: There are 15 trees in the grove. Grove workers will plant trees in the grove today. After they are done, there will be 21 trees. How many trees did the grove workers plant today?\n"
		"A: There are 15 trees originally. Then there were 21 trees after some more were planted. So there must have been 21 - 15 = 6. The answer is 6.\n\n"
		"Q: If there are 3 cars in the parking lot and 2 more cars arrive, how many cars are in the parking lot?\n"
		"A: There are originally 3 cars. 2 more cars arrive. 3 + 2 = 5. The answer is 5.\n\n"
		"Q: Leah had 32 chocolates and her sister had 42. If they ate 35, how many pieces do they have left in total?\n"
		"A: Originally, Leah had 32 chocolates. Her sister had 42. So in total they had 32 + 42 = 74. After eating 35, they had 74 - 35 = 39. The answer is 39.\n\n"
		"Q: Jason had 20 lollipops. He gave Denny some lollipops. Now Jason has 12 lollipops. How many lollipops did Jason give to Denny?\n"
		"A: Jason started with 20 lollipops. Then he had 12 after giving some to Denny. So he gave Denny 20 - 12 = 8. The answer is 8.\n\n"
		"Q: Shawn has five toys. For Christmas, he got two toys each from his mom and dad. How many toys does he have now?\n"
		"A: Shawn started with 5 toys. If he got 2 toys each from his mom and dad, then that is 4 more toys. 5 + 4 = 9. The answer is 9.\n\n"
		"Q: There were nine computers in the server room. Five more computers were installed each day, from monday to thursday. How many computers are now in the server room?\n"
		"A: There were originally 9 computers. For each of 4 days, 5 more computers were added. So 5 * 4 = 20 computers were added. 9 + 20 is 29. The answer is 29.\n\n"
		"Q: Michael had 58 golf balls. On tuesday, he lost 23 golf balls. On wednesday, he lost 2 more. How many golf balls did he have at the end of wednesday?\n"
		"A: Michael started with 58 golf balls. After losing 23 on tuesday, he had 58 - 23 = 35. After losing 2 more, he had 35 - 2 = 33 golf balls. The answer is 33.\n\n"
		"Q: Olivia has $23. She bought five bagels for $3 each. How much money does she have left?\n"
		"A: Olivia had 23 dollars. 5 bagels for 3 dollars each will be 5 x 3 = 15 dollars. So she has 23 - 15 dollars left. 23 - 15 is 8. The answer is 8.\n\n"
		"Q: {question}\n"
		"A: "
	)
}

def call_function_with_args(parameter):
	# outstr = '\noutput = answer('
	# for parameter in case['parameter_value']:
	# 	para_name = parameter.split(':')[0]
	# 	if ': str' not in parameter:
	# 		value = str(case['parameter_value'][parameter])
	# 	else:
	# 		value = '"' + case['parameter_value'][parameter] + '"'
	# 	# print(para_name, value)
	# 	outstr += para_name + '=' + value + ', '
	# outstr += ')\nprint(output)'

	outstr = '\noutput = answer({})\nprint(output)'.format(parameter)
	return outstr


def perturb_parameter_value(case):
	prompt_template = PROMPT_DICT['prompt_new_parameter_value']
	prompt = prompt_template.format_map(
		{"question": case['question'], "parameters": case['parameters']}
	)
	response = client.chat.completions.create(
		model="gpt-4o",
		messages=[
			{"role": "system", "content": "You are a helpful assistant."},
			{"role": "user", "content": prompt}
		]
	)
	return response


def clear_parameter_output(response):
	response = response.replace('Parameters:', '').replace('```', '').replace('- ', '').strip().split('\n')
	for idx, para in enumerate(response):
		para.replace(str(idx)+'. ', '').strip()
	response = [x for x in response if len(x) > 0]
	return response

def generate_new_parameter_value():
	infile = open('/shared/xdyu/msr/reasoning_hallucination/data/math/test_dump_gsm8k_train_perturbed.json', 'r')
	program_data = json.load(infile)

	correct_counter = 0
	compile_fail_counter = 0

	correct_case = []

	for case in program_data:
		program = case['candidate_programs'][0]
		program += call_function_with_args(case['parameters'])
		# print(program)
		try:
			f = StringIO()
			with redirect_stdout(f):
				exec(program)
			s = f.getvalue().strip()
			if round(float(s)) == round(float(case['answer'])):
				correct_counter += 1
				correct_case.append(case)
		# else:
		# 	print(s)
		# 	print(case['answer'])
		except Exception as e:
			print(e)
			print(program)
			compile_fail_counter += 1
	print(correct_counter)

	for case in tqdm(correct_case):
		if 'new_answers' in case and len(case['new_answers']) == 5:
			continue
		response = perturb_parameter_value(case)
		new_values = clear_parameter_output(response.choices[0].message.content)
		if len(new_values) == 6:
			new_values = new_values[1:]
		case['new_parameters'] = new_values
		try:
			case['new_answers'] = []
			for parameter in case['new_parameters']:
				program = case['candidate_programs'][0]
				program += call_function_with_args(parameter)
				f = StringIO()
				with redirect_stdout(f):
					exec(program)
				s = f.getvalue().strip()
				case['new_answers'].append(s)
		except Exception as e:
			print(e)
			print(new_values)
			continue
	# break
	outfile = open('data/math/test_dump_gsm8k_train_perturbed.json', 'w')
	json.dump(correct_case, outfile, indent=4)


def rewrite_question(case):
	prompt_template = PROMPT_DICT['prompt_rewrite_question']
	prompt = prompt_template.format_map(
		{"question": case['question'], "parameters": case['parameters'], "new_parameters": "\n".join(case['new_parameters'])}
	)
	response = client.chat.completions.create(
		model="gpt-4o",
		messages=[
			{"role": "system", "content": "You are a helpful assistant."},
			{"role": "user", "content": prompt}
		]
	)
	return response


def update_question_with_new_parameters():
	infile = open('/shared/xdyu/msr/reasoning_hallucination/data/math/test_dump_gsm8k_train_perturbed.json', 'r')
	program_data = json.load(infile)
	print(len(program_data))
	for case in tqdm(program_data):
		response = rewrite_question(case)
		new_values = [x.strip() for x in response.choices[0].message.content.split('\n') if len(x) > 0]
		# print(new_values)
		if len(new_values) == 6:
			new_values = new_values[1:]
		case['new_questions'] = new_values
		# print(case)
		# break
	outfile = open('data/math/test_dump_gsm8k_train_perturbed_with_new_questions.json', 'w')
	json.dump(program_data, outfile, indent=4)


def call_answer_question(question):
	prompt_template = PROMPT_DICT['prompt_answer_question_few_shot_cot']
	prompt = prompt_template.format_map(
		{"question": question}
	)
	# print(prompt)
	response = client.chat.completions.create(
		model="gpt-4o",
		messages=[
			{"role": "system", "content": "You are a helpful assistant."},
			{"role": "user", "content": prompt}
		],
		temperature=0,
		max_tokens=300,
		top_p=1
	)
	return response


def answer_question():
	infile = open('/shared/xdyu/msr/reasoning_hallucination/data/math/test_dump_gsm8k_train_perturbed_with_new_questions.json', 'r')
	program_data = json.load(infile)
	print(len(program_data))
	for case in tqdm(program_data):
		response = call_answer_question(case['question'])
		case['prediction'] = response.choices[0].message.content
		# print(case['prediction'])
		case['new_prediction'] = []
		for question in case['new_questions']:
			response = call_answer_question(question)
			case['new_prediction'].append(response.choices[0].message.content)
		# print(case)
		# break
	# print(case)
	# break
	outfile = open('data/math/test_dump_gsm8k_train_perturbed_with_new_questions_answer_few_shot_cot.json', 'w')
	json.dump(program_data, outfile, indent=4)


def parse_answer(answer):
	if 'answer is' in answer:
		answer = answer.split('answer is')[-1].strip()
	else:
		answer = answer.split(' ')[-1]
	if len(answer) > 0 and answer[-1] == '.':
			answer = answer[0:-1]
	answer = answer.replace('$','').replace(',','').strip()
	return answer

def evaluator(infile_path):
	infile = open(infile_path, 'r')
	data = json.load(infile)
	correct_case = 0
	total_case = 0
	total_percentage = 0
	new_parameter_correct_counter = {}
	for case in data:
		if 'new_answers' not in case or len(case['new_answers']) != len(case['new_prediction']):
			continue
		total_case += 1
		prediction = parse_answer(case['prediction'])
		if prediction == case['answer'] or case['answer'] in prediction:
			correct_case += 1
			new_parameter_correct_case = 0
			for idx, pred in enumerate(case['new_prediction']):
				parsed_pred = parse_answer(pred)
				if parsed_pred == case['new_answers'][idx] or case['new_answers'][idx] in parsed_pred:
					new_parameter_correct_case += 1
				else:
					try:
						parsed_pred = round(float(parsed_pred))
						new_answer = round(float(case['new_answers'][idx]))
						if parsed_pred == new_answer:
							new_parameter_correct_case += 1
						else:
							print(parsed_pred, case['new_answers'][idx])
					except:
						continue
			total_parameter_correct_case = len(case['new_prediction'])
			percentage = float(new_parameter_correct_case / total_parameter_correct_case)
			total_percentage += percentage
			if new_parameter_correct_case not in new_parameter_correct_counter:
				new_parameter_correct_counter[new_parameter_correct_case] = 0
			new_parameter_correct_counter[new_parameter_correct_case] += 1

		# else:
		# 	print(prediction, case['answer'])
	print(correct_case, total_case, correct_case/total_case)
	print(total_percentage/correct_case)
	print(new_parameter_correct_counter)

def main():
	# generate_new_parameter_value()
	# update_question_with_new_parameters()
	# answer_question()
	evaluator('data/math/test_dump_gsm8k_train_perturbed_with_new_questions_answer_few_shot_cot.json')


if __name__ == "__main__":
	main()