-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgpt4prompt.py
172 lines (157 loc) · 8.5 KB
/
gpt4prompt.py
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
import openai
from prompts import *
import time
import json
import random
import datetime
import os
import utils
# MODEL = "gpt-3.5-turbo"
MODEL = "gpt-4"
# MODEL = "text-davinci-003"
seed = 2024
openai.api_key = utils.openai_api_key
openai.organization = utils.openai_edinburgh_organization
split_formalization_and_proof = False
use_COT = True
use_COT_in_all = True
add_comment_and_use_COT= True
if not split_formalization_and_proof:
prompt_inputs = [ProofWriter_example_true_textual_input, ProofWriter_example_false_textual_input, ProofWriter_example_unknown_textual_input]
if not use_COT_in_all:
prompt_outputs = [ProofWriter_example_true_all_output, ProofWriter_example_false_all_output, ProofWriter_example_unknown_all_output]
else:
if not add_comment_and_use_COT:
prompt_outputs = [ProofWriter_example_true_all_COT_output, ProofWriter_example_false_all_COT_output, ProofWriter_example_unknown_all_COT_output]
else:
prompt_outputs = [ProofWriter_example_true_all_COT_comment_output, ProofWriter_example_false_all_COT_comment_output, ProofWriter_example_unknown_all_COT_comment_output]
else:
prompt_inputs = [ProofWriter_example_true_textual_input + '\n---\n' + ProofWriter_example_true_formalization, \
ProofWriter_example_false_textual_input + '\n---\n' + ProofWriter_example_false_formalization, \
ProofWriter_example_unknown_textual_input + '\n---\n' + ProofWriter_example_unknown_formalization]
if not use_COT:
prompt_outputs = [ProofWriter_example_true_proof, ProofWriter_example_false_proof, ProofWriter_example_unknown_proof]
else:
prompt_outputs = [ProofWriter_example_true_proof_COT, ProofWriter_example_false_proof_COT, ProofWriter_example_unknown_proof_COT]
proof_writer_answer_map = {"True": "A", "False": "B", "Unknown": "C"}
def data_generation_proofwriter(filename):
qa_pairs = []
# open jsonl file
with open(filename, 'r') as json_file:
json_list = list(json_file)
for l in json_list:
d = json.loads(l.strip())
theory = d.get('theory')
questions = d.get("questions")
for key in questions.keys():
q = questions.get(key)
if q.get("QDep") == 5 and q.get("answer") != "Unknown":
question_temp = q.get("question")
answer = q.get("answer")
real_question = theory + " Question: " + question_temp + "?"
qa_pairs.append((real_question, answer))
random.seed(seed)
random_qa_pairs = random.sample(qa_pairs, 50)
random_qa_pairs_new = random.sample(qa_pairs, 300)
temp_random_qa_pairs = []
for item in random_qa_pairs_new:
if item not in random_qa_pairs:
temp_random_qa_pairs.append(item)
random_qa_pairs = random_qa_pairs[:5]
return temp_random_qa_pairs
def data_generation_proofwriter_logiclm(json_file):
d = json.load(open(json_file, 'r'))
qa_pairs = []
random.seed(seed)
for item in d:
qa_pairs.append((item['context'], item['question'], item['answer']))
# random_qa_pairs = random.sample(qa_pairs, 100)
return qa_pairs
def run_prompt(random_qa_pairs):
# make a folder to store the outputs and config files, make sure the folder contain current timestamp and model name
timestamp = datetime.datetime.now().strftime('%Y_%b_%d_%H_%M_%S')
folder_name = 'ProofWriter_' + timestamp + '_' + MODEL
os.mkdir(folder_name)
# dump the prompt to a file
write_file = open(folder_name + '/prompt.txt', 'w')
write_file.write("System message:\n")
write_file.write(system_message + "\n\n")
for i in range(len(prompt_inputs)):
write_file.write("Example " + str(i + 1) + ":\n")
write_file.write("Input:\n" + prompt_inputs[i] + "\n\n" + "Output:\n" + prompt_outputs[i] + "\n\n")
write_file.close()
# dump the config to a json file
divinci_config = {
"temperature": 0,
"top_p": 1.0,
"frequency_penalty": 0.0,
"presence_penalty": 0.0,
"stop": "\n------------",
"max_tokens": 512,
}
gpt_config = {
"temperature": 0,
"top_p": 1.0,
}
with open(folder_name + '/config.json', 'w') as json_file:
if MODEL == 'text-davinci-003':
json.dump(divinci_config, json_file)
elif MODEL.startswith('gpt'):
json.dump(gpt_config, json_file)
# make a json file to store the random_qa_pairs and its corresponding outputs
for i in range(0, len(random_qa_pairs)):
try:
qa_pair = random_qa_pairs[i]
if not split_formalization_and_proof:
prompt_input = "Textual context: " + qa_pair[0] + "\n" + "Question: " + qa_pair[1]
else:
print('If you want to separate the formalization and proof process, you need to first generate the formalization then put the formalization into the prompt to generate proof. It is not supported in this project because it will generate inferior results.')
exit(0)
if MODEL == "text-davinci-003":
prompt = "Task Description: " + system_message + "\n\n------------" + "Input:\n" + prompt_inputs[0] + "- - - - - - - - - - - -" + prompt_outputs[0] + '\n------------' + \
"Input:\n" + prompt_inputs[1] + "- - - - - - - - - - - -" + prompt_outputs[1] + '\n------------' + \
"Input:\n" + prompt_inputs[2] + "- - - - - - - - - - - -" + prompt_outputs[2] + '\n------------' + \
"Input:\n" + prompt_input + "- - - - - - - - - - - -"
response = openai.Completion.create(
model=MODEL,
prompt=prompt,
temperature=divinci_config["temperature"],
max_tokens=divinci_config["max_tokens"],
stop=divinci_config["stop"],
presence_penalty=divinci_config["presence_penalty"],
frequency_penalty=divinci_config["frequency_penalty"],
top_p=divinci_config["top_p"],
)
res = response['choices'][0]['text'].strip()
elif MODEL == 'gpt-4' or MODEL == 'gpt-3.5-turbo':
response = openai.ChatCompletion.create(
model=MODEL,
messages=[
{"role": "system", "content": "Task Description: " + system_message + '\nI will give you some examples'},
{"role": "user", "content": "Input:\n" + prompt_inputs[0] + "\n\nOutput:\n" + prompt_outputs[0]},
{"role": "user", "content": "Input:\n" + prompt_inputs[1] + "\n\nOutput:\n" + prompt_outputs[1]},
{"role": "user", "content": "Input:\n" + prompt_inputs[2] + "\n\nOutput:\n" + prompt_outputs[2]},
{"role": "assistant", "content": "Now give me the result for this input: Input:\n" + prompt_input + "\n\nOutput:\n"},
],
temperature=gpt_config["temperature"],
top_p=gpt_config["top_p"],
)
res = response["choices"][0]["message"]["content"].strip()
json_file = open(folder_name + '/output_' + str(i) + '.json', 'w')
predicted_answer = proof_writer_answer_map[res.strip().split('\n')[-1].split(' ')[-1]]
d = {"input": prompt_input, "input_tokens": response["usage"]["prompt_tokens"], "output": res, "output_tokens": response["usage"]["completion_tokens"], \
"pred_answer": predicted_answer, "gt_answer": qa_pair[-1], "problem_id": i}
print("This is problem: " + str(i) + ". The predicted answer is: " + predicted_answer + ", The GT answer is: " + str(qa_pair[-1]))
json.dump(d, json_file, indent=4, ensure_ascii=False)
json_file.close()
except Exception as e:
print(e)
print("Error in problem: " + str(i) + ".")
if __name__ == "__main__":
start_time = time.time()
# select random questions from proofwriter OWA depth-5 dataset, to use it, download it from https://allenai.org/data/proofwriter
# random_qa_pairs = data_generation_proofwriter(filename='proofwriter-dataset-V2020.12.3/OWA/depth-5/meta-test.jsonl')
# as we're following the same setup as LogicLM, we use the same data
proof_writer_dev_qa_pairs = data_generation_proofwriter_logiclm("data/ProofWriter/dev.json")
run_prompt(proof_writer_dev_qa_pairs)
print("Time elapsed: ", time.time() - start_time)