Muennighoff mamta commited on
Commit
ea58aa2
0 Parent(s):

Duplicate from evaluate-metric/code_eval

Browse files

Co-authored-by: Mamta Narang <[email protected]>

Files changed (6) hide show
  1. .gitattributes +27 -0
  2. README.md +147 -0
  3. app.py +6 -0
  4. code_eval.py +213 -0
  5. execute.py +236 -0
  6. requirements.txt +1 -0
.gitattributes ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.model filter=lfs diff=lfs merge=lfs -text
11
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
12
+ *.onnx filter=lfs diff=lfs merge=lfs -text
13
+ *.ot filter=lfs diff=lfs merge=lfs -text
14
+ *.parquet filter=lfs diff=lfs merge=lfs -text
15
+ *.pb filter=lfs diff=lfs merge=lfs -text
16
+ *.pt filter=lfs diff=lfs merge=lfs -text
17
+ *.pth filter=lfs diff=lfs merge=lfs -text
18
+ *.rar filter=lfs diff=lfs merge=lfs -text
19
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
20
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
21
+ *.tflite filter=lfs diff=lfs merge=lfs -text
22
+ *.tgz filter=lfs diff=lfs merge=lfs -text
23
+ *.wasm filter=lfs diff=lfs merge=lfs -text
24
+ *.xz filter=lfs diff=lfs merge=lfs -text
25
+ *.zip filter=lfs diff=lfs merge=lfs -text
26
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
27
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Code Eval
3
+ emoji: 🤗
4
+ colorFrom: blue
5
+ colorTo: red
6
+ sdk: gradio
7
+ sdk_version: 3.19.1
8
+ app_file: app.py
9
+ pinned: false
10
+ tags:
11
+ - evaluate
12
+ - metric
13
+ description: >-
14
+ This metric implements the evaluation harness for the HumanEval problem
15
+ solving dataset described in the paper "Evaluating Large Language Models
16
+ Trained on Code" (https://arxiv.org/abs/2107.03374).
17
+ duplicated_from: evaluate-metric/code_eval
18
+ ---
19
+
20
+ # Metric Card for Code Eval
21
+
22
+ ## Metric description
23
+
24
+ The CodeEval metric estimates the pass@k metric for code synthesis.
25
+
26
+ It implements the evaluation harness for the HumanEval problem solving dataset described in the paper ["Evaluating Large Language Models Trained on Code"](https://arxiv.org/abs/2107.03374).
27
+
28
+
29
+ ## How to use
30
+
31
+ The Code Eval metric calculates how good are predictions given a set of references. Its arguments are:
32
+
33
+ `predictions`: a list of candidates to evaluate. Each candidate should be a list of strings with several code candidates to solve the problem.
34
+
35
+ `references`: a list with a test for each prediction. Each test should evaluate the correctness of a code candidate.
36
+
37
+ `k`: number of code candidates to consider in the evaluation. The default value is `[1, 10, 100]`.
38
+
39
+ `num_workers`: the number of workers used to evaluate the candidate programs (The default value is `4`).
40
+
41
+ `timeout`: The maximum time taken to produce a prediction before it is considered a "timeout". The default value is `3.0` (i.e. 3 seconds).
42
+
43
+ ```python
44
+ from evaluate import load
45
+ code_eval = load("code_eval")
46
+ test_cases = ["assert add(2,3)==5"]
47
+ candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]
48
+ pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])
49
+ ```
50
+
51
+ N.B.
52
+ This metric exists to run untrusted model-generated code. Users are strongly encouraged not to do so outside of a robust security sandbox. Before running this metric and once you've taken the necessary precautions, you will need to set the `HF_ALLOW_CODE_EVAL` environment variable. Use it at your own risk:
53
+ ```python
54
+ import os
55
+ os.environ["HF_ALLOW_CODE_EVAL"] = "1"`
56
+ ```
57
+
58
+ ## Output values
59
+
60
+ The Code Eval metric outputs two things:
61
+
62
+ `pass_at_k`: a dictionary with the pass rates for each k value defined in the arguments.
63
+
64
+ `results`: a dictionary with granular results of each unit test.
65
+
66
+ ### Values from popular papers
67
+ The [original CODEX paper](https://arxiv.org/pdf/2107.03374.pdf) reported that the CODEX-12B model had a pass@k score of 28.8% at `k=1`, 46.8% at `k=10` and 72.3% at `k=100`. However, since the CODEX model is not open source, it is hard to verify these numbers.
68
+
69
+
70
+
71
+ ## Examples
72
+
73
+ Full match at `k=1`:
74
+
75
+ ```python
76
+ from evaluate import load
77
+ code_eval = load("code_eval")
78
+ test_cases = ["assert add(2,3)==5"]
79
+ candidates = [["def add(a, b): return a+b"]]
80
+ pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1])
81
+ print(pass_at_k)
82
+ {'pass@1': 1.0}
83
+ ```
84
+
85
+ No match for k = 1:
86
+
87
+ ```python
88
+ from evaluate import load
89
+ code_eval = load("code_eval")
90
+ test_cases = ["assert add(2,3)==5"]
91
+ candidates = [["def add(a,b): return a*b"]]
92
+ pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1])
93
+ print(pass_at_k)
94
+ {'pass@1': 0.0}
95
+ ```
96
+
97
+ Partial match at k=1, full match at k=2:
98
+
99
+ ```python
100
+ from evaluate import load
101
+ code_eval = load("code_eval")
102
+ test_cases = ["assert add(2,3)==5"]
103
+ candidates = [["def add(a, b): return a+b", "def add(a,b): return a*b"]]
104
+ pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])
105
+ print(pass_at_k)
106
+ {'pass@1': 0.5, 'pass@2': 1.0}
107
+ ```
108
+
109
+ ## Limitations and bias
110
+
111
+ As per the warning included in the metric code itself:
112
+ > This program exists to execute untrusted model-generated code. Although it is highly unlikely that model-generated code will do something overtly malicious in response to this test suite, model-generated code may act destructively due to a lack of model capability or alignment. Users are strongly encouraged to sandbox this evaluation suite so that it does not perform destructive actions on their host or network. For more information on how OpenAI sandboxes its code, see the accompanying paper. Once you have read this disclaimer and taken appropriate precautions, uncomment the following line and proceed at your own risk:
113
+
114
+ More information about the limitations of the code can be found on the [Human Eval Github repository](https://github.com/openai/human-eval).
115
+
116
+ ## Citation
117
+
118
+ ```bibtex
119
+ @misc{chen2021evaluating,
120
+ title={Evaluating Large Language Models Trained on Code},
121
+ author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \
122
+ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \
123
+ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \
124
+ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \
125
+ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \
126
+ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \
127
+ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \
128
+ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \
129
+ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \
130
+ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \
131
+ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \
132
+ and William Saunders and Christopher Hesse and Andrew N. Carr \
133
+ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \
134
+ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \
135
+ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \
136
+ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},
137
+ year={2021},
138
+ eprint={2107.03374},
139
+ archivePrefix={arXiv},
140
+ primaryClass={cs.LG}
141
+ }
142
+ ```
143
+
144
+ ## Further References
145
+
146
+ - [Human Eval Github repository](https://github.com/openai/human-eval)
147
+ - [OpenAI Codex website](https://openai.com/blog/openai-codex/)
app.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import evaluate
2
+ from evaluate.utils import launch_gradio_widget
3
+
4
+
5
+ module = evaluate.load("code_eval")
6
+ launch_gradio_widget(module)
code_eval.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """The CodeEval metric estimates the pass@k metric for code synthesis.
15
+ This is an evaluation harness for the HumanEval problem solving dataset
16
+ described in the paper "Evaluating Large Language Models Trained on Code"
17
+ (https://arxiv.org/abs/2107.03374)."""
18
+
19
+ import itertools
20
+ import os
21
+ from collections import Counter, defaultdict
22
+ from concurrent.futures import ThreadPoolExecutor, as_completed
23
+
24
+ import datasets
25
+ import numpy as np
26
+
27
+ import evaluate
28
+
29
+ from .execute import check_correctness
30
+
31
+
32
+ _CITATION = """\
33
+ @misc{chen2021evaluating,
34
+ title={Evaluating Large Language Models Trained on Code},
35
+ author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \
36
+ and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \
37
+ and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \
38
+ and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \
39
+ and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \
40
+ and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \
41
+ and Mohammad Bavarian and Clemens Winter and Philippe Tillet \
42
+ and Felipe Petroski Such and Dave Cummings and Matthias Plappert \
43
+ and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \
44
+ and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \
45
+ and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \
46
+ and William Saunders and Christopher Hesse and Andrew N. Carr \
47
+ and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \
48
+ and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \
49
+ and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \
50
+ and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},
51
+ year={2021},
52
+ eprint={2107.03374},
53
+ archivePrefix={arXiv},
54
+ primaryClass={cs.LG}
55
+ }
56
+ """
57
+
58
+ _DESCRIPTION = """\
59
+ This metric implements the evaluation harness for the HumanEval problem solving dataset
60
+ described in the paper "Evaluating Large Language Models Trained on Code"
61
+ (https://arxiv.org/abs/2107.03374).
62
+ """
63
+
64
+
65
+ _KWARGS_DESCRIPTION = """
66
+ Calculates how good are predictions given some references, using certain scores
67
+ Args:
68
+ predictions: list of candidates to evaluate. Each candidates should be a list
69
+ of strings with several code candidates to solve the problem.
70
+ references: a list with a test for each prediction. Each test should evaluate the
71
+ correctness of a code candidate.
72
+ k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])
73
+ num_workers: number of workers used to evaluate the canidate programs (Default: 4).
74
+ timeout:
75
+ Returns:
76
+ pass_at_k: dict with pass rates for each k
77
+ results: dict with granular results of each unittest
78
+ Examples:
79
+ >>> code_eval = evaluate.load("code_eval")
80
+ >>> test_cases = ["assert add(2,3)==5"]
81
+ >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]
82
+ >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])
83
+ >>> print(pass_at_k)
84
+ {'pass@1': 0.5, 'pass@2': 1.0}
85
+ """
86
+
87
+
88
+ _WARNING = """
89
+ ################################################################################
90
+ !!!WARNING!!!
91
+ ################################################################################
92
+ The "code_eval" metric executes untrusted model-generated code in Python.
93
+ Although it is highly unlikely that model-generated code will do something
94
+ overtly malicious in response to this test suite, model-generated code may act
95
+ destructively due to a lack of model capability or alignment.
96
+ Users are strongly encouraged to sandbox this evaluation suite so that it
97
+ does not perform destructive actions on their host or network. For more
98
+ information on how OpenAI sandboxes its code, see the paper "Evaluating Large
99
+ Language Models Trained on Code" (https://arxiv.org/abs/2107.03374).
100
+
101
+ Once you have read this disclaimer and taken appropriate precautions,
102
+ set the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this
103
+ with:
104
+
105
+ >>> import os
106
+ >>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"
107
+
108
+ ################################################################################\
109
+ """
110
+
111
+ _LICENSE = """The MIT License
112
+
113
+ Copyright (c) OpenAI (https://openai.com)
114
+
115
+ Permission is hereby granted, free of charge, to any person obtaining a copy
116
+ of this software and associated documentation files (the "Software"), to deal
117
+ in the Software without restriction, including without limitation the rights
118
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
119
+ copies of the Software, and to permit persons to whom the Software is
120
+ furnished to do so, subject to the following conditions:
121
+
122
+ The above copyright notice and this permission notice shall be included in
123
+ all copies or substantial portions of the Software.
124
+
125
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
126
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
127
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
128
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
129
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
130
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
131
+ THE SOFTWARE."""
132
+
133
+
134
+ @evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
135
+ class CodeEval(evaluate.Metric):
136
+ def _info(self):
137
+ return evaluate.MetricInfo(
138
+ # This is the description that will appear on the metrics page.
139
+ description=_DESCRIPTION,
140
+ citation=_CITATION,
141
+ inputs_description=_KWARGS_DESCRIPTION,
142
+ # This defines the format of each prediction and reference
143
+ features=datasets.Features(
144
+ {
145
+ "predictions": datasets.Sequence(datasets.Value("string")),
146
+ "references": datasets.Value("string"),
147
+ }
148
+ ),
149
+ homepage="https://github.com/openai/human-eval",
150
+ codebase_urls=["https://github.com/openai/human-eval"],
151
+ reference_urls=["https://github.com/openai/human-eval"],
152
+ license=_LICENSE,
153
+ )
154
+
155
+ def _compute(self, predictions, references, k=[1, 10, 100], num_workers=4, timeout=3.0):
156
+ """Returns the scores"""
157
+
158
+ if os.getenv("HF_ALLOW_CODE_EVAL", 0) != "1":
159
+ raise ValueError(_WARNING)
160
+
161
+ if os.name == "nt":
162
+ raise NotImplementedError("This metric is currently not supported on Windows.")
163
+
164
+ with ThreadPoolExecutor(max_workers=num_workers) as executor:
165
+ futures = []
166
+ completion_id = Counter()
167
+ n_samples = 0
168
+ results = defaultdict(list)
169
+
170
+ for task_id, (candidates, test_case) in enumerate(zip(predictions, references)):
171
+ for candidate in candidates:
172
+ test_program = candidate + "\n" + test_case
173
+ args = (test_program, timeout, task_id, completion_id[task_id])
174
+ future = executor.submit(check_correctness, *args)
175
+ futures.append(future)
176
+ completion_id[task_id] += 1
177
+ n_samples += 1
178
+
179
+ for future in as_completed(futures):
180
+ result = future.result()
181
+ results[result["task_id"]].append((result["completion_id"], result))
182
+
183
+ total, correct = [], []
184
+ for result in results.values():
185
+ result.sort()
186
+ passed = [r[1]["passed"] for r in result]
187
+ total.append(len(passed))
188
+ correct.append(sum(passed))
189
+ total = np.array(total)
190
+ correct = np.array(correct)
191
+
192
+ ks = k
193
+ pass_at_k = {f"pass@{k}": estimate_pass_at_k(total, correct, k).mean() for k in ks if (total >= k).all()}
194
+
195
+ return pass_at_k, results
196
+
197
+
198
+ def estimate_pass_at_k(num_samples, num_correct, k):
199
+ """Estimates pass@k of each problem and returns them in an array."""
200
+
201
+ def estimator(n: int, c: int, k: int) -> float:
202
+ """Calculates 1 - comb(n - c, k) / comb(n, k)."""
203
+ if n - c < k:
204
+ return 1.0
205
+ return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
206
+
207
+ if isinstance(num_samples, int):
208
+ num_samples_it = itertools.repeat(num_samples, len(num_correct))
209
+ else:
210
+ assert len(num_samples) == len(num_correct)
211
+ num_samples_it = iter(num_samples)
212
+
213
+ return np.array([estimator(int(n), int(c), k) for n, c in zip(num_samples_it, num_correct)])
execute.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # This code is adapted from OpenAI's release
16
+ # https://github.com/openai/human-eval/blob/master/human_eval/execution.py
17
+
18
+ import contextlib
19
+ import faulthandler
20
+ import io
21
+ import multiprocessing
22
+ import os
23
+ import platform
24
+ import signal
25
+ import tempfile
26
+
27
+
28
+ def check_correctness(check_program, timeout, task_id, completion_id):
29
+ """
30
+ Evaluates the functional correctness of a completion by running the test
31
+ suite provided in the problem.
32
+
33
+ :param completion_id: an optional completion ID so we can match
34
+ the results later even if execution finishes asynchronously.
35
+ """
36
+ manager = multiprocessing.Manager()
37
+ result = manager.list()
38
+
39
+ p = multiprocessing.Process(target=unsafe_execute, args=(check_program, result, timeout))
40
+ p.start()
41
+ p.join(timeout=timeout + 1)
42
+ if p.is_alive():
43
+ p.kill()
44
+
45
+ if not result:
46
+ result.append("timed out")
47
+
48
+ return dict(
49
+ task_id=task_id,
50
+ passed=result[0] == "passed",
51
+ result=result[0],
52
+ completion_id=completion_id,
53
+ )
54
+
55
+
56
+ def unsafe_execute(check_program, result, timeout):
57
+
58
+ with create_tempdir():
59
+
60
+ # These system calls are needed when cleaning up tempdir.
61
+ import os
62
+ import shutil
63
+
64
+ rmtree = shutil.rmtree
65
+ rmdir = os.rmdir
66
+ chdir = os.chdir
67
+
68
+ # Disable functionalities that can make destructive changes to the test.
69
+ reliability_guard()
70
+
71
+ # Run program.
72
+ try:
73
+ exec_globals = {}
74
+ with swallow_io():
75
+ with time_limit(timeout):
76
+ exec(check_program, exec_globals)
77
+ result.append("passed")
78
+ except TimeoutException:
79
+ result.append("timed out")
80
+ except BaseException as e:
81
+ result.append(f"failed: {e}")
82
+
83
+ # Needed for cleaning up.
84
+ shutil.rmtree = rmtree
85
+ os.rmdir = rmdir
86
+ os.chdir = chdir
87
+
88
+
89
+ @contextlib.contextmanager
90
+ def time_limit(seconds):
91
+ def signal_handler(signum, frame):
92
+ raise TimeoutException("Timed out!")
93
+
94
+ signal.setitimer(signal.ITIMER_REAL, seconds)
95
+ signal.signal(signal.SIGALRM, signal_handler)
96
+ try:
97
+ yield
98
+ finally:
99
+ signal.setitimer(signal.ITIMER_REAL, 0)
100
+
101
+
102
+ @contextlib.contextmanager
103
+ def swallow_io():
104
+ stream = WriteOnlyStringIO()
105
+ with contextlib.redirect_stdout(stream):
106
+ with contextlib.redirect_stderr(stream):
107
+ with redirect_stdin(stream):
108
+ yield
109
+
110
+
111
+ @contextlib.contextmanager
112
+ def create_tempdir():
113
+ with tempfile.TemporaryDirectory() as dirname:
114
+ with chdir(dirname):
115
+ yield dirname
116
+
117
+
118
+ class TimeoutException(Exception):
119
+ pass
120
+
121
+
122
+ class WriteOnlyStringIO(io.StringIO):
123
+ """StringIO that throws an exception when it's read from"""
124
+
125
+ def read(self, *args, **kwargs):
126
+ raise OSError
127
+
128
+ def readline(self, *args, **kwargs):
129
+ raise OSError
130
+
131
+ def readlines(self, *args, **kwargs):
132
+ raise OSError
133
+
134
+ def readable(self, *args, **kwargs):
135
+ """Returns True if the IO object can be read."""
136
+ return False
137
+
138
+
139
+ class redirect_stdin(contextlib._RedirectStream): # type: ignore
140
+ _stream = "stdin"
141
+
142
+
143
+ @contextlib.contextmanager
144
+ def chdir(root):
145
+ if root == ".":
146
+ yield
147
+ return
148
+ cwd = os.getcwd()
149
+ os.chdir(root)
150
+ try:
151
+ yield
152
+ except BaseException as exc:
153
+ raise exc
154
+ finally:
155
+ os.chdir(cwd)
156
+
157
+
158
+ def reliability_guard(maximum_memory_bytes=None):
159
+ """
160
+ This disables various destructive functions and prevents the generated code
161
+ from interfering with the test (e.g. fork bomb, killing other processes,
162
+ removing filesystem files, etc.)
163
+
164
+ WARNING
165
+ This function is NOT a security sandbox. Untrusted code, including, model-
166
+ generated code, should not be blindly executed outside of one. See the
167
+ Codex paper for more information about OpenAI's code sandbox, and proceed
168
+ with caution.
169
+ """
170
+
171
+ if maximum_memory_bytes is not None:
172
+ import resource
173
+
174
+ resource.setrlimit(resource.RLIMIT_AS, (maximum_memory_bytes, maximum_memory_bytes))
175
+ resource.setrlimit(resource.RLIMIT_DATA, (maximum_memory_bytes, maximum_memory_bytes))
176
+ if not platform.uname().system == "Darwin":
177
+ resource.setrlimit(resource.RLIMIT_STACK, (maximum_memory_bytes, maximum_memory_bytes))
178
+
179
+ faulthandler.disable()
180
+
181
+ import builtins
182
+
183
+ builtins.exit = None
184
+ builtins.quit = None
185
+
186
+ import os
187
+
188
+ os.environ["OMP_NUM_THREADS"] = "1"
189
+
190
+ os.kill = None
191
+ os.system = None
192
+ os.putenv = None
193
+ os.remove = None
194
+ os.removedirs = None
195
+ os.rmdir = None
196
+ os.fchdir = None
197
+ os.setuid = None
198
+ os.fork = None
199
+ os.forkpty = None
200
+ os.killpg = None
201
+ os.rename = None
202
+ os.renames = None
203
+ os.truncate = None
204
+ os.replace = None
205
+ os.unlink = None
206
+ os.fchmod = None
207
+ os.fchown = None
208
+ os.chmod = None
209
+ os.chown = None
210
+ os.chroot = None
211
+ os.fchdir = None
212
+ os.lchflags = None
213
+ os.lchmod = None
214
+ os.lchown = None
215
+ os.getcwd = None
216
+ os.chdir = None
217
+
218
+ import shutil
219
+
220
+ shutil.rmtree = None
221
+ shutil.move = None
222
+ shutil.chown = None
223
+
224
+ import subprocess
225
+
226
+ subprocess.Popen = None # type: ignore
227
+
228
+ __builtins__["help"] = None
229
+
230
+ import sys
231
+
232
+ sys.modules["ipdb"] = None
233
+ sys.modules["joblib"] = None
234
+ sys.modules["resource"] = None
235
+ sys.modules["psutil"] = None
236
+ sys.modules["tkinter"] = None
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ git+https://github.com/huggingface/evaluate@8b9373dc8693ffe0244a52551ac5573cffa503aa