Repository navigation
Expand file tree
/
Copy pathcode_eval_codellama.py
More file actions
209 lines (183 loc) · 7.55 KB
/
Copy pathcode_eval_codellama.py
File metadata and controls
209 lines (183 loc) · 7.55 KB
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
import json
import os
import io
import sys
import tqdm
import multiprocessing as mp
#from code_gen_gpt4 import foo
def run_code_with_io_handling(code, func_name=None, inputs=None):
"""
Executes code with simulated input/output handling.
:param code: String of code to execute.
:param func_name: Name of the function to call (optional).
:param inputs: List of inputs to simulate user input via stdin.
:return: Captured output or error message.
"""
# Prepare input and output streams
input_stream = io.StringIO("\n".join(inputs) if inputs else "")
output_stream = io.StringIO()
# Backup original stdin and stdout
original_stdin = sys.stdin
original_stdout = sys.stdout
try:
# Redirect stdin and stdout
sys.stdin = input_stream
sys.stdout = output_stream
# Compile and execute the code
compiled_code = compile(code, "<string>", "exec")
local_namespace = {}
exec(compiled_code, local_namespace)
# If a function name is provided, call it
if func_name and func_name in local_namespace:
local_namespace[func_name]() # Call the function
# Get the captured output
output = output_stream.getvalue()
return output
except SyntaxError as se:
return f"Failed: Syntax Error - {se}"
except Exception as e:
return f"Failed: Runtime Error - {e}"
finally:
# Restore original stdin and stdout
sys.stdin = original_stdin
sys.stdout = original_stdout
def run_code_with_io_handling(code, func_name=None, inputs=None, timeout=5):
"""
Executes code with simulated I/O and ensures each test case completes within the timeout.
:param code: String of code to execute.
:param func_name: Name of the function to call (optional).
:param inputs: List or string for stdin simulation.
:param expected_output: Expected output to compare against.
:param timeout: Maximum time (in seconds) allowed for the code to run.
:return: Result message indicating success, failure, or timeout.
"""
def _execute_code(queue):
"""Helper function to execute code in a separate process."""
# Prepare input stream
input_stream = io.StringIO("\n".join(inputs) if isinstance(inputs, list) else inputs)
output_stream = io.StringIO()
# Backup original stdin and stdout
original_stdin = sys.stdin
original_stdout = sys.stdout
try:
# Redirect stdin and stdout
sys.stdin = input_stream
sys.stdout = output_stream
# Compile and execute the code
compiled_code = compile(code, "<string>", "exec")
local_namespace = {}
exec(compiled_code, local_namespace)
return_val = None
# Call the function if provided
if func_name and func_name in local_namespace:
#local_namespace[func_name]()
return_val = local_namespace[func_name]()
if return_val:
print(return_val)
# Get the captured output
output = output_stream.getvalue().strip()
queue.put(output) # Send the output back via the queue
except AssertionError as e:
queue.put(f"Failed: Assertion Error - {e}")
except Exception as e:
queue.put(f"Failed: Runtime Error - {e}")
finally:
# Restore original stdin and stdout
sys.stdin = original_stdin
sys.stdout = original_stdout
# Use a queue to retrieve output from the process
queue = mp.Queue()
process = mp.Process(target=_execute_code, args=(queue,))
# Start the process and wait for it to finish
process.start()
process.join(timeout)
# If the process is still running after the timeout, terminate it
if process.is_alive():
process.terminate()
process.join()
return f"Failed: Timeout - Code did not finish within {timeout} seconds."
# Retrieve the output from the queue
try:
output = queue.get_nowait()
except:
return "Failed: No output was captured."
return output
# result = foo()
# text = result['choices'][0]['message']['content']
# code = text[text.find('def solution'):]
# code = code.rstrip('`')
evaluated = {}
#generated_code_dir = 'generated_code_gpt4_100_1.json'
#generated_code_dir = 'generated_code_llama-I_100.json'
#generated_code_dir = 'generated_code_codellama_100.json'
#generated_code_dir = 'generated_code_codellama_humaneval_3-2.json'
# generated_code_dir = 'generated_code_codellama_humaneval_3-2_partial.json'
#generated_code_dir = 'generated_code_beam-finetune-1119-50_humaneval_3-2.json'
generated_code_dir = 'code_5_0.json'
with open(generated_code_dir,'r') as file:
generated_code = json.load(file)
dataset = 'human_eval'
if dataset == 'apps':
dataset_dir = 'APPS/test'
for problem in os.listdir(dataset_dir):
if not problem in generated_code:
continue
problem_path = os.path.join(dataset_dir,problem)
if 'gpt' in generated_code_dir:
text = generated_code[problem]['choices'][0]['message']['content']
else:
text = generated_code[problem]
code = text[text.find('def solution'):]
code = code.replace('`','')
if code.find('if __name__') != -1:
code = code[:code.find('if __name__')]
lines = code.split('\n')
imports = """
import math
import sys
from collections import deque
"""
code = imports + lines[0] + '\n'
for line in lines[1:]:
if not line or line[0] == ' ':
code += line + '\n'
else:
break
print(problem)
print(code)
with open(os.path.join(problem_path,'input_output.json'), 'r') as file:
data = json.load(file)
inputs = [(x[:-1] if x[-1] == '\n' else x) for x in data['inputs']]
outputs = [(y[:-1] if y[-1] == '\n' else y) for y in data['outputs']]
results = [run_code_with_io_handling(code, func_name="solution", inputs=x.split('\n'), timeout=0.5) for x in inputs]
results = [r.rstrip('\n') for r in results]
accuracy = sum([(1 if str(r) == y else 0) for (r,y) in zip(results,outputs)])
print(results)
print(f"accuracy:{accuracy}/{len(inputs)}={accuracy/len(inputs)}")
evaluated[problem] = {'code':code,'results':results,'accuracy':accuracy/len(inputs)}
with open('evaluated_code_codellama_100.json','w') as file:
json.dump(evaluated,file)
elif dataset == 'human_eval':
evaluated = {}
for key,problem in tqdm.tqdm(generated_code.items()):
codes = problem['code'] if type(problem['code']) == list else [problem['code']]
results = []
for code in codes:
fn = code[code.find('def ')+4:code.find('(')]
print(fn)
#code = code[code.find('def '):]
if code.find('if __name__') != -1:
code = code[:code.find('if __name__')]
code += '\n' + problem['test'] + '\n'
code += f'check({fn})'
print(code)
num_tests = problem['test'].count('assert')
result = run_code_with_io_handling(code, func_name="solution", timeout=0.5*num_tests)
print(result)
if result.find('Failed: ') != 0:
result = 'Accepted'
results.append(result)
evaluated[key] = problem.copy()
evaluated[key]['result'] = results
with open('code_5_0e.json','w') as file:
json.dump(evaluated,file)