Download tasks/pb-advanced-017/tests/grade_task.py from HuggingFaceSwarms/IMO-ProofBench: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/datasets/HuggingFaceSwarms/IMO-ProofBench/resolve/main/tasks/pb-advanced-017/tests/grade_task.py
- Command line
-
hf download hf://datasets/HuggingFaceSwarms/IMO-ProofBench/tasks/pb-advanced-017/tests/grade_task.py
-
curl -L -o grade_task.py https://huggingface.co/datasets/HuggingFaceSwarms/IMO-ProofBench/resolve/main/tasks/pb-advanced-017/tests/grade_task.py
12.9 kB
| """Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. | |
| The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) | |
| are adapted from CMU-AIRe/QED-Nano (Apache License 2.0, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718): | |
| https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench | |
| See LICENSE and NOTICE for details. | |
| """ | |
| import email.utils | |
| import json | |
| import os | |
| import re | |
| import stat | |
| import sys | |
| import time | |
| import urllib.error | |
| import urllib.request | |
| LIMIT = 200_000 | |
| MIN_NON_WS_CHARS = 20 | |
| DEFAULT_JUDGE_MODEL = "moonshotai/Kimi-K3.1-Pro" | |
| DEFAULT_JUDGE_BASE_URL = "https://router.huggingface.co/v1" | |
| DEFAULT_TIMEOUT_SEC = 240.0 | |
| DEFAULT_MAX_ATTEMPTS = 5 | |
| MAX_RETRY_AFTER_SEC = 120.0 | |
| MAX_TOKENS_SCHEDULE = (16384, 32768, 65536) | |
| RETRYABLE_HTTP_CODES = frozenset({408, 429, 500, 502, 503, 504}) | |
| def read_own(path): | |
| """Reject links, special files, multiple hard links, and oversized files.""" | |
| parts = os.path.abspath(path).split("/")[1:] | |
| folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY) | |
| try: | |
| for part in parts[:-1]: | |
| inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder) | |
| os.close(folder) | |
| folder = inner | |
| fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder) | |
| finally: | |
| os.close(folder) | |
| with os.fdopen(fd, "rb") as stream: | |
| info = os.fstat(stream.fileno()) | |
| if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1: | |
| raise ValueError("not a regular file with one link") | |
| data = stream.read(LIMIT + 1) | |
| if len(data) > LIMIT: | |
| raise ValueError(f"file exceeds {LIMIT} bytes") | |
| return data | |
| def write_new(path, data): | |
| try: | |
| os.unlink(path) | |
| except FileNotFoundError: | |
| pass | |
| fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644) | |
| with os.fdopen(fd, "wb") as handle: | |
| handle.write(data) | |
| def write_json(path, payload): | |
| write_new(path, (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")) | |
| def remove_self_evaluation(text): | |
| """Apply QED-Nano's evaluation-heading cleanup to a candidate solution.""" | |
| pattern = r"(?ms)^#+\s*[*\s]*(?:(?:Self|Final)\s*[*\s]*){0,2}Evaluation\b.*$" | |
| return re.sub(pattern, "", text).strip() | |
| def parse_proof_points(text): | |
| """Parse the first <points>N out of 7</points> tag with N in {0, 1, 6, 7}.""" | |
| match = re.search(r"<points(?:\s[^>]*)?>(.*?)</points>", text, re.DOTALL) | |
| points = ( | |
| re.fullmatch(r"\s*([0167])\s+out\s+of\s+7\s*", match.group(1), re.IGNORECASE) | |
| if match | |
| else None | |
| ) | |
| if points is None: | |
| raise ValueError("Judge must return a first <points>N out of 7</points> with N in 0, 1, 6, 7") | |
| return int(points.group(1)) | |
| def parse_retry_after(headers): | |
| if not headers: | |
| return None | |
| raw = headers.get("Retry-After") | |
| if raw is None: | |
| return None | |
| text = str(raw).strip() | |
| if not text: | |
| return None | |
| try: | |
| seconds = float(text) | |
| except ValueError: | |
| try: | |
| dt = email.utils.parsedate_to_datetime(text) | |
| except (TypeError, ValueError): | |
| return None | |
| seconds = dt.timestamp() - time.time() | |
| if seconds <= 0: | |
| return 0.0 | |
| return min(seconds, MAX_RETRY_AFTER_SEC) | |
| class NonRetryableJudgeError(RuntimeError): | |
| """Raised on permanent client/configuration errors such as HTTP 400/401/403/404.""" | |
| def call_judge_once(prompt, model, base_url, api_key, max_tokens, timeout_sec): | |
| url = base_url.rstrip("/") + "/chat/completions" | |
| body = json.dumps( | |
| { | |
| "model": model, | |
| "messages": [{"role": "user", "content": prompt}], | |
| "max_tokens": max_tokens, | |
| } | |
| ).encode("utf-8") | |
| request = urllib.request.Request( | |
| url, | |
| data=body, | |
| headers={ | |
| "Authorization": f"Bearer {api_key}", | |
| "Content-Type": "application/json", | |
| "User-Agent": "harbor-imo-proofbench-verifier/1.0", | |
| }, | |
| method="POST", | |
| ) | |
| try: | |
| with urllib.request.urlopen(request, timeout=timeout_sec) as response: | |
| raw_body = response.read() | |
| except urllib.error.HTTPError as exc: | |
| err_snippet = "" | |
| try: | |
| err_snippet = exc.read().decode("utf-8", "replace")[:300] | |
| except Exception: | |
| pass | |
| retry_after = parse_retry_after(exc.headers) if exc.code in (429, 503) else None | |
| msg = f"HTTP {exc.code}: {err_snippet}".strip() | |
| if exc.code not in RETRYABLE_HTTP_CODES and not (500 <= exc.code <= 599): | |
| raise NonRetryableJudgeError(msg) from exc | |
| err = RuntimeError(msg) | |
| err.retry_after = retry_after | |
| raise err from exc | |
| if not raw_body.strip(): | |
| raise ValueError("Judge returned an empty HTTP body") | |
| data = json.loads(raw_body.decode("utf-8")) | |
| choices = data.get("choices") or [] | |
| content = (choices[0].get("message") or {}).get("content") if choices else None | |
| if not isinstance(content, str) or not content.strip(): | |
| raise ValueError("Judge returned empty message content") | |
| usage = data.get("usage") or {} | |
| return content, usage.get("completion_tokens") | |
| def judge_proof(prompt, model, base_url, api_key): | |
| max_attempts = max(1, int(os.environ.get("JUDGE_MAX_ATTEMPTS", str(DEFAULT_MAX_ATTEMPTS)))) | |
| timeout_sec = float(os.environ.get("JUDGE_TIMEOUT_SEC", str(DEFAULT_TIMEOUT_SEC))) | |
| base_delay = float(os.environ.get("JUDGE_RETRY_BASE_DELAY", "2.0")) | |
| last_error = None | |
| last_raw = "" | |
| for attempt in range(1, max_attempts + 1): | |
| max_tokens = MAX_TOKENS_SCHEDULE[min(attempt - 1, len(MAX_TOKENS_SCHEDULE) - 1)] | |
| try: | |
| raw, completion_tokens = call_judge_once( | |
| prompt, model, base_url, api_key, max_tokens, timeout_sec | |
| ) | |
| last_raw = raw | |
| points = parse_proof_points(raw) | |
| return points, raw, completion_tokens, attempt, None | |
| except NonRetryableJudgeError as exc: | |
| last_error = f"{type(exc).__name__}: {exc}" | |
| return None, last_raw, None, attempt, last_error | |
| except (urllib.error.URLError, TimeoutError, OSError, ValueError, RuntimeError) as exc: | |
| last_error = f"{type(exc).__name__}: {exc}" | |
| retry_after = getattr(exc, "retry_after", None) | |
| print( | |
| f"[imo-proofbench-verifier] attempt {attempt}/{max_attempts} failed: {last_error}", | |
| file=sys.stderr, | |
| flush=True, | |
| ) | |
| if attempt < max_attempts: | |
| delay = min(60.0, base_delay * (2 ** (attempt - 1))) | |
| if retry_after is not None: | |
| delay = max(delay, retry_after) | |
| if delay > 0: | |
| time.sleep(delay) | |
| return None, last_raw, None, max_attempts, last_error | |
| def main(): | |
| out = os.environ["VERIFIER_DIR"] | |
| tests_dir = os.environ["TESTS_DIR"] | |
| os.makedirs(out, exist_ok=True) | |
| for stale in ("reward.txt", "reward.json"): | |
| try: | |
| os.unlink(os.path.join(out, stale)) | |
| except FileNotFoundError: | |
| pass | |
| proof_out_path = os.path.join(out, "proof.md") | |
| try: | |
| os.unlink(proof_out_path) | |
| except FileNotFoundError: | |
| pass | |
| reference_bytes = open(os.path.join(tests_dir, "reference.json"), "rb").read() | |
| ref = json.loads(reference_bytes.decode("utf-8")) | |
| if ref.get("max_score") != 7: | |
| raise ValueError("Expected ProofBench reference with max_score=7") | |
| for field in ("problem", "solution", "grading_guidelines"): | |
| if not isinstance(ref.get(field), str): | |
| raise TypeError(f"Missing reference {field}") | |
| write_new(os.path.join(out, "reference.json"), reference_bytes) | |
| judge_model = (os.environ.get("JUDGE_MODEL") or DEFAULT_JUDGE_MODEL).strip() or DEFAULT_JUDGE_MODEL | |
| judge_base_url = ( | |
| (os.environ.get("JUDGE_BASE_URL") or DEFAULT_JUDGE_BASE_URL).strip() | |
| or DEFAULT_JUDGE_BASE_URL | |
| ) | |
| api_key = ( | |
| (os.environ.get("JUDGE_API_KEY") or "").strip() | |
| or (os.environ.get("HF_INFERENCE_TOKEN") or "").strip() | |
| ) | |
| structural_status = "missing" | |
| structural_reason = "proof unavailable or invalid" | |
| char_count = 0 | |
| non_ws_count = 0 | |
| proof = "" | |
| try: | |
| raw = read_own(os.environ["PROOF"]) | |
| proof = raw.decode("utf-8", "strict") | |
| char_count = len(proof) | |
| non_ws_count = sum(not ch.isspace() for ch in proof) | |
| write_new(proof_out_path, raw) | |
| if non_ws_count < MIN_NON_WS_CHARS: | |
| structural_status = "empty" | |
| structural_reason = f"fewer than {MIN_NON_WS_CHARS} non-whitespace characters" | |
| else: | |
| structural_status = "ok" | |
| structural_reason = "structurally valid submission" | |
| except (OSError, ValueError, UnicodeError) as exc: | |
| structural_reason = "proof unavailable or invalid: " + str(exc)[:200] | |
| structural = { | |
| "status": structural_status, | |
| "char_count": char_count, | |
| "non_whitespace_count": non_ws_count, | |
| "reason": structural_reason, | |
| } | |
| if structural_status != "ok": | |
| judgment = { | |
| "status": structural_status, | |
| "structural": structural, | |
| "judged_by_api": False, | |
| "judge_model": judge_model, | |
| "judge_base_url": judge_base_url, | |
| "points": 0, | |
| "max_score": 7, | |
| "reward": 0.0, | |
| "passed_6": False, | |
| "attempts": 0, | |
| "judge_output_tokens": 0, | |
| "raw_response": "", | |
| "reason": structural_reason, | |
| "error": None, | |
| } | |
| write_json(os.path.join(out, "judgment.json"), judgment) | |
| write_json(os.path.join(out, "reward.json"), {"reward": 0.0, "points": 0}) | |
| print(f"{structural_status}: points=0 reward=0.0 ({structural_reason})") | |
| return | |
| if not api_key: | |
| error_msg = "Missing judge API key: set JUDGE_API_KEY or HF_INFERENCE_TOKEN" | |
| judgment = { | |
| "status": "judge_error", | |
| "structural": structural, | |
| "judged_by_api": False, | |
| "judge_model": judge_model, | |
| "judge_base_url": judge_base_url, | |
| "points": None, | |
| "max_score": 7, | |
| "reward": None, | |
| "passed_6": None, | |
| "attempts": 0, | |
| "judge_output_tokens": None, | |
| "raw_response": "", | |
| "reason": error_msg, | |
| "error": error_msg, | |
| } | |
| write_json(os.path.join(out, "judgment.json"), judgment) | |
| print(f"ERROR: {error_msg}", file=sys.stderr) | |
| sys.exit(1) | |
| template = open(os.path.join(tests_dir, "proofbench_prompt.txt"), encoding="utf-8").read() | |
| prompt = template.format( | |
| problem_statement=ref["problem"], | |
| solution=ref["solution"], | |
| guidelines=ref["grading_guidelines"], | |
| student_answer=remove_self_evaluation(proof), | |
| ) | |
| points, raw_response, completion_tokens, attempts, error_msg = judge_proof( | |
| prompt, judge_model, judge_base_url, api_key | |
| ) | |
| if error_msg is not None: | |
| judgment = { | |
| "status": "judge_error", | |
| "structural": structural, | |
| "judged_by_api": True, | |
| "judge_model": judge_model, | |
| "judge_base_url": judge_base_url, | |
| "points": None, | |
| "max_score": 7, | |
| "reward": None, | |
| "passed_6": None, | |
| "attempts": attempts, | |
| "judge_output_tokens": None, | |
| "raw_response": raw_response, | |
| "reason": error_msg, | |
| "error": error_msg, | |
| } | |
| write_json(os.path.join(out, "judgment.json"), judgment) | |
| print(f"ERROR: judge failed after {attempts} attempt(s): {error_msg}", file=sys.stderr) | |
| sys.exit(1) | |
| reward = round(points / 7.0, 6) | |
| judgment = { | |
| "status": "judged", | |
| "structural": structural, | |
| "judged_by_api": True, | |
| "judge_model": judge_model, | |
| "judge_base_url": judge_base_url, | |
| "points": points, | |
| "max_score": 7, | |
| "reward": reward, | |
| "passed_6": points >= 6, | |
| "attempts": attempts, | |
| "judge_output_tokens": completion_tokens, | |
| "raw_response": raw_response, | |
| "reason": f"Judge awarded {points} out of 7", | |
| "error": None, | |
| } | |
| write_json(os.path.join(out, "judgment.json"), judgment) | |
| write_json(os.path.join(out, "reward.json"), {"reward": reward, "points": points}) | |
| print(f"judged: points={points}/7 reward={reward} attempts={attempts} model={judge_model}") | |
| if __name__ == "__main__": | |
| main() | |