-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathnl2code_codex.py
208 lines (172 loc) · 6.87 KB
/
nl2code_codex.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
"""Evaluate Codex performance on NL-to-Code generation. """
import os, random
import time, json, argparse
from typing import Dict, List
from src.utils import get_test_path, get_prediction_path, load_testset
from prompt import create_fewshot_prompt_nl2code
from verify import get_valid_solutions, wrap_check
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
def get_response_001(
prompt: str,
verbose: bool = False,
) -> List[str]:
if verbose: print(f"[prompt] \n{prompt}\n------")
response = openai.Completion.create(
model=args.model_name,
prompt=prompt,
max_tokens=args.max_tokens,
temperature=args.temperature,
top_p=args.top_p,
n=args.n,
frequency_penalty=0.0,
presence_penalty=0.0,
stop=["###"],
)
return [choice["text"] for choice in response["choices"]]
def get_response_davinci_002(
prompt: str,
sample: Dict,
verbose: bool = False,
) -> List[str]:
if verbose: print(f"[prompt] \n{prompt}\n------")
response = openai.Completion.create(
model=args.model_name,
prompt=prompt,
suffix=sample["suffix"],
max_tokens=args.max_tokens,
temperature=args.temperature,
top_p=args.top_p,
n=args.n,
frequency_penalty=0.0,
presence_penalty=0.0,
stop=["###"],
)
return [choice["text"] for choice in response["choices"]]
RESPOND_DICT = {
"code-cushman-001": get_response_001,
"code-davinci-001": get_response_001,
"code-davinci-002": get_response_davinci_002,
}
def get_predictions(
model_name: str, prompt: str,
sample: Dict, index: int,
sleep_time: int, verbose: bool,
) -> List[str]:
if sleep_time == 0:
return RESPOND_DICT[model_name](prompt, sample, verbose)
# enable sleep time otherwise
predictions = None
while predictions is None:
try:
predictions = RESPOND_DICT[model_name](prompt, sample, verbose)
except:
print(f"sleep for {sleep_time} at sample #{index}")
time.sleep(sleep_time)
return predictions
def select_fewshot_examples(
sample: Dict, candidates: List[Dict],
num_examples: int = 1, method: str = "random",
) -> List[Dict]:
"""Select example as prefix to the prompt of the current sample. """
if method == "random":
num_examples = min(num_examples, len(candidates))
return random.sample(candidates, num_examples)
def main():
# load source dataset
dataset = load_testset(args.input_path)
predset = []
scores_dict = {f"pass@{idx}": [] for idx in range(1, args.n+1)}
for i, sample in enumerate(dataset):
# create model input -- prompt
examples = select_fewshot_examples(
sample=sample,
candidates=dataset[:i]+dataset[i+1:],
num_examples=args.num_examples,
method=args.fewshot_method,
)
prompt = create_fewshot_prompt_nl2code(
sample=sample,
examples=examples,
num_tests=args.num_tests,
function_name=args.function_name,
)
if args.strip_prompt:
prompt = prompt.rstrip()
# collect code predictions
predictions = get_predictions(
model_name=args.model_name,
prompt=prompt, sample=sample, index=i,
sleep_time=args.sleep_time, verbose=args.verbose,
)
# simple cleansing of predicions
valid_predictions = get_valid_solutions(predictions, deduplicate=False)
num_valid = len(valid_predictions)
assert num_valid == args.n, f"# num_valid"
scores, outputs = wrap_check(
sample, valid_predictions,
k=[i+1 for i in range(num_valid)],
num_workers=args.n,
max_num_tests=args.num_tests_eval,
verbose=args.verbose,
function_name=args.function_name,
)
if i % 10 == 0:
print(f"[scores@{i:3d}] {scores}")
for idx in range(num_valid):
key = f"pass@{idx+1}"
if key in scores:
scores_dict[key].append(scores[key])
predset.append({
"output": outputs,
"predictions": valid_predictions,
})
# write records to prediction file
json.dump(predset, open(args.output_path, 'w'))
for idx in range(args.n):
key = f"pass@{idx+1}"
scores = scores_dict[key]
print(f"[{key}] {sum(scores)/len(scores):.3f} ({len(scores)})")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--language", type=str, default="en",
choices=["en", "es", "ja", "ru"])
parser.add_argument("--input_path", type=str, default=None)
parser.add_argument("--output_path", type=str, default=None)
parser.add_argument("--num_tests", type=int, default=0)
parser.add_argument("--num_tests_eval", type=int, default=100)
parser.add_argument("--model_name", type=str, default="code-davinci-002",
choices=["code-cushman-001", "code-davinci-001", "code-davinci-002"])
parser.add_argument("--max_tokens", type=int, default=200)
parser.add_argument("--temperature", type=float, default=0.8)
parser.add_argument("--top_p", type=float, default=0.95)
parser.add_argument("--n", type=int, default=10,
help="Number of predictions required for each api call.")
parser.add_argument("--sleep_time", type=int, default=60,
help="Specify a positive integer if enable time sleep.")
parser.add_argument("--function_name", type=str, default="id",
choices=["id", "constant", "intent"],
help="Method to construct the function name. ")
parser.add_argument("--num_examples", type=int, default=0,
help="Number of examples included in the current prompt input. ")
parser.add_argument("--fewshot_method", type=str, default="random",
choices=["random"],
help="Method to select the prefix examples for prompt creation.")
parser.add_argument("--strip_prompt", action="store_true",
help="Whether to strip the trailing whitespaces in the prompt. ")
parser.add_argument("--openai_api_key", type=str, default=None)
parser.add_argument("--verbose", action="store_true")
args = parser.parse_args()
if (not args.input_path) or (not args.output_path):
if not args.language:
raise Exception(f"Need to specify [language] or [i/o path]")
if not args.input_path:
args.input_path = get_test_path(args.language)
if not args.output_path:
args.output_path = get_prediction_path(
args.model_name, args.language,
args.num_examples, args.num_tests,
)
if args.openai_api_key is not None:
openai.api_key = args.openai_api_key
main()