diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/README.md b/README.md index 39736e0a3fb003f135860b8c585ff87b43ba8a64..b1a07ab10f90a381ea002aded31b93a5434b75ac 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ tags: 60 natural-language mathematical proof tasks adapted from Google DeepMind's [IMO-ProofBench v2](https://github.com/google-deepmind/superhuman/blob/8cea546c9c7209306b4d4ced7c5eacd51f23f928/imobench/proofbench_v2.csv), part of IMO-Bench. The data is from *Towards Robust Mathematical Reasoning* ([Luong et al., EMNLP 2025](https://aclanthology.org/2025.emnlp-main.1794/)). We convert each source row into a Harbor task and retain the original problem, reference solution and grading guidelines. No GradingBench rows are included. Copyright 2025 Google LLC. Upstream software is [Apache-2.0](https://www.apache.org/licenses/LICENSE-2.0); its other materials, including benchmark content, are [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). The dataset card's Apache license tag refers to software; benchmark content remains CC BY 4.0. See [upstream license and citation](https://github.com/google-deepmind/superhuman/blob/main/imobench/README.md). +The rubric prompt (`tests/proofbench_prompt.txt`) and adapted self-evaluation cleanup / `` parser in `tests/grade_task.py` are derived from [CMU-AIRe/QED-Nano](https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718) under the Apache License 2.0 (see `LICENSE` and `NOTICE`). + | Category | Basic | Advanced | Total | |---|---:|---:|---:| | Algebra | 8 | 8 | 16 | @@ -24,10 +26,29 @@ Basic and Advanced are the groups in the problem IDs. The source `Level` is a se ## Running and grading -Each `tasks/` contains a Harbor 1.4 task, an instruction, a reference oracle and an offline verifier. The solver must produce `/app/proof.md` using its own reasoning and local tools without web lookups or external models. The verifier reads a regular single-link UTF-8 file of at most 200,000 bytes, rejecting symlinks in the path, hard links and special files. At least 20 non-whitespace characters are required. `PROOF` and `VERIFIER_DIR` override paths for local testing. The verifier copies the submission and `reference.json` to the verifier directory, alongside `grade.json` and `reward.txt`. Missing, invalid or too-short proofs receive reward 0; structurally valid submissions receive reward 1 and status `submitted_for_judge`. Invalid files use status `missing`, while short or whitespace-only files use `empty`. +Each `tasks/` is a Harbor 1.4 task (tested with Harbor 0.25.0) containing an instruction, a reference oracle, and a Harbor-native LLM-judged verifier. + +- **Agent phase:** network-isolated (`[agent].network_mode = "allowlist"` with no allowed hosts). The solver writes `/app/proof.md` using its own reasoning and local tools without web lookups or external models. Harbor collects `artifacts = ["/app/proof.md"]` after the agent finishes. +- **Verifier phase:** runs in a dedicated container (`[verifier].environment_mode = "separate"`) with `network_mode = "allowlist"` and `allowed_hosts = ["router.huggingface.co"]`, so the agent can never inspect or tamper with verifier credentials and `harbor jobs regrade` works directly on collected artifacts. +- **Structural validation:** `tests/grade_task.py` reads `/app/proof.md` as a regular single-link UTF-8 file of at most 200,000 bytes (rejecting symlinks, hard links, and special files) with at least 20 non-whitespace characters. Missing, invalid, or empty proofs receive `reward.json = {"reward": 0.0, "points": 0}` and `judgment.json` with exit code `0`. +- **LLM rubric judging:** Structurally valid proofs are stripped of self-evaluation headings (`remove_self_evaluation`), formatted with QED-Nano's verbatim `tests/proofbench_prompt.txt` rubric against `tests/reference.json`, and graded by an OpenAI-compatible chat completions endpoint using Python stdlib `urllib.request` with bounded retries. The judge returns a discrete IMO score `points ∈ {0, 1, 6, 7}` in `N out of 7`. The verifier writes: + - `/logs/verifier/reward.json`: `{"reward": round(points / 7.0, 6), "points": points}` + - `/logs/verifier/judgment.json`: full diagnostic record (judge model, base URL, parsed points, raw judge output, structural check) +- **Fail-loud on judge/infra errors:** If no API key is configured, the HTTP request fails after retries, or the judge output fails `` parsing, the verifier writes error diagnostics to `judgment.json` and stderr, writes **no** `reward.json`, and exits non-zero so Harbor records a verifier error instead of a false `0`. + +### Verifier environment variables + +Configured under `[verifier.env]` in each `task.toml`: + +| Variable | Default | Purpose | +|---|---|---| +| `HF_INFERENCE_TOKEN` | *(empty)* | Hugging Face Router bearer token (used when `JUDGE_API_KEY` is unset) | +| `JUDGE_API_KEY` | *(empty)* | Explicit API key override (takes precedence over `HF_INFERENCE_TOKEN`) | +| `JUDGE_MODEL` | `moonshotai/Kimi-K3.1-Pro` | Judge model passed to `/chat/completions` | +| `JUDGE_BASE_URL` | `https://router.huggingface.co/v1` | OpenAI-compatible judge API base URL (must match `allowed_hosts` when allowlisted) | -**This reward measures submission validity only, not mathematical correctness.** An external rubric-guided LLM judge must evaluate the submitted proof against the reference solution and grading guidelines in `reference.json` and assign an IMO score from 0 to 7; report percentage as 100 × score / 7. No external judge is bundled, and an oracle pass demonstrates only structural validity. The reference solution is for evaluation and oracle testing and must not be exposed to the solver during an evaluation. +For local testing of `tests/test.sh`, `PROOF` and `VERIFIER_DIR` override `/app/proof.md` and `/logs/verifier`. -`tasks/manifest.json` indexes all tasks; `subsets/basic_tasks.jsonl`, `advanced_tasks.jsonl`, and `all_tasks.jsonl` index 30, 30, and 60 tasks respectively. Each JSONL row includes its task path and metadata. +`tasks/manifest.json` indexes all tasks; `subsets/basic_tasks.jsonl`, `advanced_tasks.jsonl`, and `all_tasks.jsonl` index 30, 30, and 60 tasks respectively. For judge calibration, upstream [gradingbench.csv](https://github.com/google-deepmind/superhuman/blob/main/imobench/gradingbench.csv) contains 1,000 examples with columns `Grading ID`, `Problem ID`, `Problem`, `Solution`, `Grading guidelines`, `Response`, `Points`, `Reward`, and `Problem Source`. It is separate from this dataset and is not included as proof tasks. diff --git a/tasks/pb-advanced-001/task.toml b/tasks/pb-advanced-001/task.toml index 98b035ec10cfcda89527c583051e35ebfee8bd0c..c0b8683b27877d5f18f44c7618086f982bd0c4cc 100644 --- a/tasks/pb-advanced-001/task.toml +++ b/tasks/pb-advanced-001/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-001/tests/NOTICE b/tasks/pb-advanced-001/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-001/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-001/tests/grade_task.py b/tasks/pb-advanced-001/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-001/tests/grade_task.py +++ b/tasks/pb-advanced-001/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-001/tests/proofbench_prompt.txt b/tasks/pb-advanced-001/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-001/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-001/tests/test.sh b/tasks/pb-advanced-001/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-001/tests/test.sh +++ b/tasks/pb-advanced-001/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-002/task.toml b/tasks/pb-advanced-002/task.toml index 008b8ecc6dbe92d5ba47304d37abceec22685132..e1c5a0308800c427102c4ce3f81b32a5b080627f 100644 --- a/tasks/pb-advanced-002/task.toml +++ b/tasks/pb-advanced-002/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-002/tests/NOTICE b/tasks/pb-advanced-002/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-002/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-002/tests/grade_task.py b/tasks/pb-advanced-002/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-002/tests/grade_task.py +++ b/tasks/pb-advanced-002/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-002/tests/proofbench_prompt.txt b/tasks/pb-advanced-002/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-002/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-002/tests/test.sh b/tasks/pb-advanced-002/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-002/tests/test.sh +++ b/tasks/pb-advanced-002/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-003/task.toml b/tasks/pb-advanced-003/task.toml index 23bfcf53e4b64c5e8dcb0a4b3705685df2361b1d..84dcf74400654fb0780eeab841bf063c7366bd27 100644 --- a/tasks/pb-advanced-003/task.toml +++ b/tasks/pb-advanced-003/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-003/tests/NOTICE b/tasks/pb-advanced-003/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-003/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-003/tests/grade_task.py b/tasks/pb-advanced-003/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-003/tests/grade_task.py +++ b/tasks/pb-advanced-003/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-003/tests/proofbench_prompt.txt b/tasks/pb-advanced-003/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-003/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-003/tests/test.sh b/tasks/pb-advanced-003/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-003/tests/test.sh +++ b/tasks/pb-advanced-003/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-004/task.toml b/tasks/pb-advanced-004/task.toml index e7d43425f1c5e6ad89d0630c2958d5ccc6eaced5..3ffd1a58ef2841da2e20458928b58b9ba70c1184 100644 --- a/tasks/pb-advanced-004/task.toml +++ b/tasks/pb-advanced-004/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-004/tests/NOTICE b/tasks/pb-advanced-004/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-004/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-004/tests/grade_task.py b/tasks/pb-advanced-004/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-004/tests/grade_task.py +++ b/tasks/pb-advanced-004/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-004/tests/proofbench_prompt.txt b/tasks/pb-advanced-004/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-004/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-004/tests/test.sh b/tasks/pb-advanced-004/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-004/tests/test.sh +++ b/tasks/pb-advanced-004/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-005/task.toml b/tasks/pb-advanced-005/task.toml index 3e6caa2bd7eb707e3c692287075b9c1ba560a903..33dbd73c6dbef659c0e8b3df4d35008f27acca10 100644 --- a/tasks/pb-advanced-005/task.toml +++ b/tasks/pb-advanced-005/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-005/tests/NOTICE b/tasks/pb-advanced-005/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-005/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-005/tests/grade_task.py b/tasks/pb-advanced-005/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-005/tests/grade_task.py +++ b/tasks/pb-advanced-005/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-005/tests/proofbench_prompt.txt b/tasks/pb-advanced-005/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-005/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-005/tests/test.sh b/tasks/pb-advanced-005/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-005/tests/test.sh +++ b/tasks/pb-advanced-005/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-006/task.toml b/tasks/pb-advanced-006/task.toml index 7d1de5c90b41ff7c64c9af43a36dbf2a45a78aa6..679c8b6ea5239a8f7db632f5586449030bfb1331 100644 --- a/tasks/pb-advanced-006/task.toml +++ b/tasks/pb-advanced-006/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-006/tests/NOTICE b/tasks/pb-advanced-006/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-006/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-006/tests/grade_task.py b/tasks/pb-advanced-006/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-006/tests/grade_task.py +++ b/tasks/pb-advanced-006/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-006/tests/proofbench_prompt.txt b/tasks/pb-advanced-006/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-006/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-006/tests/test.sh b/tasks/pb-advanced-006/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-006/tests/test.sh +++ b/tasks/pb-advanced-006/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-007/task.toml b/tasks/pb-advanced-007/task.toml index 60a574f56b5920643e9f76d4ada4bca39cef6d32..68bf8244138a76e745eb0e1e37619ab65c7c623a 100644 --- a/tasks/pb-advanced-007/task.toml +++ b/tasks/pb-advanced-007/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-007/tests/NOTICE b/tasks/pb-advanced-007/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-007/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-007/tests/grade_task.py b/tasks/pb-advanced-007/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-007/tests/grade_task.py +++ b/tasks/pb-advanced-007/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-007/tests/proofbench_prompt.txt b/tasks/pb-advanced-007/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-007/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-007/tests/test.sh b/tasks/pb-advanced-007/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-007/tests/test.sh +++ b/tasks/pb-advanced-007/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-008/task.toml b/tasks/pb-advanced-008/task.toml index 2ea71e09235f6f435ad4ce0523688d32991b3ba2..cfb9e3bfebe35a8b4ede658e2f1e6c0fa141cf8c 100644 --- a/tasks/pb-advanced-008/task.toml +++ b/tasks/pb-advanced-008/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-008/tests/NOTICE b/tasks/pb-advanced-008/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-008/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-008/tests/grade_task.py b/tasks/pb-advanced-008/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-008/tests/grade_task.py +++ b/tasks/pb-advanced-008/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-008/tests/proofbench_prompt.txt b/tasks/pb-advanced-008/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-008/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-008/tests/test.sh b/tasks/pb-advanced-008/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-008/tests/test.sh +++ b/tasks/pb-advanced-008/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-009/task.toml b/tasks/pb-advanced-009/task.toml index 220aaafbbf626d51393081dfba79ac05a02542a9..ac4a949e2efdfb095e1573bd1e888f4a0bf1f328 100644 --- a/tasks/pb-advanced-009/task.toml +++ b/tasks/pb-advanced-009/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-009/tests/NOTICE b/tasks/pb-advanced-009/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-009/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-009/tests/grade_task.py b/tasks/pb-advanced-009/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-009/tests/grade_task.py +++ b/tasks/pb-advanced-009/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-009/tests/proofbench_prompt.txt b/tasks/pb-advanced-009/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-009/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-009/tests/test.sh b/tasks/pb-advanced-009/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-009/tests/test.sh +++ b/tasks/pb-advanced-009/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-010/task.toml b/tasks/pb-advanced-010/task.toml index 241d16d0c7e3e0203f45dd415b00bb3ebbb43675..1053e23fb45dbed8319e6a8f195e720de85f0b6a 100644 --- a/tasks/pb-advanced-010/task.toml +++ b/tasks/pb-advanced-010/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-010/tests/NOTICE b/tasks/pb-advanced-010/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-010/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-010/tests/grade_task.py b/tasks/pb-advanced-010/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-010/tests/grade_task.py +++ b/tasks/pb-advanced-010/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-010/tests/proofbench_prompt.txt b/tasks/pb-advanced-010/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-010/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-010/tests/test.sh b/tasks/pb-advanced-010/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-010/tests/test.sh +++ b/tasks/pb-advanced-010/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-011/task.toml b/tasks/pb-advanced-011/task.toml index a7aac26a6ffba235b1d490dcf3209805e454a107..16018dc320ed9c8b09b994b5b4a6a78912c9fb00 100644 --- a/tasks/pb-advanced-011/task.toml +++ b/tasks/pb-advanced-011/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-011/tests/NOTICE b/tasks/pb-advanced-011/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-011/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-011/tests/grade_task.py b/tasks/pb-advanced-011/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-011/tests/grade_task.py +++ b/tasks/pb-advanced-011/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-011/tests/proofbench_prompt.txt b/tasks/pb-advanced-011/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-011/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-011/tests/test.sh b/tasks/pb-advanced-011/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-011/tests/test.sh +++ b/tasks/pb-advanced-011/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-012/task.toml b/tasks/pb-advanced-012/task.toml index 2692b13c6ccf8a76b78d3d432ca9aa3bfdafb180..0c09cd438f0a4bc194e37bf0e475add26f3e607e 100644 --- a/tasks/pb-advanced-012/task.toml +++ b/tasks/pb-advanced-012/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-012/tests/NOTICE b/tasks/pb-advanced-012/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-012/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-012/tests/grade_task.py b/tasks/pb-advanced-012/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-012/tests/grade_task.py +++ b/tasks/pb-advanced-012/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-012/tests/proofbench_prompt.txt b/tasks/pb-advanced-012/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-012/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-012/tests/test.sh b/tasks/pb-advanced-012/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-012/tests/test.sh +++ b/tasks/pb-advanced-012/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-013/task.toml b/tasks/pb-advanced-013/task.toml index b039a9b3fd9557a13391e8d5ef727155c61a8514..eac1243c55edff4c74c4c7d3f401cb4851fa1ca4 100644 --- a/tasks/pb-advanced-013/task.toml +++ b/tasks/pb-advanced-013/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-013/tests/NOTICE b/tasks/pb-advanced-013/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-013/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-013/tests/grade_task.py b/tasks/pb-advanced-013/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-013/tests/grade_task.py +++ b/tasks/pb-advanced-013/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-013/tests/proofbench_prompt.txt b/tasks/pb-advanced-013/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-013/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-013/tests/test.sh b/tasks/pb-advanced-013/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-013/tests/test.sh +++ b/tasks/pb-advanced-013/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-014/task.toml b/tasks/pb-advanced-014/task.toml index eafb22fd97d2f90e88fbce2d130415771aaa43a0..21e29bec8610e895da561caf7825fcf0d9fd24bb 100644 --- a/tasks/pb-advanced-014/task.toml +++ b/tasks/pb-advanced-014/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-014/tests/NOTICE b/tasks/pb-advanced-014/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-014/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-014/tests/grade_task.py b/tasks/pb-advanced-014/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-014/tests/grade_task.py +++ b/tasks/pb-advanced-014/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-014/tests/proofbench_prompt.txt b/tasks/pb-advanced-014/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-014/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-014/tests/test.sh b/tasks/pb-advanced-014/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-014/tests/test.sh +++ b/tasks/pb-advanced-014/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-015/task.toml b/tasks/pb-advanced-015/task.toml index b82e202e6d86a4b9006c87324ad27ccd5a5cebca..ea50d6430600b42a0406d3719fcc0d0cf575f740 100644 --- a/tasks/pb-advanced-015/task.toml +++ b/tasks/pb-advanced-015/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-015/tests/NOTICE b/tasks/pb-advanced-015/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-015/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-015/tests/grade_task.py b/tasks/pb-advanced-015/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-015/tests/grade_task.py +++ b/tasks/pb-advanced-015/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-015/tests/proofbench_prompt.txt b/tasks/pb-advanced-015/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-015/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-015/tests/test.sh b/tasks/pb-advanced-015/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-015/tests/test.sh +++ b/tasks/pb-advanced-015/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-016/task.toml b/tasks/pb-advanced-016/task.toml index 97879da53c0ff025a139770cf76c330faa21cbfb..662cbf42518bf94014b4270676fee478b6fb110b 100644 --- a/tasks/pb-advanced-016/task.toml +++ b/tasks/pb-advanced-016/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-016/tests/NOTICE b/tasks/pb-advanced-016/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-016/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-016/tests/grade_task.py b/tasks/pb-advanced-016/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-016/tests/grade_task.py +++ b/tasks/pb-advanced-016/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-016/tests/proofbench_prompt.txt b/tasks/pb-advanced-016/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-016/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-016/tests/test.sh b/tasks/pb-advanced-016/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-016/tests/test.sh +++ b/tasks/pb-advanced-016/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-017/task.toml b/tasks/pb-advanced-017/task.toml index 66139bd0bb5ec1d2a2b8a9a498bf815d21c7d9b8..5172e2f798cac6e4ca05acf92976d13302cf00cc 100644 --- a/tasks/pb-advanced-017/task.toml +++ b/tasks/pb-advanced-017/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-017/tests/NOTICE b/tasks/pb-advanced-017/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-017/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-017/tests/grade_task.py b/tasks/pb-advanced-017/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-017/tests/grade_task.py +++ b/tasks/pb-advanced-017/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-017/tests/proofbench_prompt.txt b/tasks/pb-advanced-017/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-017/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-017/tests/test.sh b/tasks/pb-advanced-017/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-017/tests/test.sh +++ b/tasks/pb-advanced-017/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-018/task.toml b/tasks/pb-advanced-018/task.toml index 36fd2f13d56d8356e66d1bfefaae85d5ac2ed3e8..62ccff89cf7a3b120a00657a72ff063ea4129030 100644 --- a/tasks/pb-advanced-018/task.toml +++ b/tasks/pb-advanced-018/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-018/tests/NOTICE b/tasks/pb-advanced-018/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-018/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-018/tests/grade_task.py b/tasks/pb-advanced-018/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-018/tests/grade_task.py +++ b/tasks/pb-advanced-018/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-018/tests/proofbench_prompt.txt b/tasks/pb-advanced-018/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-018/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-018/tests/test.sh b/tasks/pb-advanced-018/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-018/tests/test.sh +++ b/tasks/pb-advanced-018/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-019/task.toml b/tasks/pb-advanced-019/task.toml index ec07a423256815e643ddb486eb8bcbb394245147..df040a9df542b8481ef822d0d1933fd40e9e20fd 100644 --- a/tasks/pb-advanced-019/task.toml +++ b/tasks/pb-advanced-019/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-019/tests/NOTICE b/tasks/pb-advanced-019/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-019/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-019/tests/grade_task.py b/tasks/pb-advanced-019/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-019/tests/grade_task.py +++ b/tasks/pb-advanced-019/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-019/tests/proofbench_prompt.txt b/tasks/pb-advanced-019/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-019/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-019/tests/test.sh b/tasks/pb-advanced-019/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-019/tests/test.sh +++ b/tasks/pb-advanced-019/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-020/task.toml b/tasks/pb-advanced-020/task.toml index f07b3510a93a08076b988c9ad1ee4914ec2fbc01..6dfea845b9b7e40d3ac93985c7b3d47ab7dad73a 100644 --- a/tasks/pb-advanced-020/task.toml +++ b/tasks/pb-advanced-020/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-020/tests/NOTICE b/tasks/pb-advanced-020/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-020/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-020/tests/grade_task.py b/tasks/pb-advanced-020/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-020/tests/grade_task.py +++ b/tasks/pb-advanced-020/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-020/tests/proofbench_prompt.txt b/tasks/pb-advanced-020/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-020/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-020/tests/test.sh b/tasks/pb-advanced-020/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-020/tests/test.sh +++ b/tasks/pb-advanced-020/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-021/task.toml b/tasks/pb-advanced-021/task.toml index 352ec842c8f0e5ea3b7361bdb3551c7cc0cf2ad0..46dbfd22dbebd3a8534cf42c473f65ca69463e37 100644 --- a/tasks/pb-advanced-021/task.toml +++ b/tasks/pb-advanced-021/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-021/tests/NOTICE b/tasks/pb-advanced-021/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-021/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-021/tests/grade_task.py b/tasks/pb-advanced-021/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-021/tests/grade_task.py +++ b/tasks/pb-advanced-021/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-021/tests/proofbench_prompt.txt b/tasks/pb-advanced-021/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-021/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-021/tests/test.sh b/tasks/pb-advanced-021/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-021/tests/test.sh +++ b/tasks/pb-advanced-021/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-022/task.toml b/tasks/pb-advanced-022/task.toml index 390c0b27fce7d93e95ad9ab7426ba6af7e54bdbe..2a760339b6c451d485e12cfb58e68091fc547b77 100644 --- a/tasks/pb-advanced-022/task.toml +++ b/tasks/pb-advanced-022/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-022/tests/NOTICE b/tasks/pb-advanced-022/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-022/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-022/tests/grade_task.py b/tasks/pb-advanced-022/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-022/tests/grade_task.py +++ b/tasks/pb-advanced-022/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-022/tests/proofbench_prompt.txt b/tasks/pb-advanced-022/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-022/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-022/tests/test.sh b/tasks/pb-advanced-022/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-022/tests/test.sh +++ b/tasks/pb-advanced-022/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-023/task.toml b/tasks/pb-advanced-023/task.toml index 7a6329b668dcd3cdd06b8354caf7166e85b2c4f0..ce748a7687f1688e99db612a54ec81ef50b64fb6 100644 --- a/tasks/pb-advanced-023/task.toml +++ b/tasks/pb-advanced-023/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-023/tests/NOTICE b/tasks/pb-advanced-023/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-023/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-023/tests/grade_task.py b/tasks/pb-advanced-023/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-023/tests/grade_task.py +++ b/tasks/pb-advanced-023/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-023/tests/proofbench_prompt.txt b/tasks/pb-advanced-023/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-023/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-023/tests/test.sh b/tasks/pb-advanced-023/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-023/tests/test.sh +++ b/tasks/pb-advanced-023/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-024/task.toml b/tasks/pb-advanced-024/task.toml index bcb9e99e39d13bc70cd58f22c762ddc2469e402f..e9ae19b8546e171576f7cd8dbb3c65f03c896c24 100644 --- a/tasks/pb-advanced-024/task.toml +++ b/tasks/pb-advanced-024/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-024/tests/NOTICE b/tasks/pb-advanced-024/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-024/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-024/tests/grade_task.py b/tasks/pb-advanced-024/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-024/tests/grade_task.py +++ b/tasks/pb-advanced-024/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-024/tests/proofbench_prompt.txt b/tasks/pb-advanced-024/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-024/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-024/tests/test.sh b/tasks/pb-advanced-024/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-024/tests/test.sh +++ b/tasks/pb-advanced-024/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-025/task.toml b/tasks/pb-advanced-025/task.toml index f131b01ec772be1bc8dd2ef35a684142047c3cd0..9abad0265d8ba5bc495d144a36e23fd905b8e357 100644 --- a/tasks/pb-advanced-025/task.toml +++ b/tasks/pb-advanced-025/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-025/tests/NOTICE b/tasks/pb-advanced-025/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-025/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-025/tests/grade_task.py b/tasks/pb-advanced-025/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-025/tests/grade_task.py +++ b/tasks/pb-advanced-025/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-025/tests/proofbench_prompt.txt b/tasks/pb-advanced-025/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-025/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-025/tests/test.sh b/tasks/pb-advanced-025/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-025/tests/test.sh +++ b/tasks/pb-advanced-025/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-026/task.toml b/tasks/pb-advanced-026/task.toml index 17c9dc19bf96060e77dccfc0e523402133109052..909ba95dd697aa4c41f54b643a09a787a03215e1 100644 --- a/tasks/pb-advanced-026/task.toml +++ b/tasks/pb-advanced-026/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-026/tests/NOTICE b/tasks/pb-advanced-026/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-026/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-026/tests/grade_task.py b/tasks/pb-advanced-026/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-026/tests/grade_task.py +++ b/tasks/pb-advanced-026/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-026/tests/proofbench_prompt.txt b/tasks/pb-advanced-026/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-026/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-026/tests/test.sh b/tasks/pb-advanced-026/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-026/tests/test.sh +++ b/tasks/pb-advanced-026/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-027/task.toml b/tasks/pb-advanced-027/task.toml index 4bce1cf76ba3fd4f00d23d58bffaf367b659b719..c51decb4ebc16bb1a7b500a0ae49072f24c303ac 100644 --- a/tasks/pb-advanced-027/task.toml +++ b/tasks/pb-advanced-027/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-027/tests/NOTICE b/tasks/pb-advanced-027/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-027/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-027/tests/grade_task.py b/tasks/pb-advanced-027/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-027/tests/grade_task.py +++ b/tasks/pb-advanced-027/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-027/tests/proofbench_prompt.txt b/tasks/pb-advanced-027/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-027/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-027/tests/test.sh b/tasks/pb-advanced-027/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-027/tests/test.sh +++ b/tasks/pb-advanced-027/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-028/task.toml b/tasks/pb-advanced-028/task.toml index 9a6ab7a2e08b4dc5829ca93e0348f81eeb91d2cf..69365293fea6a4144108ff0f17cecf855808a02a 100644 --- a/tasks/pb-advanced-028/task.toml +++ b/tasks/pb-advanced-028/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-028/tests/NOTICE b/tasks/pb-advanced-028/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-028/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-028/tests/grade_task.py b/tasks/pb-advanced-028/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-028/tests/grade_task.py +++ b/tasks/pb-advanced-028/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-028/tests/proofbench_prompt.txt b/tasks/pb-advanced-028/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-028/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-028/tests/test.sh b/tasks/pb-advanced-028/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-028/tests/test.sh +++ b/tasks/pb-advanced-028/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-029/task.toml b/tasks/pb-advanced-029/task.toml index 5671faec87f0735719ce900727ffe82263fa023b..ee79a2bdbf8dfab517020947b98f8731cfcc40a5 100644 --- a/tasks/pb-advanced-029/task.toml +++ b/tasks/pb-advanced-029/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-029/tests/NOTICE b/tasks/pb-advanced-029/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-029/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-029/tests/grade_task.py b/tasks/pb-advanced-029/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-029/tests/grade_task.py +++ b/tasks/pb-advanced-029/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-029/tests/proofbench_prompt.txt b/tasks/pb-advanced-029/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-029/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-029/tests/test.sh b/tasks/pb-advanced-029/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-029/tests/test.sh +++ b/tasks/pb-advanced-029/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-advanced-030/task.toml b/tasks/pb-advanced-030/task.toml index d0c8f631bb7ca7c91af652ed7a60c7681818185e..94486f9999807ae86c256d9cd120e3f8a01c62c3 100644 --- a/tasks/pb-advanced-030/task.toml +++ b/tasks/pb-advanced-030/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-advanced-030/tests/NOTICE b/tasks/pb-advanced-030/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-advanced-030/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-advanced-030/tests/grade_task.py b/tasks/pb-advanced-030/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-advanced-030/tests/grade_task.py +++ b/tasks/pb-advanced-030/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-advanced-030/tests/proofbench_prompt.txt b/tasks/pb-advanced-030/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-advanced-030/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-advanced-030/tests/test.sh b/tasks/pb-advanced-030/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-advanced-030/tests/test.sh +++ b/tasks/pb-advanced-030/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-001/task.toml b/tasks/pb-basic-001/task.toml index 87aa9bace283e1a0abdd4ff6de4ce951275628b2..8eb6e753b047f2ca0a0fba89cbae848615278ff6 100644 --- a/tasks/pb-basic-001/task.toml +++ b/tasks/pb-basic-001/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-001/tests/NOTICE b/tasks/pb-basic-001/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-001/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-001/tests/grade_task.py b/tasks/pb-basic-001/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-001/tests/grade_task.py +++ b/tasks/pb-basic-001/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-001/tests/proofbench_prompt.txt b/tasks/pb-basic-001/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-001/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-001/tests/test.sh b/tasks/pb-basic-001/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-001/tests/test.sh +++ b/tasks/pb-basic-001/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-002/task.toml b/tasks/pb-basic-002/task.toml index 771108ddea3033c105d361637294881b639267cd..9ab7a7c7c84009f78178f08b8d096a47a0601b00 100644 --- a/tasks/pb-basic-002/task.toml +++ b/tasks/pb-basic-002/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-002/tests/NOTICE b/tasks/pb-basic-002/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-002/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-002/tests/grade_task.py b/tasks/pb-basic-002/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-002/tests/grade_task.py +++ b/tasks/pb-basic-002/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-002/tests/proofbench_prompt.txt b/tasks/pb-basic-002/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-002/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-002/tests/test.sh b/tasks/pb-basic-002/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-002/tests/test.sh +++ b/tasks/pb-basic-002/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-003/task.toml b/tasks/pb-basic-003/task.toml index 450c7811c2b372a486ae4b0d10094f171f5bc189..eb393a2f086d052018ed1a67d162eb6deee39df0 100644 --- a/tasks/pb-basic-003/task.toml +++ b/tasks/pb-basic-003/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-003/tests/NOTICE b/tasks/pb-basic-003/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-003/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-003/tests/grade_task.py b/tasks/pb-basic-003/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-003/tests/grade_task.py +++ b/tasks/pb-basic-003/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-003/tests/proofbench_prompt.txt b/tasks/pb-basic-003/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-003/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-003/tests/test.sh b/tasks/pb-basic-003/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-003/tests/test.sh +++ b/tasks/pb-basic-003/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-004/task.toml b/tasks/pb-basic-004/task.toml index 4b27b299801f3e0ae3d96d1ba60f022041a4e6f3..83e475b41d236ad0b09f8f8b03c1dce77c8b0355 100644 --- a/tasks/pb-basic-004/task.toml +++ b/tasks/pb-basic-004/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-004/tests/NOTICE b/tasks/pb-basic-004/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-004/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-004/tests/grade_task.py b/tasks/pb-basic-004/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-004/tests/grade_task.py +++ b/tasks/pb-basic-004/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-004/tests/proofbench_prompt.txt b/tasks/pb-basic-004/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-004/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-004/tests/test.sh b/tasks/pb-basic-004/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-004/tests/test.sh +++ b/tasks/pb-basic-004/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-005/task.toml b/tasks/pb-basic-005/task.toml index e07fe21d18c5eb337a610b2c42b2e8c46f59a6ad..9f844a3f89e3004b43e5edffdf0c14aa3461dc33 100644 --- a/tasks/pb-basic-005/task.toml +++ b/tasks/pb-basic-005/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-005/tests/NOTICE b/tasks/pb-basic-005/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-005/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-005/tests/grade_task.py b/tasks/pb-basic-005/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-005/tests/grade_task.py +++ b/tasks/pb-basic-005/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-005/tests/proofbench_prompt.txt b/tasks/pb-basic-005/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-005/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-005/tests/test.sh b/tasks/pb-basic-005/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-005/tests/test.sh +++ b/tasks/pb-basic-005/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-006/task.toml b/tasks/pb-basic-006/task.toml index b676b36e1d884bc0fe109f06cc622609b0c97c4a..b52f614e1cf5e6415f21dde3a566e969fc7f47a7 100644 --- a/tasks/pb-basic-006/task.toml +++ b/tasks/pb-basic-006/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-006/tests/NOTICE b/tasks/pb-basic-006/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-006/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-006/tests/grade_task.py b/tasks/pb-basic-006/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-006/tests/grade_task.py +++ b/tasks/pb-basic-006/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-006/tests/proofbench_prompt.txt b/tasks/pb-basic-006/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-006/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-006/tests/test.sh b/tasks/pb-basic-006/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-006/tests/test.sh +++ b/tasks/pb-basic-006/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-007/task.toml b/tasks/pb-basic-007/task.toml index e10bc47ca58c98788dfe0f37b91469266fb7167b..c298cc1e2c9b93fe1fd359574a61a6abc2a4dd26 100644 --- a/tasks/pb-basic-007/task.toml +++ b/tasks/pb-basic-007/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-007/tests/NOTICE b/tasks/pb-basic-007/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-007/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-007/tests/grade_task.py b/tasks/pb-basic-007/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-007/tests/grade_task.py +++ b/tasks/pb-basic-007/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-007/tests/proofbench_prompt.txt b/tasks/pb-basic-007/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-007/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-007/tests/test.sh b/tasks/pb-basic-007/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-007/tests/test.sh +++ b/tasks/pb-basic-007/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-008/task.toml b/tasks/pb-basic-008/task.toml index edb2f487cc8d39f430a0acd7eafc2871309ce861..f37f608489733668bae7304acae70f821abcc71d 100644 --- a/tasks/pb-basic-008/task.toml +++ b/tasks/pb-basic-008/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-008/tests/NOTICE b/tasks/pb-basic-008/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-008/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-008/tests/grade_task.py b/tasks/pb-basic-008/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-008/tests/grade_task.py +++ b/tasks/pb-basic-008/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-008/tests/proofbench_prompt.txt b/tasks/pb-basic-008/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-008/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-008/tests/test.sh b/tasks/pb-basic-008/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-008/tests/test.sh +++ b/tasks/pb-basic-008/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-009/task.toml b/tasks/pb-basic-009/task.toml index 021a6d684f7f6b41cd6c6c4340f7f4a4cbce245e..982ecdce476f2f893a5ff72e318161b98c855ba7 100644 --- a/tasks/pb-basic-009/task.toml +++ b/tasks/pb-basic-009/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-009/tests/NOTICE b/tasks/pb-basic-009/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-009/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-009/tests/grade_task.py b/tasks/pb-basic-009/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-009/tests/grade_task.py +++ b/tasks/pb-basic-009/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-009/tests/proofbench_prompt.txt b/tasks/pb-basic-009/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-009/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-009/tests/test.sh b/tasks/pb-basic-009/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-009/tests/test.sh +++ b/tasks/pb-basic-009/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-010/task.toml b/tasks/pb-basic-010/task.toml index 309ec2fe5e7dcfab81c776236bf00bc18a250803..aef0c43faf5a0fe356be925acff3dd0e5364fd65 100644 --- a/tasks/pb-basic-010/task.toml +++ b/tasks/pb-basic-010/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-010/tests/NOTICE b/tasks/pb-basic-010/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-010/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-010/tests/grade_task.py b/tasks/pb-basic-010/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-010/tests/grade_task.py +++ b/tasks/pb-basic-010/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-010/tests/proofbench_prompt.txt b/tasks/pb-basic-010/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-010/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-010/tests/test.sh b/tasks/pb-basic-010/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-010/tests/test.sh +++ b/tasks/pb-basic-010/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-011/task.toml b/tasks/pb-basic-011/task.toml index 4a60a6fdc6b9c4367f297727ad94778bf72bf654..d42f1fc626ad5cce84a5434c2012c0522631d7ea 100644 --- a/tasks/pb-basic-011/task.toml +++ b/tasks/pb-basic-011/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-011/tests/NOTICE b/tasks/pb-basic-011/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-011/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-011/tests/grade_task.py b/tasks/pb-basic-011/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-011/tests/grade_task.py +++ b/tasks/pb-basic-011/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-011/tests/proofbench_prompt.txt b/tasks/pb-basic-011/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-011/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-011/tests/test.sh b/tasks/pb-basic-011/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-011/tests/test.sh +++ b/tasks/pb-basic-011/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-012/task.toml b/tasks/pb-basic-012/task.toml index 89cc0ee506d9fa9b9d1d526a10e097761dcf3149..4da5ad0ec49831dc2ca0657f301c1625ca17a155 100644 --- a/tasks/pb-basic-012/task.toml +++ b/tasks/pb-basic-012/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-012/tests/NOTICE b/tasks/pb-basic-012/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-012/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-012/tests/grade_task.py b/tasks/pb-basic-012/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-012/tests/grade_task.py +++ b/tasks/pb-basic-012/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-012/tests/proofbench_prompt.txt b/tasks/pb-basic-012/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-012/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-012/tests/test.sh b/tasks/pb-basic-012/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-012/tests/test.sh +++ b/tasks/pb-basic-012/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-013/task.toml b/tasks/pb-basic-013/task.toml index d6421b2a62b2967dcda2e8fafdd27a63cb3c535b..3e1f472b3ac1c65ebfbb2da417eac3bb74b37e14 100644 --- a/tasks/pb-basic-013/task.toml +++ b/tasks/pb-basic-013/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-013/tests/NOTICE b/tasks/pb-basic-013/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-013/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-013/tests/grade_task.py b/tasks/pb-basic-013/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-013/tests/grade_task.py +++ b/tasks/pb-basic-013/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-013/tests/proofbench_prompt.txt b/tasks/pb-basic-013/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-013/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-013/tests/test.sh b/tasks/pb-basic-013/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-013/tests/test.sh +++ b/tasks/pb-basic-013/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-014/task.toml b/tasks/pb-basic-014/task.toml index 21c99857b74e08b35dec4de0192df0026aa88ac5..b5d97e2b8765a007f6bbc7bad4e1a51c6550dba1 100644 --- a/tasks/pb-basic-014/task.toml +++ b/tasks/pb-basic-014/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-014/tests/NOTICE b/tasks/pb-basic-014/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-014/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-014/tests/grade_task.py b/tasks/pb-basic-014/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-014/tests/grade_task.py +++ b/tasks/pb-basic-014/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-014/tests/proofbench_prompt.txt b/tasks/pb-basic-014/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-014/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-014/tests/test.sh b/tasks/pb-basic-014/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-014/tests/test.sh +++ b/tasks/pb-basic-014/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-015/task.toml b/tasks/pb-basic-015/task.toml index fbf7f2cb5febdc8222d1cbfe11835961a00f79b9..bec65851ec4716a16cd22eef924e555e793579ce 100644 --- a/tasks/pb-basic-015/task.toml +++ b/tasks/pb-basic-015/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-015/tests/NOTICE b/tasks/pb-basic-015/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-015/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-015/tests/grade_task.py b/tasks/pb-basic-015/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-015/tests/grade_task.py +++ b/tasks/pb-basic-015/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-015/tests/proofbench_prompt.txt b/tasks/pb-basic-015/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-015/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-015/tests/test.sh b/tasks/pb-basic-015/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-015/tests/test.sh +++ b/tasks/pb-basic-015/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-016/task.toml b/tasks/pb-basic-016/task.toml index d5faea4374d302058a6ce92cd303da9a7edfd1d1..98b4850454288b8ce73e0e98c1ac95c42338f0df 100644 --- a/tasks/pb-basic-016/task.toml +++ b/tasks/pb-basic-016/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-016/tests/NOTICE b/tasks/pb-basic-016/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-016/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-016/tests/grade_task.py b/tasks/pb-basic-016/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-016/tests/grade_task.py +++ b/tasks/pb-basic-016/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-016/tests/proofbench_prompt.txt b/tasks/pb-basic-016/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-016/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-016/tests/test.sh b/tasks/pb-basic-016/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-016/tests/test.sh +++ b/tasks/pb-basic-016/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-017/task.toml b/tasks/pb-basic-017/task.toml index 58364486422c9f3600f27b9cd7d59cc8af6220d6..e7c7c43779e2a6bfcd1697d60e2a69c0d5e3d575 100644 --- a/tasks/pb-basic-017/task.toml +++ b/tasks/pb-basic-017/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-017/tests/NOTICE b/tasks/pb-basic-017/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-017/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-017/tests/grade_task.py b/tasks/pb-basic-017/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-017/tests/grade_task.py +++ b/tasks/pb-basic-017/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-017/tests/proofbench_prompt.txt b/tasks/pb-basic-017/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-017/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-017/tests/test.sh b/tasks/pb-basic-017/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-017/tests/test.sh +++ b/tasks/pb-basic-017/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-018/task.toml b/tasks/pb-basic-018/task.toml index 691d92ed2998513de3d41faa17b508b1deecc7e3..cd64d6a009d55161bd3761b158f8488873289678 100644 --- a/tasks/pb-basic-018/task.toml +++ b/tasks/pb-basic-018/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-018/tests/NOTICE b/tasks/pb-basic-018/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-018/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-018/tests/grade_task.py b/tasks/pb-basic-018/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-018/tests/grade_task.py +++ b/tasks/pb-basic-018/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-018/tests/proofbench_prompt.txt b/tasks/pb-basic-018/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-018/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-018/tests/test.sh b/tasks/pb-basic-018/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-018/tests/test.sh +++ b/tasks/pb-basic-018/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-019/task.toml b/tasks/pb-basic-019/task.toml index 5fb9fda3119e5d8734984665f5e9d6fa6bd50080..71cbaa7551ffa00bc42243fd429de295689acc4b 100644 --- a/tasks/pb-basic-019/task.toml +++ b/tasks/pb-basic-019/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-019/tests/NOTICE b/tasks/pb-basic-019/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-019/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-019/tests/grade_task.py b/tasks/pb-basic-019/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-019/tests/grade_task.py +++ b/tasks/pb-basic-019/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-019/tests/proofbench_prompt.txt b/tasks/pb-basic-019/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-019/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-019/tests/test.sh b/tasks/pb-basic-019/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-019/tests/test.sh +++ b/tasks/pb-basic-019/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-020/task.toml b/tasks/pb-basic-020/task.toml index 42077632e49a3650ce46d8ac5f02f5021392bb97..558f958dd87f673b32f4d997556f0cea20ae993b 100644 --- a/tasks/pb-basic-020/task.toml +++ b/tasks/pb-basic-020/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-020/tests/NOTICE b/tasks/pb-basic-020/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-020/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-020/tests/grade_task.py b/tasks/pb-basic-020/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-020/tests/grade_task.py +++ b/tasks/pb-basic-020/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-020/tests/proofbench_prompt.txt b/tasks/pb-basic-020/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-020/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-020/tests/test.sh b/tasks/pb-basic-020/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-020/tests/test.sh +++ b/tasks/pb-basic-020/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-021/task.toml b/tasks/pb-basic-021/task.toml index 63b26494fcdbe2a2c31bf2ef8f98709656a2f8a7..b40eadab24cd0f0366e4e6b912e31d9a7d61d3bd 100644 --- a/tasks/pb-basic-021/task.toml +++ b/tasks/pb-basic-021/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-021/tests/NOTICE b/tasks/pb-basic-021/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-021/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-021/tests/grade_task.py b/tasks/pb-basic-021/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-021/tests/grade_task.py +++ b/tasks/pb-basic-021/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-021/tests/proofbench_prompt.txt b/tasks/pb-basic-021/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-021/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-021/tests/test.sh b/tasks/pb-basic-021/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-021/tests/test.sh +++ b/tasks/pb-basic-021/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-022/task.toml b/tasks/pb-basic-022/task.toml index 1516e0ecee742e36627a3da3f1cdc97be86a5bb1..4686462c29db6eb67afa5687ebbac78efe81c6a2 100644 --- a/tasks/pb-basic-022/task.toml +++ b/tasks/pb-basic-022/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-022/tests/NOTICE b/tasks/pb-basic-022/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-022/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-022/tests/grade_task.py b/tasks/pb-basic-022/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-022/tests/grade_task.py +++ b/tasks/pb-basic-022/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-022/tests/proofbench_prompt.txt b/tasks/pb-basic-022/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-022/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-022/tests/test.sh b/tasks/pb-basic-022/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-022/tests/test.sh +++ b/tasks/pb-basic-022/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-023/task.toml b/tasks/pb-basic-023/task.toml index c09041b2c58896a0350f27a63e260847dc66a823..de929664ce86bab0f9c718a49675ac2860752020 100644 --- a/tasks/pb-basic-023/task.toml +++ b/tasks/pb-basic-023/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-023/tests/NOTICE b/tasks/pb-basic-023/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-023/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-023/tests/grade_task.py b/tasks/pb-basic-023/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-023/tests/grade_task.py +++ b/tasks/pb-basic-023/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-023/tests/proofbench_prompt.txt b/tasks/pb-basic-023/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-023/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-023/tests/test.sh b/tasks/pb-basic-023/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-023/tests/test.sh +++ b/tasks/pb-basic-023/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-024/task.toml b/tasks/pb-basic-024/task.toml index f6c6b29b879aa1437f91de959771e3f8b2570121..be37c84f506514ab808b012fd8dfe7b23e47532a 100644 --- a/tasks/pb-basic-024/task.toml +++ b/tasks/pb-basic-024/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-024/tests/NOTICE b/tasks/pb-basic-024/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-024/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-024/tests/grade_task.py b/tasks/pb-basic-024/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-024/tests/grade_task.py +++ b/tasks/pb-basic-024/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-024/tests/proofbench_prompt.txt b/tasks/pb-basic-024/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-024/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-024/tests/test.sh b/tasks/pb-basic-024/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-024/tests/test.sh +++ b/tasks/pb-basic-024/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-025/task.toml b/tasks/pb-basic-025/task.toml index cf2831ad699fa14441153bbafdde2eb35d9b9eb5..4c439e94c4018b92e96714fa6552570de6b03cf5 100644 --- a/tasks/pb-basic-025/task.toml +++ b/tasks/pb-basic-025/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-025/tests/NOTICE b/tasks/pb-basic-025/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-025/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-025/tests/grade_task.py b/tasks/pb-basic-025/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-025/tests/grade_task.py +++ b/tasks/pb-basic-025/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-025/tests/proofbench_prompt.txt b/tasks/pb-basic-025/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-025/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-025/tests/test.sh b/tasks/pb-basic-025/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-025/tests/test.sh +++ b/tasks/pb-basic-025/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-026/task.toml b/tasks/pb-basic-026/task.toml index 1b9ca84a8db974b91bc564ab820663abf90ff8df..01400e5499aebd78d27c72e3c4e86fb01879df22 100644 --- a/tasks/pb-basic-026/task.toml +++ b/tasks/pb-basic-026/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-026/tests/NOTICE b/tasks/pb-basic-026/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-026/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-026/tests/grade_task.py b/tasks/pb-basic-026/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-026/tests/grade_task.py +++ b/tasks/pb-basic-026/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-026/tests/proofbench_prompt.txt b/tasks/pb-basic-026/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-026/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-026/tests/test.sh b/tasks/pb-basic-026/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-026/tests/test.sh +++ b/tasks/pb-basic-026/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-027/task.toml b/tasks/pb-basic-027/task.toml index 595054f234d1e61773f2c27ee511664b1c5a7e14..c8629ba88c2a3ae60056c9f66508e2b897eac2a4 100644 --- a/tasks/pb-basic-027/task.toml +++ b/tasks/pb-basic-027/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-027/tests/NOTICE b/tasks/pb-basic-027/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-027/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-027/tests/grade_task.py b/tasks/pb-basic-027/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-027/tests/grade_task.py +++ b/tasks/pb-basic-027/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-027/tests/proofbench_prompt.txt b/tasks/pb-basic-027/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-027/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-027/tests/test.sh b/tasks/pb-basic-027/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-027/tests/test.sh +++ b/tasks/pb-basic-027/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-028/task.toml b/tasks/pb-basic-028/task.toml index b38b8b091e0f60305f9e7aab529abff5c2db1abc..dbb8d9a55965aaae9004888023ce62e7b545fbba 100644 --- a/tasks/pb-basic-028/task.toml +++ b/tasks/pb-basic-028/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-028/tests/NOTICE b/tasks/pb-basic-028/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-028/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-028/tests/grade_task.py b/tasks/pb-basic-028/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-028/tests/grade_task.py +++ b/tasks/pb-basic-028/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-028/tests/proofbench_prompt.txt b/tasks/pb-basic-028/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-028/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-028/tests/test.sh b/tasks/pb-basic-028/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-028/tests/test.sh +++ b/tasks/pb-basic-028/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-029/task.toml b/tasks/pb-basic-029/task.toml index 3e3bb31b8d63f14326e15bbf58bdcb2b66dc4180..87bfe51cf5fc02d844302fd3f441caea47f132a1 100644 --- a/tasks/pb-basic-029/task.toml +++ b/tasks/pb-basic-029/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-029/tests/NOTICE b/tasks/pb-basic-029/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-029/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-029/tests/grade_task.py b/tasks/pb-basic-029/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-029/tests/grade_task.py +++ b/tasks/pb-basic-029/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-029/tests/proofbench_prompt.txt b/tasks/pb-basic-029/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-029/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-029/tests/test.sh b/tasks/pb-basic-029/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-029/tests/test.sh +++ b/tasks/pb-basic-029/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py" diff --git a/tasks/pb-basic-030/task.toml b/tasks/pb-basic-030/task.toml index a90ab2295f352c4212dd6dab4634ca8572d99c1b..09adb9149e835af4606e4135441a598149f9151b 100644 --- a/tasks/pb-basic-030/task.toml +++ b/tasks/pb-basic-030/task.toml @@ -16,5 +16,13 @@ docker_image = "docker.io/library/python:3.12-slim" cpus = 1 memory_mb = 2048 [verifier] +environment_mode = "separate" network_mode = "allowlist" -timeout_sec = 180 +allowed_hosts = ["router.huggingface.co"] +timeout_sec = 600 + +[verifier.env] +HF_INFERENCE_TOKEN = "${HF_INFERENCE_TOKEN:-}" +JUDGE_API_KEY = "${JUDGE_API_KEY:-}" +JUDGE_MODEL = "${JUDGE_MODEL:-moonshotai/Kimi-K3.1-Pro}" +JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://router.huggingface.co/v1}" diff --git a/tasks/pb-basic-030/tests/NOTICE b/tasks/pb-basic-030/tests/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..db3495dc045a62eba7132ebe4a29a26c8a7f5ce0 --- /dev/null +++ b/tasks/pb-basic-030/tests/NOTICE @@ -0,0 +1,7 @@ +The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes from +CMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718: +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txt +QED-Nano is distributed under the Apache License 2.0 (see LICENSE). +The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) in +tests/grade_task.py are adapted from +https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench diff --git a/tasks/pb-basic-030/tests/grade_task.py b/tasks/pb-basic-030/tests/grade_task.py index 6ca83b5eace2d49f37e715b235faa046e7e66322..f2409bfcead990699a61cc97975032a1cc66d4d5 100644 --- a/tasks/pb-basic-030/tests/grade_task.py +++ b/tasks/pb-basic-030/tests/grade_task.py @@ -1,11 +1,36 @@ -"""Offline structural validation only; external rubric judge assigns 0–7 points.""" -import json, os, stat +"""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) + 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) @@ -14,45 +39,317 @@ def read_own(path): 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: + 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') + raise ValueError("not a regular file with one link") data = stream.read(LIMIT + 1) if len(data) > LIMIT: - raise ValueError('file exceeds 200000 bytes') + raise ValueError(f"file exceeds {LIMIT} bytes") return data + def write_new(path, data): - try: os.unlink(path) - except FileNotFoundError: pass + 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 f: f.write(data) + 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 N out of 7 tag with N in {0, 1, 6, 7}.""" + match = re.search(r"]*)?>(.*?)", 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 N out of 7 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'] + out = os.environ["VERIFIER_DIR"] + tests_dir = os.environ["TESTS_DIR"] os.makedirs(out, exist_ok=True) - write_new(os.path.join(out, 'reward.txt'), b'0\n') - proof_path = os.path.join(out, 'proof.md') - try: os.unlink(proof_path) - except FileNotFoundError: pass - reference = open(os.path.join(os.environ['TESTS_DIR'], 'reference.json'), 'rb').read() - json.loads(reference) - write_new(os.path.join(out, 'reference.json'), reference) - status, count, reason = 'missing', 0, 'proof unavailable or invalid' + 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: - raw = read_own(os.environ['PROOF']) - proof = raw.decode('utf-8', 'strict') - count = len(proof) - write_new(proof_path, raw) - if sum(not c.isspace() for c in proof) < 20: - status, reason = 'empty', 'fewer than 20 non-whitespace characters' + 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: - status, reason = 'submitted_for_judge', 'structurally valid submission' - except (OSError, ValueError, UnicodeError) as e: - reason = 'proof unavailable or invalid: ' + str(e)[:200] - result = {'status': status, 'char_count': count, 'requires_llm_judge': True, 'max_score': 7, 'reason': reason} - write_new(os.path.join(out, 'grade.json'), (json.dumps(result, ensure_ascii=False, indent=2)+'\n').encode()) - if status == 'submitted_for_judge': write_new(os.path.join(out, 'reward.txt'), b'1\n') - print(status, 'structural reward:', int(status == 'submitted_for_judge')) -if __name__ == '__main__': main() + 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() diff --git a/tasks/pb-basic-030/tests/proofbench_prompt.txt b/tasks/pb-basic-030/tests/proofbench_prompt.txt new file mode 100644 index 0000000000000000000000000000000000000000..6746a9b24ffdcc368944f9957c1d4c5983a4254d --- /dev/null +++ b/tasks/pb-basic-030/tests/proofbench_prompt.txt @@ -0,0 +1,43 @@ +You are an expert grader for the International Mathematics Olympiad (IMO). Your task is to evaluate a proposed solution strictly and rigorously. Keep in mind the standards at the IMO are extremely high: only arguments that are logically sound, complete, and precise should be rewarded. + +### General Scoring Rubric +Scores are assigned on a 0-7 scale. The general guidelines are: +* **7 Points (Correct):** The solution is complete, correct, and fully rigorous. If the submission contains incorrect attempts or lines of reasoning but ultimately presents a complete and correct solution, it should still be awarded full points; the presence of earlier, discarded work does not detract from the final correct proof. +* **6 Points (Almost Correct):** The solution is almost correct with a sound core argument, but contains minor errors in calculation or small gaps in logic. Missing proofs for major components, unjustified claims, or sketchy arguments are **not** eligible for 6 points. +* **1 Point (Partial Progress):** The solution demonstrates substantial progress explicitly mentioned in the grading guidelines. Initial observations, reformulating the problem without making substantive headway, or proving partial results not mentioned in the grading guidelines are generally **not** eligible for this score. +* **0 Points (Incorrect):** The solution doesn't make substantial progress that is a key step in the full solution or is fundamentally flawed. All partial progress without key results or lacking rigor also fall in this category. + +### Input Data and Interpretation +You are provided with the following: +1. **Problem Statement:** The IMO problem. +2. **Ground Truth Solution:** A reference solution. Assume this solution is correct. It demonstrates one valid approach. +3. **Specific Grading Guidelines:** Criteria for awarding credit for this specific problem. These guidelines take precedence over the General Scoring Rubric, especially for partial credit. +4. **Proposed Solution:** The student submission. + +### Evaluation Process +You must follow this structured process: +1. **Analyze References:** Meticulously read and understand the problem and Ground Truth Solution check the Specific Grading Guidelines. Identify the key steps for a complete solution and the criteria for partial credit. +2. **Step-by-Step Verification:** Verify the logical validity and rigor of every step. Identify all flaws, gaps, assumptions, and errors. **Make sure you fully understand every piece of logic behind each step of the proposed solution, you must be careful for solutions that 'pretend' to be correct.** +3. **Assess Progress:** Determine the extent of non-trivial progress made. +4. **Score Determination:** Compare the findings against the Specific Grading Guidelines and the General Rubric to determine the final score. + +### Output Requirements +You must provide your final score in the format N out of 7. Ensure the '' block is used **only once**, as your answer will be parsed based on the first block that appears in your whole response. + +-------------------------------------------------------------- +**PROBLEM STATEMENT** +{problem_statement} +**GROUND-TRUTH SOLUTION** +{solution} +**SPECIFIC GRADING GUIDELINES** +{guidelines} +**PROPOSED SOLUTION** +{student_answer} +-------------------------------------------------------------- + +Present your detailed thought process and formal justification based on the scoring rubric and grading guidelines, and finally present your final score in the format below. +[Select one of the following options] +7 out of 7 +6 out of 7 +1 out of 7 +0 out of 7 \ No newline at end of file diff --git a/tasks/pb-basic-030/tests/test.sh b/tasks/pb-basic-030/tests/test.sh old mode 100644 new mode 100755 index 8d1127f34b10138ec2f993696eafb1775ec248bb..e5f07d2ab45b6c98a522a4f9cff0bcfb0b0ddd3d --- a/tasks/pb-basic-030/tests/test.sh +++ b/tasks/pb-basic-030/tests/test.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Reward measures structural submission validity only, not mathematical correctness. -# External rubric-guided LLM judging against reference.json awards 0–7 points. -# Offline, isolated Python; PROOF and VERIFIER_DIR allow local verification. +# Harbor-native IMO-ProofBench verifier: structural validation + QED-Nano rubric LLM judge. +# Isolated stdlib Python; PROOF and VERIFIER_DIR override paths for local verification. set -eu here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}" mkdir -p "$VERIFIER_DIR" -printf '0\n' > "$VERIFIER_DIR/reward.txt" -python3 -I -S "$here/grade_task.py" +rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json" +exec python3 -B -I -S "$here/grade_task.py"