Agent Manager commited on
Commit ·
706935f
1
Parent(s): 10d6c29
Make IMO-ProofBench verifier Harbor-native with QED-Nano rubric LLM judge
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- LICENSEAdded+201
- NOTICEAdded+7
- README.md+24-3
- tasks/pb-advanced-001/task.toml+9-1
- tasks/pb-advanced-001/tests/NOTICEAdded+7
- tasks/pb-advanced-001/tests/grade_task.py+330-33
- tasks/pb-advanced-001/tests/proofbench_prompt.txtAdded+43
- tasks/pb-advanced-001/tests/test.sh+4-5
- tasks/pb-advanced-002/task.toml+9-1
- tasks/pb-advanced-002/tests/NOTICEAdded+7
- tasks/pb-advanced-002/tests/grade_task.py+330-33
- tasks/pb-advanced-002/tests/proofbench_prompt.txtAdded+43
- tasks/pb-advanced-002/tests/test.sh+4-5
- tasks/pb-advanced-003/task.toml+9-1
- tasks/pb-advanced-003/tests/NOTICEAdded+7
- tasks/pb-advanced-003/tests/grade_task.py+330-33
- tasks/pb-advanced-003/tests/proofbench_prompt.txtAdded+43
- tasks/pb-advanced-003/tests/test.sh+4-5
- tasks/pb-advanced-004/task.toml+9-1
- tasks/pb-advanced-004/tests/NOTICEAdded+7
- tasks/pb-advanced-004/tests/grade_task.py+330-33
- tasks/pb-advanced-004/tests/proofbench_prompt.txtAdded+43
- tasks/pb-advanced-004/tests/test.sh+4-5
- tasks/pb-advanced-005/task.toml+9-1
- tasks/pb-advanced-005/tests/NOTICEAdded+7
- tasks/pb-advanced-005/tests/grade_task.py+330-33
- tasks/pb-advanced-005/tests/proofbench_prompt.txtAdded+43
- tasks/pb-advanced-005/tests/test.sh+4-5
- tasks/pb-advanced-006/task.toml+9-1
- tasks/pb-advanced-006/tests/NOTICEAdded+7
- tasks/pb-advanced-006/tests/grade_task.py+330-33
- tasks/pb-advanced-006/tests/proofbench_prompt.txtAdded+43
- tasks/pb-advanced-006/tests/test.sh+4-5
- tasks/pb-advanced-007/task.toml+9-1
- tasks/pb-advanced-007/tests/NOTICEAdded+7
- tasks/pb-advanced-007/tests/grade_task.py+330-33
- tasks/pb-advanced-007/tests/proofbench_prompt.txtAdded+43
- tasks/pb-advanced-007/tests/test.sh+4-5
- tasks/pb-advanced-008/task.toml+9-1
- tasks/pb-advanced-008/tests/NOTICEAdded+7
- tasks/pb-advanced-008/tests/grade_task.py+330-33
- tasks/pb-advanced-008/tests/proofbench_prompt.txtAdded+43
- tasks/pb-advanced-008/tests/test.sh+4-5
- tasks/pb-advanced-009/task.toml+9-1
- tasks/pb-advanced-009/tests/NOTICEAdded+7
- tasks/pb-advanced-009/tests/grade_task.py+330-33
- tasks/pb-advanced-009/tests/proofbench_prompt.txtAdded+43
- tasks/pb-advanced-009/tests/test.sh+4-5
- tasks/pb-advanced-010/task.toml+9-1
- tasks/pb-advanced-010/tests/NOTICEAdded+7
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 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.1234567The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes fromCMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718:https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txtQED-Nano is distributed under the Apache License 2.0 (see LICENSE).The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) intests/grade_task.py are adapted fromhttps://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench11 unmodified lines1213141516176 unmodified lines2425262728293031323311 unmodified lines60 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).| Category | Basic | Advanced | Total ||---|---:|---:|---:|| Algebra | 8 | 8 | 16 |6 unmodified lines## Running and gradingEach `tasks/<task_id>` 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`.**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.`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.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.11 unmodified lines12131415161718196 unmodified lines262728293031323334353637383940414243444546474849505152535411 unmodified lines60 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 / `<points>` 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 |6 unmodified lines## Running and gradingEach `tasks/<task_id>` 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 `<points>N out of 7</points>`. 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 `<points>` 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 variablesConfigured 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) |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.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.
15 unmodified lines161718192015 unmodified linescpus = 1memory_mb = 2048[verifier]network_mode = "allowlist"timeout_sec = 18015 unmodified lines1617181920212223242526272815 unmodified linescpus = 1memory_mb = 2048[verifier]environment_mode = "separate"network_mode = "allowlist"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}"
1234567The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes fromCMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718:https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txtQED-Nano is distributed under the Apache License 2.0 (see LICENSE).The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) intests/grade_task.py are adapted fromhttps://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench12345678910112 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""Offline structural validation only; external rubric judge assigns 0–7 points."""import json, os, statLIMIT = 200_000def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split('/')[1:]folder = os.open('/', os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, 'rb') as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError('not a regular file with one link')data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError('file exceeds 200000 bytes')return datadef write_new(path, data):try: os.unlink(path)except FileNotFoundError: passfd = 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)def main():out = os.environ['VERIFIER_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: passreference = 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'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'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()1234567891011121314151617181920212223242526272829303132333435362 unmodified lines39404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355"""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/imobenchSee LICENSE and NOTICE for details."""import email.utilsimport jsonimport osimport reimport statimport sysimport timeimport urllib.errorimport urllib.requestLIMIT = 200_000MIN_NON_WS_CHARS = 20DEFAULT_JUDGE_MODEL = "moonshotai/Kimi-K3.1-Pro"DEFAULT_JUDGE_BASE_URL = "https://router.huggingface.co/v1"DEFAULT_TIMEOUT_SEC = 240.0DEFAULT_MAX_ATTEMPTS = 5MAX_RETRY_AFTER_SEC = 120.0MAX_TOKENS_SCHEDULE = (16384, 32768, 65536)RETRYABLE_HTTP_CODES = frozenset({408, 429, 500, 502, 503, 504})def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split("/")[1:]folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, "rb") as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError("not a regular file with one link")data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError(f"file exceeds {LIMIT} bytes")return datadef write_new(path, data):try:os.unlink(path)except FileNotFoundError:passfd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)with os.fdopen(fd, "wb") as handle:handle.write(data)def write_json(path, payload):write_new(path, (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8"))def remove_self_evaluation(text):"""Apply QED-Nano's evaluation-heading cleanup to a candidate solution."""pattern = r"(?ms)^#+\s*[*\s]*(?:(?:Self|Final)\s*[*\s]*){0,2}Evaluation\b.*$"return re.sub(pattern, "", text).strip()def parse_proof_points(text):"""Parse the first <points>N out of 7</points> tag with N in {0, 1, 6, 7}."""match = re.search(r"<points(?:\s[^>]*)?>(.*?)</points>", text, re.DOTALL)points = (re.fullmatch(r"\s*([0167])\s+out\s+of\s+7\s*", match.group(1), re.IGNORECASE)if matchelse None)if points is None:raise ValueError("Judge must return a first <points>N out of 7</points> with N in 0, 1, 6, 7")return int(points.group(1))def parse_retry_after(headers):if not headers:return Noneraw = headers.get("Retry-After")if raw is None:return Nonetext = str(raw).strip()if not text:return Nonetry:seconds = float(text)except ValueError:try:dt = email.utils.parsedate_to_datetime(text)except (TypeError, ValueError):return Noneseconds = dt.timestamp() - time.time()if seconds <= 0:return 0.0return 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:passretry_after = parse_retry_after(exc.headers) if exc.code in (429, 503) else Nonemsg = 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 excerr = RuntimeError(msg)err.retry_after = retry_afterraise err from excif 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 Noneif 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 = Nonelast_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 = rawpoints = parse_proof_points(raw)return points, raw, completion_tokens, attempt, Noneexcept NonRetryableJudgeError as exc:last_error = f"{type(exc).__name__}: {exc}"return None, last_raw, None, attempt, last_errorexcept (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_errordef main():out = os.environ["VERIFIER_DIR"]tests_dir = os.environ["TESTS_DIR"]os.makedirs(out, exist_ok=True)for stale in ("reward.txt", "reward.json"):try:os.unlink(os.path.join(out, stale))except FileNotFoundError:passproof_out_path = os.path.join(out, "proof.md")try:os.unlink(proof_out_path)except FileNotFoundError:passreference_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_MODELjudge_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 = 0non_ws_count = 0proof = ""try:raw = read_own(os.environ["PROOF"])proof = raw.decode("utf-8", "strict")char_count = len(proof)non_ws_count = sum(not ch.isspace() for ch in proof)write_new(proof_out_path, raw)if non_ws_count < MIN_NON_WS_CHARS:structural_status = "empty"structural_reason = f"fewer than {MIN_NON_WS_CHARS} non-whitespace characters"else:structural_status = "ok"structural_reason = "structurally valid submission"except (OSError, ValueError, UnicodeError) as exc:structural_reason = "proof unavailable or invalid: " + str(exc)[:200]structural = {"status": structural_status,"char_count": char_count,"non_whitespace_count": non_ws_count,"reason": structural_reason,}if structural_status != "ok":judgment = {"status": structural_status,"structural": structural,"judged_by_api": False,"judge_model": judge_model,"judge_base_url": judge_base_url,"points": 0,"max_score": 7,"reward": 0.0,"passed_6": False,"attempts": 0,"judge_output_tokens": 0,"raw_response": "","reason": structural_reason,"error": None,}write_json(os.path.join(out, "judgment.json"), judgment)write_json(os.path.join(out, "reward.json"), {"reward": 0.0, "points": 0})print(f"{structural_status}: points=0 reward=0.0 ({structural_reason})")returnif 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()
12345678910111213141516171819202122232425262728293031323334353637383940414243You 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 RubricScores 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 InterpretationYou 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 ProcessYou 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 RequirementsYou must provide your final score in the format <points>N out of 7</points>. Ensure the '<points>' block is used **only once**, as your answer will be parsed based on the first <points> </points> 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]<points>7 out of 7</points><points>6 out of 7</points><points>1 out of 7</points><points>0 out of 7</points>12345678910#!/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.set -euhere=$(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"123456789#!/bin/sh# 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 -euhere=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}"mkdir -p "$VERIFIER_DIR"rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json"exec python3 -B -I -S "$here/grade_task.py"
15 unmodified lines161718192015 unmodified linescpus = 1memory_mb = 2048[verifier]network_mode = "allowlist"timeout_sec = 18015 unmodified lines1617181920212223242526272815 unmodified linescpus = 1memory_mb = 2048[verifier]environment_mode = "separate"network_mode = "allowlist"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}"
1234567The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes fromCMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718:https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txtQED-Nano is distributed under the Apache License 2.0 (see LICENSE).The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) intests/grade_task.py are adapted fromhttps://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench12345678910112 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""Offline structural validation only; external rubric judge assigns 0–7 points."""import json, os, statLIMIT = 200_000def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split('/')[1:]folder = os.open('/', os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, 'rb') as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError('not a regular file with one link')data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError('file exceeds 200000 bytes')return datadef write_new(path, data):try: os.unlink(path)except FileNotFoundError: passfd = 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)def main():out = os.environ['VERIFIER_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: passreference = 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'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'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()1234567891011121314151617181920212223242526272829303132333435362 unmodified lines39404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355"""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/imobenchSee LICENSE and NOTICE for details."""import email.utilsimport jsonimport osimport reimport statimport sysimport timeimport urllib.errorimport urllib.requestLIMIT = 200_000MIN_NON_WS_CHARS = 20DEFAULT_JUDGE_MODEL = "moonshotai/Kimi-K3.1-Pro"DEFAULT_JUDGE_BASE_URL = "https://router.huggingface.co/v1"DEFAULT_TIMEOUT_SEC = 240.0DEFAULT_MAX_ATTEMPTS = 5MAX_RETRY_AFTER_SEC = 120.0MAX_TOKENS_SCHEDULE = (16384, 32768, 65536)RETRYABLE_HTTP_CODES = frozenset({408, 429, 500, 502, 503, 504})def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split("/")[1:]folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, "rb") as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError("not a regular file with one link")data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError(f"file exceeds {LIMIT} bytes")return datadef write_new(path, data):try:os.unlink(path)except FileNotFoundError:passfd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)with os.fdopen(fd, "wb") as handle:handle.write(data)def write_json(path, payload):write_new(path, (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8"))def remove_self_evaluation(text):"""Apply QED-Nano's evaluation-heading cleanup to a candidate solution."""pattern = r"(?ms)^#+\s*[*\s]*(?:(?:Self|Final)\s*[*\s]*){0,2}Evaluation\b.*$"return re.sub(pattern, "", text).strip()def parse_proof_points(text):"""Parse the first <points>N out of 7</points> tag with N in {0, 1, 6, 7}."""match = re.search(r"<points(?:\s[^>]*)?>(.*?)</points>", text, re.DOTALL)points = (re.fullmatch(r"\s*([0167])\s+out\s+of\s+7\s*", match.group(1), re.IGNORECASE)if matchelse None)if points is None:raise ValueError("Judge must return a first <points>N out of 7</points> with N in 0, 1, 6, 7")return int(points.group(1))def parse_retry_after(headers):if not headers:return Noneraw = headers.get("Retry-After")if raw is None:return Nonetext = str(raw).strip()if not text:return Nonetry:seconds = float(text)except ValueError:try:dt = email.utils.parsedate_to_datetime(text)except (TypeError, ValueError):return Noneseconds = dt.timestamp() - time.time()if seconds <= 0:return 0.0return 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:passretry_after = parse_retry_after(exc.headers) if exc.code in (429, 503) else Nonemsg = 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 excerr = RuntimeError(msg)err.retry_after = retry_afterraise err from excif 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 Noneif 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 = Nonelast_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 = rawpoints = parse_proof_points(raw)return points, raw, completion_tokens, attempt, Noneexcept NonRetryableJudgeError as exc:last_error = f"{type(exc).__name__}: {exc}"return None, last_raw, None, attempt, last_errorexcept (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_errordef main():out = os.environ["VERIFIER_DIR"]tests_dir = os.environ["TESTS_DIR"]os.makedirs(out, exist_ok=True)for stale in ("reward.txt", "reward.json"):try:os.unlink(os.path.join(out, stale))except FileNotFoundError:passproof_out_path = os.path.join(out, "proof.md")try:os.unlink(proof_out_path)except FileNotFoundError:passreference_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_MODELjudge_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 = 0non_ws_count = 0proof = ""try:raw = read_own(os.environ["PROOF"])proof = raw.decode("utf-8", "strict")char_count = len(proof)non_ws_count = sum(not ch.isspace() for ch in proof)write_new(proof_out_path, raw)if non_ws_count < MIN_NON_WS_CHARS:structural_status = "empty"structural_reason = f"fewer than {MIN_NON_WS_CHARS} non-whitespace characters"else:structural_status = "ok"structural_reason = "structurally valid submission"except (OSError, ValueError, UnicodeError) as exc:structural_reason = "proof unavailable or invalid: " + str(exc)[:200]structural = {"status": structural_status,"char_count": char_count,"non_whitespace_count": non_ws_count,"reason": structural_reason,}if structural_status != "ok":judgment = {"status": structural_status,"structural": structural,"judged_by_api": False,"judge_model": judge_model,"judge_base_url": judge_base_url,"points": 0,"max_score": 7,"reward": 0.0,"passed_6": False,"attempts": 0,"judge_output_tokens": 0,"raw_response": "","reason": structural_reason,"error": None,}write_json(os.path.join(out, "judgment.json"), judgment)write_json(os.path.join(out, "reward.json"), {"reward": 0.0, "points": 0})print(f"{structural_status}: points=0 reward=0.0 ({structural_reason})")returnif 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()
12345678910111213141516171819202122232425262728293031323334353637383940414243You 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 RubricScores 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 InterpretationYou 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 ProcessYou 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 RequirementsYou must provide your final score in the format <points>N out of 7</points>. Ensure the '<points>' block is used **only once**, as your answer will be parsed based on the first <points> </points> 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]<points>7 out of 7</points><points>6 out of 7</points><points>1 out of 7</points><points>0 out of 7</points>12345678910#!/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.set -euhere=$(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"123456789#!/bin/sh# 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 -euhere=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}"mkdir -p "$VERIFIER_DIR"rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json"exec python3 -B -I -S "$here/grade_task.py"
15 unmodified lines161718192015 unmodified linescpus = 1memory_mb = 2048[verifier]network_mode = "allowlist"timeout_sec = 18015 unmodified lines1617181920212223242526272815 unmodified linescpus = 1memory_mb = 2048[verifier]environment_mode = "separate"network_mode = "allowlist"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}"
1234567The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes fromCMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718:https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txtQED-Nano is distributed under the Apache License 2.0 (see LICENSE).The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) intests/grade_task.py are adapted fromhttps://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench12345678910112 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""Offline structural validation only; external rubric judge assigns 0–7 points."""import json, os, statLIMIT = 200_000def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split('/')[1:]folder = os.open('/', os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, 'rb') as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError('not a regular file with one link')data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError('file exceeds 200000 bytes')return datadef write_new(path, data):try: os.unlink(path)except FileNotFoundError: passfd = 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)def main():out = os.environ['VERIFIER_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: passreference = 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'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'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()1234567891011121314151617181920212223242526272829303132333435362 unmodified lines39404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355"""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/imobenchSee LICENSE and NOTICE for details."""import email.utilsimport jsonimport osimport reimport statimport sysimport timeimport urllib.errorimport urllib.requestLIMIT = 200_000MIN_NON_WS_CHARS = 20DEFAULT_JUDGE_MODEL = "moonshotai/Kimi-K3.1-Pro"DEFAULT_JUDGE_BASE_URL = "https://router.huggingface.co/v1"DEFAULT_TIMEOUT_SEC = 240.0DEFAULT_MAX_ATTEMPTS = 5MAX_RETRY_AFTER_SEC = 120.0MAX_TOKENS_SCHEDULE = (16384, 32768, 65536)RETRYABLE_HTTP_CODES = frozenset({408, 429, 500, 502, 503, 504})def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split("/")[1:]folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, "rb") as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError("not a regular file with one link")data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError(f"file exceeds {LIMIT} bytes")return datadef write_new(path, data):try:os.unlink(path)except FileNotFoundError:passfd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)with os.fdopen(fd, "wb") as handle:handle.write(data)def write_json(path, payload):write_new(path, (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8"))def remove_self_evaluation(text):"""Apply QED-Nano's evaluation-heading cleanup to a candidate solution."""pattern = r"(?ms)^#+\s*[*\s]*(?:(?:Self|Final)\s*[*\s]*){0,2}Evaluation\b.*$"return re.sub(pattern, "", text).strip()def parse_proof_points(text):"""Parse the first <points>N out of 7</points> tag with N in {0, 1, 6, 7}."""match = re.search(r"<points(?:\s[^>]*)?>(.*?)</points>", text, re.DOTALL)points = (re.fullmatch(r"\s*([0167])\s+out\s+of\s+7\s*", match.group(1), re.IGNORECASE)if matchelse None)if points is None:raise ValueError("Judge must return a first <points>N out of 7</points> with N in 0, 1, 6, 7")return int(points.group(1))def parse_retry_after(headers):if not headers:return Noneraw = headers.get("Retry-After")if raw is None:return Nonetext = str(raw).strip()if not text:return Nonetry:seconds = float(text)except ValueError:try:dt = email.utils.parsedate_to_datetime(text)except (TypeError, ValueError):return Noneseconds = dt.timestamp() - time.time()if seconds <= 0:return 0.0return 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:passretry_after = parse_retry_after(exc.headers) if exc.code in (429, 503) else Nonemsg = 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 excerr = RuntimeError(msg)err.retry_after = retry_afterraise err from excif 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 Noneif 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 = Nonelast_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 = rawpoints = parse_proof_points(raw)return points, raw, completion_tokens, attempt, Noneexcept NonRetryableJudgeError as exc:last_error = f"{type(exc).__name__}: {exc}"return None, last_raw, None, attempt, last_errorexcept (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_errordef main():out = os.environ["VERIFIER_DIR"]tests_dir = os.environ["TESTS_DIR"]os.makedirs(out, exist_ok=True)for stale in ("reward.txt", "reward.json"):try:os.unlink(os.path.join(out, stale))except FileNotFoundError:passproof_out_path = os.path.join(out, "proof.md")try:os.unlink(proof_out_path)except FileNotFoundError:passreference_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_MODELjudge_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 = 0non_ws_count = 0proof = ""try:raw = read_own(os.environ["PROOF"])proof = raw.decode("utf-8", "strict")char_count = len(proof)non_ws_count = sum(not ch.isspace() for ch in proof)write_new(proof_out_path, raw)if non_ws_count < MIN_NON_WS_CHARS:structural_status = "empty"structural_reason = f"fewer than {MIN_NON_WS_CHARS} non-whitespace characters"else:structural_status = "ok"structural_reason = "structurally valid submission"except (OSError, ValueError, UnicodeError) as exc:structural_reason = "proof unavailable or invalid: " + str(exc)[:200]structural = {"status": structural_status,"char_count": char_count,"non_whitespace_count": non_ws_count,"reason": structural_reason,}if structural_status != "ok":judgment = {"status": structural_status,"structural": structural,"judged_by_api": False,"judge_model": judge_model,"judge_base_url": judge_base_url,"points": 0,"max_score": 7,"reward": 0.0,"passed_6": False,"attempts": 0,"judge_output_tokens": 0,"raw_response": "","reason": structural_reason,"error": None,}write_json(os.path.join(out, "judgment.json"), judgment)write_json(os.path.join(out, "reward.json"), {"reward": 0.0, "points": 0})print(f"{structural_status}: points=0 reward=0.0 ({structural_reason})")returnif 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()
12345678910111213141516171819202122232425262728293031323334353637383940414243You 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 RubricScores 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 InterpretationYou 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 ProcessYou 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 RequirementsYou must provide your final score in the format <points>N out of 7</points>. Ensure the '<points>' block is used **only once**, as your answer will be parsed based on the first <points> </points> 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]<points>7 out of 7</points><points>6 out of 7</points><points>1 out of 7</points><points>0 out of 7</points>12345678910#!/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.set -euhere=$(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"123456789#!/bin/sh# 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 -euhere=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}"mkdir -p "$VERIFIER_DIR"rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json"exec python3 -B -I -S "$here/grade_task.py"
15 unmodified lines161718192015 unmodified linescpus = 1memory_mb = 2048[verifier]network_mode = "allowlist"timeout_sec = 18015 unmodified lines1617181920212223242526272815 unmodified linescpus = 1memory_mb = 2048[verifier]environment_mode = "separate"network_mode = "allowlist"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}"
1234567The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes fromCMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718:https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txtQED-Nano is distributed under the Apache License 2.0 (see LICENSE).The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) intests/grade_task.py are adapted fromhttps://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench12345678910112 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""Offline structural validation only; external rubric judge assigns 0–7 points."""import json, os, statLIMIT = 200_000def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split('/')[1:]folder = os.open('/', os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, 'rb') as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError('not a regular file with one link')data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError('file exceeds 200000 bytes')return datadef write_new(path, data):try: os.unlink(path)except FileNotFoundError: passfd = 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)def main():out = os.environ['VERIFIER_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: passreference = 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'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'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()1234567891011121314151617181920212223242526272829303132333435362 unmodified lines39404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355"""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/imobenchSee LICENSE and NOTICE for details."""import email.utilsimport jsonimport osimport reimport statimport sysimport timeimport urllib.errorimport urllib.requestLIMIT = 200_000MIN_NON_WS_CHARS = 20DEFAULT_JUDGE_MODEL = "moonshotai/Kimi-K3.1-Pro"DEFAULT_JUDGE_BASE_URL = "https://router.huggingface.co/v1"DEFAULT_TIMEOUT_SEC = 240.0DEFAULT_MAX_ATTEMPTS = 5MAX_RETRY_AFTER_SEC = 120.0MAX_TOKENS_SCHEDULE = (16384, 32768, 65536)RETRYABLE_HTTP_CODES = frozenset({408, 429, 500, 502, 503, 504})def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split("/")[1:]folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, "rb") as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError("not a regular file with one link")data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError(f"file exceeds {LIMIT} bytes")return datadef write_new(path, data):try:os.unlink(path)except FileNotFoundError:passfd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)with os.fdopen(fd, "wb") as handle:handle.write(data)def write_json(path, payload):write_new(path, (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8"))def remove_self_evaluation(text):"""Apply QED-Nano's evaluation-heading cleanup to a candidate solution."""pattern = r"(?ms)^#+\s*[*\s]*(?:(?:Self|Final)\s*[*\s]*){0,2}Evaluation\b.*$"return re.sub(pattern, "", text).strip()def parse_proof_points(text):"""Parse the first <points>N out of 7</points> tag with N in {0, 1, 6, 7}."""match = re.search(r"<points(?:\s[^>]*)?>(.*?)</points>", text, re.DOTALL)points = (re.fullmatch(r"\s*([0167])\s+out\s+of\s+7\s*", match.group(1), re.IGNORECASE)if matchelse None)if points is None:raise ValueError("Judge must return a first <points>N out of 7</points> with N in 0, 1, 6, 7")return int(points.group(1))def parse_retry_after(headers):if not headers:return Noneraw = headers.get("Retry-After")if raw is None:return Nonetext = str(raw).strip()if not text:return Nonetry:seconds = float(text)except ValueError:try:dt = email.utils.parsedate_to_datetime(text)except (TypeError, ValueError):return Noneseconds = dt.timestamp() - time.time()if seconds <= 0:return 0.0return 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:passretry_after = parse_retry_after(exc.headers) if exc.code in (429, 503) else Nonemsg = 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 excerr = RuntimeError(msg)err.retry_after = retry_afterraise err from excif 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 Noneif 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 = Nonelast_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 = rawpoints = parse_proof_points(raw)return points, raw, completion_tokens, attempt, Noneexcept NonRetryableJudgeError as exc:last_error = f"{type(exc).__name__}: {exc}"return None, last_raw, None, attempt, last_errorexcept (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_errordef main():out = os.environ["VERIFIER_DIR"]tests_dir = os.environ["TESTS_DIR"]os.makedirs(out, exist_ok=True)for stale in ("reward.txt", "reward.json"):try:os.unlink(os.path.join(out, stale))except FileNotFoundError:passproof_out_path = os.path.join(out, "proof.md")try:os.unlink(proof_out_path)except FileNotFoundError:passreference_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_MODELjudge_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 = 0non_ws_count = 0proof = ""try:raw = read_own(os.environ["PROOF"])proof = raw.decode("utf-8", "strict")char_count = len(proof)non_ws_count = sum(not ch.isspace() for ch in proof)write_new(proof_out_path, raw)if non_ws_count < MIN_NON_WS_CHARS:structural_status = "empty"structural_reason = f"fewer than {MIN_NON_WS_CHARS} non-whitespace characters"else:structural_status = "ok"structural_reason = "structurally valid submission"except (OSError, ValueError, UnicodeError) as exc:structural_reason = "proof unavailable or invalid: " + str(exc)[:200]structural = {"status": structural_status,"char_count": char_count,"non_whitespace_count": non_ws_count,"reason": structural_reason,}if structural_status != "ok":judgment = {"status": structural_status,"structural": structural,"judged_by_api": False,"judge_model": judge_model,"judge_base_url": judge_base_url,"points": 0,"max_score": 7,"reward": 0.0,"passed_6": False,"attempts": 0,"judge_output_tokens": 0,"raw_response": "","reason": structural_reason,"error": None,}write_json(os.path.join(out, "judgment.json"), judgment)write_json(os.path.join(out, "reward.json"), {"reward": 0.0, "points": 0})print(f"{structural_status}: points=0 reward=0.0 ({structural_reason})")returnif 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()
12345678910111213141516171819202122232425262728293031323334353637383940414243You 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 RubricScores 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 InterpretationYou 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 ProcessYou 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 RequirementsYou must provide your final score in the format <points>N out of 7</points>. Ensure the '<points>' block is used **only once**, as your answer will be parsed based on the first <points> </points> 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]<points>7 out of 7</points><points>6 out of 7</points><points>1 out of 7</points><points>0 out of 7</points>12345678910#!/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.set -euhere=$(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"123456789#!/bin/sh# 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 -euhere=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}"mkdir -p "$VERIFIER_DIR"rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json"exec python3 -B -I -S "$here/grade_task.py"
15 unmodified lines161718192015 unmodified linescpus = 1memory_mb = 2048[verifier]network_mode = "allowlist"timeout_sec = 18015 unmodified lines1617181920212223242526272815 unmodified linescpus = 1memory_mb = 2048[verifier]environment_mode = "separate"network_mode = "allowlist"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}"
1234567The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes fromCMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718:https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txtQED-Nano is distributed under the Apache License 2.0 (see LICENSE).The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) intests/grade_task.py are adapted fromhttps://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench12345678910112 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""Offline structural validation only; external rubric judge assigns 0–7 points."""import json, os, statLIMIT = 200_000def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split('/')[1:]folder = os.open('/', os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, 'rb') as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError('not a regular file with one link')data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError('file exceeds 200000 bytes')return datadef write_new(path, data):try: os.unlink(path)except FileNotFoundError: passfd = 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)def main():out = os.environ['VERIFIER_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: passreference = 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'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'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()1234567891011121314151617181920212223242526272829303132333435362 unmodified lines39404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355"""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/imobenchSee LICENSE and NOTICE for details."""import email.utilsimport jsonimport osimport reimport statimport sysimport timeimport urllib.errorimport urllib.requestLIMIT = 200_000MIN_NON_WS_CHARS = 20DEFAULT_JUDGE_MODEL = "moonshotai/Kimi-K3.1-Pro"DEFAULT_JUDGE_BASE_URL = "https://router.huggingface.co/v1"DEFAULT_TIMEOUT_SEC = 240.0DEFAULT_MAX_ATTEMPTS = 5MAX_RETRY_AFTER_SEC = 120.0MAX_TOKENS_SCHEDULE = (16384, 32768, 65536)RETRYABLE_HTTP_CODES = frozenset({408, 429, 500, 502, 503, 504})def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split("/")[1:]folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, "rb") as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError("not a regular file with one link")data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError(f"file exceeds {LIMIT} bytes")return datadef write_new(path, data):try:os.unlink(path)except FileNotFoundError:passfd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)with os.fdopen(fd, "wb") as handle:handle.write(data)def write_json(path, payload):write_new(path, (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8"))def remove_self_evaluation(text):"""Apply QED-Nano's evaluation-heading cleanup to a candidate solution."""pattern = r"(?ms)^#+\s*[*\s]*(?:(?:Self|Final)\s*[*\s]*){0,2}Evaluation\b.*$"return re.sub(pattern, "", text).strip()def parse_proof_points(text):"""Parse the first <points>N out of 7</points> tag with N in {0, 1, 6, 7}."""match = re.search(r"<points(?:\s[^>]*)?>(.*?)</points>", text, re.DOTALL)points = (re.fullmatch(r"\s*([0167])\s+out\s+of\s+7\s*", match.group(1), re.IGNORECASE)if matchelse None)if points is None:raise ValueError("Judge must return a first <points>N out of 7</points> with N in 0, 1, 6, 7")return int(points.group(1))def parse_retry_after(headers):if not headers:return Noneraw = headers.get("Retry-After")if raw is None:return Nonetext = str(raw).strip()if not text:return Nonetry:seconds = float(text)except ValueError:try:dt = email.utils.parsedate_to_datetime(text)except (TypeError, ValueError):return Noneseconds = dt.timestamp() - time.time()if seconds <= 0:return 0.0return 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:passretry_after = parse_retry_after(exc.headers) if exc.code in (429, 503) else Nonemsg = 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 excerr = RuntimeError(msg)err.retry_after = retry_afterraise err from excif 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 Noneif 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 = Nonelast_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 = rawpoints = parse_proof_points(raw)return points, raw, completion_tokens, attempt, Noneexcept NonRetryableJudgeError as exc:last_error = f"{type(exc).__name__}: {exc}"return None, last_raw, None, attempt, last_errorexcept (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_errordef main():out = os.environ["VERIFIER_DIR"]tests_dir = os.environ["TESTS_DIR"]os.makedirs(out, exist_ok=True)for stale in ("reward.txt", "reward.json"):try:os.unlink(os.path.join(out, stale))except FileNotFoundError:passproof_out_path = os.path.join(out, "proof.md")try:os.unlink(proof_out_path)except FileNotFoundError:passreference_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_MODELjudge_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 = 0non_ws_count = 0proof = ""try:raw = read_own(os.environ["PROOF"])proof = raw.decode("utf-8", "strict")char_count = len(proof)non_ws_count = sum(not ch.isspace() for ch in proof)write_new(proof_out_path, raw)if non_ws_count < MIN_NON_WS_CHARS:structural_status = "empty"structural_reason = f"fewer than {MIN_NON_WS_CHARS} non-whitespace characters"else:structural_status = "ok"structural_reason = "structurally valid submission"except (OSError, ValueError, UnicodeError) as exc:structural_reason = "proof unavailable or invalid: " + str(exc)[:200]structural = {"status": structural_status,"char_count": char_count,"non_whitespace_count": non_ws_count,"reason": structural_reason,}if structural_status != "ok":judgment = {"status": structural_status,"structural": structural,"judged_by_api": False,"judge_model": judge_model,"judge_base_url": judge_base_url,"points": 0,"max_score": 7,"reward": 0.0,"passed_6": False,"attempts": 0,"judge_output_tokens": 0,"raw_response": "","reason": structural_reason,"error": None,}write_json(os.path.join(out, "judgment.json"), judgment)write_json(os.path.join(out, "reward.json"), {"reward": 0.0, "points": 0})print(f"{structural_status}: points=0 reward=0.0 ({structural_reason})")returnif 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()
12345678910111213141516171819202122232425262728293031323334353637383940414243You 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 RubricScores 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 InterpretationYou 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 ProcessYou 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 RequirementsYou must provide your final score in the format <points>N out of 7</points>. Ensure the '<points>' block is used **only once**, as your answer will be parsed based on the first <points> </points> 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]<points>7 out of 7</points><points>6 out of 7</points><points>1 out of 7</points><points>0 out of 7</points>12345678910#!/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.set -euhere=$(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"123456789#!/bin/sh# 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 -euhere=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}"mkdir -p "$VERIFIER_DIR"rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json"exec python3 -B -I -S "$here/grade_task.py"
15 unmodified lines161718192015 unmodified linescpus = 1memory_mb = 2048[verifier]network_mode = "allowlist"timeout_sec = 18015 unmodified lines1617181920212223242526272815 unmodified linescpus = 1memory_mb = 2048[verifier]environment_mode = "separate"network_mode = "allowlist"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}"
1234567The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes fromCMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718:https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txtQED-Nano is distributed under the Apache License 2.0 (see LICENSE).The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) intests/grade_task.py are adapted fromhttps://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench12345678910112 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""Offline structural validation only; external rubric judge assigns 0–7 points."""import json, os, statLIMIT = 200_000def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split('/')[1:]folder = os.open('/', os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, 'rb') as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError('not a regular file with one link')data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError('file exceeds 200000 bytes')return datadef write_new(path, data):try: os.unlink(path)except FileNotFoundError: passfd = 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)def main():out = os.environ['VERIFIER_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: passreference = 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'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'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()1234567891011121314151617181920212223242526272829303132333435362 unmodified lines39404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355"""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/imobenchSee LICENSE and NOTICE for details."""import email.utilsimport jsonimport osimport reimport statimport sysimport timeimport urllib.errorimport urllib.requestLIMIT = 200_000MIN_NON_WS_CHARS = 20DEFAULT_JUDGE_MODEL = "moonshotai/Kimi-K3.1-Pro"DEFAULT_JUDGE_BASE_URL = "https://router.huggingface.co/v1"DEFAULT_TIMEOUT_SEC = 240.0DEFAULT_MAX_ATTEMPTS = 5MAX_RETRY_AFTER_SEC = 120.0MAX_TOKENS_SCHEDULE = (16384, 32768, 65536)RETRYABLE_HTTP_CODES = frozenset({408, 429, 500, 502, 503, 504})def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split("/")[1:]folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, "rb") as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError("not a regular file with one link")data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError(f"file exceeds {LIMIT} bytes")return datadef write_new(path, data):try:os.unlink(path)except FileNotFoundError:passfd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)with os.fdopen(fd, "wb") as handle:handle.write(data)def write_json(path, payload):write_new(path, (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8"))def remove_self_evaluation(text):"""Apply QED-Nano's evaluation-heading cleanup to a candidate solution."""pattern = r"(?ms)^#+\s*[*\s]*(?:(?:Self|Final)\s*[*\s]*){0,2}Evaluation\b.*$"return re.sub(pattern, "", text).strip()def parse_proof_points(text):"""Parse the first <points>N out of 7</points> tag with N in {0, 1, 6, 7}."""match = re.search(r"<points(?:\s[^>]*)?>(.*?)</points>", text, re.DOTALL)points = (re.fullmatch(r"\s*([0167])\s+out\s+of\s+7\s*", match.group(1), re.IGNORECASE)if matchelse None)if points is None:raise ValueError("Judge must return a first <points>N out of 7</points> with N in 0, 1, 6, 7")return int(points.group(1))def parse_retry_after(headers):if not headers:return Noneraw = headers.get("Retry-After")if raw is None:return Nonetext = str(raw).strip()if not text:return Nonetry:seconds = float(text)except ValueError:try:dt = email.utils.parsedate_to_datetime(text)except (TypeError, ValueError):return Noneseconds = dt.timestamp() - time.time()if seconds <= 0:return 0.0return 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:passretry_after = parse_retry_after(exc.headers) if exc.code in (429, 503) else Nonemsg = 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 excerr = RuntimeError(msg)err.retry_after = retry_afterraise err from excif 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 Noneif 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 = Nonelast_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 = rawpoints = parse_proof_points(raw)return points, raw, completion_tokens, attempt, Noneexcept NonRetryableJudgeError as exc:last_error = f"{type(exc).__name__}: {exc}"return None, last_raw, None, attempt, last_errorexcept (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_errordef main():out = os.environ["VERIFIER_DIR"]tests_dir = os.environ["TESTS_DIR"]os.makedirs(out, exist_ok=True)for stale in ("reward.txt", "reward.json"):try:os.unlink(os.path.join(out, stale))except FileNotFoundError:passproof_out_path = os.path.join(out, "proof.md")try:os.unlink(proof_out_path)except FileNotFoundError:passreference_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_MODELjudge_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 = 0non_ws_count = 0proof = ""try:raw = read_own(os.environ["PROOF"])proof = raw.decode("utf-8", "strict")char_count = len(proof)non_ws_count = sum(not ch.isspace() for ch in proof)write_new(proof_out_path, raw)if non_ws_count < MIN_NON_WS_CHARS:structural_status = "empty"structural_reason = f"fewer than {MIN_NON_WS_CHARS} non-whitespace characters"else:structural_status = "ok"structural_reason = "structurally valid submission"except (OSError, ValueError, UnicodeError) as exc:structural_reason = "proof unavailable or invalid: " + str(exc)[:200]structural = {"status": structural_status,"char_count": char_count,"non_whitespace_count": non_ws_count,"reason": structural_reason,}if structural_status != "ok":judgment = {"status": structural_status,"structural": structural,"judged_by_api": False,"judge_model": judge_model,"judge_base_url": judge_base_url,"points": 0,"max_score": 7,"reward": 0.0,"passed_6": False,"attempts": 0,"judge_output_tokens": 0,"raw_response": "","reason": structural_reason,"error": None,}write_json(os.path.join(out, "judgment.json"), judgment)write_json(os.path.join(out, "reward.json"), {"reward": 0.0, "points": 0})print(f"{structural_status}: points=0 reward=0.0 ({structural_reason})")returnif 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()
12345678910111213141516171819202122232425262728293031323334353637383940414243You 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 RubricScores 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 InterpretationYou 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 ProcessYou 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 RequirementsYou must provide your final score in the format <points>N out of 7</points>. Ensure the '<points>' block is used **only once**, as your answer will be parsed based on the first <points> </points> 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]<points>7 out of 7</points><points>6 out of 7</points><points>1 out of 7</points><points>0 out of 7</points>12345678910#!/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.set -euhere=$(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"123456789#!/bin/sh# 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 -euhere=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}"mkdir -p "$VERIFIER_DIR"rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json"exec python3 -B -I -S "$here/grade_task.py"
15 unmodified lines161718192015 unmodified linescpus = 1memory_mb = 2048[verifier]network_mode = "allowlist"timeout_sec = 18015 unmodified lines1617181920212223242526272815 unmodified linescpus = 1memory_mb = 2048[verifier]environment_mode = "separate"network_mode = "allowlist"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}"
1234567The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes fromCMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718:https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txtQED-Nano is distributed under the Apache License 2.0 (see LICENSE).The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) intests/grade_task.py are adapted fromhttps://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench12345678910112 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""Offline structural validation only; external rubric judge assigns 0–7 points."""import json, os, statLIMIT = 200_000def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split('/')[1:]folder = os.open('/', os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, 'rb') as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError('not a regular file with one link')data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError('file exceeds 200000 bytes')return datadef write_new(path, data):try: os.unlink(path)except FileNotFoundError: passfd = 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)def main():out = os.environ['VERIFIER_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: passreference = 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'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'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()1234567891011121314151617181920212223242526272829303132333435362 unmodified lines39404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355"""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/imobenchSee LICENSE and NOTICE for details."""import email.utilsimport jsonimport osimport reimport statimport sysimport timeimport urllib.errorimport urllib.requestLIMIT = 200_000MIN_NON_WS_CHARS = 20DEFAULT_JUDGE_MODEL = "moonshotai/Kimi-K3.1-Pro"DEFAULT_JUDGE_BASE_URL = "https://router.huggingface.co/v1"DEFAULT_TIMEOUT_SEC = 240.0DEFAULT_MAX_ATTEMPTS = 5MAX_RETRY_AFTER_SEC = 120.0MAX_TOKENS_SCHEDULE = (16384, 32768, 65536)RETRYABLE_HTTP_CODES = frozenset({408, 429, 500, 502, 503, 504})def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split("/")[1:]folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, "rb") as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError("not a regular file with one link")data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError(f"file exceeds {LIMIT} bytes")return datadef write_new(path, data):try:os.unlink(path)except FileNotFoundError:passfd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)with os.fdopen(fd, "wb") as handle:handle.write(data)def write_json(path, payload):write_new(path, (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8"))def remove_self_evaluation(text):"""Apply QED-Nano's evaluation-heading cleanup to a candidate solution."""pattern = r"(?ms)^#+\s*[*\s]*(?:(?:Self|Final)\s*[*\s]*){0,2}Evaluation\b.*$"return re.sub(pattern, "", text).strip()def parse_proof_points(text):"""Parse the first <points>N out of 7</points> tag with N in {0, 1, 6, 7}."""match = re.search(r"<points(?:\s[^>]*)?>(.*?)</points>", text, re.DOTALL)points = (re.fullmatch(r"\s*([0167])\s+out\s+of\s+7\s*", match.group(1), re.IGNORECASE)if matchelse None)if points is None:raise ValueError("Judge must return a first <points>N out of 7</points> with N in 0, 1, 6, 7")return int(points.group(1))def parse_retry_after(headers):if not headers:return Noneraw = headers.get("Retry-After")if raw is None:return Nonetext = str(raw).strip()if not text:return Nonetry:seconds = float(text)except ValueError:try:dt = email.utils.parsedate_to_datetime(text)except (TypeError, ValueError):return Noneseconds = dt.timestamp() - time.time()if seconds <= 0:return 0.0return 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:passretry_after = parse_retry_after(exc.headers) if exc.code in (429, 503) else Nonemsg = 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 excerr = RuntimeError(msg)err.retry_after = retry_afterraise err from excif 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 Noneif 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 = Nonelast_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 = rawpoints = parse_proof_points(raw)return points, raw, completion_tokens, attempt, Noneexcept NonRetryableJudgeError as exc:last_error = f"{type(exc).__name__}: {exc}"return None, last_raw, None, attempt, last_errorexcept (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_errordef main():out = os.environ["VERIFIER_DIR"]tests_dir = os.environ["TESTS_DIR"]os.makedirs(out, exist_ok=True)for stale in ("reward.txt", "reward.json"):try:os.unlink(os.path.join(out, stale))except FileNotFoundError:passproof_out_path = os.path.join(out, "proof.md")try:os.unlink(proof_out_path)except FileNotFoundError:passreference_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_MODELjudge_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 = 0non_ws_count = 0proof = ""try:raw = read_own(os.environ["PROOF"])proof = raw.decode("utf-8", "strict")char_count = len(proof)non_ws_count = sum(not ch.isspace() for ch in proof)write_new(proof_out_path, raw)if non_ws_count < MIN_NON_WS_CHARS:structural_status = "empty"structural_reason = f"fewer than {MIN_NON_WS_CHARS} non-whitespace characters"else:structural_status = "ok"structural_reason = "structurally valid submission"except (OSError, ValueError, UnicodeError) as exc:structural_reason = "proof unavailable or invalid: " + str(exc)[:200]structural = {"status": structural_status,"char_count": char_count,"non_whitespace_count": non_ws_count,"reason": structural_reason,}if structural_status != "ok":judgment = {"status": structural_status,"structural": structural,"judged_by_api": False,"judge_model": judge_model,"judge_base_url": judge_base_url,"points": 0,"max_score": 7,"reward": 0.0,"passed_6": False,"attempts": 0,"judge_output_tokens": 0,"raw_response": "","reason": structural_reason,"error": None,}write_json(os.path.join(out, "judgment.json"), judgment)write_json(os.path.join(out, "reward.json"), {"reward": 0.0, "points": 0})print(f"{structural_status}: points=0 reward=0.0 ({structural_reason})")returnif 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()
12345678910111213141516171819202122232425262728293031323334353637383940414243You 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 RubricScores 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 InterpretationYou 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 ProcessYou 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 RequirementsYou must provide your final score in the format <points>N out of 7</points>. Ensure the '<points>' block is used **only once**, as your answer will be parsed based on the first <points> </points> 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]<points>7 out of 7</points><points>6 out of 7</points><points>1 out of 7</points><points>0 out of 7</points>12345678910#!/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.set -euhere=$(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"123456789#!/bin/sh# 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 -euhere=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}"mkdir -p "$VERIFIER_DIR"rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json"exec python3 -B -I -S "$here/grade_task.py"
15 unmodified lines161718192015 unmodified linescpus = 1memory_mb = 2048[verifier]network_mode = "allowlist"timeout_sec = 18015 unmodified lines1617181920212223242526272815 unmodified linescpus = 1memory_mb = 2048[verifier]environment_mode = "separate"network_mode = "allowlist"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}"
1234567The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes fromCMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718:https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txtQED-Nano is distributed under the Apache License 2.0 (see LICENSE).The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) intests/grade_task.py are adapted fromhttps://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench12345678910112 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""Offline structural validation only; external rubric judge assigns 0–7 points."""import json, os, statLIMIT = 200_000def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split('/')[1:]folder = os.open('/', os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, 'rb') as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError('not a regular file with one link')data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError('file exceeds 200000 bytes')return datadef write_new(path, data):try: os.unlink(path)except FileNotFoundError: passfd = 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)def main():out = os.environ['VERIFIER_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: passreference = 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'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'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()1234567891011121314151617181920212223242526272829303132333435362 unmodified lines39404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355"""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/imobenchSee LICENSE and NOTICE for details."""import email.utilsimport jsonimport osimport reimport statimport sysimport timeimport urllib.errorimport urllib.requestLIMIT = 200_000MIN_NON_WS_CHARS = 20DEFAULT_JUDGE_MODEL = "moonshotai/Kimi-K3.1-Pro"DEFAULT_JUDGE_BASE_URL = "https://router.huggingface.co/v1"DEFAULT_TIMEOUT_SEC = 240.0DEFAULT_MAX_ATTEMPTS = 5MAX_RETRY_AFTER_SEC = 120.0MAX_TOKENS_SCHEDULE = (16384, 32768, 65536)RETRYABLE_HTTP_CODES = frozenset({408, 429, 500, 502, 503, 504})def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split("/")[1:]folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, "rb") as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError("not a regular file with one link")data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError(f"file exceeds {LIMIT} bytes")return datadef write_new(path, data):try:os.unlink(path)except FileNotFoundError:passfd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)with os.fdopen(fd, "wb") as handle:handle.write(data)def write_json(path, payload):write_new(path, (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8"))def remove_self_evaluation(text):"""Apply QED-Nano's evaluation-heading cleanup to a candidate solution."""pattern = r"(?ms)^#+\s*[*\s]*(?:(?:Self|Final)\s*[*\s]*){0,2}Evaluation\b.*$"return re.sub(pattern, "", text).strip()def parse_proof_points(text):"""Parse the first <points>N out of 7</points> tag with N in {0, 1, 6, 7}."""match = re.search(r"<points(?:\s[^>]*)?>(.*?)</points>", text, re.DOTALL)points = (re.fullmatch(r"\s*([0167])\s+out\s+of\s+7\s*", match.group(1), re.IGNORECASE)if matchelse None)if points is None:raise ValueError("Judge must return a first <points>N out of 7</points> with N in 0, 1, 6, 7")return int(points.group(1))def parse_retry_after(headers):if not headers:return Noneraw = headers.get("Retry-After")if raw is None:return Nonetext = str(raw).strip()if not text:return Nonetry:seconds = float(text)except ValueError:try:dt = email.utils.parsedate_to_datetime(text)except (TypeError, ValueError):return Noneseconds = dt.timestamp() - time.time()if seconds <= 0:return 0.0return 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:passretry_after = parse_retry_after(exc.headers) if exc.code in (429, 503) else Nonemsg = 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 excerr = RuntimeError(msg)err.retry_after = retry_afterraise err from excif 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 Noneif 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 = Nonelast_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 = rawpoints = parse_proof_points(raw)return points, raw, completion_tokens, attempt, Noneexcept NonRetryableJudgeError as exc:last_error = f"{type(exc).__name__}: {exc}"return None, last_raw, None, attempt, last_errorexcept (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_errordef main():out = os.environ["VERIFIER_DIR"]tests_dir = os.environ["TESTS_DIR"]os.makedirs(out, exist_ok=True)for stale in ("reward.txt", "reward.json"):try:os.unlink(os.path.join(out, stale))except FileNotFoundError:passproof_out_path = os.path.join(out, "proof.md")try:os.unlink(proof_out_path)except FileNotFoundError:passreference_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_MODELjudge_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 = 0non_ws_count = 0proof = ""try:raw = read_own(os.environ["PROOF"])proof = raw.decode("utf-8", "strict")char_count = len(proof)non_ws_count = sum(not ch.isspace() for ch in proof)write_new(proof_out_path, raw)if non_ws_count < MIN_NON_WS_CHARS:structural_status = "empty"structural_reason = f"fewer than {MIN_NON_WS_CHARS} non-whitespace characters"else:structural_status = "ok"structural_reason = "structurally valid submission"except (OSError, ValueError, UnicodeError) as exc:structural_reason = "proof unavailable or invalid: " + str(exc)[:200]structural = {"status": structural_status,"char_count": char_count,"non_whitespace_count": non_ws_count,"reason": structural_reason,}if structural_status != "ok":judgment = {"status": structural_status,"structural": structural,"judged_by_api": False,"judge_model": judge_model,"judge_base_url": judge_base_url,"points": 0,"max_score": 7,"reward": 0.0,"passed_6": False,"attempts": 0,"judge_output_tokens": 0,"raw_response": "","reason": structural_reason,"error": None,}write_json(os.path.join(out, "judgment.json"), judgment)write_json(os.path.join(out, "reward.json"), {"reward": 0.0, "points": 0})print(f"{structural_status}: points=0 reward=0.0 ({structural_reason})")returnif 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()
12345678910111213141516171819202122232425262728293031323334353637383940414243You 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 RubricScores 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 InterpretationYou 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 ProcessYou 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 RequirementsYou must provide your final score in the format <points>N out of 7</points>. Ensure the '<points>' block is used **only once**, as your answer will be parsed based on the first <points> </points> 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]<points>7 out of 7</points><points>6 out of 7</points><points>1 out of 7</points><points>0 out of 7</points>12345678910#!/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.set -euhere=$(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"123456789#!/bin/sh# 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 -euhere=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}"mkdir -p "$VERIFIER_DIR"rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json"exec python3 -B -I -S "$here/grade_task.py"
15 unmodified lines161718192015 unmodified linescpus = 1memory_mb = 2048[verifier]network_mode = "allowlist"timeout_sec = 18015 unmodified lines1617181920212223242526272815 unmodified linescpus = 1memory_mb = 2048[verifier]environment_mode = "separate"network_mode = "allowlist"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}"
1234567The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes fromCMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718:https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txtQED-Nano is distributed under the Apache License 2.0 (see LICENSE).The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) intests/grade_task.py are adapted fromhttps://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobench12345678910112 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""Offline structural validation only; external rubric judge assigns 0–7 points."""import json, os, statLIMIT = 200_000def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split('/')[1:]folder = os.open('/', os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, 'rb') as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError('not a regular file with one link')data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError('file exceeds 200000 bytes')return datadef write_new(path, data):try: os.unlink(path)except FileNotFoundError: passfd = 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)def main():out = os.environ['VERIFIER_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: passreference = 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'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'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()1234567891011121314151617181920212223242526272829303132333435362 unmodified lines39404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355"""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/imobenchSee LICENSE and NOTICE for details."""import email.utilsimport jsonimport osimport reimport statimport sysimport timeimport urllib.errorimport urllib.requestLIMIT = 200_000MIN_NON_WS_CHARS = 20DEFAULT_JUDGE_MODEL = "moonshotai/Kimi-K3.1-Pro"DEFAULT_JUDGE_BASE_URL = "https://router.huggingface.co/v1"DEFAULT_TIMEOUT_SEC = 240.0DEFAULT_MAX_ATTEMPTS = 5MAX_RETRY_AFTER_SEC = 120.0MAX_TOKENS_SCHEDULE = (16384, 32768, 65536)RETRYABLE_HTTP_CODES = frozenset({408, 429, 500, 502, 503, 504})def read_own(path):"""Reject links, special files, multiple hard links, and oversized files."""parts = os.path.abspath(path).split("/")[1:]folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY)try:for part in parts[:-1]:inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)2 unmodified linesfd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)finally:os.close(folder)with os.fdopen(fd, "rb") as stream:info = os.fstat(stream.fileno())if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:raise ValueError("not a regular file with one link")data = stream.read(LIMIT + 1)if len(data) > LIMIT:raise ValueError(f"file exceeds {LIMIT} bytes")return datadef write_new(path, data):try:os.unlink(path)except FileNotFoundError:passfd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)with os.fdopen(fd, "wb") as handle:handle.write(data)def write_json(path, payload):write_new(path, (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8"))def remove_self_evaluation(text):"""Apply QED-Nano's evaluation-heading cleanup to a candidate solution."""pattern = r"(?ms)^#+\s*[*\s]*(?:(?:Self|Final)\s*[*\s]*){0,2}Evaluation\b.*$"return re.sub(pattern, "", text).strip()def parse_proof_points(text):"""Parse the first <points>N out of 7</points> tag with N in {0, 1, 6, 7}."""match = re.search(r"<points(?:\s[^>]*)?>(.*?)</points>", text, re.DOTALL)points = (re.fullmatch(r"\s*([0167])\s+out\s+of\s+7\s*", match.group(1), re.IGNORECASE)if matchelse None)if points is None:raise ValueError("Judge must return a first <points>N out of 7</points> with N in 0, 1, 6, 7")return int(points.group(1))def parse_retry_after(headers):if not headers:return Noneraw = headers.get("Retry-After")if raw is None:return Nonetext = str(raw).strip()if not text:return Nonetry:seconds = float(text)except ValueError:try:dt = email.utils.parsedate_to_datetime(text)except (TypeError, ValueError):return Noneseconds = dt.timestamp() - time.time()if seconds <= 0:return 0.0return 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:passretry_after = parse_retry_after(exc.headers) if exc.code in (429, 503) else Nonemsg = 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 excerr = RuntimeError(msg)err.retry_after = retry_afterraise err from excif 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 Noneif 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 = Nonelast_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 = rawpoints = parse_proof_points(raw)return points, raw, completion_tokens, attempt, Noneexcept NonRetryableJudgeError as exc:last_error = f"{type(exc).__name__}: {exc}"return None, last_raw, None, attempt, last_errorexcept (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_errordef main():out = os.environ["VERIFIER_DIR"]tests_dir = os.environ["TESTS_DIR"]os.makedirs(out, exist_ok=True)for stale in ("reward.txt", "reward.json"):try:os.unlink(os.path.join(out, stale))except FileNotFoundError:passproof_out_path = os.path.join(out, "proof.md")try:os.unlink(proof_out_path)except FileNotFoundError:passreference_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_MODELjudge_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 = 0non_ws_count = 0proof = ""try:raw = read_own(os.environ["PROOF"])proof = raw.decode("utf-8", "strict")char_count = len(proof)non_ws_count = sum(not ch.isspace() for ch in proof)write_new(proof_out_path, raw)if non_ws_count < MIN_NON_WS_CHARS:structural_status = "empty"structural_reason = f"fewer than {MIN_NON_WS_CHARS} non-whitespace characters"else:structural_status = "ok"structural_reason = "structurally valid submission"except (OSError, ValueError, UnicodeError) as exc:structural_reason = "proof unavailable or invalid: " + str(exc)[:200]structural = {"status": structural_status,"char_count": char_count,"non_whitespace_count": non_ws_count,"reason": structural_reason,}if structural_status != "ok":judgment = {"status": structural_status,"structural": structural,"judged_by_api": False,"judge_model": judge_model,"judge_base_url": judge_base_url,"points": 0,"max_score": 7,"reward": 0.0,"passed_6": False,"attempts": 0,"judge_output_tokens": 0,"raw_response": "","reason": structural_reason,"error": None,}write_json(os.path.join(out, "judgment.json"), judgment)write_json(os.path.join(out, "reward.json"), {"reward": 0.0, "points": 0})print(f"{structural_status}: points=0 reward=0.0 ({structural_reason})")returnif 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()
12345678910111213141516171819202122232425262728293031323334353637383940414243You 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 RubricScores 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 InterpretationYou 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 ProcessYou 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 RequirementsYou must provide your final score in the format <points>N out of 7</points>. Ensure the '<points>' block is used **only once**, as your answer will be parsed based on the first <points> </points> 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]<points>7 out of 7</points><points>6 out of 7</points><points>1 out of 7</points><points>0 out of 7</points>12345678910#!/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.set -euhere=$(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"123456789#!/bin/sh# 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 -euhere=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)export TESTS_DIR="$here" PROOF="${PROOF:-/app/proof.md}" VERIFIER_DIR="${VERIFIER_DIR:-/logs/verifier}"mkdir -p "$VERIFIER_DIR"rm -f "$VERIFIER_DIR/reward.txt" "$VERIFIER_DIR/reward.json"exec python3 -B -I -S "$here/grade_task.py"
15 unmodified lines161718192015 unmodified linescpus = 1memory_mb = 2048[verifier]network_mode = "allowlist"timeout_sec = 18015 unmodified lines1617181920212223242526272815 unmodified linescpus = 1memory_mb = 2048[verifier]environment_mode = "separate"network_mode = "allowlist"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}"
1234567The prompt template tests/proofbench_prompt.txt in each task is reproduced without changes fromCMU-AIRe/QED-Nano, revision 02a4699ed380f8e980a8d44c755b8bfd4e310718:https://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/configs/prompts/proofbench.txtQED-Nano is distributed under the Apache License 2.0 (see LICENSE).The self-evaluation cleanup (remove_self_evaluation) and points parser (parse_proof_points) intests/grade_task.py are adapted fromhttps://github.com/CMU-AIRe/QED-Nano/tree/02a4699ed380f8e980a8d44c755b8bfd4e310718/eval/src/imobenchLICENSEAdded+201
NOTICEAdded+7
README.md+24-3
tasks/pb-advanced-001/task.toml+9-1
tasks/pb-advanced-001/tests/NOTICEAdded+7
tasks/pb-advanced-001/tests/grade_task.py+330-33
tasks/pb-advanced-001/tests/proofbench_prompt.txtAdded+43
tasks/pb-advanced-001/tests/test.sh+4-5
tasks/pb-advanced-002/task.toml+9-1
tasks/pb-advanced-002/tests/NOTICEAdded+7
tasks/pb-advanced-002/tests/grade_task.py+330-33
tasks/pb-advanced-002/tests/proofbench_prompt.txtAdded+43
tasks/pb-advanced-002/tests/test.sh+4-5
tasks/pb-advanced-003/task.toml+9-1
tasks/pb-advanced-003/tests/NOTICEAdded+7
tasks/pb-advanced-003/tests/grade_task.py+330-33
tasks/pb-advanced-003/tests/proofbench_prompt.txtAdded+43
tasks/pb-advanced-003/tests/test.sh+4-5
tasks/pb-advanced-004/task.toml+9-1
tasks/pb-advanced-004/tests/NOTICEAdded+7
tasks/pb-advanced-004/tests/grade_task.py+330-33
tasks/pb-advanced-004/tests/proofbench_prompt.txtAdded+43
tasks/pb-advanced-004/tests/test.sh+4-5
tasks/pb-advanced-005/task.toml+9-1
tasks/pb-advanced-005/tests/NOTICEAdded+7
tasks/pb-advanced-005/tests/grade_task.py+330-33
tasks/pb-advanced-005/tests/proofbench_prompt.txtAdded+43
tasks/pb-advanced-005/tests/test.sh+4-5
tasks/pb-advanced-006/task.toml+9-1
tasks/pb-advanced-006/tests/NOTICEAdded+7
tasks/pb-advanced-006/tests/grade_task.py+330-33
tasks/pb-advanced-006/tests/proofbench_prompt.txtAdded+43
tasks/pb-advanced-006/tests/test.sh+4-5
tasks/pb-advanced-007/task.toml+9-1
tasks/pb-advanced-007/tests/NOTICEAdded+7
tasks/pb-advanced-007/tests/grade_task.py+330-33
tasks/pb-advanced-007/tests/proofbench_prompt.txtAdded+43
tasks/pb-advanced-007/tests/test.sh+4-5
tasks/pb-advanced-008/task.toml+9-1
tasks/pb-advanced-008/tests/NOTICEAdded+7
tasks/pb-advanced-008/tests/grade_task.py+330-33
tasks/pb-advanced-008/tests/proofbench_prompt.txtAdded+43
tasks/pb-advanced-008/tests/test.sh+4-5
tasks/pb-advanced-009/task.toml+9-1
tasks/pb-advanced-009/tests/NOTICEAdded+7
tasks/pb-advanced-009/tests/grade_task.py+330-33
tasks/pb-advanced-009/tests/proofbench_prompt.txtAdded+43
tasks/pb-advanced-009/tests/test.sh+4-5
tasks/pb-advanced-010/task.toml+9-1
tasks/pb-advanced-010/tests/NOTICEAdded+7