-
Notifications
You must be signed in to change notification settings - Fork 48
/
run_prediction.py
217 lines (195 loc) · 8.47 KB
/
run_prediction.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
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
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import openai_api
from src import utils, dataset_loader
import os
from dataclasses import asdict
import json
def query_openai(context_list, setting_name, n_multiply=3):
n = len(openai_api.API_name_key_list) * n_multiply
print("multi-thread n =", n)
if setting_name == 'complete':
results = openai_api.multi_threading_running(
openai_api.query_azure_openai_complete, context_list, n=n)
else:
results = openai_api.multi_threading_running(
openai_api.query_azure_openai_chat, context_list, n=n)
# except openai.error.APIConnectionError as e:
# print("found error:", e)
# return query_openai(context_list, setting_name, max(max(n_multiply-5, n_multiply//2), 1))
return results
def query_openai_with_retry(context_list, setting_name, retry_time=4, results=None):
if results is None:
results = query_openai(context_list, setting_name)
while retry_time > 0:
filtered_context_list = []
for i in range(len(results)):
if utils.extract_answer(results[i]) == "":
filtered_context_list.append(context_list[i])
if len(filtered_context_list) == 0:
# print("nothing need to retry")
break
filtered_results = query_openai(filtered_context_list, setting_name)
print("filtered_results in query_openai_with_retry:", filtered_results)
p = 0
for i in range(len(results)):
if utils.extract_answer(results[i]) == "":
results[i] = filtered_results[p]
p += 1
assert p == len(filtered_results)
retry_succeeded = 0
for item in filtered_results:
if utils.extract_answer(item) != "":
retry_succeeded += 1
print("In the retry, {0} samples succeeded, {1} samples failed".format(
retry_succeeded, len(filtered_results) - retry_succeeded))
if retry_succeeded <= 3:
retry_time -= 1
assert len(results) == len(context_list)
return results
def chat_completion_to_json(chat_completion):
return json.dumps(asdict(chat_completion), ensure_ascii=False, indent=4)
def run_multiple_dataset_batch(work_items):
if len(work_items) == 0:
return
print("work items:", work_items)
dataset_list = []
item_list = []
for (input_path, output_path, mode, _) in work_items:
assert mode == work_items[0][2]
js_list = utils.read_jsonl(input_path)
content_list = [item["context"] for item in js_list]
dataset_list.append(len(content_list))
item_list += content_list
results = query_openai_with_retry(context_list=item_list, setting_name=work_items[0][2])
results = [utils.extract_answer(item) for item in results]
print("results:", results)
s = 0
for i in range(len(dataset_list)):
utils.save_jsonl(results[s:s + dataset_list[i]], work_items[i][1])
s += dataset_list[i]
assert s == len(results)
def run_multiple_dataset(work_items):
batch = []
count = 0
batch_size = 1000
if openai_api.default_engine == 'gpt-35-turbo':
batch_size = 500
for item in work_items:
if os.path.exists(item[1]):
if len(utils.read_jsonl(item[1])) == item[3]:
continue
if count + item[3] > batch_size:
run_multiple_dataset_batch(batch)
batch = []
count = 0
batch.append(item)
count += item[3]
if len(batch) > 0:
run_multiple_dataset_batch(batch)
if __name__ == "__main__":
run_experiment = True
dataset_dir = "data/v1_1"
raw_prompt_path = "./data/few_shot_prompts.csv"
output_dir = "outputs/gpt-35-turbo"
gpt_model = "gpt-35-turbo"
openai_api.default_engine = gpt_model
os.makedirs(os.path.join(output_dir, "inputs"), exist_ok=True)
os.makedirs(os.path.join(output_dir, "outputs"), exist_ok=True)
# dataset_name_list = ["gaokao-english"]
dataset_name_list = [
"gaokao-chinese",
"gaokao-geography",
"gaokao-history",
"gaokao-biology",
"gaokao-chemistry",
"gaokao-physics",
"gaokao-mathqa",
"gaokao-english",
"sat-math",
"sat-en",
"aqua-rat",
"lsat-ar",
"lsat-lr", "lsat-rc",
"logiqa-en", "logiqa-zh",
"gaokao-mathcloze",
"jec-qa-kd", "jec-qa-ca",
"math",
"sat-en-without-passage",
]
setting_name_list = [
# 'few-shot',
# 'few-shot-CoT',
'zero-shot',
# 'zero-shot-CoT'
]
skip_stage_1 = False
skip_stage_2 = False
skip_stage_3 = True
chat_mode = True
work_items = []
for dataset_name in dataset_name_list:
for setting_name in setting_name_list:
dataset = dataset_loader.load_dataset(
dataset_name, setting_name, dataset_dir,
prompt_path=raw_prompt_path, max_tokens=2048,
end_of_example="<END>\n", verbose=True, chat_mode=chat_mode)
# dataset = dataset[:10]
input_path = os.path.join(output_dir, "inputs", f"{dataset_name}.{setting_name}.jsonl")
utils.save_jsonl(dataset, input_path)
# dataset = dataset[:10]
# print(dataset[0]['context'])
output_path = os.path.join(
output_dir, "outputs", f'predict.{gpt_model}.{dataset_name}.{setting_name}.jsonl')
first_stage_output_path = os.path.join(
output_dir, "outputs", f'predict.{gpt_model}.{dataset_name}.{setting_name}.first_stage.jsonl')
if 'few-shot' in setting_name:
work_items.append((input_path, output_path, 'chat' if chat_mode else 'complete', len(dataset)))
else:
work_items.append((input_path, first_stage_output_path, 'chat', len(dataset)))
if not skip_stage_1:
run_multiple_dataset([item for item in work_items if item[2] == 'complete'])
run_multiple_dataset([item for item in work_items if item[2] == 'chat'])
work_items = []
for dataset_name in dataset_name_list:
for setting_name in setting_name_list:
if 'few-shot' in setting_name:
continue
dataset = dataset_loader.load_dataset(
dataset_name, setting_name, dataset_dir,
prompt_path=raw_prompt_path, max_tokens=2048,
end_of_example="<END>\n", verbose=True)
# dataset = dataset[:10]
input_path = os.path.join(output_dir, "inputs", f"{dataset_name}.{setting_name}.jsonl")
# dataset = dataset[:10]
# print(dataset[0]['context'])
output_path = os.path.join(
output_dir, "outputs", f'predict.{gpt_model}.{dataset_name}.{setting_name}.jsonl')
first_stage_output_path = os.path.join(
output_dir, "outputs", f'predict.{gpt_model}.{dataset_name}.{setting_name}.first_stage.jsonl')
first_stage_results = utils.read_jsonl(first_stage_output_path)
second_stage_input = dataset_loader.generate_second_stage_input(
dataset_name, dataset, first_stage_results)
second_stage_input_path = os.path.join(output_dir, "inputs", f"{dataset_name}.{setting_name}.second_stage.jsonl")
utils.save_jsonl(second_stage_input, second_stage_input_path)
work_items.append((second_stage_input_path, output_path, 'chat', len(dataset)))
if not skip_stage_2:
openai_api.default_engine = "gpt-35-turbo"
run_multiple_dataset(work_items)
if not skip_stage_3:
openai_api.default_engine = "gpt-35-turbo"
wrong_dataset_name_setting_name_list = [
("aqua-rat", "few-shot-CoT"),
("math", "few-shot"),
("math", "few-shot-CoT"),
("gaokao-physics", "few-shot-CoT"),
]
for dataset_name, setting_name in wrong_dataset_name_setting_name_list:
zero_shot_dataset = dataset_loader.load_dataset(
dataset_name, "zero-shot", dataset_dir,
prompt_path=raw_prompt_path, max_tokens=2048,
end_of_example="<END>\n", verbose=True)
few_shot_output_path = os.path.join(
output_dir, "outputs", f'predict.{gpt_model}.{dataset_name}.{setting_name}.jsonl')
few_shot_second_stage_output_path = os.path.join(
output_dir, "outputs", f'predict.{gpt_model}.{dataset_name}.{setting_name}.second_stage.jsonl')