Skip to content

Commit 77c879d

Browse files
authored
Adding BigCodeBench (#3186)
1 parent e577004 commit 77c879d

15 files changed

+691
-10
lines changed

MANIFEST.in

+1
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ recursive-include src/helm/benchmark/ *.json
44
recursive-include src/helm/benchmark/static/ *.css *.html *.js *.png *.yaml
55
recursive-include src/helm/benchmark/static_build/ *.css *.html *.js *.png *.yaml
66
recursive-include src/helm/config/ *.yaml
7+
recursive-include src/helm/benchmark/annotation/omni_math/ *.txt

setup.cfg

+1
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ metrics =
8181
sacrebleu~=2.2.1 # For disinformation_metrics, machine_translation_metrics
8282
langdetect~=1.0.9 # For ifeval_metrics
8383
immutabledict~=4.2.0 # For ifeval_metrics
84+
gradio_client~=1.3 # For bigcodebench_metrics
8485

8586
summarization =
8687
summ-eval~=0.892 # For summarization_metrics

src/helm/benchmark/annotation/annotator.py

+5
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@ def annotate(self, request_state: RequestState) -> Any:
2020
that are implementation specific."""
2121
pass
2222

23+
def annotate_all(self, request_states: List[RequestState]) -> List[Dict[str, Any]]:
24+
"""Fills the annotations field of all request states with additional information
25+
that are implementation specific."""
26+
return [self.annotate(request_state) for request_state in request_states]
27+
2328

2429
@dataclass(frozen=True)
2530
class AnnotatorSpec(ObjectSpec):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import ast
2+
import traceback
3+
import json
4+
5+
from helm.benchmark.adaptation.request_state import RequestState
6+
from helm.benchmark.annotation.annotator import Annotator
7+
from helm.common.hierarchical_logger import hlog
8+
9+
from typing import Any, List, Dict
10+
from gradio_client import Client, handle_file
11+
from tempfile import TemporaryDirectory
12+
from retrying import retry
13+
14+
15+
OUTPUT_FILENAME = "tmp_result.jsonl"
16+
17+
18+
def syntax_check(code, verbose=False):
19+
try:
20+
ast.parse(code)
21+
return True
22+
except (SyntaxError, MemoryError):
23+
if verbose:
24+
traceback.print_exc()
25+
return False
26+
27+
28+
def code_extract(text: str) -> str:
29+
lines = text.split("\n")
30+
longest_line_pair = (0, 0)
31+
longest_so_far = 0
32+
33+
for i in range(len(lines)):
34+
for j in range(i + 1, len(lines)):
35+
current_lines = "\n".join(lines[i : j + 1])
36+
if syntax_check(current_lines):
37+
current_length = sum(1 for line in lines[i : j + 1] if line.strip())
38+
if current_length > longest_so_far:
39+
longest_so_far = current_length
40+
longest_line_pair = (i, j)
41+
42+
return "\n".join(lines[longest_line_pair[0] : longest_line_pair[1] + 1])
43+
44+
45+
class BigCodeBenchAnnotator(Annotator):
46+
"""The BigCodeBench autograder."""
47+
48+
name = "bigcodebench"
49+
50+
def __init__(self):
51+
self.remote_execute_api = "https://bigcode-bigcodebench-evaluator.hf.space/"
52+
self.split = "instruct"
53+
self.subset = "full"
54+
self.pass_k = "1" # Original: "1,5,10"
55+
self.use_global_metric = True
56+
self.num_instances = 1140 # Instruct full seting of the dataset
57+
58+
def annotate(self, request_state: RequestState) -> Any:
59+
pass
60+
61+
@retry(stop_max_attempt_number=3, wait_fixed=4000)
62+
def predict_with_retry(self, filename: str):
63+
client = Client(self.remote_execute_api)
64+
results, evals = client.predict(
65+
split=self.split,
66+
subset=self.subset,
67+
samples=handle_file(filename),
68+
pass_k=self.pass_k,
69+
api_name="/predict",
70+
)
71+
pass_at_one = evals["pass@1"]
72+
return results, pass_at_one
73+
74+
def annotate_all(self, request_states: List[RequestState]) -> List[Dict[str, Any]]:
75+
assert all(request_state.result is not None for request_state in request_states)
76+
assert all(
77+
request_state.result is not None and len(request_state.result.completions) == 1
78+
for request_state in request_states
79+
)
80+
assert all(request_state.instance.extra_data for request_state in request_states)
81+
82+
with TemporaryDirectory() as tmpdir:
83+
with open(OUTPUT_FILENAME, "w") as file:
84+
hlog(f"Temp Dir: {tmpdir}")
85+
res = []
86+
for i in range(self.num_instances):
87+
init_line = f'{{"task_id": "BigCodeBench/{i}", "solution": ""}}\n'
88+
res.append(init_line)
89+
for request_state in request_states:
90+
line: str
91+
assert request_state.result is not None
92+
model_output_text = request_state.result.completions[0].text
93+
solution = code_extract(model_output_text)
94+
assert request_state.instance.id is not None
95+
idx = int(request_state.instance.id.split("/")[-1])
96+
res[idx] = json.dumps({"task_id": request_state.instance.id, "solution": solution}) + "\n"
97+
for line in res:
98+
file.write(line)
99+
100+
try:
101+
results, _ = self.predict_with_retry(OUTPUT_FILENAME)
102+
ret = [
103+
{"bigcodebench": {"pass_at_one": results["eval"][state.instance.id][0]["status"] == "pass"}}
104+
for state in request_states
105+
]
106+
return ret
107+
except Exception as e:
108+
hlog(f"Failed to complete the operation after 3 attempts. Exception: {e}")
109+
raise e
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
# CONTEXT #
2+
I am a teacher, and I have some high-level math problems. I am tasked with evaluating the correctness of a student's answer.
3+
Below, I am provided with a problem and a reference answer. Additionally, a student's answer is provided. My job is to assess whether the student's answer captures the same meaning as the reference answer, even when expressed with different wording or format.
4+
5+
# OBJECTIVE #
6+
I need you to judge whether the student's answer is correct given the ground truth answer.
7+
8+
Your tasks include:
9+
A. Identify Mathematical or Notational Equivalence: Pay special attention to any LaTeX expressions in both answers. Confirm that the mathematical relationships, variables, and operations conveyed are equivalent.
10+
B. Provide a Justification: Conclude with a brief explanation as to why you believe the student's output is correct or incorrect, highlighting any key differences in meaning or content.
11+
12+
# STYLE #
13+
Teaching report.
14+
15+
# TONE #
16+
Professional, scientific.
17+
18+
# AUDIENCE #
19+
Students. Enable them to better understand whether the answer they produce is correct.
20+
21+
# RESPONSE: MARKDOWN REPORT #
22+
## Student Final Answer
23+
[Extract the student's final answer, which is enclosed in "\\boxed{}".]
24+
## Equivalence Judgement
25+
[Whether the student's answer share the same meaning with the reference answer. (TRUE or FALSE)]
26+
## Justification
27+
[Conclude with a brief explanation as to why you believe the student's answer is correct or incorrect.]
28+
29+
30+
# ATTENTION #
31+
- The reference answer is ALWAYS correct. You should carefully judge whether the student gives the same answer as reference answer.
32+
- The Equivalence Judgement is only TRUE or FALSE. The answer is FALSE even if the student's final answer almost correct with a minor mistakes.
33+
- The answer is contained within the "boxed" section, so you can focus solely on comparing the content in the student's answer box with the reference answer, without needing to consider the intermediate steps.
34+
- Add "=== report over ===" at the end of the report.
35+
36+
<example math solution>
37+
**Question**:
38+
The numbers $1447$ , $1005$ and $1231$ have something in common: each is a $4$ -digit number beginning with $1$ that has exactly two identical digits. How many such numbers are there?
39+
40+
**Reference Answer**
41+
432
42+
43+
**Student Solution**:
44+
To determine how many 4-digit numbers beginning with 1 have exactly two identical digits, we need to consider the structure of these numbers. A number of this form can be represented as \(1abc\), where \(a\), \(b\), and \(c\) are digits from 0 to 9, and exactly one of the digits \(a\), \(b\), or \(c\) is 1, while the other two are different from each other and different from 1.
45+
46+
We can break down the problem into the following steps:
47+
48+
1. **Choose the digit that is 1**: There are 3 positions (a, b, c) where the digit 1 can be placed. So, there are 3 choices for the position of the digit 1.
49+
50+
2. **Choose the other two digits**: The remaining two digits must be different from each other and different from 1. Therefore, we have 9 choices for the first of these two digits (0-9 except 1) and 8 choices for the second digit (0-9 except 1 and the first digit). This gives us \(9 \times 8 = 72\) choices for the other two digits.
51+
52+
Combining these choices, the total number of 4-digit numbers beginning with 1 that have exactly two identical digits is:
53+
\[3 \times 72 = 216.\]
54+
55+
Thus, the number of such numbers is \(\boxed{216}\).
56+
57+
</example math solution>
58+
59+
## Student Final Answer
60+
216
61+
62+
## Equivalence Judgement
63+
FALSE
64+
65+
## Justification
66+
The student's answer of 216 is incorrect in the context of the problem, which asks for the total count of 4-digit numbers beginning with 1 that have exactly two identical digits. The reference answer is 432.
67+
In the student's solution, they consider only cases where the digit '1' is one of the identical digits. However, the problem also includes the scenario where the identical digits could be different from '1'. Thus, the student's calculation does not account for all valid configurations. The discrepancy in figures indicates that the student's answer does not share the same meaning as the reference answer.
68+
69+
=== report over ===
70+
71+
72+
<example math solution>
73+
**Question**:
74+
Susana and Brenda play a game writing polynomials on the board. Susana starts and they play taking turns.
75+
1) On the preparatory turn (turn 0), Susana choose a positive integer $n_0$ and writes the polynomial $P_0(x)=n_0$.
76+
2) On turn 1, Brenda choose a positive integer $n_1$, different from $n_0$, and either writes the polynomial
77+
78+
$$P_1(x)=n_1x+P_0(x) \textup{ or } P_1(x)=n_1x-P_0(x)$$
79+
80+
3) In general, on turn $k$, the respective player chooses an integer $n_k$, different from $n_0, n_1, \ldots, n_{k-1}$, and either writes the polynomial
81+
$$P_k(x)=n_kx^k+P_{k-1}(x) \textup{ or } P_k(x)=n_kx^k-P_{k-1}(x)$$
82+
The first player to write a polynomial with at least one whole whole number root wins. Find and describe a winning strategy.
83+
84+
**Reference Answer**
85+
\\text{No winning strategy; the game can last indefinitely.}
86+
87+
**Student Solution**:
88+
To determine a winning strategy for Susana, we need to analyze the game and the conditions under which a player can win. The goal is to write a polynomial that has at least one integer root.
89+
90+
Let's start by examining the polynomials that are written on the board after each turn.
91+
92+
1. On turn 0, Susana writes the polynomial \( P_0(x) = n_0 \), where \( n_0 \) is a positive integer. This polynomial is a constant polynomial with no integer roots unless \( n_0 = 0 \), which is not allowed since \( n_0 \) is a positive integer.
93+
94+
2. On turn 1, Brenda chooses a positive integer \( n_1 \) different from \( n_0 \) and writes either \( P_1(x) = n_1 x + P_0(x) = n_1 x + n_0 \) or \( P_1(x) = n_1 x - P_0(x) = n_1 x - n_0 \). In both cases, \( P_1(x) \) is a linear polynomial. A linear polynomial \( ax + b \) has an integer root if and only if \( b/a \) is an integer. Therefore, Brenda can choose \( n_1 \) and \( n_0 \) such that \( n_1 n_0 \) is divisible by \( n_1 \), which is always possible since \( n_1 \) and \( n_0 \) are different positive integers. For example, if \( n_1 = 2 \) and \( n_0 = 2 \), then \( P_1(x) = 2x - 2 \) has the integer root \( x = 1 \). However, since \( n_1 \) must be different from \( n_0 \), we need to consider the next turn.
95+
96+
3. On turn 2, Susana chooses a positive integer \( n_2 \) different from \( n_0 \) and \( n_1 \) and writes either \( P_2(x) = n_2 x^2 + P_1(x) \) or \( P_2(x) = n_2 x^2 - P_1(x) \). To ensure a win, Susana should choose \( n_2 \) such that the resulting polynomial has an integer root. Notice that if \( P_1(x) = n_1 x + n_0 \) or \( P_1(x) = n_1 x - n_0 \), then \( P_2(x) = n_2 x^2 + P_1(x) \) or \( P_2(x) = n_2 x^2 - P_1(x) \) will have an integer root if \( n_2 \) is chosen appropriately. For example, if \( P_1(x) = 2x - 2 \), then \( P_2(x) = n_2 x^2 + 2x - 2 \) or \( P_2(x) = n_2 x^2 - 2x + 2 \) will have an integer root if \( n_2 \) is chosen such that the polynomial can be factored to have an integer root.
97+
98+
By following this strategy, Susana can always choose \( n_2 \) such that the resulting polynomial has an integer root. Therefore, Susana has a winning strategy.
99+
100+
The winning strategy for Susana is to choose \( n_2 \) such that the resulting polynomial has an integer root. Specifically, if \( P_1(x) = n_1 x + n_0 \) or \( P_1(x) = n_1 x - n_0 \), then Susana should choose \( n_2 \) such that \( P_2(x) = n_2 x^2 + P_1(x) \) or \( P_2(x) = n_2 x^2 - P_1(x) \) has an integer root.
101+
102+
The answer is: \(\boxed{\text{Susana has a winning strategy.}}\)
103+
104+
</example math solution>
105+
106+
107+
## Student Final Answer
108+
\text{Susana has a winning strategy.}
109+
110+
## Equivalence Judgement
111+
FALSE
112+
113+
## Justification
114+
The student's answer states that "Susana has a winning strategy," which is not in agreement with the reference answer indicating "No winning strategy; the game can last indefinitely." The essence of the problem is that neither player can guarantee a win because the game can go on indefinitely without either player being able to write a polynomial with an integer root. The student's conclusion contradicts this, suggesting that a specific winning strategy exists for Susana, which is fundamentally incorrect according to the problem's conditions. Thus, the student's answer does not capture the same meaning as the reference answer.
115+
116+
117+
=== report over ===
118+
119+
<example math solution>
120+
**Question**:
121+
Determine if there exists a (three-variable) polynomial $P(x,y,z)$ with integer coefficients satisfying the following property: a positive integer $n$ is [i]not[/i] a perfect square if and only if there is a triple $(x,y,z)$ of positive integers such that $P(x,y,z) = n$.
122+
123+
**Reference Answer**
124+
P(x,y,z) = x^2 + y^2 + z^2 + 2xyz
125+
126+
**Student Solution**:
127+
**Claim:** There exists a three-variable polynomial $P(x, y
128+
129+
</example math solution>
130+
131+
## Student Final Answer
132+
None
133+
134+
## Equivalence Judgement
135+
FALSE
136+
137+
## Justification
138+
The student's answer does not provide a final conclusion and the final answer is missing, which indicates a lack of conclusion.
139+
140+
=== report over ===
141+
142+
<math solution>
143+
**Question**:
144+
{{Problem}}
145+
146+
**Reference Answer**
147+
{{Reference Answer}}
148+
149+
**Student Solution**:
150+
{{Solution}}
151+
152+
</math solution>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
from typing import Any
2+
from importlib.resources import files
3+
4+
from helm.benchmark.adaptation.request_state import RequestState
5+
from helm.benchmark.annotation.annotator import Annotator
6+
from helm.clients.auto_client import AutoClient
7+
from helm.common.request import Request
8+
9+
10+
# Following https://github.com/KbsdJames/Omni-MATH/blob/main/GPT_eval/get_result.py
11+
def parse_report(report):
12+
parts = report.split("## ")
13+
data = {}
14+
for part in parts[1:]:
15+
lines = part.strip().split("\n")
16+
title = lines[0].strip()
17+
content = "\n".join(lines[1:]).strip()
18+
if title == "Justification":
19+
data[title] = content
20+
else:
21+
data[title] = lines[1].strip() if len(lines) > 1 else ""
22+
return data
23+
24+
25+
class OmniMATHAnnotator(Annotator):
26+
"""The Omni-MATH autograder."""
27+
28+
name = "omni_math"
29+
30+
def __init__(self, auto_client: AutoClient):
31+
self._auto_client = auto_client
32+
template_path = files("src.helm.benchmark.annotation.omni_math").joinpath("gpt_evaluation_template.txt")
33+
with template_path.open("r") as file:
34+
self._score_template = file.read()
35+
36+
def annotate(self, request_state: RequestState) -> Any:
37+
assert request_state.result
38+
assert len(request_state.result.completions) == 1
39+
prompt_template = self._score_template
40+
model_output_text = request_state.result.completions[0].text
41+
annotator_prompt = (
42+
prompt_template.replace("{{Problem}}", request_state.instance.input.text)
43+
.replace("{{Reference Answer}}", request_state.instance.references[0].output.text)
44+
.replace("{{Solution}}", model_output_text)
45+
)
46+
if not model_output_text.strip():
47+
return {"prompt_text": annotator_prompt, "correctness": 0.0}
48+
49+
annotator_request = Request(
50+
model="openai/gpt-4o-2024-05-13",
51+
model_deployment="openai/gpt-4o-2024-05-13",
52+
prompt=annotator_prompt,
53+
temperature=0.0,
54+
max_tokens=1000,
55+
)
56+
annotator_response = self._auto_client.make_request(annotator_request)
57+
if not annotator_response.success:
58+
raise Exception(f"Annotation request failed: {annotator_response.error}")
59+
assert len(annotator_response.completions) == 1
60+
annotator_response_text = annotator_response.completions[0].text
61+
62+
info = parse_report(annotator_response_text)
63+
64+
correctness = info.get("Equivalence Judgement", "FALSE")
65+
66+
if correctness == "TRUE":
67+
return {"prompt_text": annotator_prompt, "correctness": 1.0}
68+
else:
69+
return {"prompt_text": annotator_prompt, "correctness": 0.0}

0 commit comments

Comments
 (0)