IMO-AnswerBench builder commited on
Commit ·
40d9d40
1
Parent(s): 66273bb
Package IMO-AnswerBench v2 as Harbor tasks
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- README.mdAdded+60
- subsets/algebra.jsonlAdded+100
- subsets/combinatorics.jsonlAdded+100
- subsets/geometry.jsonlAdded+100
- subsets/number_theory.jsonlAdded+100
- tasks/imo-bench-algebra-001/instruction.mdAdded+5
- tasks/imo-bench-algebra-001/solution/solve.shAdded+7
- tasks/imo-bench-algebra-001/task.tomlAdded+28
- tasks/imo-bench-algebra-001/tests/grade_task.pyAdded+104
- tasks/imo-bench-algebra-001/tests/grader.pyAdded+501
- tasks/imo-bench-algebra-001/tests/grader_struct.pyAdded+476
- tasks/imo-bench-algebra-001/tests/mpmath-1.3.0-py3-none-any.whl.b64Added
- tasks/imo-bench-algebra-001/tests/reference.jsonAdded+10
- tasks/imo-bench-algebra-001/tests/sympy-1.14.0-py3-none-any.whl.b64Added
- tasks/imo-bench-algebra-001/tests/test.shAdded+13
- tasks/imo-bench-algebra-002/instruction.mdAdded+6
- tasks/imo-bench-algebra-002/solution/solve.shAdded+7
- tasks/imo-bench-algebra-002/task.tomlAdded+28
- tasks/imo-bench-algebra-002/tests/grade_task.pyAdded+104
- tasks/imo-bench-algebra-002/tests/grader.pyAdded+501
- tasks/imo-bench-algebra-002/tests/grader_struct.pyAdded+476
- tasks/imo-bench-algebra-002/tests/mpmath-1.3.0-py3-none-any.whl.b64Added
- tasks/imo-bench-algebra-002/tests/reference.jsonAdded+10
- tasks/imo-bench-algebra-002/tests/sympy-1.14.0-py3-none-any.whl.b64Added
- tasks/imo-bench-algebra-002/tests/test.shAdded+13
- tasks/imo-bench-algebra-003/instruction.mdAdded+12
- tasks/imo-bench-algebra-003/solution/solve.shAdded+7
- tasks/imo-bench-algebra-003/task.tomlAdded+28
- tasks/imo-bench-algebra-003/tests/grade_task.pyAdded+104
- tasks/imo-bench-algebra-003/tests/grader.pyAdded+501
- tasks/imo-bench-algebra-003/tests/grader_struct.pyAdded+476
- tasks/imo-bench-algebra-003/tests/mpmath-1.3.0-py3-none-any.whl.b64Added
- tasks/imo-bench-algebra-003/tests/reference.jsonAdded+10
- tasks/imo-bench-algebra-003/tests/sympy-1.14.0-py3-none-any.whl.b64Added
- tasks/imo-bench-algebra-003/tests/test.shAdded+13
- tasks/imo-bench-algebra-004/instruction.mdAdded+5
- tasks/imo-bench-algebra-004/solution/solve.shAdded+7
- tasks/imo-bench-algebra-004/task.tomlAdded+28
- tasks/imo-bench-algebra-004/tests/grade_task.pyAdded+104
- tasks/imo-bench-algebra-004/tests/grader.pyAdded+501
- tasks/imo-bench-algebra-004/tests/grader_struct.pyAdded+476
- tasks/imo-bench-algebra-004/tests/mpmath-1.3.0-py3-none-any.whl.b64Added
- tasks/imo-bench-algebra-004/tests/reference.jsonAdded+10
- tasks/imo-bench-algebra-004/tests/sympy-1.14.0-py3-none-any.whl.b64Added
- tasks/imo-bench-algebra-004/tests/test.shAdded+13
- tasks/imo-bench-algebra-005/instruction.mdAdded+9
- tasks/imo-bench-algebra-005/solution/solve.shAdded+7
- tasks/imo-bench-algebra-005/task.tomlAdded+28
- tasks/imo-bench-algebra-005/tests/grade_task.pyAdded+104
- tasks/imo-bench-algebra-005/tests/grader.pyAdded+501
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960---language:- enlicense: apache-2.0license_name: apache-2.0-and-cc-by-4.0license_link: https://github.com/google-deepmind/superhuman/blob/main/imobench/README.md#license-and-disclaimertags:- library:harbor- harbor- math- evaluation- agent-environment- license:apache-2.0- imosize_categories:- 100<n<1K---
# IMO-AnswerBench: Harbor evaluation tasks
This dataset packages all 400 problems in Google DeepMind's [IMO-AnswerBench v2](https://github.com/google-deepmind/superhuman/blob/955558ad67ef24dccd27545c326988bdad1b4471/imobench/answerbench_v2.csv) as standalone Harbor 1.4 tasks. It uses the upstream short answers and preserves the problem IDs and source metadata. The original benchmark accompanies Luong et al., [“Towards Robust Mathematical Reasoning” (EMNLP 2025)](https://aclanthology.org/2025.emnlp-main.1794/). The upstream v2 data was released after that paper and corrects problems in the original benchmark.
## Composition
| Category | Tasks || --- | ---: || Algebra | 100 || Combinatorics | 100 || Geometry | 100 || Number theory | 100 || Total | 400 |
| Grading kind | Tasks || --- | ---: || Exact number | 272 || Expression | 36 || Finite set | 20 || Tuple | 7 || Interval | 4 || Literal notation / text | 61 |
The kinds indicate verifier behavior, not necessarily the mathematical form of every underlying answer. Literal tasks include constrained families, prose answers, unsupported notation, and malformed or otherwise unparseable source answers. The upstream row `imo-bench-algebra-036` has a missing closing CSV quote: its problem, answer, category, subcategory and source have been recovered from the row's visible delimiters. The geometry answer in `imo-bench-geometry-096` has an unmatched dollar delimiter in the upstream data and is preserved literally.
`tasks/manifest.json` lists the tasks and metadata; `subsets/*.jsonl` are category-specific lists. Each task contains `instruction.md`, `task.toml`, `solution/solve.sh`, and verifier files under `tests/`. The image is `python:3.12-slim`; each agent writes `/app/answer.txt`. The agent and verifier use allowlist network mode and have 3600 and 180 seconds respectively; the environment requests one CPU and 2048 MB memory. The reference answers are verifier data and should not be exposed to an agent before its run.
## Grading contract and limitations
The binary verifier writes `reward.txt`: 1 for an accepted answer, otherwise 0. It reads a single regular answer file of at most 10,000 bytes without following symlinks, rejects hard links and FIFOs, and defaults to zero on errors. SymPy 1.14.0 and mpmath 1.3.0 are packaged as SHA-256 checked base64 wheel text and extracted offline. The grader derives from [aops-math-bench](https://huggingface.co/datasets/HuggingFaceSwarms/aops-math-bench); structured expressions use real rather than universally positive symbols, and the reference grader's 24-point sequence acceptance is disabled because finite samples do not prove symbolic identity.
Numbers, finite sets, ordered tuples and intervals use the adapted exact grader. Expressions require symbolic equality the grader can establish, with random evaluations used only to reject. Supported notation and symbolic identities are limited; mathematically equivalent answers can be rejected. The expression parser does not encode problem-specific domains or all constraints on parameters.
For literal tasks the verifier compares the complete answer after Unicode NFC normalization and whitespace collapsing; it preserves case, punctuation, mathematical symbols, and LaTeX delimiters. It does not infer synonyms or algebraic equivalence. **A mathematically correct alternative can be rejected**, including reformulations of short text or parameterized families. This conservative fallback is explicit in each such task's instruction and avoids claiming an unproved symbolic equivalence. Source answers can themselves be abbreviated or imperfect; this is a short-answer benchmark, not a proof checker.
## Verification
Before publication, all 400 oracle scripts were run against their task verifiers using temporary `ANSWER` and `VERIFIER_DIR` overrides. The six answer kinds were sampled with wrong, empty, missing, symlinked, oversized, and FIFO answers. All 400 of 400 oracle runs passed. All 36 negative checks (six failure modes across six grading kinds) returned zero. All task files were checked: zero Git LFS pointers and zero binary files.
## Attribution and licenses
Copyright 2025 Google LLC and the IMO-Bench authors. Upstream software is Apache-2.0, while other materials including problem statements and answers are CC-BY-4.0, as specified in the [upstream license and disclaimer](https://github.com/google-deepmind/superhuman/blob/main/imobench/README.md#license-and-disclaimer). The `license: apache-2.0` Hub metadata describes the software; it does not replace the CC-BY-4.0 terms for the benchmark materials. The verifier adapts the aops-math-bench graders.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100{"task": "imo-bench-algebra-001", "problem_id": "imo-bench-algebra-001", "task_id": "imo-bench-algebra-001", "category": "Algebra", "subcategory": "Operation", "source": "IMO Shortlist 2021", "answer_kind": "number"}{"task": "imo-bench-algebra-002", "problem_id": "imo-bench-algebra-002", "task_id": "imo-bench-algebra-002", "category": "Algebra", "subcategory": "Inequality", "source": "IMO Shortlist 2021", "answer_kind": "literal"}{"task": "imo-bench-algebra-003", "problem_id": "imo-bench-algebra-003", "task_id": "imo-bench-algebra-003", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2021", "answer_kind": "literal"}{"task": "imo-bench-algebra-004", "problem_id": "imo-bench-algebra-004", "task_id": "imo-bench-algebra-004", "category": "Algebra", "subcategory": "Inequality", "source": "IMO Shortlist 2021", "answer_kind": "expression"}{"task": "imo-bench-algebra-005", "problem_id": "imo-bench-algebra-005", "task_id": "imo-bench-algebra-005", "category": "Algebra", "subcategory": "Inequality", "source": "IMO Shortlist 2020", "answer_kind": "number"}{"task": "imo-bench-algebra-006", "problem_id": "imo-bench-algebra-006", "task_id": "imo-bench-algebra-006", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2020", "answer_kind": "literal"}{"task": "imo-bench-algebra-007", "problem_id": "imo-bench-algebra-007", "task_id": "imo-bench-algebra-007", "category": "Algebra", "subcategory": "Equation", "source": "IMO Shortlist 2020", "answer_kind": "number"}{"task": "imo-bench-algebra-008", "problem_id": "imo-bench-algebra-008", "task_id": "imo-bench-algebra-008", "category": "Algebra", "subcategory": "Sequence", "source": "IMO Shortlist 2019", "answer_kind": "number"}{"task": "imo-bench-algebra-009", "problem_id": "imo-bench-algebra-009", "task_id": "imo-bench-algebra-009", "category": "Algebra", "subcategory": "Inequality", "source": "IMO Shortlist 2018", "answer_kind": "number"}{"task": "imo-bench-algebra-010", "problem_id": "imo-bench-algebra-010", "task_id": "imo-bench-algebra-010", "category": "Algebra", "subcategory": "Operation", "source": "IMO Shortlist 2018", "answer_kind": "set"}{"task": "imo-bench-algebra-011", "problem_id": "imo-bench-algebra-011", "task_id": "imo-bench-algebra-011", "category": "Algebra", "subcategory": "Inequality", "source": "IMO Shortlist 2017", "answer_kind": "expression"}{"task": "imo-bench-algebra-012", "problem_id": "imo-bench-algebra-012", "task_id": "imo-bench-algebra-012", "category": "Algebra", "subcategory": "Other", "source": "IMO Shortlist 2017", "answer_kind": "number"}{"task": "imo-bench-algebra-013", "problem_id": "imo-bench-algebra-013", "task_id": "imo-bench-algebra-013", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2016", "answer_kind": "literal"}{"task": "imo-bench-algebra-014", "problem_id": "imo-bench-algebra-014", "task_id": "imo-bench-algebra-014", "category": "Algebra", "subcategory": "Inequality", "source": "IMO Shortlist 2016", "answer_kind": "expression"}{"task": "imo-bench-algebra-015", "problem_id": "imo-bench-algebra-015", "task_id": "imo-bench-algebra-015", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2015", "answer_kind": "number"}{"task": "imo-bench-algebra-016", "problem_id": "imo-bench-algebra-016", "task_id": "imo-bench-algebra-016", "category": "Algebra", "subcategory": "Sequence", "source": "IMO Shortlist 2015", "answer_kind": "number"}{"task": "imo-bench-algebra-017", "problem_id": "imo-bench-algebra-017", "task_id": "imo-bench-algebra-017", "category": "Algebra", "subcategory": "Polynomial", "source": "IMO Shortlist 2014", "answer_kind": "literal"}{"task": "imo-bench-algebra-018", "problem_id": "imo-bench-algebra-018", "task_id": "imo-bench-algebra-018", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2014", "answer_kind": "set"}{"task": "imo-bench-algebra-019", "problem_id": "imo-bench-algebra-019", "task_id": "imo-bench-algebra-019", "category": "Algebra", "subcategory": "Equation", "source": "IMO Shortlist 2013", "answer_kind": "number"}{"task": "imo-bench-algebra-020", "problem_id": "imo-bench-algebra-020", "task_id": "imo-bench-algebra-020", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2011", "answer_kind": "expression"}{"task": "imo-bench-algebra-021", "problem_id": "imo-bench-algebra-021", "task_id": "imo-bench-algebra-021", "category": "Algebra", "subcategory": "Inequality", "source": "IMO Shortlist 2011", "answer_kind": "number"}{"task": "imo-bench-algebra-022", "problem_id": "imo-bench-algebra-022", "task_id": "imo-bench-algebra-022", "category": "Algebra", "subcategory": "Inequality", "source": "IMO Shortlist 2010", "answer_kind": "number"}{"task": "imo-bench-algebra-023", "problem_id": "imo-bench-algebra-023", "task_id": "imo-bench-algebra-023", "category": "Algebra", "subcategory": "Sequence", "source": "IMO Shortlist 2010", "answer_kind": "number"}{"task": "imo-bench-algebra-024", "problem_id": "imo-bench-algebra-024", "task_id": "imo-bench-algebra-024", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2009", "answer_kind": "literal"}{"task": "imo-bench-algebra-025", "problem_id": "imo-bench-algebra-025", "task_id": "imo-bench-algebra-025", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2007", "answer_kind": "literal"}{"task": "imo-bench-algebra-026", "problem_id": "imo-bench-algebra-026", "task_id": "imo-bench-algebra-026", "category": "Algebra", "subcategory": "Other", "source": "IMO Shortlist 2005", "answer_kind": "number"}{"task": "imo-bench-algebra-027", "problem_id": "imo-bench-algebra-027", "task_id": "imo-bench-algebra-027", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2004", "answer_kind": "interval"}{"task": "imo-bench-algebra-028", "problem_id": "imo-bench-algebra-028", "task_id": "imo-bench-algebra-028", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2004", "answer_kind": "interval"}{"task": "imo-bench-algebra-029", "problem_id": "imo-bench-algebra-029", "task_id": "imo-bench-algebra-029", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2003", "answer_kind": "literal"}{"task": "imo-bench-algebra-030", "problem_id": "imo-bench-algebra-030", "task_id": "imo-bench-algebra-030", "category": "Algebra", "subcategory": "Inequality", "source": "IMO Shortlist 2003", "answer_kind": "number"}{"task": "imo-bench-algebra-031", "problem_id": "imo-bench-algebra-031", "task_id": "imo-bench-algebra-031", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2002", "answer_kind": "literal"}{"task": "imo-bench-algebra-032", "problem_id": "imo-bench-algebra-032", "task_id": "imo-bench-algebra-032", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2001", "answer_kind": "number"}{"task": "imo-bench-algebra-033", "problem_id": "imo-bench-algebra-033", "task_id": "imo-bench-algebra-033", "category": "Algebra", "subcategory": "Sequence", "source": "IMO Shortlist 2001", "answer_kind": "tuple"}{"task": "imo-bench-algebra-034", "problem_id": "imo-bench-algebra-034", "task_id": "imo-bench-algebra-034", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2001", "answer_kind": "literal"}{"task": "imo-bench-algebra-035", "problem_id": "imo-bench-algebra-035", "task_id": "imo-bench-algebra-035", "category": "Algebra", "subcategory": "Polynomial", "source": "Iran 2002", "answer_kind": "literal"}{"task": "imo-bench-algebra-036", "problem_id": "imo-bench-algebra-036", "task_id": "imo-bench-algebra-036", "category": "Algebra", "subcategory": "Functional Equation", "source": "Iran 2002", "answer_kind": "expression"}{"task": "imo-bench-algebra-037", "problem_id": "imo-bench-algebra-037", "task_id": "imo-bench-algebra-037", "category": "Algebra", "subcategory": "Functional Equation", "source": "Iran 2024", "answer_kind": "literal"}{"task": "imo-bench-algebra-038", "problem_id": "imo-bench-algebra-038", "task_id": "imo-bench-algebra-038", "category": "Algebra", "subcategory": "Polynomial", "source": "Iran 2024", "answer_kind": "literal"}{"task": "imo-bench-algebra-039", "problem_id": "imo-bench-algebra-039", "task_id": "imo-bench-algebra-039", "category": "Algebra", "subcategory": "Equation", "source": "Ukraine 1997", "answer_kind": "number"}{"task": "imo-bench-algebra-040", "problem_id": "imo-bench-algebra-040", "task_id": "imo-bench-algebra-040", "category": "Algebra", "subcategory": "Functional Equation", "source": "Korea 2018", "answer_kind": "expression"}{"task": "imo-bench-algebra-041", "problem_id": "imo-bench-algebra-041", "task_id": "imo-bench-algebra-041", "category": "Algebra", "subcategory": "Polynomial", "source": "Iran 2009", "answer_kind": "literal"}{"task": "imo-bench-algebra-042", "problem_id": "imo-bench-algebra-042", "task_id": "imo-bench-algebra-042", "category": "Algebra", "subcategory": "Sequence", "source": "Iran 2010", "answer_kind": "number"}{"task": "imo-bench-algebra-043", "problem_id": "imo-bench-algebra-043", "task_id": "imo-bench-algebra-043", "category": "Algebra", "subcategory": "Inequality", "source": "IMO Shortlist 1986", "answer_kind": "number"}{"task": "imo-bench-algebra-044", "problem_id": "imo-bench-algebra-044", "task_id": "imo-bench-algebra-044", "category": "Algebra", "subcategory": "Inequality", "source": "APMO 2004", "answer_kind": "number"}{"task": "imo-bench-algebra-045", "problem_id": "imo-bench-algebra-045", "task_id": "imo-bench-algebra-045", "category": "Algebra", "subcategory": "Inequality", "source": "Vietnam 2004", "answer_kind": "number"}{"task": "imo-bench-algebra-046", "problem_id": "imo-bench-algebra-046", "task_id": "imo-bench-algebra-046", "category": "Algebra", "subcategory": "Inequality", "source": "Vietnam 2002", "answer_kind": "number"}{"task": "imo-bench-algebra-047", "problem_id": "imo-bench-algebra-047", "task_id": "imo-bench-algebra-047", "category": "Algebra", "subcategory": "Polynomial", "source": "Vietnam 1997", "answer_kind": "expression"}{"task": "imo-bench-algebra-048", "problem_id": "imo-bench-algebra-048", "task_id": "imo-bench-algebra-048", "category": "Algebra", "subcategory": "Polynomial", "source": "Czech-Slovakia 1995", "answer_kind": "interval"}{"task": "imo-bench-algebra-049", "problem_id": "imo-bench-algebra-049", "task_id": "imo-bench-algebra-049", "category": "Algebra", "subcategory": "Inequality", "source": "Moldova 2008", "answer_kind": "number"}{"task": "imo-bench-algebra-050", "problem_id": "imo-bench-algebra-050", "task_id": "imo-bench-algebra-050", "category": "Algebra", "subcategory": "Polynomial", "source": "Vietnam 2015", "answer_kind": "number"}{"task": "imo-bench-algebra-051", "problem_id": "imo-bench-algebra-051", "task_id": "imo-bench-algebra-051", "category": "Algebra", "subcategory": "Polynomial", "source": "Czech-Polish-Slovak Match 2005", "answer_kind": "literal"}{"task": "imo-bench-algebra-052", "problem_id": "imo-bench-algebra-052", "task_id": "imo-bench-algebra-052", "category": "Algebra", "subcategory": "Sequence", "source": "Argentina 2017", "answer_kind": "number"}{"task": "imo-bench-algebra-053", "problem_id": "imo-bench-algebra-053", "task_id": "imo-bench-algebra-053", "category": "Algebra", "subcategory": "Inequality", "source": "Czech and Slovak 2018", "answer_kind": "interval"}{"task": "imo-bench-algebra-054", "problem_id": "imo-bench-algebra-054", "task_id": "imo-bench-algebra-054", "category": "Algebra", "subcategory": "Sequence", "source": "Italia 2018", "answer_kind": "number"}{"task": "imo-bench-algebra-055", "problem_id": "imo-bench-algebra-055", "task_id": "imo-bench-algebra-055", "category": "Algebra", "subcategory": "Sequence", "source": "Japan 2018", "answer_kind": "number"}{"task": "imo-bench-algebra-056", "problem_id": "imo-bench-algebra-056", "task_id": "imo-bench-algebra-056", "category": "Algebra", "subcategory": "Polynomial", "source": "Korea 2018", "answer_kind": "number"}{"task": "imo-bench-algebra-057", "problem_id": "imo-bench-algebra-057", "task_id": "imo-bench-algebra-057", "category": "Algebra", "subcategory": "Operation", "source": "Balkan 2018", "answer_kind": "set"}{"task": "imo-bench-algebra-058", "problem_id": "imo-bench-algebra-058", "task_id": "imo-bench-algebra-058", "category": "Algebra", "subcategory": "Inequality", "source": "Romania 2018", "answer_kind": "number"}{"task": "imo-bench-algebra-059", "problem_id": "imo-bench-algebra-059", "task_id": "imo-bench-algebra-059", "category": "Algebra", "subcategory": "Inequality", "source": "Romania 2018", "answer_kind": "number"}{"task": "imo-bench-algebra-060", "problem_id": "imo-bench-algebra-060", "task_id": "imo-bench-algebra-060", "category": "Algebra", "subcategory": "Inequality", "source": "Singapore 2018", "answer_kind": "number"}{"task": "imo-bench-algebra-061", "problem_id": "imo-bench-algebra-061", "task_id": "imo-bench-algebra-061", "category": "Algebra", "subcategory": "Polynomial", "source": "Singapore 2018", "answer_kind": "number"}{"task": "imo-bench-algebra-062", "problem_id": "imo-bench-algebra-062", "task_id": "imo-bench-algebra-062", "category": "Algebra", "subcategory": "Sequence", "source": "Turkey 2018", "answer_kind": "number"}{"task": "imo-bench-algebra-063", "problem_id": "imo-bench-algebra-063", "task_id": "imo-bench-algebra-063", "category": "Algebra", "subcategory": "Inequality", "source": "Austria 2017", "answer_kind": "number"}{"task": "imo-bench-algebra-064", "problem_id": "imo-bench-algebra-064", "task_id": "imo-bench-algebra-064", "category": "Algebra", "subcategory": "Inequality", "source": "Belarus 2017", "answer_kind": "number"}{"task": "imo-bench-algebra-065", "problem_id": "imo-bench-algebra-065", "task_id": "imo-bench-algebra-065", "category": "Algebra", "subcategory": "Sequence", "source": "Belarus 2017", "answer_kind": "literal"}{"task": "imo-bench-algebra-066", "problem_id": "imo-bench-algebra-066", "task_id": "imo-bench-algebra-066", "category": "Algebra", "subcategory": "Sequence", "source": "Korea 2017", "answer_kind": "set"}{"task": "imo-bench-algebra-067", "problem_id": "imo-bench-algebra-067", "task_id": "imo-bench-algebra-067", "category": "Algebra", "subcategory": "Equation", "source": "Romania 2017", "answer_kind": "tuple"}{"task": "imo-bench-algebra-068", "problem_id": "imo-bench-algebra-068", "task_id": "imo-bench-algebra-068", "category": "Algebra", "subcategory": "Polynomial", "source": "RMM 2017", "answer_kind": "number"}{"task": "imo-bench-algebra-069", "problem_id": "imo-bench-algebra-069", "task_id": "imo-bench-algebra-069", "category": "Algebra", "subcategory": "Sequence", "source": "Serbia 2017", "answer_kind": "literal"}{"task": "imo-bench-algebra-070", "problem_id": "imo-bench-algebra-070", "task_id": "imo-bench-algebra-070", "category": "Algebra", "subcategory": "Inequality", "source": "Ukraine 2017", "answer_kind": "number"}{"task": "imo-bench-algebra-071", "problem_id": "imo-bench-algebra-071", "task_id": "imo-bench-algebra-071", "category": "Algebra", "subcategory": "Inequality", "source": "USAMO 2017", "answer_kind": "number"}{"task": "imo-bench-algebra-072", "problem_id": "imo-bench-algebra-072", "task_id": "imo-bench-algebra-072", "category": "Algebra", "subcategory": "Sequence", "source": "Vietnam 2017 (modified)", "answer_kind": "literal"}{"task": "imo-bench-algebra-073", "problem_id": "imo-bench-algebra-073", "task_id": "imo-bench-algebra-073", "category": "Algebra", "subcategory": "Inequality", "source": "Austria 2016 (modified)", "answer_kind": "number"}{"task": "imo-bench-algebra-074", "problem_id": "imo-bench-algebra-074", "task_id": "imo-bench-algebra-074", "category": "Algebra", "subcategory": "Sequence", "source": "Dutch 2015", "answer_kind": "set"}{"task": "imo-bench-algebra-075", "problem_id": "imo-bench-algebra-075", "task_id": "imo-bench-algebra-075", "category": "Algebra", "subcategory": "Inequality", "source": "Hong Kong TST 2015", "answer_kind": "number"}{"task": "imo-bench-algebra-076", "problem_id": "imo-bench-algebra-076", "task_id": "imo-bench-algebra-076", "category": "Algebra", "subcategory": "Inequality", "source": "Hong Kong 2015", "answer_kind": "number"}{"task": "imo-bench-algebra-077", "problem_id": "imo-bench-algebra-077", "task_id": "imo-bench-algebra-077", "category": "Algebra", "subcategory": "Inequality", "source": "Korea 2016", "answer_kind": "number"}{"task": "imo-bench-algebra-078", "problem_id": "imo-bench-algebra-078", "task_id": "imo-bench-algebra-078", "category": "Algebra", "subcategory": "Inequality", "source": "Romania 2016 (modified)", "answer_kind": "number"}{"task": "imo-bench-algebra-079", "problem_id": "imo-bench-algebra-079", "task_id": "imo-bench-algebra-079", "category": "Algebra", "subcategory": "Functional Equation", "source": "Vietnam TST 2014", "answer_kind": "expression"}{"task": "imo-bench-algebra-080", "problem_id": "imo-bench-algebra-080", "task_id": "imo-bench-algebra-080", "category": "Algebra", "subcategory": "Polynomial", "source": "Vietnam TST 2014", "answer_kind": "number"}{"task": "imo-bench-algebra-081", "problem_id": "imo-bench-algebra-081", "task_id": "imo-bench-algebra-081", "category": "Algebra", "subcategory": "Polynomial", "source": "Bulgaria 2014", "answer_kind": "literal"}{"task": "imo-bench-algebra-082", "problem_id": "imo-bench-algebra-082", "task_id": "imo-bench-algebra-082", "category": "Algebra", "subcategory": "Inequality", "source": "China TST 2014", "answer_kind": "literal"}{"task": "imo-bench-algebra-083", "problem_id": "imo-bench-algebra-083", "task_id": "imo-bench-algebra-083", "category": "Algebra", "subcategory": "Sequence", "source": "China MO 2014", "answer_kind": "number"}{"task": "imo-bench-algebra-084", "problem_id": "imo-bench-algebra-084", "task_id": "imo-bench-algebra-084", "category": "Algebra", "subcategory": "Polynomial", "source": "Greece 2014", "answer_kind": "expression"}{"task": "imo-bench-algebra-085", "problem_id": "imo-bench-algebra-085", "task_id": "imo-bench-algebra-085", "category": "Algebra", "subcategory": "Inequality", "source": "Japan MO 2014", "answer_kind": "number"}{"task": "imo-bench-algebra-086", "problem_id": "imo-bench-algebra-086", "task_id": "imo-bench-algebra-086", "category": "Algebra", "subcategory": "Inequality", "source": "Japan TST 2014", "answer_kind": "literal"}{"task": "imo-bench-algebra-087", "problem_id": "imo-bench-algebra-087", "task_id": "imo-bench-algebra-087", "category": "Algebra", "subcategory": "Polynomial", "source": "Bulgaria 1998", "answer_kind": "literal"}{"task": "imo-bench-algebra-088", "problem_id": "imo-bench-algebra-088", "task_id": "imo-bench-algebra-088", "category": "Algebra", "subcategory": "Equation", "source": "Czech and Slovak 1998", "answer_kind": "number"}{"task": "imo-bench-algebra-089", "problem_id": "imo-bench-algebra-089", "task_id": "imo-bench-algebra-089", "category": "Algebra", "subcategory": "Sequence", "source": "Turkey 1998", "answer_kind": "number"}{"task": "imo-bench-algebra-090", "problem_id": "imo-bench-algebra-090", "task_id": "imo-bench-algebra-090", "category": "Algebra", "subcategory": "Functional Equation", "source": "Czech-Slovak Match 1998", "answer_kind": "set"}{"task": "imo-bench-algebra-091", "problem_id": "imo-bench-algebra-091", "task_id": "imo-bench-algebra-091", "category": "Algebra", "subcategory": "Sequence", "source": "Iran 2011", "answer_kind": "literal"}{"task": "imo-bench-algebra-092", "problem_id": "imo-bench-algebra-092", "task_id": "imo-bench-algebra-092", "category": "Algebra", "subcategory": "Inequality", "source": "Iran 2012", "answer_kind": "number"}{"task": "imo-bench-algebra-093", "problem_id": "imo-bench-algebra-093", "task_id": "imo-bench-algebra-093", "category": "Algebra", "subcategory": "Sequence", "source": "Iran 2018", "answer_kind": "number"}{"task": "imo-bench-algebra-094", "problem_id": "imo-bench-algebra-094", "task_id": "imo-bench-algebra-094", "category": "Algebra", "subcategory": "Polynomial", "source": "Iran 2014", "answer_kind": "number"}{"task": "imo-bench-algebra-095", "problem_id": "imo-bench-algebra-095", "task_id": "imo-bench-algebra-095", "category": "Algebra", "subcategory": "Sequence", "source": "Taiwan 2000", "answer_kind": "number"}{"task": "imo-bench-algebra-096", "problem_id": "imo-bench-algebra-096", "task_id": "imo-bench-algebra-096", "category": "Algebra", "subcategory": "Inequality", "source": "Iran 2000", "answer_kind": "number"}{"task": "imo-bench-algebra-097", "problem_id": "imo-bench-algebra-097", "task_id": "imo-bench-algebra-097", "category": "Algebra", "subcategory": "Sequence", "source": "Iran 2000", "answer_kind": "literal"}{"task": "imo-bench-algebra-098", "problem_id": "imo-bench-algebra-098", "task_id": "imo-bench-algebra-098", "category": "Algebra", "subcategory": "Inequality", "source": "Iran 2000", "answer_kind": "literal"}{"task": "imo-bench-algebra-099", "problem_id": "imo-bench-algebra-099", "task_id": "imo-bench-algebra-099", "category": "Algebra", "subcategory": "Functional Equation", "source": "Iran 2019", "answer_kind": "literal"}{"task": "imo-bench-algebra-100", "problem_id": "imo-bench-algebra-100", "task_id": "imo-bench-algebra-100", "category": "Algebra", "subcategory": "Inequality", "source": "Variation of Vasc's inequality", "answer_kind": "number"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100{"task": "imo-bench-combinatorics-001", "problem_id": "imo-bench-combinatorics-001", "task_id": "imo-bench-combinatorics-001", "category": "Combinatorics", "subcategory": "Graph Theory", "source": "HKMO 2002", "answer_kind": "number"}{"task": "imo-bench-combinatorics-002", "problem_id": "imo-bench-combinatorics-002", "task_id": "imo-bench-combinatorics-002", "category": "Combinatorics", "subcategory": "Existence Combinatorics", "source": "Germany 2006", "answer_kind": "number"}{"task": "imo-bench-combinatorics-003", "problem_id": "imo-bench-combinatorics-003", "task_id": "imo-bench-combinatorics-003", "category": "Combinatorics", "subcategory": "Operations", "source": "Tournament of Towns 2019", "answer_kind": "number"}{"task": "imo-bench-combinatorics-004", "problem_id": "imo-bench-combinatorics-004", "task_id": "imo-bench-combinatorics-004", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "Vietnam Mathematical Olympiad 1990", "answer_kind": "number"}{"task": "imo-bench-combinatorics-005", "problem_id": "imo-bench-combinatorics-005", "task_id": "imo-bench-combinatorics-005", "category": "Combinatorics", "subcategory": "Enumerative Combinatorics", "source": "Vietnam Mathematical Olympiad 2015", "answer_kind": "number"}{"task": "imo-bench-combinatorics-006", "problem_id": "imo-bench-combinatorics-006", "task_id": "imo-bench-combinatorics-006", "category": "Combinatorics", "subcategory": "Graph Theory", "source": "Vietnam TST 2019", "answer_kind": "number"}{"task": "imo-bench-combinatorics-007", "problem_id": "imo-bench-combinatorics-007", "task_id": "imo-bench-combinatorics-007", "category": "Combinatorics", "subcategory": "Graph Theory", "source": "USA TST 2001", "answer_kind": "number"}{"task": "imo-bench-combinatorics-008", "problem_id": "imo-bench-combinatorics-008", "task_id": "imo-bench-combinatorics-008", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "USA TST 2005", "answer_kind": "number"}{"task": "imo-bench-combinatorics-009", "problem_id": "imo-bench-combinatorics-009", "task_id": "imo-bench-combinatorics-009", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "APMO 2010", "answer_kind": "number"}{"task": "imo-bench-combinatorics-010", "problem_id": "imo-bench-combinatorics-010", "task_id": "imo-bench-combinatorics-010", "category": "Combinatorics", "subcategory": "Game Theory", "source": "USAJMO 2023", "answer_kind": "number"}{"task": "imo-bench-combinatorics-011", "problem_id": "imo-bench-combinatorics-011", "task_id": "imo-bench-combinatorics-011", "category": "Combinatorics", "subcategory": "Operations", "source": "EGMO 2023", "answer_kind": "number"}{"task": "imo-bench-combinatorics-012", "problem_id": "imo-bench-combinatorics-012", "task_id": "imo-bench-combinatorics-012", "category": "Combinatorics", "subcategory": "Enumerative Combinatorics", "source": "EGMO 2015", "answer_kind": "literal"}{"task": "imo-bench-combinatorics-013", "problem_id": "imo-bench-combinatorics-013", "task_id": "imo-bench-combinatorics-013", "category": "Combinatorics", "subcategory": "Enumerative Combinatorics", "source": "Vietnam Mathematical Olympiad 2009", "answer_kind": "number"}{"task": "imo-bench-combinatorics-014", "problem_id": "imo-bench-combinatorics-014", "task_id": "imo-bench-combinatorics-014", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "Vietnam TST 2021", "answer_kind": "number"}{"task": "imo-bench-combinatorics-015", "problem_id": "imo-bench-combinatorics-015", "task_id": "imo-bench-combinatorics-015", "category": "Combinatorics", "subcategory": "Enumerative Combinatorics", "source": "Putnam 2017", "answer_kind": "number"}{"task": "imo-bench-combinatorics-016", "problem_id": "imo-bench-combinatorics-016", "task_id": "imo-bench-combinatorics-016", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "China 2006", "answer_kind": "number"}{"task": "imo-bench-combinatorics-017", "problem_id": "imo-bench-combinatorics-017", "task_id": "imo-bench-combinatorics-017", "category": "Combinatorics", "subcategory": "Enumerative Combinatorics", "source": "China 2009", "answer_kind": "number"}{"task": "imo-bench-combinatorics-018", "problem_id": "imo-bench-combinatorics-018", "task_id": "imo-bench-combinatorics-018", "category": "Combinatorics", "subcategory": "Additive Combinatorics", "source": "China 2012", "answer_kind": "number"}{"task": "imo-bench-combinatorics-019", "problem_id": "imo-bench-combinatorics-019", "task_id": "imo-bench-combinatorics-019", "category": "Combinatorics", "subcategory": "Enumerative Combinatorics", "source": "China 2012", "answer_kind": "number"}{"task": "imo-bench-combinatorics-020", "problem_id": "imo-bench-combinatorics-020", "task_id": "imo-bench-combinatorics-020", "category": "Combinatorics", "subcategory": "Graph Theory", "source": "Vietnam TST 2020", "answer_kind": "number"}{"task": "imo-bench-combinatorics-021", "problem_id": "imo-bench-combinatorics-021", "task_id": "imo-bench-combinatorics-021", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "Vietnam TST 2016", "answer_kind": "number"}{"task": "imo-bench-combinatorics-022", "problem_id": "imo-bench-combinatorics-022", "task_id": "imo-bench-combinatorics-022", "category": "Combinatorics", "subcategory": "Enumerative Combinatorics", "source": "Balkan MO 2014", "answer_kind": "number"}{"task": "imo-bench-combinatorics-023", "problem_id": "imo-bench-combinatorics-023", "task_id": "imo-bench-combinatorics-023", "category": "Combinatorics", "subcategory": "Graph Theory", "source": "USA TST 2017", "answer_kind": "number"}{"task": "imo-bench-combinatorics-024", "problem_id": "imo-bench-combinatorics-024", "task_id": "imo-bench-combinatorics-024", "category": "Combinatorics", "subcategory": "Enumerative Combinatorics", "source": "Putnam 2005", "answer_kind": "number"}{"task": "imo-bench-combinatorics-025", "problem_id": "imo-bench-combinatorics-025", "task_id": "imo-bench-combinatorics-025", "category": "Combinatorics", "subcategory": "Game Theory", "source": "Putnam 2022", "answer_kind": "number"}{"task": "imo-bench-combinatorics-026", "problem_id": "imo-bench-combinatorics-026", "task_id": "imo-bench-combinatorics-026", "category": "Combinatorics", "subcategory": "Enumerative Combinatorics", "source": "USA 2015", "answer_kind": "number"}{"task": "imo-bench-combinatorics-027", "problem_id": "imo-bench-combinatorics-027", "task_id": "imo-bench-combinatorics-027", "category": "Combinatorics", "subcategory": "Operations", "source": "USA 2019", "answer_kind": "number"}{"task": "imo-bench-combinatorics-028", "problem_id": "imo-bench-combinatorics-028", "task_id": "imo-bench-combinatorics-028", "category": "Combinatorics", "subcategory": "Operations", "source": "Vietnam Mathematical Olympiad 2013", "answer_kind": "number"}{"task": "imo-bench-combinatorics-029", "problem_id": "imo-bench-combinatorics-029", "task_id": "imo-bench-combinatorics-029", "category": "Combinatorics", "subcategory": "Tiling", "source": "Vietnam TST 2010", "answer_kind": "number"}{"task": "imo-bench-combinatorics-030", "problem_id": "imo-bench-combinatorics-030", "task_id": "imo-bench-combinatorics-030", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "Vietnam TST 2013", "answer_kind": "number"}{"task": "imo-bench-combinatorics-031", "problem_id": "imo-bench-combinatorics-031", "task_id": "imo-bench-combinatorics-031", "category": "Combinatorics", "subcategory": "Game Theory", "source": "USA TST 2020", "answer_kind": "number"}{"task": "imo-bench-combinatorics-032", "problem_id": "imo-bench-combinatorics-032", "task_id": "imo-bench-combinatorics-032", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "USAMO 2010", "answer_kind": "number"}{"task": "imo-bench-combinatorics-033", "problem_id": "imo-bench-combinatorics-033", "task_id": "imo-bench-combinatorics-033", "category": "Combinatorics", "subcategory": "Operations", "source": "USAMO 2021", "answer_kind": "number"}{"task": "imo-bench-combinatorics-034", "problem_id": "imo-bench-combinatorics-034", "task_id": "imo-bench-combinatorics-034", "category": "Combinatorics", "subcategory": "Operations", "source": "China TST 2022", "answer_kind": "expression"}{"task": "imo-bench-combinatorics-035", "problem_id": "imo-bench-combinatorics-035", "task_id": "imo-bench-combinatorics-035", "category": "Combinatorics", "subcategory": "Combinatorial Geometry", "source": "Iran TST 2012", "answer_kind": "number"}{"task": "imo-bench-combinatorics-036", "problem_id": "imo-bench-combinatorics-036", "task_id": "imo-bench-combinatorics-036", "category": "Combinatorics", "subcategory": "Operations", "source": "China MO 2024", "answer_kind": "number"}{"task": "imo-bench-combinatorics-037", "problem_id": "imo-bench-combinatorics-037", "task_id": "imo-bench-combinatorics-037", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2000", "answer_kind": "number"}{"task": "imo-bench-combinatorics-038", "problem_id": "imo-bench-combinatorics-038", "task_id": "imo-bench-combinatorics-038", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2001", "answer_kind": "number"}{"task": "imo-bench-combinatorics-039", "problem_id": "imo-bench-combinatorics-039", "task_id": "imo-bench-combinatorics-039", "category": "Combinatorics", "subcategory": "Tiling", "source": "IMO Shortlist 2002", "answer_kind": "number"}{"task": "imo-bench-combinatorics-040", "problem_id": "imo-bench-combinatorics-040", "task_id": "imo-bench-combinatorics-040", "category": "Combinatorics", "subcategory": "Enumerative Combinatorics", "source": "IMO Shortlist 2002", "answer_kind": "number"}{"task": "imo-bench-combinatorics-041", "problem_id": "imo-bench-combinatorics-041", "task_id": "imo-bench-combinatorics-041", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2002", "answer_kind": "number"}{"task": "imo-bench-combinatorics-042", "problem_id": "imo-bench-combinatorics-042", "task_id": "imo-bench-combinatorics-042", "category": "Combinatorics", "subcategory": "Graph Theory", "source": "IMO Shortlist 2002", "answer_kind": "number"}{"task": "imo-bench-combinatorics-043", "problem_id": "imo-bench-combinatorics-043", "task_id": "imo-bench-combinatorics-043", "category": "Combinatorics", "subcategory": "Existence Combinatorics", "source": "IMO Shortlist 2004", "answer_kind": "number"}{"task": "imo-bench-combinatorics-044", "problem_id": "imo-bench-combinatorics-044", "task_id": "imo-bench-combinatorics-044", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2004", "answer_kind": "number"}{"task": "imo-bench-combinatorics-045", "problem_id": "imo-bench-combinatorics-045", "task_id": "imo-bench-combinatorics-045", "category": "Combinatorics", "subcategory": "Game Theory", "source": "IMO Shortlist 2004", "answer_kind": "number"}{"task": "imo-bench-combinatorics-046", "problem_id": "imo-bench-combinatorics-046", "task_id": "imo-bench-combinatorics-046", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2004", "answer_kind": "number"}{"task": "imo-bench-combinatorics-047", "problem_id": "imo-bench-combinatorics-047", "task_id": "imo-bench-combinatorics-047", "category": "Combinatorics", "subcategory": "Graph Theory", "source": "IMO Shortlist 2004", "answer_kind": "number"}{"task": "imo-bench-combinatorics-048", "problem_id": "imo-bench-combinatorics-048", "task_id": "imo-bench-combinatorics-048", "category": "Combinatorics", "subcategory": "Existence Combinatorics", "source": "IMO Shortlist 2007", "answer_kind": "number"}{"task": "imo-bench-combinatorics-049", "problem_id": "imo-bench-combinatorics-049", "task_id": "imo-bench-combinatorics-049", "category": "Combinatorics", "subcategory": "Operations", "source": "China TST 2023", "answer_kind": "number"}{"task": "imo-bench-combinatorics-050", "problem_id": "imo-bench-combinatorics-050", "task_id": "imo-bench-combinatorics-050", "category": "Combinatorics", "subcategory": "Existence Combinatorics", "source": "IMO Shortlist 2010", "answer_kind": "number"}{"task": "imo-bench-combinatorics-051", "problem_id": "imo-bench-combinatorics-051", "task_id": "imo-bench-combinatorics-051", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "Korean Final 2022", "answer_kind": "number"}{"task": "imo-bench-combinatorics-052", "problem_id": "imo-bench-combinatorics-052", "task_id": "imo-bench-combinatorics-052", "category": "Combinatorics", "subcategory": "Enumerative Combinatorics", "source": "IMO Shortlist 2011", "answer_kind": "literal"}{"task": "imo-bench-combinatorics-053", "problem_id": "imo-bench-combinatorics-053", "task_id": "imo-bench-combinatorics-053", "category": "Combinatorics", "subcategory": "Combinatorial Geometry", "source": "China TST 2007", "answer_kind": "number"}{"task": "imo-bench-combinatorics-054", "problem_id": "imo-bench-combinatorics-054", "task_id": "imo-bench-combinatorics-054", "category": "Combinatorics", "subcategory": "Operations", "source": "IMO Shortlist 2011", "answer_kind": "number"}{"task": "imo-bench-combinatorics-055", "problem_id": "imo-bench-combinatorics-055", "task_id": "imo-bench-combinatorics-055", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2011", "answer_kind": "number"}{"task": "imo-bench-combinatorics-056", "problem_id": "imo-bench-combinatorics-056", "task_id": "imo-bench-combinatorics-056", "category": "Combinatorics", "subcategory": "Set Combinatorics", "source": "IMO Shortlist 2013", "answer_kind": "number"}{"task": "imo-bench-combinatorics-057", "problem_id": "imo-bench-combinatorics-057", "task_id": "imo-bench-combinatorics-057", "category": "Combinatorics", "subcategory": "Combinatorial Geometry", "source": "IMO Shortlist 2013", "answer_kind": "number"}{"task": "imo-bench-combinatorics-058", "problem_id": "imo-bench-combinatorics-058", "task_id": "imo-bench-combinatorics-058", "category": "Combinatorics", "subcategory": "Tiling", "source": "IMO Shortlist 2014", "answer_kind": "literal"}{"task": "imo-bench-combinatorics-059", "problem_id": "imo-bench-combinatorics-059", "task_id": "imo-bench-combinatorics-059", "category": "Combinatorics", "subcategory": "Game Theory", "source": "IMO Shortlist 2014", "answer_kind": "literal"}{"task": "imo-bench-combinatorics-060", "problem_id": "imo-bench-combinatorics-060", "task_id": "imo-bench-combinatorics-060", "category": "Combinatorics", "subcategory": "Additive Combinatorics", "source": "China TST 2011", "answer_kind": "number"}{"task": "imo-bench-combinatorics-061", "problem_id": "imo-bench-combinatorics-061", "task_id": "imo-bench-combinatorics-061", "category": "Combinatorics", "subcategory": "Set Combinatorics", "source": "IMO Shortlist 2015", "answer_kind": "number"}{"task": "imo-bench-combinatorics-062", "problem_id": "imo-bench-combinatorics-062", "task_id": "imo-bench-combinatorics-062", "category": "Combinatorics", "subcategory": "Game Theory", "source": "IMO Shortlist 2015", "answer_kind": "number"}{"task": "imo-bench-combinatorics-063", "problem_id": "imo-bench-combinatorics-063", "task_id": "imo-bench-combinatorics-063", "category": "Combinatorics", "subcategory": "Game Theory", "source": "IMO Shortlist 2016", "answer_kind": "number"}{"task": "imo-bench-combinatorics-064", "problem_id": "imo-bench-combinatorics-064", "task_id": "imo-bench-combinatorics-064", "category": "Combinatorics", "subcategory": "Existence Combinatorics", "source": "IMO Shortlist 2016", "answer_kind": "literal"}{"task": "imo-bench-combinatorics-065", "problem_id": "imo-bench-combinatorics-065", "task_id": "imo-bench-combinatorics-065", "category": "Combinatorics", "subcategory": "Existence Combinatorics", "source": "IMO Shortlist 2016", "answer_kind": "number"}{"task": "imo-bench-combinatorics-066", "problem_id": "imo-bench-combinatorics-066", "task_id": "imo-bench-combinatorics-066", "category": "Combinatorics", "subcategory": "Combinatorial Geometry", "source": "IMO Shortlist 2016", "answer_kind": "number"}{"task": "imo-bench-combinatorics-067", "problem_id": "imo-bench-combinatorics-067", "task_id": "imo-bench-combinatorics-067", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2016", "answer_kind": "number"}{"task": "imo-bench-combinatorics-068", "problem_id": "imo-bench-combinatorics-068", "task_id": "imo-bench-combinatorics-068", "category": "Combinatorics", "subcategory": "Operations", "source": "IMO Shortlist 2017", "answer_kind": "number"}{"task": "imo-bench-combinatorics-069", "problem_id": "imo-bench-combinatorics-069", "task_id": "imo-bench-combinatorics-069", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2017", "answer_kind": "number"}{"task": "imo-bench-combinatorics-070", "problem_id": "imo-bench-combinatorics-070", "task_id": "imo-bench-combinatorics-070", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2018", "answer_kind": "number"}{"task": "imo-bench-combinatorics-071", "problem_id": "imo-bench-combinatorics-071", "task_id": "imo-bench-combinatorics-071", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2018", "answer_kind": "number"}{"task": "imo-bench-combinatorics-072", "problem_id": "imo-bench-combinatorics-072", "task_id": "imo-bench-combinatorics-072", "category": "Combinatorics", "subcategory": "Operations", "source": "IMO Shortlist 2019", "answer_kind": "number"}{"task": "imo-bench-combinatorics-073", "problem_id": "imo-bench-combinatorics-073", "task_id": "imo-bench-combinatorics-073", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "China TST 2023", "answer_kind": "number"}{"task": "imo-bench-combinatorics-074", "problem_id": "imo-bench-combinatorics-074", "task_id": "imo-bench-combinatorics-074", "category": "Combinatorics", "subcategory": "Game Theory", "source": "IMO Shortlist 2019", "answer_kind": "number"}{"task": "imo-bench-combinatorics-075", "problem_id": "imo-bench-combinatorics-075", "task_id": "imo-bench-combinatorics-075", "category": "Combinatorics", "subcategory": "Graph Theory", "source": "IMO Shortlist 2020", "answer_kind": "number"}{"task": "imo-bench-combinatorics-076", "problem_id": "imo-bench-combinatorics-076", "task_id": "imo-bench-combinatorics-076", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2020", "answer_kind": "number"}{"task": "imo-bench-combinatorics-077", "problem_id": "imo-bench-combinatorics-077", "task_id": "imo-bench-combinatorics-077", "category": "Combinatorics", "subcategory": "Game Theory", "source": "IMO Shortlist 2020", "answer_kind": "number"}{"task": "imo-bench-combinatorics-078", "problem_id": "imo-bench-combinatorics-078", "task_id": "imo-bench-combinatorics-078", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2021", "answer_kind": "number"}{"task": "imo-bench-combinatorics-079", "problem_id": "imo-bench-combinatorics-079", "task_id": "imo-bench-combinatorics-079", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2021", "answer_kind": "number"}{"task": "imo-bench-combinatorics-080", "problem_id": "imo-bench-combinatorics-080", "task_id": "imo-bench-combinatorics-080", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2022", "answer_kind": "number"}{"task": "imo-bench-combinatorics-081", "problem_id": "imo-bench-combinatorics-081", "task_id": "imo-bench-combinatorics-081", "category": "Combinatorics", "subcategory": "Operations", "source": "IMO Shortlist 2022", "answer_kind": "number"}{"task": "imo-bench-combinatorics-082", "problem_id": "imo-bench-combinatorics-082", "task_id": "imo-bench-combinatorics-082", "category": "Combinatorics", "subcategory": "Operations", "source": "IMO Shortlist 2022", "answer_kind": "number"}{"task": "imo-bench-combinatorics-083", "problem_id": "imo-bench-combinatorics-083", "task_id": "imo-bench-combinatorics-083", "category": "Combinatorics", "subcategory": "Operations", "source": "IMO Shortlist 2022", "answer_kind": "number"}{"task": "imo-bench-combinatorics-084", "problem_id": "imo-bench-combinatorics-084", "task_id": "imo-bench-combinatorics-084", "category": "Combinatorics", "subcategory": "Operations", "source": "IMO Shortlist 2022", "answer_kind": "number"}{"task": "imo-bench-combinatorics-085", "problem_id": "imo-bench-combinatorics-085", "task_id": "imo-bench-combinatorics-085", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "IMO Shortlist 2022", "answer_kind": "number"}{"task": "imo-bench-combinatorics-086", "problem_id": "imo-bench-combinatorics-086", "task_id": "imo-bench-combinatorics-086", "category": "Combinatorics", "subcategory": "Other", "source": "IMO Shortlist 2022", "answer_kind": "number"}{"task": "imo-bench-combinatorics-087", "problem_id": "imo-bench-combinatorics-087", "task_id": "imo-bench-combinatorics-087", "category": "Combinatorics", "subcategory": "Game Theory", "source": "Komal", "answer_kind": "number"}{"task": "imo-bench-combinatorics-088", "problem_id": "imo-bench-combinatorics-088", "task_id": "imo-bench-combinatorics-088", "category": "Combinatorics", "subcategory": "Graph Theory", "source": "Komal", "answer_kind": "number"}{"task": "imo-bench-combinatorics-089", "problem_id": "imo-bench-combinatorics-089", "task_id": "imo-bench-combinatorics-089", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "Komal", "answer_kind": "number"}{"task": "imo-bench-combinatorics-090", "problem_id": "imo-bench-combinatorics-090", "task_id": "imo-bench-combinatorics-090", "category": "Combinatorics", "subcategory": "Tiling", "source": "Komal", "answer_kind": "number"}{"task": "imo-bench-combinatorics-091", "problem_id": "imo-bench-combinatorics-091", "task_id": "imo-bench-combinatorics-091", "category": "Combinatorics", "subcategory": "Graph Theory", "source": "Komal", "answer_kind": "literal"}{"task": "imo-bench-combinatorics-092", "problem_id": "imo-bench-combinatorics-092", "task_id": "imo-bench-combinatorics-092", "category": "Combinatorics", "subcategory": "Graph Theory", "source": "Komal", "answer_kind": "number"}{"task": "imo-bench-combinatorics-093", "problem_id": "imo-bench-combinatorics-093", "task_id": "imo-bench-combinatorics-093", "category": "Combinatorics", "subcategory": "Extremal Combinatorics", "source": "Komal", "answer_kind": "number"}{"task": "imo-bench-combinatorics-094", "problem_id": "imo-bench-combinatorics-094", "task_id": "imo-bench-combinatorics-094", "category": "Combinatorics", "subcategory": "Game Theory", "source": "Komal", "answer_kind": "number"}{"task": "imo-bench-combinatorics-095", "problem_id": "imo-bench-combinatorics-095", "task_id": "imo-bench-combinatorics-095", "category": "Combinatorics", "subcategory": "Enumerative Combinatorics", "source": "Alibaba Math Competition 2021", "answer_kind": "number"}{"task": "imo-bench-combinatorics-096", "problem_id": "imo-bench-combinatorics-096", "task_id": "imo-bench-combinatorics-096", "category": "Combinatorics", "subcategory": "Graph Theory", "source": "China TST 2011", "answer_kind": "number"}{"task": "imo-bench-combinatorics-097", "problem_id": "imo-bench-combinatorics-097", "task_id": "imo-bench-combinatorics-097", "category": "Combinatorics", "subcategory": "Enumerative Combinatorics", "source": "Korean Final 2014", "answer_kind": "number"}{"task": "imo-bench-combinatorics-098", "problem_id": "imo-bench-combinatorics-098", "task_id": "imo-bench-combinatorics-098", "category": "Combinatorics", "subcategory": "Enumerative Combinatorics", "source": "Statistical Mechanics method for Combinatorics", "answer_kind": "expression"}{"task": "imo-bench-combinatorics-099", "problem_id": "imo-bench-combinatorics-099", "task_id": "imo-bench-combinatorics-099", "category": "Combinatorics", "subcategory": "Graph Theory", "source": "USAMTS 2022", "answer_kind": "number"}{"task": "imo-bench-combinatorics-100", "problem_id": "imo-bench-combinatorics-100", "task_id": "imo-bench-combinatorics-100", "category": "Combinatorics", "subcategory": "Game Theory", "source": "USAMTS 2022", "answer_kind": "number"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100{"task": "imo-bench-geometry-001", "problem_id": "imo-bench-geometry-001", "task_id": "imo-bench-geometry-001", "category": "Geometry", "subcategory": "3d_geometry", "source": "Sharygin 2008", "answer_kind": "number"}{"task": "imo-bench-geometry-002", "problem_id": "imo-bench-geometry-002", "task_id": "imo-bench-geometry-002", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2008", "answer_kind": "number"}{"task": "imo-bench-geometry-003", "problem_id": "imo-bench-geometry-003", "task_id": "imo-bench-geometry-003", "category": "Geometry", "subcategory": "combinatorial_geometry", "source": "Sharygin 2009", "answer_kind": "number"}{"task": "imo-bench-geometry-004", "problem_id": "imo-bench-geometry-004", "task_id": "imo-bench-geometry-004", "category": "Geometry", "subcategory": "combinatorial_geometry", "source": "Sharygin 2009", "answer_kind": "number"}{"task": "imo-bench-geometry-005", "problem_id": "imo-bench-geometry-005", "task_id": "imo-bench-geometry-005", "category": "Geometry", "subcategory": "proof_based_geometry", "source": "Sharygin 2009", "answer_kind": "number"}{"task": "imo-bench-geometry-006", "problem_id": "imo-bench-geometry-006", "task_id": "imo-bench-geometry-006", "category": "Geometry", "subcategory": "extremal_geometry", "source": "Sharygin 2009", "answer_kind": "expression"}{"task": "imo-bench-geometry-007", "problem_id": "imo-bench-geometry-007", "task_id": "imo-bench-geometry-007", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2009", "answer_kind": "expression"}{"task": "imo-bench-geometry-008", "problem_id": "imo-bench-geometry-008", "task_id": "imo-bench-geometry-008", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2010", "answer_kind": "expression"}{"task": "imo-bench-geometry-009", "problem_id": "imo-bench-geometry-009", "task_id": "imo-bench-geometry-009", "category": "Geometry", "subcategory": "combinatorial_geometry", "source": "Sharygin 2011", "answer_kind": "number"}{"task": "imo-bench-geometry-010", "problem_id": "imo-bench-geometry-010", "task_id": "imo-bench-geometry-010", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2012", "answer_kind": "expression"}{"task": "imo-bench-geometry-011", "problem_id": "imo-bench-geometry-011", "task_id": "imo-bench-geometry-011", "category": "Geometry", "subcategory": "3d_geometry", "source": "Sharygin 2013", "answer_kind": "number"}{"task": "imo-bench-geometry-012", "problem_id": "imo-bench-geometry-012", "task_id": "imo-bench-geometry-012", "category": "Geometry", "subcategory": "proof_based_geometry", "source": "Sharygin 2014", "answer_kind": "number"}{"task": "imo-bench-geometry-013", "problem_id": "imo-bench-geometry-013", "task_id": "imo-bench-geometry-013", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2015", "answer_kind": "number"}{"task": "imo-bench-geometry-014", "problem_id": "imo-bench-geometry-014", "task_id": "imo-bench-geometry-014", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2015", "answer_kind": "number"}{"task": "imo-bench-geometry-015", "problem_id": "imo-bench-geometry-015", "task_id": "imo-bench-geometry-015", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2016", "answer_kind": "number"}{"task": "imo-bench-geometry-016", "problem_id": "imo-bench-geometry-016", "task_id": "imo-bench-geometry-016", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2016", "answer_kind": "number"}{"task": "imo-bench-geometry-017", "problem_id": "imo-bench-geometry-017", "task_id": "imo-bench-geometry-017", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2016", "answer_kind": "number"}{"task": "imo-bench-geometry-018", "problem_id": "imo-bench-geometry-018", "task_id": "imo-bench-geometry-018", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2017", "answer_kind": "number"}{"task": "imo-bench-geometry-019", "problem_id": "imo-bench-geometry-019", "task_id": "imo-bench-geometry-019", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2017", "answer_kind": "number"}{"task": "imo-bench-geometry-020", "problem_id": "imo-bench-geometry-020", "task_id": "imo-bench-geometry-020", "category": "Geometry", "subcategory": "combinatorial_geometry", "source": "Sharygin 2017", "answer_kind": "number"}{"task": "imo-bench-geometry-021", "problem_id": "imo-bench-geometry-021", "task_id": "imo-bench-geometry-021", "category": "Geometry", "subcategory": "combinatorial_geometry", "source": "Sharygin 2019", "answer_kind": "number"}{"task": "imo-bench-geometry-022", "problem_id": "imo-bench-geometry-022", "task_id": "imo-bench-geometry-022", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2019", "answer_kind": "number"}{"task": "imo-bench-geometry-023", "problem_id": "imo-bench-geometry-023", "task_id": "imo-bench-geometry-023", "category": "Geometry", "subcategory": "3d_geometry", "source": "Sharygin 2021 (correspondence)", "answer_kind": "literal"}{"task": "imo-bench-geometry-024", "problem_id": "imo-bench-geometry-024", "task_id": "imo-bench-geometry-024", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2021", "answer_kind": "number"}{"task": "imo-bench-geometry-025", "problem_id": "imo-bench-geometry-025", "task_id": "imo-bench-geometry-025", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2021", "answer_kind": "number"}{"task": "imo-bench-geometry-026", "problem_id": "imo-bench-geometry-026", "task_id": "imo-bench-geometry-026", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2022", "answer_kind": "number"}{"task": "imo-bench-geometry-027", "problem_id": "imo-bench-geometry-027", "task_id": "imo-bench-geometry-027", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2023", "answer_kind": "expression"}{"task": "imo-bench-geometry-028", "problem_id": "imo-bench-geometry-028", "task_id": "imo-bench-geometry-028", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2023", "answer_kind": "expression"}{"task": "imo-bench-geometry-029", "problem_id": "imo-bench-geometry-029", "task_id": "imo-bench-geometry-029", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2023", "answer_kind": "number"}{"task": "imo-bench-geometry-030", "problem_id": "imo-bench-geometry-030", "task_id": "imo-bench-geometry-030", "category": "Geometry", "subcategory": "computation", "source": "Sharygin 2024", "answer_kind": "number"}{"task": "imo-bench-geometry-031", "problem_id": "imo-bench-geometry-031", "task_id": "imo-bench-geometry-031", "category": "Geometry", "subcategory": "combinatorial_geometry", "source": "Sharygin 2024", "answer_kind": "number"}{"task": "imo-bench-geometry-032", "problem_id": "imo-bench-geometry-032", "task_id": "imo-bench-geometry-032", "category": "Geometry", "subcategory": "computation", "source": "Hanoi Open Mathematical Olympiad 2012", "answer_kind": "number"}{"task": "imo-bench-geometry-033", "problem_id": "imo-bench-geometry-033", "task_id": "imo-bench-geometry-033", "category": "Geometry", "subcategory": "computation", "source": "Hanoi Open Mathematical Olympiad 2013", "answer_kind": "number"}{"task": "imo-bench-geometry-034", "problem_id": "imo-bench-geometry-034", "task_id": "imo-bench-geometry-034", "category": "Geometry", "subcategory": "computation", "source": "Hanoi Open Mathematical Olympiad 2014", "answer_kind": "expression"}{"task": "imo-bench-geometry-035", "problem_id": "imo-bench-geometry-035", "task_id": "imo-bench-geometry-035", "category": "Geometry", "subcategory": "computation", "source": "Hanoi Open Mathematical Olympiad 2018", "answer_kind": "number"}{"task": "imo-bench-geometry-036", "problem_id": "imo-bench-geometry-036", "task_id": "imo-bench-geometry-036", "category": "Geometry", "subcategory": "computation", "source": "Hanoi Open Mathematical Olympiad 2018", "answer_kind": "expression"}{"task": "imo-bench-geometry-037", "problem_id": "imo-bench-geometry-037", "task_id": "imo-bench-geometry-037", "category": "Geometry", "subcategory": "computation", "source": "Hanoi Open Mathematical Olympiad 2018", "answer_kind": "number"}{"task": "imo-bench-geometry-038", "problem_id": "imo-bench-geometry-038", "task_id": "imo-bench-geometry-038", "category": "Geometry", "subcategory": "locus_geometry", "source": "Vietnam Mathematical Olympiad 2007", "answer_kind": "literal"}{"task": "imo-bench-geometry-039", "problem_id": "imo-bench-geometry-039", "task_id": "imo-bench-geometry-039", "category": "Geometry", "subcategory": "computation", "source": "Vietnam Mathematical Olympiad 2015", "answer_kind": "expression"}{"task": "imo-bench-geometry-040", "problem_id": "imo-bench-geometry-040", "task_id": "imo-bench-geometry-040", "category": "Geometry", "subcategory": "proof_based_geometry", "source": "Vietnam TST 2008", "answer_kind": "set"}{"task": "imo-bench-geometry-041", "problem_id": "imo-bench-geometry-041", "task_id": "imo-bench-geometry-041", "category": "Geometry", "subcategory": "computation", "source": "Iran Geometry Olympiad 2015", "answer_kind": "number"}{"task": "imo-bench-geometry-042", "problem_id": "imo-bench-geometry-042", "task_id": "imo-bench-geometry-042", "category": "Geometry", "subcategory": "computation", "source": "Iran Geometry Olympiad 2016", "answer_kind": "number"}{"task": "imo-bench-geometry-043", "problem_id": "imo-bench-geometry-043", "task_id": "imo-bench-geometry-043", "category": "Geometry", "subcategory": "computation", "source": "Iran Geometry Olympiad 2017", "answer_kind": "expression"}{"task": "imo-bench-geometry-044", "problem_id": "imo-bench-geometry-044", "task_id": "imo-bench-geometry-044", "category": "Geometry", "subcategory": "computation", "source": "Iran Geometry Olympiad 2018", "answer_kind": "number"}{"task": "imo-bench-geometry-045", "problem_id": "imo-bench-geometry-045", "task_id": "imo-bench-geometry-045", "category": "Geometry", "subcategory": "combinatorial_geometry", "source": "Iran Geometry Olympiad 2018", "answer_kind": "number"}{"task": "imo-bench-geometry-046", "problem_id": "imo-bench-geometry-046", "task_id": "imo-bench-geometry-046", "category": "Geometry", "subcategory": "computation", "source": "Iran Geometry Olympiad 2020", "answer_kind": "expression"}{"task": "imo-bench-geometry-047", "problem_id": "imo-bench-geometry-047", "task_id": "imo-bench-geometry-047", "category": "Geometry", "subcategory": "computation", "source": "Iran Geometry Olympiad 2022", "answer_kind": "number"}{"task": "imo-bench-geometry-048", "problem_id": "imo-bench-geometry-048", "task_id": "imo-bench-geometry-048", "category": "Geometry", "subcategory": "computation", "source": "USA TST 2024", "answer_kind": "number"}{"task": "imo-bench-geometry-049", "problem_id": "imo-bench-geometry-049", "task_id": "imo-bench-geometry-049", "category": "Geometry", "subcategory": "combinatorial_geometry", "source": "Iran Geometry Olympiad 2023", "answer_kind": "expression"}{"task": "imo-bench-geometry-050", "problem_id": "imo-bench-geometry-050", "task_id": "imo-bench-geometry-050", "category": "Geometry", "subcategory": "computation", "source": "AIME 2019", "answer_kind": "number"}{"task": "imo-bench-geometry-051", "problem_id": "imo-bench-geometry-051", "task_id": "imo-bench-geometry-051", "category": "Geometry", "subcategory": "computation", "source": "AIME 2019", "answer_kind": "number"}{"task": "imo-bench-geometry-052", "problem_id": "imo-bench-geometry-052", "task_id": "imo-bench-geometry-052", "category": "Geometry", "subcategory": "computation", "source": "AIME 2019", "answer_kind": "number"}{"task": "imo-bench-geometry-053", "problem_id": "imo-bench-geometry-053", "task_id": "imo-bench-geometry-053", "category": "Geometry", "subcategory": "computation", "source": "AIME 2020", "answer_kind": "number"}{"task": "imo-bench-geometry-054", "problem_id": "imo-bench-geometry-054", "task_id": "imo-bench-geometry-054", "category": "Geometry", "subcategory": "computation", "source": "AIME 2020", "answer_kind": "number"}{"task": "imo-bench-geometry-055", "problem_id": "imo-bench-geometry-055", "task_id": "imo-bench-geometry-055", "category": "Geometry", "subcategory": "computation", "source": "AIME 2020", "answer_kind": "number"}{"task": "imo-bench-geometry-056", "problem_id": "imo-bench-geometry-056", "task_id": "imo-bench-geometry-056", "category": "Geometry", "subcategory": "locus_geometry", "source": "Komal", "answer_kind": "number"}{"task": "imo-bench-geometry-057", "problem_id": "imo-bench-geometry-057", "task_id": "imo-bench-geometry-057", "category": "Geometry", "subcategory": "computation", "source": "AIME 2021", "answer_kind": "number"}{"task": "imo-bench-geometry-058", "problem_id": "imo-bench-geometry-058", "task_id": "imo-bench-geometry-058", "category": "Geometry", "subcategory": "computation", "source": "AIME 2021", "answer_kind": "number"}{"task": "imo-bench-geometry-059", "problem_id": "imo-bench-geometry-059", "task_id": "imo-bench-geometry-059", "category": "Geometry", "subcategory": "computation", "source": "AIME 2021", "answer_kind": "number"}{"task": "imo-bench-geometry-060", "problem_id": "imo-bench-geometry-060", "task_id": "imo-bench-geometry-060", "category": "Geometry", "subcategory": "computation", "source": "AIME 2022", "answer_kind": "number"}{"task": "imo-bench-geometry-061", "problem_id": "imo-bench-geometry-061", "task_id": "imo-bench-geometry-061", "category": "Geometry", "subcategory": "3d_geometry", "source": "AIME 2022", "answer_kind": "number"}{"task": "imo-bench-geometry-062", "problem_id": "imo-bench-geometry-062", "task_id": "imo-bench-geometry-062", "category": "Geometry", "subcategory": "computation", "source": "AIME 2022", "answer_kind": "number"}{"task": "imo-bench-geometry-063", "problem_id": "imo-bench-geometry-063", "task_id": "imo-bench-geometry-063", "category": "Geometry", "subcategory": "computation", "source": "AIME 2022", "answer_kind": "number"}{"task": "imo-bench-geometry-064", "problem_id": "imo-bench-geometry-064", "task_id": "imo-bench-geometry-064", "category": "Geometry", "subcategory": "computation", "source": "AIME 2022", "answer_kind": "number"}{"task": "imo-bench-geometry-065", "problem_id": "imo-bench-geometry-065", "task_id": "imo-bench-geometry-065", "category": "Geometry", "subcategory": "computation", "source": "AIME 2023", "answer_kind": "number"}{"task": "imo-bench-geometry-066", "problem_id": "imo-bench-geometry-066", "task_id": "imo-bench-geometry-066", "category": "Geometry", "subcategory": "computation", "source": "AIME 2023", "answer_kind": "number"}{"task": "imo-bench-geometry-067", "problem_id": "imo-bench-geometry-067", "task_id": "imo-bench-geometry-067", "category": "Geometry", "subcategory": "computation", "source": "AIME 2023", "answer_kind": "number"}{"task": "imo-bench-geometry-068", "problem_id": "imo-bench-geometry-068", "task_id": "imo-bench-geometry-068", "category": "Geometry", "subcategory": "computation", "source": "AIME 2023", "answer_kind": "number"}{"task": "imo-bench-geometry-069", "problem_id": "imo-bench-geometry-069", "task_id": "imo-bench-geometry-069", "category": "Geometry", "subcategory": "computation", "source": "AIME 2023", "answer_kind": "number"}{"task": "imo-bench-geometry-070", "problem_id": "imo-bench-geometry-070", "task_id": "imo-bench-geometry-070", "category": "Geometry", "subcategory": "3d_geometry", "source": "AIME 2024", "answer_kind": "number"}{"task": "imo-bench-geometry-071", "problem_id": "imo-bench-geometry-071", "task_id": "imo-bench-geometry-071", "category": "Geometry", "subcategory": "computation", "source": "AIME 2024", "answer_kind": "number"}{"task": "imo-bench-geometry-072", "problem_id": "imo-bench-geometry-072", "task_id": "imo-bench-geometry-072", "category": "Geometry", "subcategory": "computation", "source": "Mathley 2011-2012", "answer_kind": "number"}{"task": "imo-bench-geometry-073", "problem_id": "imo-bench-geometry-073", "task_id": "imo-bench-geometry-073", "category": "Geometry", "subcategory": "computation", "source": "Mathley 2011-2012", "answer_kind": "expression"}{"task": "imo-bench-geometry-074", "problem_id": "imo-bench-geometry-074", "task_id": "imo-bench-geometry-074", "category": "Geometry", "subcategory": "computation", "source": "China 1992", "answer_kind": "number"}{"task": "imo-bench-geometry-075", "problem_id": "imo-bench-geometry-075", "task_id": "imo-bench-geometry-075", "category": "Geometry", "subcategory": "extremal_geometry", "source": "China 1996", "answer_kind": "number"}{"task": "imo-bench-geometry-076", "problem_id": "imo-bench-geometry-076", "task_id": "imo-bench-geometry-076", "category": "Geometry", "subcategory": "extremal_geometry", "source": "China 2001", "answer_kind": "expression"}{"task": "imo-bench-geometry-077", "problem_id": "imo-bench-geometry-077", "task_id": "imo-bench-geometry-077", "category": "Geometry", "subcategory": "extremal_geometry", "source": "USA 1999", "answer_kind": "number"}{"task": "imo-bench-geometry-078", "problem_id": "imo-bench-geometry-078", "task_id": "imo-bench-geometry-078", "category": "Geometry", "subcategory": "proof_based_geometry", "source": "USA 2013", "answer_kind": "literal"}{"task": "imo-bench-geometry-079", "problem_id": "imo-bench-geometry-079", "task_id": "imo-bench-geometry-079", "category": "Geometry", "subcategory": "3d_geometry", "source": "Romania 2010", "answer_kind": "number"}{"task": "imo-bench-geometry-080", "problem_id": "imo-bench-geometry-080", "task_id": "imo-bench-geometry-080", "category": "Geometry", "subcategory": "computation", "source": "Romania 2012", "answer_kind": "number"}{"task": "imo-bench-geometry-081", "problem_id": "imo-bench-geometry-081", "task_id": "imo-bench-geometry-081", "category": "Geometry", "subcategory": "computation", "source": "Romania 2017", "answer_kind": "number"}{"task": "imo-bench-geometry-082", "problem_id": "imo-bench-geometry-082", "task_id": "imo-bench-geometry-082", "category": "Geometry", "subcategory": "computation", "source": "Baltic Way 2015", "answer_kind": "number"}{"task": "imo-bench-geometry-083", "problem_id": "imo-bench-geometry-083", "task_id": "imo-bench-geometry-083", "category": "Geometry", "subcategory": "computation", "source": "Baltic Way 2015", "answer_kind": "number"}{"task": "imo-bench-geometry-084", "problem_id": "imo-bench-geometry-084", "task_id": "imo-bench-geometry-084", "category": "Geometry", "subcategory": "computation", "source": "Baltic Way 2016", "answer_kind": "number"}{"task": "imo-bench-geometry-085", "problem_id": "imo-bench-geometry-085", "task_id": "imo-bench-geometry-085", "category": "Geometry", "subcategory": "combinatorial_geometry", "source": "HMIC 2014", "answer_kind": "number"}{"task": "imo-bench-geometry-086", "problem_id": "imo-bench-geometry-086", "task_id": "imo-bench-geometry-086", "category": "Geometry", "subcategory": "3d_geometry", "source": "HMIC 2020", "answer_kind": "number"}{"task": "imo-bench-geometry-087", "problem_id": "imo-bench-geometry-087", "task_id": "imo-bench-geometry-087", "category": "Geometry", "subcategory": "computation", "source": "HMMT 2008", "answer_kind": "number"}{"task": "imo-bench-geometry-088", "problem_id": "imo-bench-geometry-088", "task_id": "imo-bench-geometry-088", "category": "Geometry", "subcategory": "combinatorial_geometry", "source": "HMMT 2010", "answer_kind": "number"}{"task": "imo-bench-geometry-089", "problem_id": "imo-bench-geometry-089", "task_id": "imo-bench-geometry-089", "category": "Geometry", "subcategory": "computation", "source": "HMMT 2020", "answer_kind": "number"}{"task": "imo-bench-geometry-090", "problem_id": "imo-bench-geometry-090", "task_id": "imo-bench-geometry-090", "category": "Geometry", "subcategory": "combinatorial_geometry", "source": "HMMT 2021", "answer_kind": "number"}{"task": "imo-bench-geometry-091", "problem_id": "imo-bench-geometry-091", "task_id": "imo-bench-geometry-091", "category": "Geometry", "subcategory": "computation", "source": "HMMT 2023", "answer_kind": "number"}{"task": "imo-bench-geometry-092", "problem_id": "imo-bench-geometry-092", "task_id": "imo-bench-geometry-092", "category": "Geometry", "subcategory": "combinatorial_geometry", "source": "USAMTS 2002", "answer_kind": "number"}{"task": "imo-bench-geometry-093", "problem_id": "imo-bench-geometry-093", "task_id": "imo-bench-geometry-093", "category": "Geometry", "subcategory": "computation", "source": "USAMTS 2004", "answer_kind": "number"}{"task": "imo-bench-geometry-094", "problem_id": "imo-bench-geometry-094", "task_id": "imo-bench-geometry-094", "category": "Geometry", "subcategory": "computation", "source": "USAMTS 2005", "answer_kind": "number"}{"task": "imo-bench-geometry-095", "problem_id": "imo-bench-geometry-095", "task_id": "imo-bench-geometry-095", "category": "Geometry", "subcategory": "computation", "source": "USAMTS 2012", "answer_kind": "number"}{"task": "imo-bench-geometry-096", "problem_id": "imo-bench-geometry-096", "task_id": "imo-bench-geometry-096", "category": "Geometry", "subcategory": "extremal_geometry", "source": "USAMTS 2016", "answer_kind": "literal"}{"task": "imo-bench-geometry-097", "problem_id": "imo-bench-geometry-097", "task_id": "imo-bench-geometry-097", "category": "Geometry", "subcategory": "combinatorial_geometry", "source": "USAMTS 2016", "answer_kind": "number"}{"task": "imo-bench-geometry-098", "problem_id": "imo-bench-geometry-098", "task_id": "imo-bench-geometry-098", "category": "Geometry", "subcategory": "extremal_geometry", "source": "USAMTS 2018", "answer_kind": "number"}{"task": "imo-bench-geometry-099", "problem_id": "imo-bench-geometry-099", "task_id": "imo-bench-geometry-099", "category": "Geometry", "subcategory": "computation", "source": "USAMTS 2019", "answer_kind": "number"}{"task": "imo-bench-geometry-100", "problem_id": "imo-bench-geometry-100", "task_id": "imo-bench-geometry-100", "category": "Geometry", "subcategory": "computation", "source": "Novosibirsk Geometry Olympiad 2023", "answer_kind": "number"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100{"task": "imo-bench-number_theory-001", "problem_id": "imo-bench-number_theory-001", "task_id": "imo-bench-number_theory-001", "category": "Number theory", "subcategory": "Perfect power", "source": "IMO Shortlist 2021", "answer_kind": "number"}{"task": "imo-bench-number_theory-002", "problem_id": "imo-bench-number_theory-002", "task_id": "imo-bench-number_theory-002", "category": "Number theory", "subcategory": "Divisibility", "source": "IMO Shortlist 2021", "answer_kind": "number"}{"task": "imo-bench-number_theory-003", "problem_id": "imo-bench-number_theory-003", "task_id": "imo-bench-number_theory-003", "category": "Number theory", "subcategory": "Functional Equation", "source": "IMO Shortlist 2020", "answer_kind": "number"}{"task": "imo-bench-number_theory-004", "problem_id": "imo-bench-number_theory-004", "task_id": "imo-bench-number_theory-004", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "IMO Shortlist 2019", "answer_kind": "tuple"}{"task": "imo-bench-number_theory-005", "problem_id": "imo-bench-number_theory-005", "task_id": "imo-bench-number_theory-005", "category": "Number theory", "subcategory": "Polynomial", "source": "IMO Shortlist 2019", "answer_kind": "literal"}{"task": "imo-bench-number_theory-006", "problem_id": "imo-bench-number_theory-006", "task_id": "imo-bench-number_theory-006", "category": "Number theory", "subcategory": "Divisor", "source": "IMO Shortlist 2018", "answer_kind": "literal"}{"task": "imo-bench-number_theory-007", "problem_id": "imo-bench-number_theory-007", "task_id": "imo-bench-number_theory-007", "category": "Number theory", "subcategory": "Divisibility", "source": "IMO Shortlist 2017", "answer_kind": "literal"}{"task": "imo-bench-number_theory-008", "problem_id": "imo-bench-number_theory-008", "task_id": "imo-bench-number_theory-008", "category": "Number theory", "subcategory": "Divisibility", "source": "IMO Shortlist 2017", "answer_kind": "number"}{"task": "imo-bench-number_theory-009", "problem_id": "imo-bench-number_theory-009", "task_id": "imo-bench-number_theory-009", "category": "Number theory", "subcategory": "Number Theoretic Functions", "source": "IMO Shortlist 2016", "answer_kind": "literal"}{"task": "imo-bench-number_theory-010", "problem_id": "imo-bench-number_theory-010", "task_id": "imo-bench-number_theory-010", "category": "Number theory", "subcategory": "Polynomial", "source": "IMO Shortlist 2016", "answer_kind": "expression"}{"task": "imo-bench-number_theory-011", "problem_id": "imo-bench-number_theory-011", "task_id": "imo-bench-number_theory-011", "category": "Number theory", "subcategory": "Sequence", "source": "IMO Shortlist 2015", "answer_kind": "literal"}{"task": "imo-bench-number_theory-012", "problem_id": "imo-bench-number_theory-012", "task_id": "imo-bench-number_theory-012", "category": "Number theory", "subcategory": "Functional Equation", "source": "IMO Shortlist 2015", "answer_kind": "literal"}{"task": "imo-bench-number_theory-013", "problem_id": "imo-bench-number_theory-013", "task_id": "imo-bench-number_theory-013", "category": "Number theory", "subcategory": "Representation", "source": "IMO Shortlist 2014", "answer_kind": "expression"}{"task": "imo-bench-number_theory-014", "problem_id": "imo-bench-number_theory-014", "task_id": "imo-bench-number_theory-014", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "IMO Shortlist 2014", "answer_kind": "literal"}{"task": "imo-bench-number_theory-015", "problem_id": "imo-bench-number_theory-015", "task_id": "imo-bench-number_theory-015", "category": "Number theory", "subcategory": "Perfect power", "source": "IMO Shortlist 2014", "answer_kind": "tuple"}{"task": "imo-bench-number_theory-016", "problem_id": "imo-bench-number_theory-016", "task_id": "imo-bench-number_theory-016", "category": "Number theory", "subcategory": "Functional Equation", "source": "IMO Shortlist 2013", "answer_kind": "literal"}{"task": "imo-bench-number_theory-017", "problem_id": "imo-bench-number_theory-017", "task_id": "imo-bench-number_theory-017", "category": "Number theory", "subcategory": "Other", "source": "IMO Shortlist 2013", "answer_kind": "number"}{"task": "imo-bench-number_theory-018", "problem_id": "imo-bench-number_theory-018", "task_id": "imo-bench-number_theory-018", "category": "Number theory", "subcategory": "Set", "source": "IMO Shortlist 2012", "answer_kind": "number"}{"task": "imo-bench-number_theory-019", "problem_id": "imo-bench-number_theory-019", "task_id": "imo-bench-number_theory-019", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "IMO Shortlist 2012", "answer_kind": "tuple"}{"task": "imo-bench-number_theory-020", "problem_id": "imo-bench-number_theory-020", "task_id": "imo-bench-number_theory-020", "category": "Number theory", "subcategory": "Divisibility", "source": "IMO Shortlist 2012", "answer_kind": "number"}{"task": "imo-bench-number_theory-021", "problem_id": "imo-bench-number_theory-021", "task_id": "imo-bench-number_theory-021", "category": "Number theory", "subcategory": "Functional Equation", "source": "IMO Shortlist 2011", "answer_kind": "number"}{"task": "imo-bench-number_theory-022", "problem_id": "imo-bench-number_theory-022", "task_id": "imo-bench-number_theory-022", "category": "Number theory", "subcategory": "Divisibility", "source": "IMO Shortlist 2011", "answer_kind": "set"}{"task": "imo-bench-number_theory-023", "problem_id": "imo-bench-number_theory-023", "task_id": "imo-bench-number_theory-023", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "IMO Shortlist 2010", "answer_kind": "number"}{"task": "imo-bench-number_theory-024", "problem_id": "imo-bench-number_theory-024", "task_id": "imo-bench-number_theory-024", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "IMO Shortlist 2010", "answer_kind": "number"}{"task": "imo-bench-number_theory-025", "problem_id": "imo-bench-number_theory-025", "task_id": "imo-bench-number_theory-025", "category": "Number theory", "subcategory": "Polynomial", "source": "IMO Shortlist 2010", "answer_kind": "number"}{"task": "imo-bench-number_theory-026", "problem_id": "imo-bench-number_theory-026", "task_id": "imo-bench-number_theory-026", "category": "Number theory", "subcategory": "Other", "source": "IMO Shortlist 2010", "answer_kind": "expression"}{"task": "imo-bench-number_theory-027", "problem_id": "imo-bench-number_theory-027", "task_id": "imo-bench-number_theory-027", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "IMO Shortlist 2009", "answer_kind": "number"}{"task": "imo-bench-number_theory-028", "problem_id": "imo-bench-number_theory-028", "task_id": "imo-bench-number_theory-028", "category": "Number theory", "subcategory": "Sequence", "source": "IMO Shortlist 2009", "answer_kind": "number"}{"task": "imo-bench-number_theory-029", "problem_id": "imo-bench-number_theory-029", "task_id": "imo-bench-number_theory-029", "category": "Number theory", "subcategory": "Functional Equation", "source": "IMO Shortlist 2008", "answer_kind": "literal"}{"task": "imo-bench-number_theory-030", "problem_id": "imo-bench-number_theory-030", "task_id": "imo-bench-number_theory-030", "category": "Number theory", "subcategory": "Binomial", "source": "IMO Shortlist 2007", "answer_kind": "expression"}{"task": "imo-bench-number_theory-031", "problem_id": "imo-bench-number_theory-031", "task_id": "imo-bench-number_theory-031", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "IMO Shortlist 2006", "answer_kind": "expression"}{"task": "imo-bench-number_theory-032", "problem_id": "imo-bench-number_theory-032", "task_id": "imo-bench-number_theory-032", "category": "Number theory", "subcategory": "Divisibility", "source": "IMO Shortlist 2005", "answer_kind": "number"}{"task": "imo-bench-number_theory-033", "problem_id": "imo-bench-number_theory-033", "task_id": "imo-bench-number_theory-033", "category": "Number theory", "subcategory": "Divisibility", "source": "IMO Shortlist 2005", "answer_kind": "literal"}{"task": "imo-bench-number_theory-034", "problem_id": "imo-bench-number_theory-034", "task_id": "imo-bench-number_theory-034", "category": "Number theory", "subcategory": "Divisor", "source": "IMO Shortlist 2004", "answer_kind": "literal"}{"task": "imo-bench-number_theory-035", "problem_id": "imo-bench-number_theory-035", "task_id": "imo-bench-number_theory-035", "category": "Number theory", "subcategory": "Sequence", "source": "IMO Shortlist 2003", "answer_kind": "expression"}{"task": "imo-bench-number_theory-036", "problem_id": "imo-bench-number_theory-036", "task_id": "imo-bench-number_theory-036", "category": "Number theory", "subcategory": "Base and Digit", "source": "IMO Shortlist 2003", "answer_kind": "literal"}{"task": "imo-bench-number_theory-037", "problem_id": "imo-bench-number_theory-037", "task_id": "imo-bench-number_theory-037", "category": "Number theory", "subcategory": "Representation", "source": "IMO Shortlist 2003", "answer_kind": "literal"}{"task": "imo-bench-number_theory-038", "problem_id": "imo-bench-number_theory-038", "task_id": "imo-bench-number_theory-038", "category": "Number theory", "subcategory": "Set", "source": "IMO Shortlist 2003", "answer_kind": "expression"}{"task": "imo-bench-number_theory-039", "problem_id": "imo-bench-number_theory-039", "task_id": "imo-bench-number_theory-039", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "IMO Shortlist 2002", "answer_kind": "number"}{"task": "imo-bench-number_theory-040", "problem_id": "imo-bench-number_theory-040", "task_id": "imo-bench-number_theory-040", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "IMO Shortlist 2001", "answer_kind": "number"}{"task": "imo-bench-number_theory-041", "problem_id": "imo-bench-number_theory-041", "task_id": "imo-bench-number_theory-041", "category": "Number theory", "subcategory": "Divisibility", "source": "IMO Shortlist 2000", "answer_kind": "set"}{"task": "imo-bench-number_theory-042", "problem_id": "imo-bench-number_theory-042", "task_id": "imo-bench-number_theory-042", "category": "Number theory", "subcategory": "Divisor", "source": "IMO Shortlist 2000", "answer_kind": "set"}{"task": "imo-bench-number_theory-043", "problem_id": "imo-bench-number_theory-043", "task_id": "imo-bench-number_theory-043", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "IMO Shortlist 2000", "answer_kind": "number"}{"task": "imo-bench-number_theory-044", "problem_id": "imo-bench-number_theory-044", "task_id": "imo-bench-number_theory-044", "category": "Number theory", "subcategory": "Set", "source": "Iran 2001", "answer_kind": "number"}{"task": "imo-bench-number_theory-045", "problem_id": "imo-bench-number_theory-045", "task_id": "imo-bench-number_theory-045", "category": "Number theory", "subcategory": "Sequence", "source": "Iran 2002", "answer_kind": "number"}{"task": "imo-bench-number_theory-046", "problem_id": "imo-bench-number_theory-046", "task_id": "imo-bench-number_theory-046", "category": "Number theory", "subcategory": "Divisibility", "source": "Ukraine 1997", "answer_kind": "expression"}{"task": "imo-bench-number_theory-047", "problem_id": "imo-bench-number_theory-047", "task_id": "imo-bench-number_theory-047", "category": "Number theory", "subcategory": "Base and Digit", "source": "United Kingdom 1997", "answer_kind": "literal"}{"task": "imo-bench-number_theory-048", "problem_id": "imo-bench-number_theory-048", "task_id": "imo-bench-number_theory-048", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "Vietnam 1997", "answer_kind": "literal"}{"task": "imo-bench-number_theory-049", "problem_id": "imo-bench-number_theory-049", "task_id": "imo-bench-number_theory-049", "category": "Number theory", "subcategory": "Set", "source": "Belarus 2000", "answer_kind": "number"}{"task": "imo-bench-number_theory-050", "problem_id": "imo-bench-number_theory-050", "task_id": "imo-bench-number_theory-050", "category": "Number theory", "subcategory": "Sequence", "source": "Belarus 2018", "answer_kind": "set"}{"task": "imo-bench-number_theory-051", "problem_id": "imo-bench-number_theory-051", "task_id": "imo-bench-number_theory-051", "category": "Number theory", "subcategory": "Set", "source": "Belarus 2018", "answer_kind": "number"}{"task": "imo-bench-number_theory-052", "problem_id": "imo-bench-number_theory-052", "task_id": "imo-bench-number_theory-052", "category": "Number theory", "subcategory": "Number Theoretic Functions", "source": "Belarus 2018", "answer_kind": "number"}{"task": "imo-bench-number_theory-053", "problem_id": "imo-bench-number_theory-053", "task_id": "imo-bench-number_theory-053", "category": "Number theory", "subcategory": "Sequence", "source": "Britain 2018", "answer_kind": "literal"}{"task": "imo-bench-number_theory-054", "problem_id": "imo-bench-number_theory-054", "task_id": "imo-bench-number_theory-054", "category": "Number theory", "subcategory": "Divisor", "source": "Dutch 2017", "answer_kind": "literal"}{"task": "imo-bench-number_theory-055", "problem_id": "imo-bench-number_theory-055", "task_id": "imo-bench-number_theory-055", "category": "Number theory", "subcategory": "Base and Digit", "source": "Estonia TST 2018", "answer_kind": "number"}{"task": "imo-bench-number_theory-056", "problem_id": "imo-bench-number_theory-056", "task_id": "imo-bench-number_theory-056", "category": "Number theory", "subcategory": "Polynomial", "source": "Estonia TST 2018", "answer_kind": "number"}{"task": "imo-bench-number_theory-057", "problem_id": "imo-bench-number_theory-057", "task_id": "imo-bench-number_theory-057", "category": "Number theory", "subcategory": "Base and Digit", "source": "Japan 2018", "answer_kind": "number"}{"task": "imo-bench-number_theory-058", "problem_id": "imo-bench-number_theory-058", "task_id": "imo-bench-number_theory-058", "category": "Number theory", "subcategory": "Sequence", "source": "Japan TST 2018", "answer_kind": "literal"}{"task": "imo-bench-number_theory-059", "problem_id": "imo-bench-number_theory-059", "task_id": "imo-bench-number_theory-059", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "Belarus 2017", "answer_kind": "set"}{"task": "imo-bench-number_theory-060", "problem_id": "imo-bench-number_theory-060", "task_id": "imo-bench-number_theory-060", "category": "Number theory", "subcategory": "Operation", "source": "Bulgaria 2017", "answer_kind": "number"}{"task": "imo-bench-number_theory-061", "problem_id": "imo-bench-number_theory-061", "task_id": "imo-bench-number_theory-061", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "Czech and Slovak 2017 (modified)", "answer_kind": "literal"}{"task": "imo-bench-number_theory-062", "problem_id": "imo-bench-number_theory-062", "task_id": "imo-bench-number_theory-062", "category": "Number theory", "subcategory": "Functional Equation", "source": "Dutch 2017", "answer_kind": "set"}{"task": "imo-bench-number_theory-063", "problem_id": "imo-bench-number_theory-063", "task_id": "imo-bench-number_theory-063", "category": "Number theory", "subcategory": "Divisibility", "source": "Dutch 2017", "answer_kind": "set"}{"task": "imo-bench-number_theory-064", "problem_id": "imo-bench-number_theory-064", "task_id": "imo-bench-number_theory-064", "category": "Number theory", "subcategory": "Divisor", "source": "Estonian Math Competition 16/17", "answer_kind": "number"}{"task": "imo-bench-number_theory-065", "problem_id": "imo-bench-number_theory-065", "task_id": "imo-bench-number_theory-065", "category": "Number theory", "subcategory": "Sequence", "source": "Romania 2017", "answer_kind": "set"}{"task": "imo-bench-number_theory-066", "problem_id": "imo-bench-number_theory-066", "task_id": "imo-bench-number_theory-066", "category": "Number theory", "subcategory": "Functional Equation", "source": "Balkan MO 2017", "answer_kind": "expression"}{"task": "imo-bench-number_theory-067", "problem_id": "imo-bench-number_theory-067", "task_id": "imo-bench-number_theory-067", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "Belarus 2016", "answer_kind": "number"}{"task": "imo-bench-number_theory-068", "problem_id": "imo-bench-number_theory-068", "task_id": "imo-bench-number_theory-068", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "Belarus 2016", "answer_kind": "set"}{"task": "imo-bench-number_theory-069", "problem_id": "imo-bench-number_theory-069", "task_id": "imo-bench-number_theory-069", "category": "Number theory", "subcategory": "Divisor", "source": "Dutch 2015", "answer_kind": "literal"}{"task": "imo-bench-number_theory-070", "problem_id": "imo-bench-number_theory-070", "task_id": "imo-bench-number_theory-070", "category": "Number theory", "subcategory": "Other", "source": "Estonia 2015/2016", "answer_kind": "number"}{"task": "imo-bench-number_theory-071", "problem_id": "imo-bench-number_theory-071", "task_id": "imo-bench-number_theory-071", "category": "Number theory", "subcategory": "Divisibility", "source": "Hong Kong 2015", "answer_kind": "number"}{"task": "imo-bench-number_theory-072", "problem_id": "imo-bench-number_theory-072", "task_id": "imo-bench-number_theory-072", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "Olimpiadi Italiane della Matematica 2016", "answer_kind": "tuple"}{"task": "imo-bench-number_theory-073", "problem_id": "imo-bench-number_theory-073", "task_id": "imo-bench-number_theory-073", "category": "Number theory", "subcategory": "Divisor", "source": "Japan 2016", "answer_kind": "expression"}{"task": "imo-bench-number_theory-074", "problem_id": "imo-bench-number_theory-074", "task_id": "imo-bench-number_theory-074", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "Korea 2026 (modified)", "answer_kind": "tuple"}{"task": "imo-bench-number_theory-075", "problem_id": "imo-bench-number_theory-075", "task_id": "imo-bench-number_theory-075", "category": "Number theory", "subcategory": "Polynomial", "source": "Balkan MO 2016", "answer_kind": "expression"}{"task": "imo-bench-number_theory-076", "problem_id": "imo-bench-number_theory-076", "task_id": "imo-bench-number_theory-076", "category": "Number theory", "subcategory": "Polynomial", "source": "RMM 2016", "answer_kind": "number"}{"task": "imo-bench-number_theory-077", "problem_id": "imo-bench-number_theory-077", "task_id": "imo-bench-number_theory-077", "category": "Number theory", "subcategory": "Operation", "source": "Japan 2015", "answer_kind": "number"}{"task": "imo-bench-number_theory-078", "problem_id": "imo-bench-number_theory-078", "task_id": "imo-bench-number_theory-078", "category": "Number theory", "subcategory": "Divisibility", "source": "Japan 2015", "answer_kind": "set"}{"task": "imo-bench-number_theory-079", "problem_id": "imo-bench-number_theory-079", "task_id": "imo-bench-number_theory-079", "category": "Number theory", "subcategory": "Sequence", "source": "Korea 2015 (modified)", "answer_kind": "literal"}{"task": "imo-bench-number_theory-080", "problem_id": "imo-bench-number_theory-080", "task_id": "imo-bench-number_theory-080", "category": "Number theory", "subcategory": "Number Theoretic Functions", "source": "RMM 2015", "answer_kind": "literal"}{"task": "imo-bench-number_theory-081", "problem_id": "imo-bench-number_theory-081", "task_id": "imo-bench-number_theory-081", "category": "Number theory", "subcategory": "Binomial", "source": "China TST 2014 ( modified)", "answer_kind": "literal"}{"task": "imo-bench-number_theory-082", "problem_id": "imo-bench-number_theory-082", "task_id": "imo-bench-number_theory-082", "category": "Number theory", "subcategory": "Polynomial", "source": "China Girl's MO 2014", "answer_kind": "number"}{"task": "imo-bench-number_theory-083", "problem_id": "imo-bench-number_theory-083", "task_id": "imo-bench-number_theory-083", "category": "Number theory", "subcategory": "Set", "source": "China Girl's MO 2014", "answer_kind": "set"}{"task": "imo-bench-number_theory-084", "problem_id": "imo-bench-number_theory-084", "task_id": "imo-bench-number_theory-084", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "Greece 2014", "answer_kind": "set"}{"task": "imo-bench-number_theory-085", "problem_id": "imo-bench-number_theory-085", "task_id": "imo-bench-number_theory-085", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "Hong Kong 2014", "answer_kind": "number"}{"task": "imo-bench-number_theory-086", "problem_id": "imo-bench-number_theory-086", "task_id": "imo-bench-number_theory-086", "category": "Number theory", "subcategory": "Base and Digit", "source": "Japan 2014", "answer_kind": "number"}{"task": "imo-bench-number_theory-087", "problem_id": "imo-bench-number_theory-087", "task_id": "imo-bench-number_theory-087", "category": "Number theory", "subcategory": "Representation", "source": "Japan TST 2014", "answer_kind": "number"}{"task": "imo-bench-number_theory-088", "problem_id": "imo-bench-number_theory-088", "task_id": "imo-bench-number_theory-088", "category": "Number theory", "subcategory": "Divisor", "source": "Hungary 1998", "answer_kind": "number"}{"task": "imo-bench-number_theory-089", "problem_id": "imo-bench-number_theory-089", "task_id": "imo-bench-number_theory-089", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "Russia 1998", "answer_kind": "number"}{"task": "imo-bench-number_theory-090", "problem_id": "imo-bench-number_theory-090", "task_id": "imo-bench-number_theory-090", "category": "Number theory", "subcategory": "Other", "source": "Iran 2004", "answer_kind": "literal"}{"task": "imo-bench-number_theory-091", "problem_id": "imo-bench-number_theory-091", "task_id": "imo-bench-number_theory-091", "category": "Number theory", "subcategory": "Set", "source": "Iran 2011", "answer_kind": "number"}{"task": "imo-bench-number_theory-092", "problem_id": "imo-bench-number_theory-092", "task_id": "imo-bench-number_theory-092", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "China 2001", "answer_kind": "number"}{"task": "imo-bench-number_theory-093", "problem_id": "imo-bench-number_theory-093", "task_id": "imo-bench-number_theory-093", "category": "Number theory", "subcategory": "Divisibility", "source": "China 2003", "answer_kind": "number"}{"task": "imo-bench-number_theory-094", "problem_id": "imo-bench-number_theory-094", "task_id": "imo-bench-number_theory-094", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "Ireland 1999", "answer_kind": "set"}{"task": "imo-bench-number_theory-095", "problem_id": "imo-bench-number_theory-095", "task_id": "imo-bench-number_theory-095", "category": "Number theory", "subcategory": "Base and Digit", "source": "Romania 1999", "answer_kind": "number"}{"task": "imo-bench-number_theory-096", "problem_id": "imo-bench-number_theory-096", "task_id": "imo-bench-number_theory-096", "category": "Number theory", "subcategory": "Set", "source": "China 2004", "answer_kind": "literal"}{"task": "imo-bench-number_theory-097", "problem_id": "imo-bench-number_theory-097", "task_id": "imo-bench-number_theory-097", "category": "Number theory", "subcategory": "Divisibility", "source": "Turkey 2000", "answer_kind": "number"}{"task": "imo-bench-number_theory-098", "problem_id": "imo-bench-number_theory-098", "task_id": "imo-bench-number_theory-098", "category": "Number theory", "subcategory": "Other", "source": "Italy 2000", "answer_kind": "number"}{"task": "imo-bench-number_theory-099", "problem_id": "imo-bench-number_theory-099", "task_id": "imo-bench-number_theory-099", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "Austrian-Polish Mathematics Competition 2000", "answer_kind": "number"}{"task": "imo-bench-number_theory-100", "problem_id": "imo-bench-number_theory-100", "task_id": "imo-bench-number_theory-100", "category": "Number theory", "subcategory": "Diophantine Equation", "source": "St. Petersburg City MO (Russia) 2000", "answer_kind": "number"}12345# Problem
For a given positive integer $N$, Henry writes the quotient of $ab$ divided by $N+1$ on the board for each integer pair $(a,b)$ where $1\le a,b\le N$. Find all $N$ such that the sum of the $N^2$ numbers Henry wrote on the board is $\frac{N^3-N^2+2}{4}$.
Write your final answer as a single exact number in `/app/answer.txt`. Do not include a derivation.1234567#!/bin/bashset -euanswer=${ANSWER:-/app/answer.txt}mkdir -p "$(dirname "$answer")"cat > "$answer" <<'ANSWER_EOF'3ANSWER_EOF12345678910111213141516171819202122232425262728schema_version = "1.4"artifacts = ["/app/answer.txt"]
[task]name = "imo-answerbench/imo-bench-algebra-001"version = "1.0.0"description = "IMO-AnswerBench v2 short-answer mathematics problem"keywords = ["math", "imo", "evaluation"]
[metadata]category = "Algebra"subcategory = "Operation"source = "IMO Shortlist 2021"problem_id = "imo-bench-algebra-001"answer_kind = "number"
[agent]network_mode = "allowlist"timeout_sec = 3600
[environment]docker_image = "docker.io/library/python:3.12-slim"cpus = 1memory_mb = 2048
[verifier]network_mode = "allowlist"timeout_sec = 180123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""Grade the answer file against tests/reference.json. Writes reward.txt (1/0), grade.json and a copy of theanswer (answer.txt) to VERIFIER_DIR. Any error -> reward 0. The sympy/mpmath wheels ship base64-encoded (plain gittext: the Hub stores binary files in LFS/Xet, which a plain `git checkout` without git-lfs cannot read)."""import base64import hashlibimport ioimport jsonimport osimport statimport sysimport tempfileimport zipfile
LIMIT = 10_000 # bytesWHEELS = {"sympy-1.14.0-py3-none-any.whl": "e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", "mpmath-1.3.0-py3-none-any.whl": "a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c"}
def read_own(path): """Bytes of the regular file at exactly `path`: every folder on the way and the file are opened without following links (a FIFO cannot block it); one link only; at most LIMIT bytes.""" parts = os.path.abspath(path).split("/")[1:] folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY) try: for part in parts[:-1]: inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder) os.close(folder) folder = inner fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder) finally: os.close(folder) with os.fdopen(fd, "rb") as stream: info = os.fstat(stream.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1: raise ValueError("answer is not a regular file of its own") data = stream.read(LIMIT + 1) if len(data) > LIMIT: raise ValueError(f"answer file larger than {LIMIT} bytes") return data
def write_new(path, text): try: os.unlink(path) except FileNotFoundError: pass fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o644) with os.fdopen(fd, "w") as stream: stream.write(text)
def load_grader(tests): lib = tempfile.mkdtemp(prefix="grader-lib-") for name, digest in WHEELS.items(): blob = base64.b64decode(open(os.path.join(tests, name + ".b64"), "rb").read()) if hashlib.sha256(blob).hexdigest() != digest: raise ValueError(f"wheel hash mismatch: {name}") with zipfile.ZipFile(io.BytesIO(blob)) as z: z.extractall(lib) sys.path[:0] = [lib, tests] import grader, grader_struct return grader, grader_struct
def main(): tests, out = os.environ["TESTS_DIR"], os.environ["VERIFIER_DIR"] os.makedirs(out, exist_ok=True) write_new(os.path.join(out, "reward.txt"), "0") passed, why, submission = False, "grader error", "" try: try: submission = read_own(os.environ["ANSWER"]).decode("utf-8", "replace") except FileNotFoundError: submission, why = None, "no answer file" except (OSError, ValueError) as e: submission, why = None, f"answer file rejected: {e}" if submission is not None: write_new(os.path.join(out, "answer.txt"), submission) ref = json.loads(open(os.path.join(tests, "reference.json")).read()) reference, kind, variables = ref["answer"], ref["kind"], ref.get("variables", "") if not submission.strip(): passed, why = False, "empty" elif kind == "literal": import unicodedata def normalize(s): # Preserve all mathematical characters, operators, punctuation and case. return " ".join(unicodedata.normalize("NFC", s).split()).strip() passed = normalize(reference) == normalize(submission) why = "literal match" if passed else "literal mismatch" else: grader, structured = load_grader(tests) if kind == "number": passed, why = grader.grade_safe(reference, submission, timeout=60) else: passed, why = structured.grade_safe(reference, submission, kind, variables, timeout=60) except Exception as e: passed, why = False, f"grader error: {type(e).__name__}: {str(e)[:200]}" if passed: write_new(os.path.join(out, "reward.txt"), "1") write_new(os.path.join(out, "grade.json"), json.dumps({"passed": passed, "why": why, "submission": (submission or "")[:500]})) print("reward:", 1 if passed else 0, "|", why)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501"""Strict, exact single-number grader for Harbor math tasks (v2).
Contract (one uniform instruction for every task): the final answer is ONE exact number, e.g. 42, -7, 3/8,\\frac{3}{8}, 2\\sqrt{3}, \\frac{\\pi}{4}. No units, words, variables, "x =", sets, ranges, percent, or approximations.
grade(reference, submission) -> (passed: bool, reason: str) grade_safe(reference, submission, timeout=10) -> same, run in a memory-capped subprocess (use this in verifiers)
How it works- Extract: the last top-level \\boxed{...} / \\fbox{...} (brace-matched; a box nested inside the chosen box is rejected), else the whole text. Normalize unicode (NFKC, every dash/minus, superscript digits, zero-width chars, BOM), strip markdown bold, "Answer:", $..$, \\(..\\), \\[..\\], a trailing period (repeatedly, so "$5$." works), \\left. \\right. (null delimiters), \\left/\\right, LaTeX spacing; plain-text forms sqrt(..), pi, ** become LaTeX. Digit grouping (1,024 / 1\\,024 / 1 024 / 1{,}024) is removed only when the whole number is grouped in threes. 0.\\overline{3} becomes 1/3 exactly.- Parse with a small recursive-descent parser over a restricted grammar: numbers, + - * / ^, \\frac (also with TeX single-token arguments, \\frac12 = 1/2), \\sqrt{x}, \\sqrt[n]{x} (odd roots of negatives are real: \\sqrt[3]{-8} = -2), \\pi, \\cdot, \\times, brackets, implicit multiplication. Functions (\\ln/\\log, \\exp/e, \\sin/\\cos/\\tan, \\arcsin/\\arccos/\\arctan) are allowed only if the REFERENCE uses their family, so the problem cannot be restated instead of solved (\\lfloor, \\binom, factorials, sums: never). Scientific notation (1e5) is off when the reference uses the constant e (so "4e+1" means 4e+1). "3\\frac{1}{6}" is a mixed number in a reference and is rejected as ambiguous in a submission. "\\sqrt 16" (TeX: sqrt(1)*6) is rejected. 0^0, division by zero, non-real and huge values are rejected; written decimals are exact rationals (0.25 = 1/4; 1.41421356 is NOT sqrt 2).- Compare EXACTLY, never with a numeric tolerance (a numeric check can only reject, for speed): rationals by equality; algebraic numbers by minimal_polynomial(s - g) == x; expressions with pi as polynomials in a symbol T with algebraic coefficients (pi is transcendental); anything with ln/e/trig only if sympy simplifies the difference to exactly 0. Anything that cannot be proved equal within the time limit fails."""import multiprocessing as mpimport reimport unicodedata
import sympyfrom sympy import Integer, Rational
__version__ = "2"MAX_LEN = 1000 # characters of the cleaned answerMAX_INT_DIGITS = 1000 # digits of any number literalMAX_EXPONENT = 3000 # |exponent| allowed in a power or in scientific notationMAX_POW_BITS = 100_000 # estimated size of an exact power before computing itMEM_LIMIT = 2 << 30 # extra address space allowed to the grade_safe worker (bytes)FUNCS = {"ln": sympy.log, "log": sympy.log, "sin": sympy.sin, "cos": sympy.cos, "tan": sympy.tan, "arcsin": sympy.asin, "arccos": sympy.acos, "arctan": sympy.atan, "exp": sympy.exp}FAMILIES = [{"ln", "log"}, {"exp", "e"}, {"sin", "cos", "tan"}, {"arcsin", "arccos", "arctan"}]TRANSCENDENTAL = (sympy.exp, sympy.log, sympy.sin, sympy.cos, sympy.tan, sympy.asin, sympy.acos, sympy.atan)_X, _T = sympy.Symbol("x"), sympy.Symbol("T")
class Reject(Exception): pass
# ---------------------------------------------------------------- extraction and cleaning_BOX = re.compile(r"\\(?:boxed|fbox)\s*\{")_SUPERSCRIPT = str.maketrans("\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079\u207b", "0123456789-")_DASHES = "\u2010\u2011\u2012\u2013\u2014\u2212\ufe63\uff0d"
def _last_top_level_box(text: str): """Content of the last \\boxed{..}/\\fbox{..} that is not inside another box; None if there is no box. Rejects an unbalanced last box and a box nested inside the chosen box.""" spans, i = [], 0 while True: m = _BOX.search(text, i) if not m: break depth, j = 1, m.end() while j < len(text) and depth: depth += {"{": 1, "}": -1}.get(text[j], 0) j += 1 if depth: raise Reject("unbalanced \\boxed") spans.append((m.end(), j - 1)) i = j # continue AFTER this box: inner boxes are not top level if not spans: return None a, b = spans[-1] inner = text[a:b] if _BOX.search(inner): raise Reject("box inside box") return inner
def _normalize_unicode(t: str) -> str: t = re.sub("[\ufeff\u200b\u200c\u200d\u2060\u00ad]", "", t) t = re.sub("[\u2070\u00b9\u00b2\u00b3\u2074-\u2079\u207b]+", lambda m: "^{" + m.group().translate(_SUPERSCRIPT) + "}", t) for ch in _DASHES: t = t.replace(ch, "-") t = t.replace("\u00d7", "\\times ").replace("\u00b7", "\\cdot ").replace("\u22c5", "\\cdot ") t = t.replace("\u03c0", "\\pi ").replace("\u221a", "\\sqrt") return unicodedata.normalize("NFKC", t)
def _repeating(m) -> str: whole, fixed, rep = m.group(1) or "0", m.group(2), m.group(3) num = Integer(int(fixed + rep)) - Integer(int(fixed or "0")) den = Integer(10) ** len(fixed) * (Integer(10) ** len(rep) - 1) v = Integer(int(whole)) + num / den return f"(\\frac{{{v.p}}}{{{v.q}}})"
_NOT_UNIT = re.compile(r"\b(?:or|and|to|for|if|is|not|no|none|either|approx|about|between|each|where|with)\b", re.I)_UNIT_TEXT = re.compile(r"\s*\\(?:text|mathrm|mbox|textrm|operatorname)\s*\{\s*([A-Za-z][A-Za-z ./^0-9-]{0,24})\}\s*$")_UNIT_WORD = re.compile(r"(?<=[\d})])\s+([A-Za-z]{2,12}(?:\s?/\s?[A-Za-z]{1,8})?(?:\^\{?\d\}?)?)\s*$")_DEGREES = re.compile(r"\s*(?:\^\s*\{?\s*\\circ\s*\}?|°|\\degree)\s*$")_LHS = re.compile(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*(?=[^=]+$)")
def strip_wrappers(t: str) -> str: """Remove a wrapper around ONE value: trailing units (30 ft/s, 111 meters, \\sqrt{109}\\text{ m}), a degree sign, or a single 'n =' prefix. Hedges ('32 \\text{ or } 33'), approximations and multi-part answers are untouched.""" prev = None while t != prev: prev = t m = _UNIT_TEXT.search(t) if m and not _NOT_UNIT.search(m.group(1)) and t[:m.start()].strip(): t = t[:m.start()].rstrip() m = _UNIT_WORD.search(t) if m and not _NOT_UNIT.search(m.group(1)): t = t[:m.start()].rstrip() if t[:-1].strip(): t = _DEGREES.sub("", t).rstrip() t = _LHS.sub("", t) return t
def clean(text: str) -> str: t = _normalize_unicode((text or "").strip()) boxed = _last_top_level_box(t) if boxed is not None: t = boxed prev = None while t != prev: # peel wrappers in any order: "**Answer:** $5$." -> 5 prev = t t = t.strip() t = re.sub(r"^(\*\*|__)(.*)\1$", r"\2", t, flags=re.S).strip() t = re.sub(r"^\**\s*(?:the\s+)?(?:final\s+)?answer\s*(?:is)?\s*[:=]?\s*\**\s*", "", t, flags=re.I).strip() for a, b in (("$$", "$$"), ("$", "$"), ("\\(", "\\)"), ("\\[", "\\]")): if t.startswith(a) and t.endswith(b) and len(t) > len(a) + len(b): t = t[len(a):-len(b)].strip() t = t.rstrip(". ").strip() t = re.sub(r"\\(?:left|right)\.", "", t) # null delimiters t = re.sub(r"\\(?:displaystyle|left|right|bigl|bigr|Bigl|Bigr|big|Big)(?![A-Za-z])", "", t) t = re.sub(r"\\mathrm\{e\}|\\mathit\{e\}", "e", t) t = re.sub(r"\\[dtc]frac(?![A-Za-z])", r"\\frac", t) t = re.sub(r"(\d*)\.(\d*)\\overline\{(\d+)\}", _repeating, t) t = re.sub(r"(?<=\d)\\[,;! ](?=\d{3}(?!\d))", "", t) # 2\,560\,320 -> 2560320 t = re.sub(r"\\[,;:! ]|~", " ", t) t = strip_wrappers(t) # 30 ft/s, n = 24^5, 30° -> the bare value t = re.sub(r"(?<=\d)\s*\{,\}\s*(?=\d{3}(?!\d))", "", t) # 3{,}100 if re.fullmatch(r"\s*-?\d{1,3}([, ]\d{3})+(\.\d+)?\s*", t) and len(set(re.findall(r"[, ]", t.strip()))) == 1: t = re.sub(r"[, ]", "", t) # 3,100 / 1,000.5 / 1 000 (one separator kind) t = t.replace("**", "^") # python power t = re.sub(r"(?<![\\A-Za-z])sqrt\s*(?=[({])", r"\\sqrt", t) # sqrt(2) -> \sqrt(2) t = re.sub(r"(?<![\\A-Za-z])pi(?![A-Za-z])", r"\\pi ", t) # pi/4 -> \pi/4 return re.sub(r"\s+", " ", t).strip()
# ---------------------------------------------------------------- parserTOKEN = re.compile(r"\s*(?:(?P<num>\d+\.\d*|\.\d+|\d+)(?:[eE](?P<exp>[+-]?\d+))?|(?P<cmd>\\[A-Za-z]+)|(?P<sym>[-+*/^(){}\[\]])|(?P<let>[A-Za-z]))")NUM_ONLY = re.compile(r"\s*(?P<num>\d+\.\d*|\.\d+|\d+)")
def tokenize(s: str, sci: bool = True): """Tokens are (kind, value, raw). sci=False turns scientific notation off (the reference uses the constant e).""" out, pos = [], 0 while pos < len(s): m = TOKEN.match(s, pos) if m and not sci and m.group("num") is not None and m.group("exp") is not None: m = NUM_ONLY.match(s, pos) # "4e+1" -> 4, e, +, 1 if not m or m.end() == pos: if s[pos:].strip() == "": break raise Reject(f"unexpected character {s[pos]!r}") pos = m.end() if m.group("num") is not None: num = m.group("num") if len(num.replace(".", "")) > MAX_INT_DIGITS: raise Reject("number too long") val = Rational(num) if "." in num else Integer(int(num)) exp = m.groupdict().get("exp") if exp is not None: if abs(int(exp)) > MAX_EXPONENT: raise Reject("exponent too large") val = val * Rational(10) ** int(exp) out.append(("num", val, m.group(0).strip())) elif m.group("cmd"): out.append(("cmd", m.group("cmd")[1:], m.group("cmd"))) elif m.group("sym"): out.append(("sym", m.group("sym"), m.group("sym"))) else: out.append(("let", m.group("let"), m.group("let"))) return out
def _mixed_numbers(tokens, is_reference: bool): """N\\frac{a}{b} with integer literals N, a, b: a mixed number (N + a/b) in a reference; ambiguous in a submission.""" out, i = [], 0 pat = ["num", ("cmd", "frac"), ("sym", "{"), "num", ("sym", "}"), ("sym", "{"), "num", ("sym", "}")] while i < len(tokens): win = tokens[i:i + 8] ok = len(win) == 8 and all((w[0] == p) if isinstance(p, str) else (w[0], w[1]) == p for w, p in zip(win, pat)) ok = ok and all(win[k][2].isdigit() for k in (0, 3, 6)) prev = out[-1] if out else None if ok and not (prev and (prev[0] == "cmd" or prev[:2] == ("sym", "^"))): if not is_reference: raise Reject("ambiguous mixed number (write 7/2, not 3\\frac{1}{2})") if win[6][1] == 0: raise Reject("division by zero") out.append(("num", win[0][1] + win[3][1] / win[6][1], "mixed")) i += 8 continue out.append(tokens[i]); i += 1 return out
def _nonzero(d): """Reject a zero divisor, including a disguised one (sqrt(3+2sqrt2)-1-sqrt2). Numeric check: reject-only.""" if d == 0 or d.is_zero: raise Reject("division by zero") if not d.is_Rational: try: v = sympy.N(d, 60) except Exception: raise Reject("cannot evaluate divisor") if not v.is_Number or abs(v) < sympy.Float("1e-45", 60): raise Reject("division by (numerically) zero") return d
def _pow_bits(expr) -> int: return sum(abs(int(r.p)).bit_length() + int(r.q).bit_length() for r in expr.atoms(sympy.Rational)) or 1
class Parser: """expr := term (('+'|'-') term)* ; term := unary (('*'|'/'|implicit) unary)* ; unary := ('-'|'+') unary | power power := atom ('^' exponent)? ; atom := number | group | \\frac A A | \\sqrt[n] A | \\pi | e | func arg"""
def __init__(self, tokens, allowed): self.t, self.i, self.allowed = list(tokens), 0, allowed
def peek(self): return self.t[self.i][:2] if self.i < len(self.t) else (None, None)
def take(self, kind=None, val=None): k, v = self.peek() if k is None or (kind and k != kind) or (val is not None and v != val): raise Reject(f"malformed near token {self.i}") self.i += 1 return v
def parse(self): if not self.t: raise Reject("empty") e = self.expr() if self.i != len(self.t): raise Reject("trailing input") return e
def expr(self): v = self.term() while self.peek() in (("sym", "+"), ("sym", "-")): op = self.take() r = self.term() v = v + r if op == "+" else v - r return v
def starts_atom(self): k, v = self.peek() return k == "num" or (k == "sym" and v in "({[") or (k == "cmd" and v in ({"frac", "sqrt", "pi"} | self.allowed)) \ or (k == "let" and v == "e" and "e" in self.allowed)
def term(self): v = self.unary() while True: k, s = self.peek() if (k, s) in (("sym", "*"), ("cmd", "cdot"), ("cmd", "times")): self.take(); v = v * self.unary() elif (k, s) == ("sym", "/"): self.take(); v = v / _nonzero(self.unary()) elif self.starts_atom(): if self.peek()[0] == "num": raise Reject("two numbers side by side") # "2 100" or "\sqrt 16" is malformed, not a product v = v * self.power() # implicit multiplication: 2\sqrt{3}, 3\pi, 2(1+x) else: return v
def unary(self): if self.peek() == ("sym", "-"): self.take(); return -self.unary() if self.peek() == ("sym", "+"): self.take(); return self.unary() return self.power()
def power(self): base = self.atom() if self.peek() != ("sym", "^"): return base self.take() if self.peek() == ("sym", "{"): exp = self.group() elif self.peek() in (("sym", "-"), ("sym", "+")): sign = -1 if self.take() == "-" else 1 # 2^-1 exp = sign * self.atom() else: exp = self.atom() if self.peek() == ("sym", "^"): raise Reject("power tower") return self._pow(base, exp)
def _pow(self, base, exp): if not exp.is_number or exp.is_real is False: raise Reject("non-numeric exponent") if not exp.is_Rational: if base == sympy.E and "e" in self.allowed and abs(sympy.N(exp, 15)) <= MAX_EXPONENT: return sympy.exp(exp) # e^{\ln 2} raise Reject("irrational exponent not supported") if abs(exp) > MAX_EXPONENT: raise Reject("exponent too large") if base == 0 and exp <= 0: raise Reject("0^0 or division by zero") if exp < 0: _nonzero(base) if _pow_bits(base) * max(1, abs(int(exp.p))) > MAX_POW_BITS: raise Reject("value too large") if base.is_negative and exp.q % 2 == 1 and exp.q > 1: return (-1) ** exp.p * (-base) ** exp # real odd root: (-8)^{1/3} = -2 return base ** exp
def group(self): open_ = self.take("sym") close = {"(": ")", "[": "]", "{": "}"}.get(open_) if close is None: raise Reject("unexpected symbol") v = self.expr() self.take("sym", close) return v
def arg(self): """A TeX macro argument: {..}, (..) / [..] (plain-text style), or ONE token (\\frac12, \\frac\\pi4, \\sqrt2).""" k, v = self.peek() if k == "sym" and v in "{([": return self.group() if k == "num": raw = self.t[self.i][2] if not raw.isdigit(): raise Reject("ambiguous unbraced argument") if len(raw) == 1: self.i += 1 return v self.t[self.i] = ("num", Integer(int(raw[1:])), raw[1:]) # TeX takes one digit: \frac12 = 1/2 return Integer(int(raw[0])) if (k == "cmd" and v == "pi") or (k == "let" and v == "e" and "e" in self.allowed): return self.atom() raise Reject("ambiguous unbraced argument")
def atom(self): k, v = self.peek() if k == "num": self.take(); return v if k == "sym" and v in "({[": return self.group() if k == "let" and v == "e" and "e" in self.allowed: self.take(); return sympy.E if k == "cmd": self.take() if v == "frac": n, d = self.arg(), self.arg() return n / _nonzero(d) if v == "sqrt": if self.peek() == ("sym", "["): self.take(); idx = self.expr(); self.take("sym", "]") if not (idx.is_Integer and 2 <= idx <= 50): raise Reject("bad root index") return self._pow(self.arg(), Rational(1, int(idx))) return self._pow(self.arg(), Rational(1, 2)) if v == "pi": return sympy.pi if v in FUNCS and v in self.allowed: if self.peek() in (("sym", "{"), ("sym", "("), ("sym", "[")): a = self.group() else: a = self.power() return FUNCS[v](a) raise Reject(f"\\{v} not allowed") if k == "let": raise Reject(f"variable or word {v!r}") raise Reject("malformed")
def allowed_from_reference(ref_clean: str) -> set: allowed = {c for c in FUNCS if re.search(r"\\" + c + r"(?![A-Za-z])", ref_clean)} if re.search(r"(?<![A-Za-z\\])e(?![A-Za-z])", re.sub(r"\\[A-Za-z]+", "", ref_clean)): allowed.add("e") for fam in FAMILIES: if allowed & fam: allowed |= fam return allowed
def value(text: str, allowed: set, is_reference: bool = False): t = clean(text) if not t: raise Reject("empty") if len(t) > MAX_LEN: raise Reject("answer too long") if re.search(r"\\(?:text|mathrm|mathbf|operatorname|boxed|fbox)\{|\\%|%|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\in(?![A-Za-z])|\\infty|\\circ|°|,", t): raise Reject("not a single exact number (units/text/relation/percent/approximation/list)") tokens = _mixed_numbers(tokenize(t, sci="e" not in allowed), is_reference) v = Parser(tokens, allowed).parse() if v.has(sympy.zoo, sympy.oo, -sympy.oo, sympy.nan) or v.is_finite is False: raise Reject("non-finite value") if v.is_real is False: raise Reject("not a real number") return v
def _is_transcendental(expr) -> bool: return expr.has(sympy.E) or any(expr.has(f) for f in TRANSCENDENTAL)
def exact_equal(s, g) -> bool: """True only if s == g is PROVED. Numeric evaluation is used to reject quickly, never to accept.""" if s.is_Rational and g.is_Rational: return s == g d = s - g if d == 0: return True try: dv, gv = sympy.N(d, 50), sympy.N(g, 50) if dv.is_Number and gv.is_Number and abs(dv) > sympy.Float("1e-30", 50) * max(1, abs(gv)): return False except Exception: pass if _is_transcendental(d): # ln / e / trig: only an exact simplification to 0 counts for cand in (sympy.expand_log(d), d): try: if sympy.simplify(cand) == 0: return True except Exception: pass return False if d.has(sympy.pi): # pi is transcendental: d == 0 iff every coefficient in T is 0 num = sympy.together(sympy.expand(d.subs(sympy.pi, _T))).as_numer_denom()[0] poly = sympy.Poly(sympy.expand(num), _T) return all(sympy.minimal_polynomial(c, _X) == _X for c in poly.coeffs()) return sympy.minimal_polynomial(d, _X) == _X
def grade(reference: str, submission: str): try: ref_clean = clean(reference) allowed = allowed_from_reference(ref_clean) g = value(reference, allowed, is_reference=True) except Reject as e: return False, f"reference unusable: {e}" except Exception as e: return False, f"reference unusable: {type(e).__name__}" try: s = value(submission, allowed) except Reject as e: return False, f"format: {e}" except (RecursionError, ValueError, TypeError, ZeroDivisionError, OverflowError) as e: return False, f"format: {type(e).__name__}" try: ok = exact_equal(s, g) except Exception as e: return False, f"could not prove equal ({type(e).__name__})" return (True, "exact match") if ok else (False, "wrong value")
def _worker(q, reference, submission): try: import resource # cap = current address space + MEM_LIMIT (an absolute cap breaks vm = 0 # workers forked from big parents: they hang instead of grading) for line in open("/proc/self/status"): if line.startswith("VmSize:"): vm = int(line.split()[1]) * 1024 resource.setrlimit(resource.RLIMIT_AS, (vm + MEM_LIMIT, vm + MEM_LIMIT)) except Exception: pass try: q.put(grade(reference, submission)) except MemoryError: q.put((False, "grader out of memory")) except Exception as e: q.put((False, f"grader error: {type(e).__name__}"))
def grade_safe(reference: str, submission: str, timeout: float = 10.0): ctx = mp.get_context("fork") q = ctx.Queue() p = ctx.Process(target=_worker, args=(q, reference, submission)) p.start(); p.join(timeout) if p.is_alive(): p.kill(); p.join() return False, "timeout" try: return q.get(timeout=1) except Exception: return False, "grader crashed"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476"""Exact grader for structured math answers (Loubna msg 1257): a SET or TUPLE of exact numbers, an INTERVAL / union ofintervals with exact endpoints, or an EXPRESSION in named variables. Builds on the single-number grader (grader.py):same extraction/cleaning, same restricted parser and the same exact number equality (never a numeric tolerance).
grade(reference, submission, kind, variables="") -> (passed, reason) grade_safe(...) same, in a memory-capped subprocess with a timeout (use this in verifiers)
kind (fixed per task, stated in the task instruction): set {a, b, c}: order and repeats do not matter; braces optional tuple (a, b, c): order matters; parentheses optional interval [a, b), (-\\infty, c] \\cup [d, \\infty) ...: compared as SETS of reals (unions are merged exactly) expression one expression in the listed variables (e.g. "n" or "a,b"): equal as functions, proved by exact symbolic simplification to 0; random numeric evaluation can only rejectNumbers inside follow grader.py (exact values, functions only if the reference uses their family)."""import multiprocessing as mpimport randomimport reimport sysfrom pathlib import Path
import sympy
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))import grader as G # noqa: E402from grader import Reject # noqa: E402
__version__ = "1"_orig_nonzero = G._nonzero
def _nonzero_sym(d): """Divisors with variables are allowed unless identically zero; numeric divisors keep grader.py's check.""" if getattr(d, "free_symbols", None): if sympy.cancel(sympy.together(d)) == 0: raise Reject("division by zero") return d return _orig_nonzero(d)
G._nonzero = _nonzero_symKINDS = ("set", "tuple", "interval", "expression")MAX_ITEMS = 60_INF = re.compile(r"^\s*([+-]?)\s*\\infty\s*$|^\s*([+-]?)\s*\\inf\s*$|^\s*([+-]?)\s*oo\s*$")
# ---------------------------------------------------------------- shared helpersdef _top_level_boxes(text: str): out, i = [], 0 while True: m = G._BOX.search(text, i) if not m: return out depth, j = 1, m.end() while j < len(text) and depth: depth += {"{": 1, "}": -1}.get(text[j], 0) j += 1 out.append(re.sub(r"\s+", "", text[m.end():j - 1])) i = j
def _clean_struct(text: str) -> str: """grader.clean without its single-value wrapper stripping of commas; keeps \\{ \\} \\cup. Several top-level boxes with different contents are a hedge: rejected (review 2026-11-24).""" if len(set(_top_level_boxes(text or ""))) > 1: raise Reject("several different boxed answers") if len(text or "") > 20_000: raise Reject("answer too long") text = re.sub(r"\\\\(?=[A-Za-z{}])", r"\\", text) # shell-doubled backslashes: \\\\frac -> \\frac t = G.clean(text) # plain-text function names (agents often write ln(x), sin x): same as grader.clean does for sqrt( and pi t = re.sub(r"(?<![\\A-Za-z])(arcsin|arccos|arctan|ln|log|sin|cos|tan|exp)(?![A-Za-z])", r"\\\1 ", t) t = re.sub(r"\\lbrace|\\\{", "{", t) t = re.sub(r"\\rbrace|\\\}", "}", t) t = re.sub(r"\\(?:lbrack)", "[", t) t = re.sub(r"\\(?:rbrack)", "]", t) t = re.sub(r"\\(?:mathbb\{R\}|R)(?![A-Za-z])", "R", t) return t.strip()
def _split_top(s: str, sep: str = ","): out, depth, cur = [], 0, [] for ch in s: if ch in "([{": depth += 1 elif ch in ")]}": depth -= 1 if depth < 0: raise Reject("unbalanced brackets") if ch == sep and depth == 0: out.append("".join(cur)); cur = [] else: cur.append(ch) if depth != 0: raise Reject("unbalanced brackets") out.append("".join(cur)) return [x.strip() for x in out]
def _number(elem: str, allowed: set, is_reference: bool, labels: bool = True): """One exact real number (grader.py rules); also strips a leading 'x =' / 'x_1 =' unless labels=False.""" if not labels and re.match(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=", elem) and not is_reference: raise Reject("labelled tuple components (write the tuple in the asked order, without names)") e = re.sub(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*", "", elem.strip()) if not e: raise Reject("empty element") if re.search(r"\\(?:text|mathrm|mbox|operatorname)\{|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\infty|%", e): raise Reject("element is not a single exact number") toks = G._mixed_numbers(G.tokenize(e, sci="e" not in allowed), is_reference) v = G.Parser(toks, allowed).parse() if v.has(sympy.zoo, sympy.oo, -sympy.oo, sympy.nan) or v.is_finite is False: raise Reject("non-finite value") if v.is_real is False: raise Reject("not a real number") return v
def _strip_outer(t: str, pairs): for a, b in pairs: if t.startswith(a) and t.endswith(b): inner = t[len(a):len(t) - len(b)] try: _split_top(inner) # the outer pair must enclose everything (not "(1,2),(3,4)") except Reject: continue depth, ok = 0, True for ch in inner: depth += {"(": 1, "[": 1, "{": 1, ")": -1, "]": -1, "}": -1}.get(ch, 0) if depth < 0: ok = False break if ok: return inner.strip(), True return t, False
def _items(text: str, allowed: set, is_reference: bool, brackets, labels: bool = True): t = _clean_struct(text) if not t: raise Reject("empty") if len(t) > G.MAX_LEN * 2: raise Reject("answer too long") if re.search(r"\\(?:text|mbox)\{[^}]*[A-Za-z]{2,}|\b(?:or|and)\b", t) and not re.search(r"\\(?:text|mbox)\{\s*,?\s*\}", t): raise Reject("words in the answer (write only the list)") inner, _ = _strip_outer(t, brackets) parts = _split_top(inner) if len(parts) > MAX_ITEMS: raise Reject("too many items") if any(not p for p in parts): raise Reject("empty item") return [_number(p, allowed, is_reference, labels) for p in parts]
def _eq(a, b) -> bool: try: return G.exact_equal(a, b) except Exception: return False
def _dedup(vals): out = [] for v in vals: if not any(_eq(v, w) for w in out): out.append(v) return out
# ---------------------------------------------------------------- set / tupledef grade_set(reference, submission, allowed): g = _dedup(_items(reference, allowed, True, [("{", "}")])) s = _dedup(_items(submission, allowed, False, [("{", "}")])) if len(s) != len(g): return False, f"wrong number of elements ({len(s)} vs {len(g)})" left = list(g) for v in s: k = next((i for i, w in enumerate(left) if _eq(v, w)), None) if k is None: return False, "wrong element" left.pop(k) return True, "exact match"
def grade_tuple(reference, submission, allowed): g = _items(reference, allowed, True, [("(", ")"), ("[", "]"), ("{", "}")]) s = _items(submission, allowed, False, [("(", ")"), ("[", "]")], labels=False) if len(s) != len(g): return False, f"wrong length ({len(s)} vs {len(g)})" for v, w in zip(s, g): if not _eq(v, w): return False, "wrong component" return True, "exact match"
# ---------------------------------------------------------------- intervalsdef _endpoint(e, allowed, is_reference): m = _INF.match(e) if m: sign = "".join(x for x in m.groups() if x) return -sympy.oo if sign == "-" else sympy.oo return _number(e, allowed, is_reference)
def _intervals(text, allowed, is_reference): t = _clean_struct(text) if not t: raise Reject("empty") t = re.sub(r"^\s*[A-Za-z]\s*\\in\s*", "", t) # "x \in [1,2)" if re.fullmatch(r"R|\(-\\infty\s*,\s*\+?\\infty\)", t.replace(" ", "")): return [(-sympy.oo, False, sympy.oo, False)] pieces = [p.strip() for p in re.split(r"\\cup|∪|(?<![A-Za-z])U(?![A-Za-z])", t)] out = [] for p in pieces: if len(p) < 5 or p[0] not in "([" or p[-1] not in ")]": raise Reject("each piece must look like (a, b), [a, b], [a, b) or (a, b]") parts = _split_top(p[1:-1]) if len(parts) != 2: raise Reject("an interval needs exactly two endpoints") lo, hi = _endpoint(parts[0], allowed, is_reference), _endpoint(parts[1], allowed, is_reference) lc, hc = p[0] == "[", p[-1] == "]" if (lo in (sympy.oo, -sympy.oo) and lc) or (hi in (sympy.oo, -sympy.oo) and hc): raise Reject("infinite endpoint must be open") if lo == sympy.oo or hi == -sympy.oo: raise Reject("bad infinite endpoint") out.append((lo, lc, hi, hc)) return out
def _num(v): return float("inf") if v == sympy.oo else float("-inf") if v == -sympy.oo else float(sympy.N(v, 30))
def _cmp(a, b): """-1/0/1 exactly (0 only if PROVED equal).""" if a in (sympy.oo, -sympy.oo) or b in (sympy.oo, -sympy.oo): return 0 if a == b else (-1 if _num(a) < _num(b) else 1) if _eq(a, b): return 0 d = sympy.N(a - b, 60) if not d.is_Number or d == 0: raise Reject("cannot order interval endpoints") return -1 if d < 0 else 1
def _normalize(ivs): """Drop empty pieces, sort, merge overlapping / touching pieces: a canonical union.""" keep = [] for lo, lc, hi, hc in ivs: c = _cmp(lo, hi) if c > 0 or (c == 0 and not (lc and hc)): continue # empty piece keep.append((lo, lc, hi, hc)) keep.sort(key=lambda x: (_num(x[0]), not x[1])) out = [] for iv in keep: if out: lo, lc, hi, hc = out[-1] c = _cmp(iv[0], hi) if c < 0 or (c == 0 and (hc or iv[1])): # overlap, or touching with the shared point included c2 = _cmp(iv[2], hi) nhi, nhc = (iv[2], iv[3]) if c2 > 0 else (hi, hc or iv[3]) if c2 == 0 else (hi, hc) out[-1] = (lo, lc, nhi, nhc) continue out.append(iv) return out
def grade_interval(reference, submission, allowed): g = _normalize(_intervals(reference, allowed, True)) s = _normalize(_intervals(submission, allowed, False)) if len(s) != len(g): return False, "different set of reals" for (a, ac, b, bc), (c, cc, d, dc) in zip(s, g): if _cmp(a, c) != 0 or _cmp(b, d) != 0 or ac != cc or bc != dc: return False, "different set of reals" return True, "exact match"
# ---------------------------------------------------------------- expressions in variablesclass VarParser(G.Parser): """grader.Parser plus named variables (single letters or greek commands) and symbolic exponents."""
def __init__(self, tokens, allowed, variables): super().__init__(tokens, allowed) # positive: AoPS variables are lengths, counts and indices (sqrt(a^2) = a); review 2026-11-24 item F self.vars = {v: sympy.Symbol(v, real=True) for v in variables}
def term(self): """grader.Parser.term, but a number may follow ')', '}', ']' or a variable: (n+1)2^n, n2^n, 2^n3^n.""" v = self.unary() while True: k, s = self.peek() if (k, s) in (("sym", "*"), ("cmd", "cdot"), ("cmd", "times")): self.take(); v = v * self.unary() elif (k, s) == ("sym", "/"): self.take(); v = v / G._nonzero(self.unary()) elif self.starts_atom(): if k == "num": pk, pv = self.t[self.i - 1][:2] if not ((pk == "sym" and pv in ")}]") or (pk in ("let", "cmd") and pv in self.vars)): raise Reject("two numbers side by side") v = v * self.power() else: return v
def arg(self): k, v = self.peek() if k in ("let", "cmd") and v in self.vars: # \frac ab return self.atom() return super().arg()
def starts_atom(self): k, v = self.peek() return super().starts_atom() or ((k == "let" or k == "cmd") and v in self.vars)
def atom(self): k, v = self.peek() if (k == "let" or k == "cmd") and v in self.vars: self.take() if self.peek() == ("sym", "_"): raise Reject("subscripts not supported") return self.vars[v] return super().atom()
def _pow(self, base, exp): if exp.free_symbols or base.free_symbols: if exp.is_Rational and abs(exp) > 60: raise Reject("exponent too large") if exp.free_symbols and base.free_symbols: raise Reject("variable in base and exponent") if base.free_symbols and exp.is_Rational and exp.q > 1: return sympy.Pow(base, exp) return sympy.Pow(base, exp) return super()._pow(base, exp)
def _expr(text, allowed, variables, is_reference): raw = G._last_top_level_box(G._normalize_unicode(text or "")) or (text or "") m0 = re.match(r"^[\s$\\(\[]*([A-Za-z])\s*=", raw) if m0 and m0.group(1) in variables: raise Reject("an equation in the variable, not an expression") if is_reference and (re.search(r"\\\{|\\lbrace|\\(?:sin|cos|tan|ln|log|exp)\s*\d+\s*[A-Za-z]|/\s*[A-Za-z]\s*[A-Za-z]", raw)): raise Reject("ambiguous reference (braces, function of a product, or a/bc)") t = _clean_struct(text) m = re.match(r"^\s*([A-Za-z])(\([^()]*\))?(?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*(?=[^=]+$)", t) # "f(n) = ...", "S = ..." if m: if m.group(1) in variables and not m.group(2): raise Reject("an equation in the variable, not an expression") t = t[m.end():] if is_reference and (re.search(r"\\(?:sin|cos|tan|ln|log|exp)\s*\d+\s*[A-Za-z]", t) or "{" in re.sub(r"\\[A-Za-z]+\s*\{|[\^_]\s*\{|\}\s*\{", "", t).replace("\\{", "{") and re.search(r"\\\{", t) or re.search(r"/\s*[A-Za-z]\s*[A-Za-z]", t)): raise Reject("ambiguous reference (function of a product, braces, or a/bc)") if not t: raise Reject("empty") if len(t) > G.MAX_LEN: raise Reject("answer too long") if re.search(r"\\(?:text|mathrm|mbox|operatorname)\{|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\infty|,|%|\\sum|\\prod|\\int|!", t): raise Reject("not a single closed-form expression") toks = G.tokenize(t, sci=False) toks = [("sym", "_", "_") if x[0] == "sym" and x[1] == "_" else x for x in toks] v = VarParser(toks, allowed, variables).parse() if v.has(sympy.zoo, sympy.nan): raise Reject("undefined value") extra = {str(s) for s in v.free_symbols} - set(variables) if extra: raise Reject(f"unknown variables {sorted(extra)}") return v
def _points(syms, rng, k=6): """Random rational points away from 0 and 1 (positive, so radicals and logs of the variables stay real).""" return [{s: sympy.Rational(rng.randint(7, 97), rng.randint(3, 13)) for s in syms} for _ in range(k)]
def grade_expression(reference, submission, allowed, variables): g = _expr(reference, allowed, variables, True) s = _expr(submission, allowed, variables, False) d = s - g if d == 0: return True, "exact match" syms = sorted(d.free_symbols | g.free_symbols, key=str) rng = random.Random(0) for pt in _points(syms, rng): try: dv, gv = sympy.N(d.subs(pt), 40), sympy.N(g.subs(pt), 40) except Exception: continue if dv.is_Number and gv.is_Number and abs(dv) > sympy.Float("1e-25", 40) * max(1, abs(gv)): return False, "different expression" try: # equal up to a constant factor 1: a(sqrt6-sqrt2) = 2a sqrt(2-sqrt3) q = sympy.cancel(sympy.together(s / g)) if not q.free_symbols and q.is_number and _eq(q, sympy.Integer(1)): return True, "exact match" except Exception: pass for cand in (lambda e: sympy.cancel(sympy.together(e)), sympy.radsimp, sympy.simplify, lambda e: sympy.simplify(sympy.expand_log(sympy.expand_power_base(e, force=False)))): try: if cand(d) == 0: return True, "exact match" except Exception: pass return False, "could not prove the expressions equal"
# ---------------------------------------------------------------- entry pointsdef parse_variables(variables): vs = [v.strip().lstrip("\\") for v in re.split(r"[,\s]+", variables or "") if v.strip()] for v in vs: if not re.fullmatch(r"[A-Za-z]|alpha|beta|gamma|theta|lambda|mu|phi|omega|rho|sigma|tau", v) or v in ("e", "i"): raise Reject(f"unsupported variable name {v!r}") return vs
def grade(reference: str, submission: str, kind: str, variables: str = ""): if kind not in KINDS: return False, f"unknown kind {kind!r}" try: ref_clean = _clean_struct(reference) allowed = G.allowed_from_reference(ref_clean) vs = parse_variables(variables) if kind == "expression" else [] if kind == "expression": allowed.discard("e") if "e" in vs else None except Reject as e: return False, f"reference unusable: {e}" try: if kind == "set": return grade_set(reference, submission, allowed) if kind == "tuple": return grade_tuple(reference, submission, allowed) if kind == "interval": return grade_interval(reference, submission, allowed) return grade_expression(reference, submission, allowed, vs) except Reject as e: return False, f"format: {e}" except (RecursionError, ValueError, TypeError, ZeroDivisionError, OverflowError, AttributeError) as e: return False, f"format: {type(e).__name__}" except Exception as e: return False, f"could not grade ({type(e).__name__})"
def check_reference(reference: str, kind: str, variables: str = ""): """Reference parses under the kind's rules and matches itself.""" return grade(reference, reference, kind, variables)
def _worker(q, *args): try: import resource vm = 0 for line in open("/proc/self/status"): if line.startswith("VmSize:"): vm = int(line.split()[1]) * 1024 resource.setrlimit(resource.RLIMIT_AS, (vm + G.MEM_LIMIT, vm + G.MEM_LIMIT)) except Exception: pass try: q.put(grade(*args)) except MemoryError: q.put((False, "grader out of memory")) except Exception as e: q.put((False, f"grader error: {type(e).__name__}"))
def grade_safe(reference: str, submission: str, kind: str, variables: str = "", timeout: float = 20.0): ctx = mp.get_context("fork") q = ctx.Queue() p = ctx.Process(target=_worker, args=(q, reference, submission, kind, variables)) p.start(); p.join(timeout) if p.is_alive(): p.kill(); p.join() return False, "timeout" try: return q.get(timeout=1) except Exception: return False, "grader crashed"12345678910{ "answer": "3", "task_id": "imo-bench-algebra-001", "category": "Algebra", "subcategory": "Operation", "source": "IMO Shortlist 2021", "answer_kind": "number", "kind": "number", "variables": ""}12345678910111213#!/bin/bash# Reward 1 if /app/answer.txt holds an answer equal to the hidden reference (a set, tuple, interval or# expression; grader.py checks it exactly with sympy).# 0 is written before anything runs, so a crash, a timeout or a missing/linked/oversized answer scores 0.# Python runs isolated (-I -S); sympy/mpmath come from the pinned wheels in this directory (hash-checked, unpacked# offline into a new directory): nothing is installed and no network is used. ANSWER and VERIFIER_DIR override# the paths, to test the grader locally.case $0 in */*) here=${0%/*} ;; *) here=. ;; esacexport ANSWER=${ANSWER:-/app/answer.txt}export VERIFIER_DIR=${VERIFIER_DIR:-/logs/verifier}export TESTS_DIR=$here[ -d "$VERIFIER_DIR" ] && echo 0 > "$VERIFIER_DIR/reward.txt"timeout 150 python3 -B -I -S "$here/grade_task.py" || true123456# Problem
Given a positive integer $a$, let $\pi:\{1,2,\ldots , a\}\to\{1,2,\ldots , a\}$ be a bijection. Find the minimum possible value of $\sum_{i=1}^{a}{\left\lfloor \frac{\pi(i)}{i} \right\rfloor}$.
Write your final answer as a short answer in the same mathematical or textual notation as the expected answer in `/app/answer.txt`. Do not include a derivation.For this task the verifier compares normalized notation literally; equivalent reformulations may be rejected.1234567#!/bin/bashset -euanswer=${ANSWER:-/app/answer.txt}mkdir -p "$(dirname "$answer")"cat > "$answer" <<'ANSWER_EOF'$\left\lfloor \log_{2}a\right\rfloor +1$.ANSWER_EOF12345678910111213141516171819202122232425262728schema_version = "1.4"artifacts = ["/app/answer.txt"]
[task]name = "imo-answerbench/imo-bench-algebra-002"version = "1.0.0"description = "IMO-AnswerBench v2 short-answer mathematics problem"keywords = ["math", "imo", "evaluation"]
[metadata]category = "Algebra"subcategory = "Inequality"source = "IMO Shortlist 2021"problem_id = "imo-bench-algebra-002"answer_kind = "literal"
[agent]network_mode = "allowlist"timeout_sec = 3600
[environment]docker_image = "docker.io/library/python:3.12-slim"cpus = 1memory_mb = 2048
[verifier]network_mode = "allowlist"timeout_sec = 180123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""Grade the answer file against tests/reference.json. Writes reward.txt (1/0), grade.json and a copy of theanswer (answer.txt) to VERIFIER_DIR. Any error -> reward 0. The sympy/mpmath wheels ship base64-encoded (plain gittext: the Hub stores binary files in LFS/Xet, which a plain `git checkout` without git-lfs cannot read)."""import base64import hashlibimport ioimport jsonimport osimport statimport sysimport tempfileimport zipfile
LIMIT = 10_000 # bytesWHEELS = {"sympy-1.14.0-py3-none-any.whl": "e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", "mpmath-1.3.0-py3-none-any.whl": "a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c"}
def read_own(path): """Bytes of the regular file at exactly `path`: every folder on the way and the file are opened without following links (a FIFO cannot block it); one link only; at most LIMIT bytes.""" parts = os.path.abspath(path).split("/")[1:] folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY) try: for part in parts[:-1]: inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder) os.close(folder) folder = inner fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder) finally: os.close(folder) with os.fdopen(fd, "rb") as stream: info = os.fstat(stream.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1: raise ValueError("answer is not a regular file of its own") data = stream.read(LIMIT + 1) if len(data) > LIMIT: raise ValueError(f"answer file larger than {LIMIT} bytes") return data
def write_new(path, text): try: os.unlink(path) except FileNotFoundError: pass fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o644) with os.fdopen(fd, "w") as stream: stream.write(text)
def load_grader(tests): lib = tempfile.mkdtemp(prefix="grader-lib-") for name, digest in WHEELS.items(): blob = base64.b64decode(open(os.path.join(tests, name + ".b64"), "rb").read()) if hashlib.sha256(blob).hexdigest() != digest: raise ValueError(f"wheel hash mismatch: {name}") with zipfile.ZipFile(io.BytesIO(blob)) as z: z.extractall(lib) sys.path[:0] = [lib, tests] import grader, grader_struct return grader, grader_struct
def main(): tests, out = os.environ["TESTS_DIR"], os.environ["VERIFIER_DIR"] os.makedirs(out, exist_ok=True) write_new(os.path.join(out, "reward.txt"), "0") passed, why, submission = False, "grader error", "" try: try: submission = read_own(os.environ["ANSWER"]).decode("utf-8", "replace") except FileNotFoundError: submission, why = None, "no answer file" except (OSError, ValueError) as e: submission, why = None, f"answer file rejected: {e}" if submission is not None: write_new(os.path.join(out, "answer.txt"), submission) ref = json.loads(open(os.path.join(tests, "reference.json")).read()) reference, kind, variables = ref["answer"], ref["kind"], ref.get("variables", "") if not submission.strip(): passed, why = False, "empty" elif kind == "literal": import unicodedata def normalize(s): # Preserve all mathematical characters, operators, punctuation and case. return " ".join(unicodedata.normalize("NFC", s).split()).strip() passed = normalize(reference) == normalize(submission) why = "literal match" if passed else "literal mismatch" else: grader, structured = load_grader(tests) if kind == "number": passed, why = grader.grade_safe(reference, submission, timeout=60) else: passed, why = structured.grade_safe(reference, submission, kind, variables, timeout=60) except Exception as e: passed, why = False, f"grader error: {type(e).__name__}: {str(e)[:200]}" if passed: write_new(os.path.join(out, "reward.txt"), "1") write_new(os.path.join(out, "grade.json"), json.dumps({"passed": passed, "why": why, "submission": (submission or "")[:500]})) print("reward:", 1 if passed else 0, "|", why)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501"""Strict, exact single-number grader for Harbor math tasks (v2).
Contract (one uniform instruction for every task): the final answer is ONE exact number, e.g. 42, -7, 3/8,\\frac{3}{8}, 2\\sqrt{3}, \\frac{\\pi}{4}. No units, words, variables, "x =", sets, ranges, percent, or approximations.
grade(reference, submission) -> (passed: bool, reason: str) grade_safe(reference, submission, timeout=10) -> same, run in a memory-capped subprocess (use this in verifiers)
How it works- Extract: the last top-level \\boxed{...} / \\fbox{...} (brace-matched; a box nested inside the chosen box is rejected), else the whole text. Normalize unicode (NFKC, every dash/minus, superscript digits, zero-width chars, BOM), strip markdown bold, "Answer:", $..$, \\(..\\), \\[..\\], a trailing period (repeatedly, so "$5$." works), \\left. \\right. (null delimiters), \\left/\\right, LaTeX spacing; plain-text forms sqrt(..), pi, ** become LaTeX. Digit grouping (1,024 / 1\\,024 / 1 024 / 1{,}024) is removed only when the whole number is grouped in threes. 0.\\overline{3} becomes 1/3 exactly.- Parse with a small recursive-descent parser over a restricted grammar: numbers, + - * / ^, \\frac (also with TeX single-token arguments, \\frac12 = 1/2), \\sqrt{x}, \\sqrt[n]{x} (odd roots of negatives are real: \\sqrt[3]{-8} = -2), \\pi, \\cdot, \\times, brackets, implicit multiplication. Functions (\\ln/\\log, \\exp/e, \\sin/\\cos/\\tan, \\arcsin/\\arccos/\\arctan) are allowed only if the REFERENCE uses their family, so the problem cannot be restated instead of solved (\\lfloor, \\binom, factorials, sums: never). Scientific notation (1e5) is off when the reference uses the constant e (so "4e+1" means 4e+1). "3\\frac{1}{6}" is a mixed number in a reference and is rejected as ambiguous in a submission. "\\sqrt 16" (TeX: sqrt(1)*6) is rejected. 0^0, division by zero, non-real and huge values are rejected; written decimals are exact rationals (0.25 = 1/4; 1.41421356 is NOT sqrt 2).- Compare EXACTLY, never with a numeric tolerance (a numeric check can only reject, for speed): rationals by equality; algebraic numbers by minimal_polynomial(s - g) == x; expressions with pi as polynomials in a symbol T with algebraic coefficients (pi is transcendental); anything with ln/e/trig only if sympy simplifies the difference to exactly 0. Anything that cannot be proved equal within the time limit fails."""import multiprocessing as mpimport reimport unicodedata
import sympyfrom sympy import Integer, Rational
__version__ = "2"MAX_LEN = 1000 # characters of the cleaned answerMAX_INT_DIGITS = 1000 # digits of any number literalMAX_EXPONENT = 3000 # |exponent| allowed in a power or in scientific notationMAX_POW_BITS = 100_000 # estimated size of an exact power before computing itMEM_LIMIT = 2 << 30 # extra address space allowed to the grade_safe worker (bytes)FUNCS = {"ln": sympy.log, "log": sympy.log, "sin": sympy.sin, "cos": sympy.cos, "tan": sympy.tan, "arcsin": sympy.asin, "arccos": sympy.acos, "arctan": sympy.atan, "exp": sympy.exp}FAMILIES = [{"ln", "log"}, {"exp", "e"}, {"sin", "cos", "tan"}, {"arcsin", "arccos", "arctan"}]TRANSCENDENTAL = (sympy.exp, sympy.log, sympy.sin, sympy.cos, sympy.tan, sympy.asin, sympy.acos, sympy.atan)_X, _T = sympy.Symbol("x"), sympy.Symbol("T")
class Reject(Exception): pass
# ---------------------------------------------------------------- extraction and cleaning_BOX = re.compile(r"\\(?:boxed|fbox)\s*\{")_SUPERSCRIPT = str.maketrans("\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079\u207b", "0123456789-")_DASHES = "\u2010\u2011\u2012\u2013\u2014\u2212\ufe63\uff0d"
def _last_top_level_box(text: str): """Content of the last \\boxed{..}/\\fbox{..} that is not inside another box; None if there is no box. Rejects an unbalanced last box and a box nested inside the chosen box.""" spans, i = [], 0 while True: m = _BOX.search(text, i) if not m: break depth, j = 1, m.end() while j < len(text) and depth: depth += {"{": 1, "}": -1}.get(text[j], 0) j += 1 if depth: raise Reject("unbalanced \\boxed") spans.append((m.end(), j - 1)) i = j # continue AFTER this box: inner boxes are not top level if not spans: return None a, b = spans[-1] inner = text[a:b] if _BOX.search(inner): raise Reject("box inside box") return inner
def _normalize_unicode(t: str) -> str: t = re.sub("[\ufeff\u200b\u200c\u200d\u2060\u00ad]", "", t) t = re.sub("[\u2070\u00b9\u00b2\u00b3\u2074-\u2079\u207b]+", lambda m: "^{" + m.group().translate(_SUPERSCRIPT) + "}", t) for ch in _DASHES: t = t.replace(ch, "-") t = t.replace("\u00d7", "\\times ").replace("\u00b7", "\\cdot ").replace("\u22c5", "\\cdot ") t = t.replace("\u03c0", "\\pi ").replace("\u221a", "\\sqrt") return unicodedata.normalize("NFKC", t)
def _repeating(m) -> str: whole, fixed, rep = m.group(1) or "0", m.group(2), m.group(3) num = Integer(int(fixed + rep)) - Integer(int(fixed or "0")) den = Integer(10) ** len(fixed) * (Integer(10) ** len(rep) - 1) v = Integer(int(whole)) + num / den return f"(\\frac{{{v.p}}}{{{v.q}}})"
_NOT_UNIT = re.compile(r"\b(?:or|and|to|for|if|is|not|no|none|either|approx|about|between|each|where|with)\b", re.I)_UNIT_TEXT = re.compile(r"\s*\\(?:text|mathrm|mbox|textrm|operatorname)\s*\{\s*([A-Za-z][A-Za-z ./^0-9-]{0,24})\}\s*$")_UNIT_WORD = re.compile(r"(?<=[\d})])\s+([A-Za-z]{2,12}(?:\s?/\s?[A-Za-z]{1,8})?(?:\^\{?\d\}?)?)\s*$")_DEGREES = re.compile(r"\s*(?:\^\s*\{?\s*\\circ\s*\}?|°|\\degree)\s*$")_LHS = re.compile(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*(?=[^=]+$)")
def strip_wrappers(t: str) -> str: """Remove a wrapper around ONE value: trailing units (30 ft/s, 111 meters, \\sqrt{109}\\text{ m}), a degree sign, or a single 'n =' prefix. Hedges ('32 \\text{ or } 33'), approximations and multi-part answers are untouched.""" prev = None while t != prev: prev = t m = _UNIT_TEXT.search(t) if m and not _NOT_UNIT.search(m.group(1)) and t[:m.start()].strip(): t = t[:m.start()].rstrip() m = _UNIT_WORD.search(t) if m and not _NOT_UNIT.search(m.group(1)): t = t[:m.start()].rstrip() if t[:-1].strip(): t = _DEGREES.sub("", t).rstrip() t = _LHS.sub("", t) return t
def clean(text: str) -> str: t = _normalize_unicode((text or "").strip()) boxed = _last_top_level_box(t) if boxed is not None: t = boxed prev = None while t != prev: # peel wrappers in any order: "**Answer:** $5$." -> 5 prev = t t = t.strip() t = re.sub(r"^(\*\*|__)(.*)\1$", r"\2", t, flags=re.S).strip() t = re.sub(r"^\**\s*(?:the\s+)?(?:final\s+)?answer\s*(?:is)?\s*[:=]?\s*\**\s*", "", t, flags=re.I).strip() for a, b in (("$$", "$$"), ("$", "$"), ("\\(", "\\)"), ("\\[", "\\]")): if t.startswith(a) and t.endswith(b) and len(t) > len(a) + len(b): t = t[len(a):-len(b)].strip() t = t.rstrip(". ").strip() t = re.sub(r"\\(?:left|right)\.", "", t) # null delimiters t = re.sub(r"\\(?:displaystyle|left|right|bigl|bigr|Bigl|Bigr|big|Big)(?![A-Za-z])", "", t) t = re.sub(r"\\mathrm\{e\}|\\mathit\{e\}", "e", t) t = re.sub(r"\\[dtc]frac(?![A-Za-z])", r"\\frac", t) t = re.sub(r"(\d*)\.(\d*)\\overline\{(\d+)\}", _repeating, t) t = re.sub(r"(?<=\d)\\[,;! ](?=\d{3}(?!\d))", "", t) # 2\,560\,320 -> 2560320 t = re.sub(r"\\[,;:! ]|~", " ", t) t = strip_wrappers(t) # 30 ft/s, n = 24^5, 30° -> the bare value t = re.sub(r"(?<=\d)\s*\{,\}\s*(?=\d{3}(?!\d))", "", t) # 3{,}100 if re.fullmatch(r"\s*-?\d{1,3}([, ]\d{3})+(\.\d+)?\s*", t) and len(set(re.findall(r"[, ]", t.strip()))) == 1: t = re.sub(r"[, ]", "", t) # 3,100 / 1,000.5 / 1 000 (one separator kind) t = t.replace("**", "^") # python power t = re.sub(r"(?<![\\A-Za-z])sqrt\s*(?=[({])", r"\\sqrt", t) # sqrt(2) -> \sqrt(2) t = re.sub(r"(?<![\\A-Za-z])pi(?![A-Za-z])", r"\\pi ", t) # pi/4 -> \pi/4 return re.sub(r"\s+", " ", t).strip()
# ---------------------------------------------------------------- parserTOKEN = re.compile(r"\s*(?:(?P<num>\d+\.\d*|\.\d+|\d+)(?:[eE](?P<exp>[+-]?\d+))?|(?P<cmd>\\[A-Za-z]+)|(?P<sym>[-+*/^(){}\[\]])|(?P<let>[A-Za-z]))")NUM_ONLY = re.compile(r"\s*(?P<num>\d+\.\d*|\.\d+|\d+)")
def tokenize(s: str, sci: bool = True): """Tokens are (kind, value, raw). sci=False turns scientific notation off (the reference uses the constant e).""" out, pos = [], 0 while pos < len(s): m = TOKEN.match(s, pos) if m and not sci and m.group("num") is not None and m.group("exp") is not None: m = NUM_ONLY.match(s, pos) # "4e+1" -> 4, e, +, 1 if not m or m.end() == pos: if s[pos:].strip() == "": break raise Reject(f"unexpected character {s[pos]!r}") pos = m.end() if m.group("num") is not None: num = m.group("num") if len(num.replace(".", "")) > MAX_INT_DIGITS: raise Reject("number too long") val = Rational(num) if "." in num else Integer(int(num)) exp = m.groupdict().get("exp") if exp is not None: if abs(int(exp)) > MAX_EXPONENT: raise Reject("exponent too large") val = val * Rational(10) ** int(exp) out.append(("num", val, m.group(0).strip())) elif m.group("cmd"): out.append(("cmd", m.group("cmd")[1:], m.group("cmd"))) elif m.group("sym"): out.append(("sym", m.group("sym"), m.group("sym"))) else: out.append(("let", m.group("let"), m.group("let"))) return out
def _mixed_numbers(tokens, is_reference: bool): """N\\frac{a}{b} with integer literals N, a, b: a mixed number (N + a/b) in a reference; ambiguous in a submission.""" out, i = [], 0 pat = ["num", ("cmd", "frac"), ("sym", "{"), "num", ("sym", "}"), ("sym", "{"), "num", ("sym", "}")] while i < len(tokens): win = tokens[i:i + 8] ok = len(win) == 8 and all((w[0] == p) if isinstance(p, str) else (w[0], w[1]) == p for w, p in zip(win, pat)) ok = ok and all(win[k][2].isdigit() for k in (0, 3, 6)) prev = out[-1] if out else None if ok and not (prev and (prev[0] == "cmd" or prev[:2] == ("sym", "^"))): if not is_reference: raise Reject("ambiguous mixed number (write 7/2, not 3\\frac{1}{2})") if win[6][1] == 0: raise Reject("division by zero") out.append(("num", win[0][1] + win[3][1] / win[6][1], "mixed")) i += 8 continue out.append(tokens[i]); i += 1 return out
def _nonzero(d): """Reject a zero divisor, including a disguised one (sqrt(3+2sqrt2)-1-sqrt2). Numeric check: reject-only.""" if d == 0 or d.is_zero: raise Reject("division by zero") if not d.is_Rational: try: v = sympy.N(d, 60) except Exception: raise Reject("cannot evaluate divisor") if not v.is_Number or abs(v) < sympy.Float("1e-45", 60): raise Reject("division by (numerically) zero") return d
def _pow_bits(expr) -> int: return sum(abs(int(r.p)).bit_length() + int(r.q).bit_length() for r in expr.atoms(sympy.Rational)) or 1
class Parser: """expr := term (('+'|'-') term)* ; term := unary (('*'|'/'|implicit) unary)* ; unary := ('-'|'+') unary | power power := atom ('^' exponent)? ; atom := number | group | \\frac A A | \\sqrt[n] A | \\pi | e | func arg"""
def __init__(self, tokens, allowed): self.t, self.i, self.allowed = list(tokens), 0, allowed
def peek(self): return self.t[self.i][:2] if self.i < len(self.t) else (None, None)
def take(self, kind=None, val=None): k, v = self.peek() if k is None or (kind and k != kind) or (val is not None and v != val): raise Reject(f"malformed near token {self.i}") self.i += 1 return v
def parse(self): if not self.t: raise Reject("empty") e = self.expr() if self.i != len(self.t): raise Reject("trailing input") return e
def expr(self): v = self.term() while self.peek() in (("sym", "+"), ("sym", "-")): op = self.take() r = self.term() v = v + r if op == "+" else v - r return v
def starts_atom(self): k, v = self.peek() return k == "num" or (k == "sym" and v in "({[") or (k == "cmd" and v in ({"frac", "sqrt", "pi"} | self.allowed)) \ or (k == "let" and v == "e" and "e" in self.allowed)
def term(self): v = self.unary() while True: k, s = self.peek() if (k, s) in (("sym", "*"), ("cmd", "cdot"), ("cmd", "times")): self.take(); v = v * self.unary() elif (k, s) == ("sym", "/"): self.take(); v = v / _nonzero(self.unary()) elif self.starts_atom(): if self.peek()[0] == "num": raise Reject("two numbers side by side") # "2 100" or "\sqrt 16" is malformed, not a product v = v * self.power() # implicit multiplication: 2\sqrt{3}, 3\pi, 2(1+x) else: return v
def unary(self): if self.peek() == ("sym", "-"): self.take(); return -self.unary() if self.peek() == ("sym", "+"): self.take(); return self.unary() return self.power()
def power(self): base = self.atom() if self.peek() != ("sym", "^"): return base self.take() if self.peek() == ("sym", "{"): exp = self.group() elif self.peek() in (("sym", "-"), ("sym", "+")): sign = -1 if self.take() == "-" else 1 # 2^-1 exp = sign * self.atom() else: exp = self.atom() if self.peek() == ("sym", "^"): raise Reject("power tower") return self._pow(base, exp)
def _pow(self, base, exp): if not exp.is_number or exp.is_real is False: raise Reject("non-numeric exponent") if not exp.is_Rational: if base == sympy.E and "e" in self.allowed and abs(sympy.N(exp, 15)) <= MAX_EXPONENT: return sympy.exp(exp) # e^{\ln 2} raise Reject("irrational exponent not supported") if abs(exp) > MAX_EXPONENT: raise Reject("exponent too large") if base == 0 and exp <= 0: raise Reject("0^0 or division by zero") if exp < 0: _nonzero(base) if _pow_bits(base) * max(1, abs(int(exp.p))) > MAX_POW_BITS: raise Reject("value too large") if base.is_negative and exp.q % 2 == 1 and exp.q > 1: return (-1) ** exp.p * (-base) ** exp # real odd root: (-8)^{1/3} = -2 return base ** exp
def group(self): open_ = self.take("sym") close = {"(": ")", "[": "]", "{": "}"}.get(open_) if close is None: raise Reject("unexpected symbol") v = self.expr() self.take("sym", close) return v
def arg(self): """A TeX macro argument: {..}, (..) / [..] (plain-text style), or ONE token (\\frac12, \\frac\\pi4, \\sqrt2).""" k, v = self.peek() if k == "sym" and v in "{([": return self.group() if k == "num": raw = self.t[self.i][2] if not raw.isdigit(): raise Reject("ambiguous unbraced argument") if len(raw) == 1: self.i += 1 return v self.t[self.i] = ("num", Integer(int(raw[1:])), raw[1:]) # TeX takes one digit: \frac12 = 1/2 return Integer(int(raw[0])) if (k == "cmd" and v == "pi") or (k == "let" and v == "e" and "e" in self.allowed): return self.atom() raise Reject("ambiguous unbraced argument")
def atom(self): k, v = self.peek() if k == "num": self.take(); return v if k == "sym" and v in "({[": return self.group() if k == "let" and v == "e" and "e" in self.allowed: self.take(); return sympy.E if k == "cmd": self.take() if v == "frac": n, d = self.arg(), self.arg() return n / _nonzero(d) if v == "sqrt": if self.peek() == ("sym", "["): self.take(); idx = self.expr(); self.take("sym", "]") if not (idx.is_Integer and 2 <= idx <= 50): raise Reject("bad root index") return self._pow(self.arg(), Rational(1, int(idx))) return self._pow(self.arg(), Rational(1, 2)) if v == "pi": return sympy.pi if v in FUNCS and v in self.allowed: if self.peek() in (("sym", "{"), ("sym", "("), ("sym", "[")): a = self.group() else: a = self.power() return FUNCS[v](a) raise Reject(f"\\{v} not allowed") if k == "let": raise Reject(f"variable or word {v!r}") raise Reject("malformed")
def allowed_from_reference(ref_clean: str) -> set: allowed = {c for c in FUNCS if re.search(r"\\" + c + r"(?![A-Za-z])", ref_clean)} if re.search(r"(?<![A-Za-z\\])e(?![A-Za-z])", re.sub(r"\\[A-Za-z]+", "", ref_clean)): allowed.add("e") for fam in FAMILIES: if allowed & fam: allowed |= fam return allowed
def value(text: str, allowed: set, is_reference: bool = False): t = clean(text) if not t: raise Reject("empty") if len(t) > MAX_LEN: raise Reject("answer too long") if re.search(r"\\(?:text|mathrm|mathbf|operatorname|boxed|fbox)\{|\\%|%|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\in(?![A-Za-z])|\\infty|\\circ|°|,", t): raise Reject("not a single exact number (units/text/relation/percent/approximation/list)") tokens = _mixed_numbers(tokenize(t, sci="e" not in allowed), is_reference) v = Parser(tokens, allowed).parse() if v.has(sympy.zoo, sympy.oo, -sympy.oo, sympy.nan) or v.is_finite is False: raise Reject("non-finite value") if v.is_real is False: raise Reject("not a real number") return v
def _is_transcendental(expr) -> bool: return expr.has(sympy.E) or any(expr.has(f) for f in TRANSCENDENTAL)
def exact_equal(s, g) -> bool: """True only if s == g is PROVED. Numeric evaluation is used to reject quickly, never to accept.""" if s.is_Rational and g.is_Rational: return s == g d = s - g if d == 0: return True try: dv, gv = sympy.N(d, 50), sympy.N(g, 50) if dv.is_Number and gv.is_Number and abs(dv) > sympy.Float("1e-30", 50) * max(1, abs(gv)): return False except Exception: pass if _is_transcendental(d): # ln / e / trig: only an exact simplification to 0 counts for cand in (sympy.expand_log(d), d): try: if sympy.simplify(cand) == 0: return True except Exception: pass return False if d.has(sympy.pi): # pi is transcendental: d == 0 iff every coefficient in T is 0 num = sympy.together(sympy.expand(d.subs(sympy.pi, _T))).as_numer_denom()[0] poly = sympy.Poly(sympy.expand(num), _T) return all(sympy.minimal_polynomial(c, _X) == _X for c in poly.coeffs()) return sympy.minimal_polynomial(d, _X) == _X
def grade(reference: str, submission: str): try: ref_clean = clean(reference) allowed = allowed_from_reference(ref_clean) g = value(reference, allowed, is_reference=True) except Reject as e: return False, f"reference unusable: {e}" except Exception as e: return False, f"reference unusable: {type(e).__name__}" try: s = value(submission, allowed) except Reject as e: return False, f"format: {e}" except (RecursionError, ValueError, TypeError, ZeroDivisionError, OverflowError) as e: return False, f"format: {type(e).__name__}" try: ok = exact_equal(s, g) except Exception as e: return False, f"could not prove equal ({type(e).__name__})" return (True, "exact match") if ok else (False, "wrong value")
def _worker(q, reference, submission): try: import resource # cap = current address space + MEM_LIMIT (an absolute cap breaks vm = 0 # workers forked from big parents: they hang instead of grading) for line in open("/proc/self/status"): if line.startswith("VmSize:"): vm = int(line.split()[1]) * 1024 resource.setrlimit(resource.RLIMIT_AS, (vm + MEM_LIMIT, vm + MEM_LIMIT)) except Exception: pass try: q.put(grade(reference, submission)) except MemoryError: q.put((False, "grader out of memory")) except Exception as e: q.put((False, f"grader error: {type(e).__name__}"))
def grade_safe(reference: str, submission: str, timeout: float = 10.0): ctx = mp.get_context("fork") q = ctx.Queue() p = ctx.Process(target=_worker, args=(q, reference, submission)) p.start(); p.join(timeout) if p.is_alive(): p.kill(); p.join() return False, "timeout" try: return q.get(timeout=1) except Exception: return False, "grader crashed"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476"""Exact grader for structured math answers (Loubna msg 1257): a SET or TUPLE of exact numbers, an INTERVAL / union ofintervals with exact endpoints, or an EXPRESSION in named variables. Builds on the single-number grader (grader.py):same extraction/cleaning, same restricted parser and the same exact number equality (never a numeric tolerance).
grade(reference, submission, kind, variables="") -> (passed, reason) grade_safe(...) same, in a memory-capped subprocess with a timeout (use this in verifiers)
kind (fixed per task, stated in the task instruction): set {a, b, c}: order and repeats do not matter; braces optional tuple (a, b, c): order matters; parentheses optional interval [a, b), (-\\infty, c] \\cup [d, \\infty) ...: compared as SETS of reals (unions are merged exactly) expression one expression in the listed variables (e.g. "n" or "a,b"): equal as functions, proved by exact symbolic simplification to 0; random numeric evaluation can only rejectNumbers inside follow grader.py (exact values, functions only if the reference uses their family)."""import multiprocessing as mpimport randomimport reimport sysfrom pathlib import Path
import sympy
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))import grader as G # noqa: E402from grader import Reject # noqa: E402
__version__ = "1"_orig_nonzero = G._nonzero
def _nonzero_sym(d): """Divisors with variables are allowed unless identically zero; numeric divisors keep grader.py's check.""" if getattr(d, "free_symbols", None): if sympy.cancel(sympy.together(d)) == 0: raise Reject("division by zero") return d return _orig_nonzero(d)
G._nonzero = _nonzero_symKINDS = ("set", "tuple", "interval", "expression")MAX_ITEMS = 60_INF = re.compile(r"^\s*([+-]?)\s*\\infty\s*$|^\s*([+-]?)\s*\\inf\s*$|^\s*([+-]?)\s*oo\s*$")
# ---------------------------------------------------------------- shared helpersdef _top_level_boxes(text: str): out, i = [], 0 while True: m = G._BOX.search(text, i) if not m: return out depth, j = 1, m.end() while j < len(text) and depth: depth += {"{": 1, "}": -1}.get(text[j], 0) j += 1 out.append(re.sub(r"\s+", "", text[m.end():j - 1])) i = j
def _clean_struct(text: str) -> str: """grader.clean without its single-value wrapper stripping of commas; keeps \\{ \\} \\cup. Several top-level boxes with different contents are a hedge: rejected (review 2026-11-24).""" if len(set(_top_level_boxes(text or ""))) > 1: raise Reject("several different boxed answers") if len(text or "") > 20_000: raise Reject("answer too long") text = re.sub(r"\\\\(?=[A-Za-z{}])", r"\\", text) # shell-doubled backslashes: \\\\frac -> \\frac t = G.clean(text) # plain-text function names (agents often write ln(x), sin x): same as grader.clean does for sqrt( and pi t = re.sub(r"(?<![\\A-Za-z])(arcsin|arccos|arctan|ln|log|sin|cos|tan|exp)(?![A-Za-z])", r"\\\1 ", t) t = re.sub(r"\\lbrace|\\\{", "{", t) t = re.sub(r"\\rbrace|\\\}", "}", t) t = re.sub(r"\\(?:lbrack)", "[", t) t = re.sub(r"\\(?:rbrack)", "]", t) t = re.sub(r"\\(?:mathbb\{R\}|R)(?![A-Za-z])", "R", t) return t.strip()
def _split_top(s: str, sep: str = ","): out, depth, cur = [], 0, [] for ch in s: if ch in "([{": depth += 1 elif ch in ")]}": depth -= 1 if depth < 0: raise Reject("unbalanced brackets") if ch == sep and depth == 0: out.append("".join(cur)); cur = [] else: cur.append(ch) if depth != 0: raise Reject("unbalanced brackets") out.append("".join(cur)) return [x.strip() for x in out]
def _number(elem: str, allowed: set, is_reference: bool, labels: bool = True): """One exact real number (grader.py rules); also strips a leading 'x =' / 'x_1 =' unless labels=False.""" if not labels and re.match(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=", elem) and not is_reference: raise Reject("labelled tuple components (write the tuple in the asked order, without names)") e = re.sub(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*", "", elem.strip()) if not e: raise Reject("empty element") if re.search(r"\\(?:text|mathrm|mbox|operatorname)\{|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\infty|%", e): raise Reject("element is not a single exact number") toks = G._mixed_numbers(G.tokenize(e, sci="e" not in allowed), is_reference) v = G.Parser(toks, allowed).parse() if v.has(sympy.zoo, sympy.oo, -sympy.oo, sympy.nan) or v.is_finite is False: raise Reject("non-finite value") if v.is_real is False: raise Reject("not a real number") return v
def _strip_outer(t: str, pairs): for a, b in pairs: if t.startswith(a) and t.endswith(b): inner = t[len(a):len(t) - len(b)] try: _split_top(inner) # the outer pair must enclose everything (not "(1,2),(3,4)") except Reject: continue depth, ok = 0, True for ch in inner: depth += {"(": 1, "[": 1, "{": 1, ")": -1, "]": -1, "}": -1}.get(ch, 0) if depth < 0: ok = False break if ok: return inner.strip(), True return t, False
def _items(text: str, allowed: set, is_reference: bool, brackets, labels: bool = True): t = _clean_struct(text) if not t: raise Reject("empty") if len(t) > G.MAX_LEN * 2: raise Reject("answer too long") if re.search(r"\\(?:text|mbox)\{[^}]*[A-Za-z]{2,}|\b(?:or|and)\b", t) and not re.search(r"\\(?:text|mbox)\{\s*,?\s*\}", t): raise Reject("words in the answer (write only the list)") inner, _ = _strip_outer(t, brackets) parts = _split_top(inner) if len(parts) > MAX_ITEMS: raise Reject("too many items") if any(not p for p in parts): raise Reject("empty item") return [_number(p, allowed, is_reference, labels) for p in parts]
def _eq(a, b) -> bool: try: return G.exact_equal(a, b) except Exception: return False
def _dedup(vals): out = [] for v in vals: if not any(_eq(v, w) for w in out): out.append(v) return out
# ---------------------------------------------------------------- set / tupledef grade_set(reference, submission, allowed): g = _dedup(_items(reference, allowed, True, [("{", "}")])) s = _dedup(_items(submission, allowed, False, [("{", "}")])) if len(s) != len(g): return False, f"wrong number of elements ({len(s)} vs {len(g)})" left = list(g) for v in s: k = next((i for i, w in enumerate(left) if _eq(v, w)), None) if k is None: return False, "wrong element" left.pop(k) return True, "exact match"
def grade_tuple(reference, submission, allowed): g = _items(reference, allowed, True, [("(", ")"), ("[", "]"), ("{", "}")]) s = _items(submission, allowed, False, [("(", ")"), ("[", "]")], labels=False) if len(s) != len(g): return False, f"wrong length ({len(s)} vs {len(g)})" for v, w in zip(s, g): if not _eq(v, w): return False, "wrong component" return True, "exact match"
# ---------------------------------------------------------------- intervalsdef _endpoint(e, allowed, is_reference): m = _INF.match(e) if m: sign = "".join(x for x in m.groups() if x) return -sympy.oo if sign == "-" else sympy.oo return _number(e, allowed, is_reference)
def _intervals(text, allowed, is_reference): t = _clean_struct(text) if not t: raise Reject("empty") t = re.sub(r"^\s*[A-Za-z]\s*\\in\s*", "", t) # "x \in [1,2)" if re.fullmatch(r"R|\(-\\infty\s*,\s*\+?\\infty\)", t.replace(" ", "")): return [(-sympy.oo, False, sympy.oo, False)] pieces = [p.strip() for p in re.split(r"\\cup|∪|(?<![A-Za-z])U(?![A-Za-z])", t)] out = [] for p in pieces: if len(p) < 5 or p[0] not in "([" or p[-1] not in ")]": raise Reject("each piece must look like (a, b), [a, b], [a, b) or (a, b]") parts = _split_top(p[1:-1]) if len(parts) != 2: raise Reject("an interval needs exactly two endpoints") lo, hi = _endpoint(parts[0], allowed, is_reference), _endpoint(parts[1], allowed, is_reference) lc, hc = p[0] == "[", p[-1] == "]" if (lo in (sympy.oo, -sympy.oo) and lc) or (hi in (sympy.oo, -sympy.oo) and hc): raise Reject("infinite endpoint must be open") if lo == sympy.oo or hi == -sympy.oo: raise Reject("bad infinite endpoint") out.append((lo, lc, hi, hc)) return out
def _num(v): return float("inf") if v == sympy.oo else float("-inf") if v == -sympy.oo else float(sympy.N(v, 30))
def _cmp(a, b): """-1/0/1 exactly (0 only if PROVED equal).""" if a in (sympy.oo, -sympy.oo) or b in (sympy.oo, -sympy.oo): return 0 if a == b else (-1 if _num(a) < _num(b) else 1) if _eq(a, b): return 0 d = sympy.N(a - b, 60) if not d.is_Number or d == 0: raise Reject("cannot order interval endpoints") return -1 if d < 0 else 1
def _normalize(ivs): """Drop empty pieces, sort, merge overlapping / touching pieces: a canonical union.""" keep = [] for lo, lc, hi, hc in ivs: c = _cmp(lo, hi) if c > 0 or (c == 0 and not (lc and hc)): continue # empty piece keep.append((lo, lc, hi, hc)) keep.sort(key=lambda x: (_num(x[0]), not x[1])) out = [] for iv in keep: if out: lo, lc, hi, hc = out[-1] c = _cmp(iv[0], hi) if c < 0 or (c == 0 and (hc or iv[1])): # overlap, or touching with the shared point included c2 = _cmp(iv[2], hi) nhi, nhc = (iv[2], iv[3]) if c2 > 0 else (hi, hc or iv[3]) if c2 == 0 else (hi, hc) out[-1] = (lo, lc, nhi, nhc) continue out.append(iv) return out
def grade_interval(reference, submission, allowed): g = _normalize(_intervals(reference, allowed, True)) s = _normalize(_intervals(submission, allowed, False)) if len(s) != len(g): return False, "different set of reals" for (a, ac, b, bc), (c, cc, d, dc) in zip(s, g): if _cmp(a, c) != 0 or _cmp(b, d) != 0 or ac != cc or bc != dc: return False, "different set of reals" return True, "exact match"
# ---------------------------------------------------------------- expressions in variablesclass VarParser(G.Parser): """grader.Parser plus named variables (single letters or greek commands) and symbolic exponents."""
def __init__(self, tokens, allowed, variables): super().__init__(tokens, allowed) # positive: AoPS variables are lengths, counts and indices (sqrt(a^2) = a); review 2026-11-24 item F self.vars = {v: sympy.Symbol(v, real=True) for v in variables}
def term(self): """grader.Parser.term, but a number may follow ')', '}', ']' or a variable: (n+1)2^n, n2^n, 2^n3^n.""" v = self.unary() while True: k, s = self.peek() if (k, s) in (("sym", "*"), ("cmd", "cdot"), ("cmd", "times")): self.take(); v = v * self.unary() elif (k, s) == ("sym", "/"): self.take(); v = v / G._nonzero(self.unary()) elif self.starts_atom(): if k == "num": pk, pv = self.t[self.i - 1][:2] if not ((pk == "sym" and pv in ")}]") or (pk in ("let", "cmd") and pv in self.vars)): raise Reject("two numbers side by side") v = v * self.power() else: return v
def arg(self): k, v = self.peek() if k in ("let", "cmd") and v in self.vars: # \frac ab return self.atom() return super().arg()
def starts_atom(self): k, v = self.peek() return super().starts_atom() or ((k == "let" or k == "cmd") and v in self.vars)
def atom(self): k, v = self.peek() if (k == "let" or k == "cmd") and v in self.vars: self.take() if self.peek() == ("sym", "_"): raise Reject("subscripts not supported") return self.vars[v] return super().atom()
def _pow(self, base, exp): if exp.free_symbols or base.free_symbols: if exp.is_Rational and abs(exp) > 60: raise Reject("exponent too large") if exp.free_symbols and base.free_symbols: raise Reject("variable in base and exponent") if base.free_symbols and exp.is_Rational and exp.q > 1: return sympy.Pow(base, exp) return sympy.Pow(base, exp) return super()._pow(base, exp)
def _expr(text, allowed, variables, is_reference): raw = G._last_top_level_box(G._normalize_unicode(text or "")) or (text or "") m0 = re.match(r"^[\s$\\(\[]*([A-Za-z])\s*=", raw) if m0 and m0.group(1) in variables: raise Reject("an equation in the variable, not an expression") if is_reference and (re.search(r"\\\{|\\lbrace|\\(?:sin|cos|tan|ln|log|exp)\s*\d+\s*[A-Za-z]|/\s*[A-Za-z]\s*[A-Za-z]", raw)): raise Reject("ambiguous reference (braces, function of a product, or a/bc)") t = _clean_struct(text) m = re.match(r"^\s*([A-Za-z])(\([^()]*\))?(?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*(?=[^=]+$)", t) # "f(n) = ...", "S = ..." if m: if m.group(1) in variables and not m.group(2): raise Reject("an equation in the variable, not an expression") t = t[m.end():] if is_reference and (re.search(r"\\(?:sin|cos|tan|ln|log|exp)\s*\d+\s*[A-Za-z]", t) or "{" in re.sub(r"\\[A-Za-z]+\s*\{|[\^_]\s*\{|\}\s*\{", "", t).replace("\\{", "{") and re.search(r"\\\{", t) or re.search(r"/\s*[A-Za-z]\s*[A-Za-z]", t)): raise Reject("ambiguous reference (function of a product, braces, or a/bc)") if not t: raise Reject("empty") if len(t) > G.MAX_LEN: raise Reject("answer too long") if re.search(r"\\(?:text|mathrm|mbox|operatorname)\{|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\infty|,|%|\\sum|\\prod|\\int|!", t): raise Reject("not a single closed-form expression") toks = G.tokenize(t, sci=False) toks = [("sym", "_", "_") if x[0] == "sym" and x[1] == "_" else x for x in toks] v = VarParser(toks, allowed, variables).parse() if v.has(sympy.zoo, sympy.nan): raise Reject("undefined value") extra = {str(s) for s in v.free_symbols} - set(variables) if extra: raise Reject(f"unknown variables {sorted(extra)}") return v
def _points(syms, rng, k=6): """Random rational points away from 0 and 1 (positive, so radicals and logs of the variables stay real).""" return [{s: sympy.Rational(rng.randint(7, 97), rng.randint(3, 13)) for s in syms} for _ in range(k)]
def grade_expression(reference, submission, allowed, variables): g = _expr(reference, allowed, variables, True) s = _expr(submission, allowed, variables, False) d = s - g if d == 0: return True, "exact match" syms = sorted(d.free_symbols | g.free_symbols, key=str) rng = random.Random(0) for pt in _points(syms, rng): try: dv, gv = sympy.N(d.subs(pt), 40), sympy.N(g.subs(pt), 40) except Exception: continue if dv.is_Number and gv.is_Number and abs(dv) > sympy.Float("1e-25", 40) * max(1, abs(gv)): return False, "different expression" try: # equal up to a constant factor 1: a(sqrt6-sqrt2) = 2a sqrt(2-sqrt3) q = sympy.cancel(sympy.together(s / g)) if not q.free_symbols and q.is_number and _eq(q, sympy.Integer(1)): return True, "exact match" except Exception: pass for cand in (lambda e: sympy.cancel(sympy.together(e)), sympy.radsimp, sympy.simplify, lambda e: sympy.simplify(sympy.expand_log(sympy.expand_power_base(e, force=False)))): try: if cand(d) == 0: return True, "exact match" except Exception: pass return False, "could not prove the expressions equal"
# ---------------------------------------------------------------- entry pointsdef parse_variables(variables): vs = [v.strip().lstrip("\\") for v in re.split(r"[,\s]+", variables or "") if v.strip()] for v in vs: if not re.fullmatch(r"[A-Za-z]|alpha|beta|gamma|theta|lambda|mu|phi|omega|rho|sigma|tau", v) or v in ("e", "i"): raise Reject(f"unsupported variable name {v!r}") return vs
def grade(reference: str, submission: str, kind: str, variables: str = ""): if kind not in KINDS: return False, f"unknown kind {kind!r}" try: ref_clean = _clean_struct(reference) allowed = G.allowed_from_reference(ref_clean) vs = parse_variables(variables) if kind == "expression" else [] if kind == "expression": allowed.discard("e") if "e" in vs else None except Reject as e: return False, f"reference unusable: {e}" try: if kind == "set": return grade_set(reference, submission, allowed) if kind == "tuple": return grade_tuple(reference, submission, allowed) if kind == "interval": return grade_interval(reference, submission, allowed) return grade_expression(reference, submission, allowed, vs) except Reject as e: return False, f"format: {e}" except (RecursionError, ValueError, TypeError, ZeroDivisionError, OverflowError, AttributeError) as e: return False, f"format: {type(e).__name__}" except Exception as e: return False, f"could not grade ({type(e).__name__})"
def check_reference(reference: str, kind: str, variables: str = ""): """Reference parses under the kind's rules and matches itself.""" return grade(reference, reference, kind, variables)
def _worker(q, *args): try: import resource vm = 0 for line in open("/proc/self/status"): if line.startswith("VmSize:"): vm = int(line.split()[1]) * 1024 resource.setrlimit(resource.RLIMIT_AS, (vm + G.MEM_LIMIT, vm + G.MEM_LIMIT)) except Exception: pass try: q.put(grade(*args)) except MemoryError: q.put((False, "grader out of memory")) except Exception as e: q.put((False, f"grader error: {type(e).__name__}"))
def grade_safe(reference: str, submission: str, kind: str, variables: str = "", timeout: float = 20.0): ctx = mp.get_context("fork") q = ctx.Queue() p = ctx.Process(target=_worker, args=(q, reference, submission, kind, variables)) p.start(); p.join(timeout) if p.is_alive(): p.kill(); p.join() return False, "timeout" try: return q.get(timeout=1) except Exception: return False, "grader crashed"12345678910{ "answer": "$\\left\\lfloor \\log_{2}a\\right\\rfloor +1$.", "task_id": "imo-bench-algebra-002", "category": "Algebra", "subcategory": "Inequality", "source": "IMO Shortlist 2021", "answer_kind": "literal", "kind": "literal", "variables": ""}12345678910111213#!/bin/bash# Reward 1 if /app/answer.txt holds an answer equal to the hidden reference (a set, tuple, interval or# expression; grader.py checks it exactly with sympy).# 0 is written before anything runs, so a crash, a timeout or a missing/linked/oversized answer scores 0.# Python runs isolated (-I -S); sympy/mpmath come from the pinned wheels in this directory (hash-checked, unpacked# offline into a new directory): nothing is installed and no network is used. ANSWER and VERIFIER_DIR override# the paths, to test the grader locally.case $0 in */*) here=${0%/*} ;; *) here=. ;; esacexport ANSWER=${ANSWER:-/app/answer.txt}export VERIFIER_DIR=${VERIFIER_DIR:-/logs/verifier}export TESTS_DIR=$here[ -d "$VERIFIER_DIR" ] && echo 0 > "$VERIFIER_DIR/reward.txt"timeout 150 python3 -B -I -S "$here/grade_task.py" || true123456789101112# Problem
Find all functions $g:\mathbb{R}\rightarrow\mathbb{R}$ which is not a linear or constant function and satisfies
\[4g\left(x^{2}y+y^{2}z+z^{2}x\right)-(g(y)-g(x))(g(z)-g(y))(g(x)-g(z))=4g\left(xy^{2}+yz^{2}+zx^{2}\right)\]
for all real numbers $x,y,z$.
Write your final answer as a short answer in the same mathematical or textual notation as the expected answer in `/app/answer.txt`. Do not include a derivation.For this task the verifier compares normalized notation literally; equivalent reformulations may be rejected.1234567#!/bin/bashset -euanswer=${ANSWER:-/app/answer.txt}mkdir -p "$(dirname "$answer")"cat > "$answer" <<'ANSWER_EOF'$g(x)=2x^{3}+c, g(x)=-2x^{3}+c$ANSWER_EOF12345678910111213141516171819202122232425262728schema_version = "1.4"artifacts = ["/app/answer.txt"]
[task]name = "imo-answerbench/imo-bench-algebra-003"version = "1.0.0"description = "IMO-AnswerBench v2 short-answer mathematics problem"keywords = ["math", "imo", "evaluation"]
[metadata]category = "Algebra"subcategory = "Functional Equation"source = "IMO Shortlist 2021"problem_id = "imo-bench-algebra-003"answer_kind = "literal"
[agent]network_mode = "allowlist"timeout_sec = 3600
[environment]docker_image = "docker.io/library/python:3.12-slim"cpus = 1memory_mb = 2048
[verifier]network_mode = "allowlist"timeout_sec = 180123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""Grade the answer file against tests/reference.json. Writes reward.txt (1/0), grade.json and a copy of theanswer (answer.txt) to VERIFIER_DIR. Any error -> reward 0. The sympy/mpmath wheels ship base64-encoded (plain gittext: the Hub stores binary files in LFS/Xet, which a plain `git checkout` without git-lfs cannot read)."""import base64import hashlibimport ioimport jsonimport osimport statimport sysimport tempfileimport zipfile
LIMIT = 10_000 # bytesWHEELS = {"sympy-1.14.0-py3-none-any.whl": "e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", "mpmath-1.3.0-py3-none-any.whl": "a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c"}
def read_own(path): """Bytes of the regular file at exactly `path`: every folder on the way and the file are opened without following links (a FIFO cannot block it); one link only; at most LIMIT bytes.""" parts = os.path.abspath(path).split("/")[1:] folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY) try: for part in parts[:-1]: inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder) os.close(folder) folder = inner fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder) finally: os.close(folder) with os.fdopen(fd, "rb") as stream: info = os.fstat(stream.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1: raise ValueError("answer is not a regular file of its own") data = stream.read(LIMIT + 1) if len(data) > LIMIT: raise ValueError(f"answer file larger than {LIMIT} bytes") return data
def write_new(path, text): try: os.unlink(path) except FileNotFoundError: pass fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o644) with os.fdopen(fd, "w") as stream: stream.write(text)
def load_grader(tests): lib = tempfile.mkdtemp(prefix="grader-lib-") for name, digest in WHEELS.items(): blob = base64.b64decode(open(os.path.join(tests, name + ".b64"), "rb").read()) if hashlib.sha256(blob).hexdigest() != digest: raise ValueError(f"wheel hash mismatch: {name}") with zipfile.ZipFile(io.BytesIO(blob)) as z: z.extractall(lib) sys.path[:0] = [lib, tests] import grader, grader_struct return grader, grader_struct
def main(): tests, out = os.environ["TESTS_DIR"], os.environ["VERIFIER_DIR"] os.makedirs(out, exist_ok=True) write_new(os.path.join(out, "reward.txt"), "0") passed, why, submission = False, "grader error", "" try: try: submission = read_own(os.environ["ANSWER"]).decode("utf-8", "replace") except FileNotFoundError: submission, why = None, "no answer file" except (OSError, ValueError) as e: submission, why = None, f"answer file rejected: {e}" if submission is not None: write_new(os.path.join(out, "answer.txt"), submission) ref = json.loads(open(os.path.join(tests, "reference.json")).read()) reference, kind, variables = ref["answer"], ref["kind"], ref.get("variables", "") if not submission.strip(): passed, why = False, "empty" elif kind == "literal": import unicodedata def normalize(s): # Preserve all mathematical characters, operators, punctuation and case. return " ".join(unicodedata.normalize("NFC", s).split()).strip() passed = normalize(reference) == normalize(submission) why = "literal match" if passed else "literal mismatch" else: grader, structured = load_grader(tests) if kind == "number": passed, why = grader.grade_safe(reference, submission, timeout=60) else: passed, why = structured.grade_safe(reference, submission, kind, variables, timeout=60) except Exception as e: passed, why = False, f"grader error: {type(e).__name__}: {str(e)[:200]}" if passed: write_new(os.path.join(out, "reward.txt"), "1") write_new(os.path.join(out, "grade.json"), json.dumps({"passed": passed, "why": why, "submission": (submission or "")[:500]})) print("reward:", 1 if passed else 0, "|", why)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501"""Strict, exact single-number grader for Harbor math tasks (v2).
Contract (one uniform instruction for every task): the final answer is ONE exact number, e.g. 42, -7, 3/8,\\frac{3}{8}, 2\\sqrt{3}, \\frac{\\pi}{4}. No units, words, variables, "x =", sets, ranges, percent, or approximations.
grade(reference, submission) -> (passed: bool, reason: str) grade_safe(reference, submission, timeout=10) -> same, run in a memory-capped subprocess (use this in verifiers)
How it works- Extract: the last top-level \\boxed{...} / \\fbox{...} (brace-matched; a box nested inside the chosen box is rejected), else the whole text. Normalize unicode (NFKC, every dash/minus, superscript digits, zero-width chars, BOM), strip markdown bold, "Answer:", $..$, \\(..\\), \\[..\\], a trailing period (repeatedly, so "$5$." works), \\left. \\right. (null delimiters), \\left/\\right, LaTeX spacing; plain-text forms sqrt(..), pi, ** become LaTeX. Digit grouping (1,024 / 1\\,024 / 1 024 / 1{,}024) is removed only when the whole number is grouped in threes. 0.\\overline{3} becomes 1/3 exactly.- Parse with a small recursive-descent parser over a restricted grammar: numbers, + - * / ^, \\frac (also with TeX single-token arguments, \\frac12 = 1/2), \\sqrt{x}, \\sqrt[n]{x} (odd roots of negatives are real: \\sqrt[3]{-8} = -2), \\pi, \\cdot, \\times, brackets, implicit multiplication. Functions (\\ln/\\log, \\exp/e, \\sin/\\cos/\\tan, \\arcsin/\\arccos/\\arctan) are allowed only if the REFERENCE uses their family, so the problem cannot be restated instead of solved (\\lfloor, \\binom, factorials, sums: never). Scientific notation (1e5) is off when the reference uses the constant e (so "4e+1" means 4e+1). "3\\frac{1}{6}" is a mixed number in a reference and is rejected as ambiguous in a submission. "\\sqrt 16" (TeX: sqrt(1)*6) is rejected. 0^0, division by zero, non-real and huge values are rejected; written decimals are exact rationals (0.25 = 1/4; 1.41421356 is NOT sqrt 2).- Compare EXACTLY, never with a numeric tolerance (a numeric check can only reject, for speed): rationals by equality; algebraic numbers by minimal_polynomial(s - g) == x; expressions with pi as polynomials in a symbol T with algebraic coefficients (pi is transcendental); anything with ln/e/trig only if sympy simplifies the difference to exactly 0. Anything that cannot be proved equal within the time limit fails."""import multiprocessing as mpimport reimport unicodedata
import sympyfrom sympy import Integer, Rational
__version__ = "2"MAX_LEN = 1000 # characters of the cleaned answerMAX_INT_DIGITS = 1000 # digits of any number literalMAX_EXPONENT = 3000 # |exponent| allowed in a power or in scientific notationMAX_POW_BITS = 100_000 # estimated size of an exact power before computing itMEM_LIMIT = 2 << 30 # extra address space allowed to the grade_safe worker (bytes)FUNCS = {"ln": sympy.log, "log": sympy.log, "sin": sympy.sin, "cos": sympy.cos, "tan": sympy.tan, "arcsin": sympy.asin, "arccos": sympy.acos, "arctan": sympy.atan, "exp": sympy.exp}FAMILIES = [{"ln", "log"}, {"exp", "e"}, {"sin", "cos", "tan"}, {"arcsin", "arccos", "arctan"}]TRANSCENDENTAL = (sympy.exp, sympy.log, sympy.sin, sympy.cos, sympy.tan, sympy.asin, sympy.acos, sympy.atan)_X, _T = sympy.Symbol("x"), sympy.Symbol("T")
class Reject(Exception): pass
# ---------------------------------------------------------------- extraction and cleaning_BOX = re.compile(r"\\(?:boxed|fbox)\s*\{")_SUPERSCRIPT = str.maketrans("\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079\u207b", "0123456789-")_DASHES = "\u2010\u2011\u2012\u2013\u2014\u2212\ufe63\uff0d"
def _last_top_level_box(text: str): """Content of the last \\boxed{..}/\\fbox{..} that is not inside another box; None if there is no box. Rejects an unbalanced last box and a box nested inside the chosen box.""" spans, i = [], 0 while True: m = _BOX.search(text, i) if not m: break depth, j = 1, m.end() while j < len(text) and depth: depth += {"{": 1, "}": -1}.get(text[j], 0) j += 1 if depth: raise Reject("unbalanced \\boxed") spans.append((m.end(), j - 1)) i = j # continue AFTER this box: inner boxes are not top level if not spans: return None a, b = spans[-1] inner = text[a:b] if _BOX.search(inner): raise Reject("box inside box") return inner
def _normalize_unicode(t: str) -> str: t = re.sub("[\ufeff\u200b\u200c\u200d\u2060\u00ad]", "", t) t = re.sub("[\u2070\u00b9\u00b2\u00b3\u2074-\u2079\u207b]+", lambda m: "^{" + m.group().translate(_SUPERSCRIPT) + "}", t) for ch in _DASHES: t = t.replace(ch, "-") t = t.replace("\u00d7", "\\times ").replace("\u00b7", "\\cdot ").replace("\u22c5", "\\cdot ") t = t.replace("\u03c0", "\\pi ").replace("\u221a", "\\sqrt") return unicodedata.normalize("NFKC", t)
def _repeating(m) -> str: whole, fixed, rep = m.group(1) or "0", m.group(2), m.group(3) num = Integer(int(fixed + rep)) - Integer(int(fixed or "0")) den = Integer(10) ** len(fixed) * (Integer(10) ** len(rep) - 1) v = Integer(int(whole)) + num / den return f"(\\frac{{{v.p}}}{{{v.q}}})"
_NOT_UNIT = re.compile(r"\b(?:or|and|to|for|if|is|not|no|none|either|approx|about|between|each|where|with)\b", re.I)_UNIT_TEXT = re.compile(r"\s*\\(?:text|mathrm|mbox|textrm|operatorname)\s*\{\s*([A-Za-z][A-Za-z ./^0-9-]{0,24})\}\s*$")_UNIT_WORD = re.compile(r"(?<=[\d})])\s+([A-Za-z]{2,12}(?:\s?/\s?[A-Za-z]{1,8})?(?:\^\{?\d\}?)?)\s*$")_DEGREES = re.compile(r"\s*(?:\^\s*\{?\s*\\circ\s*\}?|°|\\degree)\s*$")_LHS = re.compile(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*(?=[^=]+$)")
def strip_wrappers(t: str) -> str: """Remove a wrapper around ONE value: trailing units (30 ft/s, 111 meters, \\sqrt{109}\\text{ m}), a degree sign, or a single 'n =' prefix. Hedges ('32 \\text{ or } 33'), approximations and multi-part answers are untouched.""" prev = None while t != prev: prev = t m = _UNIT_TEXT.search(t) if m and not _NOT_UNIT.search(m.group(1)) and t[:m.start()].strip(): t = t[:m.start()].rstrip() m = _UNIT_WORD.search(t) if m and not _NOT_UNIT.search(m.group(1)): t = t[:m.start()].rstrip() if t[:-1].strip(): t = _DEGREES.sub("", t).rstrip() t = _LHS.sub("", t) return t
def clean(text: str) -> str: t = _normalize_unicode((text or "").strip()) boxed = _last_top_level_box(t) if boxed is not None: t = boxed prev = None while t != prev: # peel wrappers in any order: "**Answer:** $5$." -> 5 prev = t t = t.strip() t = re.sub(r"^(\*\*|__)(.*)\1$", r"\2", t, flags=re.S).strip() t = re.sub(r"^\**\s*(?:the\s+)?(?:final\s+)?answer\s*(?:is)?\s*[:=]?\s*\**\s*", "", t, flags=re.I).strip() for a, b in (("$$", "$$"), ("$", "$"), ("\\(", "\\)"), ("\\[", "\\]")): if t.startswith(a) and t.endswith(b) and len(t) > len(a) + len(b): t = t[len(a):-len(b)].strip() t = t.rstrip(". ").strip() t = re.sub(r"\\(?:left|right)\.", "", t) # null delimiters t = re.sub(r"\\(?:displaystyle|left|right|bigl|bigr|Bigl|Bigr|big|Big)(?![A-Za-z])", "", t) t = re.sub(r"\\mathrm\{e\}|\\mathit\{e\}", "e", t) t = re.sub(r"\\[dtc]frac(?![A-Za-z])", r"\\frac", t) t = re.sub(r"(\d*)\.(\d*)\\overline\{(\d+)\}", _repeating, t) t = re.sub(r"(?<=\d)\\[,;! ](?=\d{3}(?!\d))", "", t) # 2\,560\,320 -> 2560320 t = re.sub(r"\\[,;:! ]|~", " ", t) t = strip_wrappers(t) # 30 ft/s, n = 24^5, 30° -> the bare value t = re.sub(r"(?<=\d)\s*\{,\}\s*(?=\d{3}(?!\d))", "", t) # 3{,}100 if re.fullmatch(r"\s*-?\d{1,3}([, ]\d{3})+(\.\d+)?\s*", t) and len(set(re.findall(r"[, ]", t.strip()))) == 1: t = re.sub(r"[, ]", "", t) # 3,100 / 1,000.5 / 1 000 (one separator kind) t = t.replace("**", "^") # python power t = re.sub(r"(?<![\\A-Za-z])sqrt\s*(?=[({])", r"\\sqrt", t) # sqrt(2) -> \sqrt(2) t = re.sub(r"(?<![\\A-Za-z])pi(?![A-Za-z])", r"\\pi ", t) # pi/4 -> \pi/4 return re.sub(r"\s+", " ", t).strip()
# ---------------------------------------------------------------- parserTOKEN = re.compile(r"\s*(?:(?P<num>\d+\.\d*|\.\d+|\d+)(?:[eE](?P<exp>[+-]?\d+))?|(?P<cmd>\\[A-Za-z]+)|(?P<sym>[-+*/^(){}\[\]])|(?P<let>[A-Za-z]))")NUM_ONLY = re.compile(r"\s*(?P<num>\d+\.\d*|\.\d+|\d+)")
def tokenize(s: str, sci: bool = True): """Tokens are (kind, value, raw). sci=False turns scientific notation off (the reference uses the constant e).""" out, pos = [], 0 while pos < len(s): m = TOKEN.match(s, pos) if m and not sci and m.group("num") is not None and m.group("exp") is not None: m = NUM_ONLY.match(s, pos) # "4e+1" -> 4, e, +, 1 if not m or m.end() == pos: if s[pos:].strip() == "": break raise Reject(f"unexpected character {s[pos]!r}") pos = m.end() if m.group("num") is not None: num = m.group("num") if len(num.replace(".", "")) > MAX_INT_DIGITS: raise Reject("number too long") val = Rational(num) if "." in num else Integer(int(num)) exp = m.groupdict().get("exp") if exp is not None: if abs(int(exp)) > MAX_EXPONENT: raise Reject("exponent too large") val = val * Rational(10) ** int(exp) out.append(("num", val, m.group(0).strip())) elif m.group("cmd"): out.append(("cmd", m.group("cmd")[1:], m.group("cmd"))) elif m.group("sym"): out.append(("sym", m.group("sym"), m.group("sym"))) else: out.append(("let", m.group("let"), m.group("let"))) return out
def _mixed_numbers(tokens, is_reference: bool): """N\\frac{a}{b} with integer literals N, a, b: a mixed number (N + a/b) in a reference; ambiguous in a submission.""" out, i = [], 0 pat = ["num", ("cmd", "frac"), ("sym", "{"), "num", ("sym", "}"), ("sym", "{"), "num", ("sym", "}")] while i < len(tokens): win = tokens[i:i + 8] ok = len(win) == 8 and all((w[0] == p) if isinstance(p, str) else (w[0], w[1]) == p for w, p in zip(win, pat)) ok = ok and all(win[k][2].isdigit() for k in (0, 3, 6)) prev = out[-1] if out else None if ok and not (prev and (prev[0] == "cmd" or prev[:2] == ("sym", "^"))): if not is_reference: raise Reject("ambiguous mixed number (write 7/2, not 3\\frac{1}{2})") if win[6][1] == 0: raise Reject("division by zero") out.append(("num", win[0][1] + win[3][1] / win[6][1], "mixed")) i += 8 continue out.append(tokens[i]); i += 1 return out
def _nonzero(d): """Reject a zero divisor, including a disguised one (sqrt(3+2sqrt2)-1-sqrt2). Numeric check: reject-only.""" if d == 0 or d.is_zero: raise Reject("division by zero") if not d.is_Rational: try: v = sympy.N(d, 60) except Exception: raise Reject("cannot evaluate divisor") if not v.is_Number or abs(v) < sympy.Float("1e-45", 60): raise Reject("division by (numerically) zero") return d
def _pow_bits(expr) -> int: return sum(abs(int(r.p)).bit_length() + int(r.q).bit_length() for r in expr.atoms(sympy.Rational)) or 1
class Parser: """expr := term (('+'|'-') term)* ; term := unary (('*'|'/'|implicit) unary)* ; unary := ('-'|'+') unary | power power := atom ('^' exponent)? ; atom := number | group | \\frac A A | \\sqrt[n] A | \\pi | e | func arg"""
def __init__(self, tokens, allowed): self.t, self.i, self.allowed = list(tokens), 0, allowed
def peek(self): return self.t[self.i][:2] if self.i < len(self.t) else (None, None)
def take(self, kind=None, val=None): k, v = self.peek() if k is None or (kind and k != kind) or (val is not None and v != val): raise Reject(f"malformed near token {self.i}") self.i += 1 return v
def parse(self): if not self.t: raise Reject("empty") e = self.expr() if self.i != len(self.t): raise Reject("trailing input") return e
def expr(self): v = self.term() while self.peek() in (("sym", "+"), ("sym", "-")): op = self.take() r = self.term() v = v + r if op == "+" else v - r return v
def starts_atom(self): k, v = self.peek() return k == "num" or (k == "sym" and v in "({[") or (k == "cmd" and v in ({"frac", "sqrt", "pi"} | self.allowed)) \ or (k == "let" and v == "e" and "e" in self.allowed)
def term(self): v = self.unary() while True: k, s = self.peek() if (k, s) in (("sym", "*"), ("cmd", "cdot"), ("cmd", "times")): self.take(); v = v * self.unary() elif (k, s) == ("sym", "/"): self.take(); v = v / _nonzero(self.unary()) elif self.starts_atom(): if self.peek()[0] == "num": raise Reject("two numbers side by side") # "2 100" or "\sqrt 16" is malformed, not a product v = v * self.power() # implicit multiplication: 2\sqrt{3}, 3\pi, 2(1+x) else: return v
def unary(self): if self.peek() == ("sym", "-"): self.take(); return -self.unary() if self.peek() == ("sym", "+"): self.take(); return self.unary() return self.power()
def power(self): base = self.atom() if self.peek() != ("sym", "^"): return base self.take() if self.peek() == ("sym", "{"): exp = self.group() elif self.peek() in (("sym", "-"), ("sym", "+")): sign = -1 if self.take() == "-" else 1 # 2^-1 exp = sign * self.atom() else: exp = self.atom() if self.peek() == ("sym", "^"): raise Reject("power tower") return self._pow(base, exp)
def _pow(self, base, exp): if not exp.is_number or exp.is_real is False: raise Reject("non-numeric exponent") if not exp.is_Rational: if base == sympy.E and "e" in self.allowed and abs(sympy.N(exp, 15)) <= MAX_EXPONENT: return sympy.exp(exp) # e^{\ln 2} raise Reject("irrational exponent not supported") if abs(exp) > MAX_EXPONENT: raise Reject("exponent too large") if base == 0 and exp <= 0: raise Reject("0^0 or division by zero") if exp < 0: _nonzero(base) if _pow_bits(base) * max(1, abs(int(exp.p))) > MAX_POW_BITS: raise Reject("value too large") if base.is_negative and exp.q % 2 == 1 and exp.q > 1: return (-1) ** exp.p * (-base) ** exp # real odd root: (-8)^{1/3} = -2 return base ** exp
def group(self): open_ = self.take("sym") close = {"(": ")", "[": "]", "{": "}"}.get(open_) if close is None: raise Reject("unexpected symbol") v = self.expr() self.take("sym", close) return v
def arg(self): """A TeX macro argument: {..}, (..) / [..] (plain-text style), or ONE token (\\frac12, \\frac\\pi4, \\sqrt2).""" k, v = self.peek() if k == "sym" and v in "{([": return self.group() if k == "num": raw = self.t[self.i][2] if not raw.isdigit(): raise Reject("ambiguous unbraced argument") if len(raw) == 1: self.i += 1 return v self.t[self.i] = ("num", Integer(int(raw[1:])), raw[1:]) # TeX takes one digit: \frac12 = 1/2 return Integer(int(raw[0])) if (k == "cmd" and v == "pi") or (k == "let" and v == "e" and "e" in self.allowed): return self.atom() raise Reject("ambiguous unbraced argument")
def atom(self): k, v = self.peek() if k == "num": self.take(); return v if k == "sym" and v in "({[": return self.group() if k == "let" and v == "e" and "e" in self.allowed: self.take(); return sympy.E if k == "cmd": self.take() if v == "frac": n, d = self.arg(), self.arg() return n / _nonzero(d) if v == "sqrt": if self.peek() == ("sym", "["): self.take(); idx = self.expr(); self.take("sym", "]") if not (idx.is_Integer and 2 <= idx <= 50): raise Reject("bad root index") return self._pow(self.arg(), Rational(1, int(idx))) return self._pow(self.arg(), Rational(1, 2)) if v == "pi": return sympy.pi if v in FUNCS and v in self.allowed: if self.peek() in (("sym", "{"), ("sym", "("), ("sym", "[")): a = self.group() else: a = self.power() return FUNCS[v](a) raise Reject(f"\\{v} not allowed") if k == "let": raise Reject(f"variable or word {v!r}") raise Reject("malformed")
def allowed_from_reference(ref_clean: str) -> set: allowed = {c for c in FUNCS if re.search(r"\\" + c + r"(?![A-Za-z])", ref_clean)} if re.search(r"(?<![A-Za-z\\])e(?![A-Za-z])", re.sub(r"\\[A-Za-z]+", "", ref_clean)): allowed.add("e") for fam in FAMILIES: if allowed & fam: allowed |= fam return allowed
def value(text: str, allowed: set, is_reference: bool = False): t = clean(text) if not t: raise Reject("empty") if len(t) > MAX_LEN: raise Reject("answer too long") if re.search(r"\\(?:text|mathrm|mathbf|operatorname|boxed|fbox)\{|\\%|%|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\in(?![A-Za-z])|\\infty|\\circ|°|,", t): raise Reject("not a single exact number (units/text/relation/percent/approximation/list)") tokens = _mixed_numbers(tokenize(t, sci="e" not in allowed), is_reference) v = Parser(tokens, allowed).parse() if v.has(sympy.zoo, sympy.oo, -sympy.oo, sympy.nan) or v.is_finite is False: raise Reject("non-finite value") if v.is_real is False: raise Reject("not a real number") return v
def _is_transcendental(expr) -> bool: return expr.has(sympy.E) or any(expr.has(f) for f in TRANSCENDENTAL)
def exact_equal(s, g) -> bool: """True only if s == g is PROVED. Numeric evaluation is used to reject quickly, never to accept.""" if s.is_Rational and g.is_Rational: return s == g d = s - g if d == 0: return True try: dv, gv = sympy.N(d, 50), sympy.N(g, 50) if dv.is_Number and gv.is_Number and abs(dv) > sympy.Float("1e-30", 50) * max(1, abs(gv)): return False except Exception: pass if _is_transcendental(d): # ln / e / trig: only an exact simplification to 0 counts for cand in (sympy.expand_log(d), d): try: if sympy.simplify(cand) == 0: return True except Exception: pass return False if d.has(sympy.pi): # pi is transcendental: d == 0 iff every coefficient in T is 0 num = sympy.together(sympy.expand(d.subs(sympy.pi, _T))).as_numer_denom()[0] poly = sympy.Poly(sympy.expand(num), _T) return all(sympy.minimal_polynomial(c, _X) == _X for c in poly.coeffs()) return sympy.minimal_polynomial(d, _X) == _X
def grade(reference: str, submission: str): try: ref_clean = clean(reference) allowed = allowed_from_reference(ref_clean) g = value(reference, allowed, is_reference=True) except Reject as e: return False, f"reference unusable: {e}" except Exception as e: return False, f"reference unusable: {type(e).__name__}" try: s = value(submission, allowed) except Reject as e: return False, f"format: {e}" except (RecursionError, ValueError, TypeError, ZeroDivisionError, OverflowError) as e: return False, f"format: {type(e).__name__}" try: ok = exact_equal(s, g) except Exception as e: return False, f"could not prove equal ({type(e).__name__})" return (True, "exact match") if ok else (False, "wrong value")
def _worker(q, reference, submission): try: import resource # cap = current address space + MEM_LIMIT (an absolute cap breaks vm = 0 # workers forked from big parents: they hang instead of grading) for line in open("/proc/self/status"): if line.startswith("VmSize:"): vm = int(line.split()[1]) * 1024 resource.setrlimit(resource.RLIMIT_AS, (vm + MEM_LIMIT, vm + MEM_LIMIT)) except Exception: pass try: q.put(grade(reference, submission)) except MemoryError: q.put((False, "grader out of memory")) except Exception as e: q.put((False, f"grader error: {type(e).__name__}"))
def grade_safe(reference: str, submission: str, timeout: float = 10.0): ctx = mp.get_context("fork") q = ctx.Queue() p = ctx.Process(target=_worker, args=(q, reference, submission)) p.start(); p.join(timeout) if p.is_alive(): p.kill(); p.join() return False, "timeout" try: return q.get(timeout=1) except Exception: return False, "grader crashed"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476"""Exact grader for structured math answers (Loubna msg 1257): a SET or TUPLE of exact numbers, an INTERVAL / union ofintervals with exact endpoints, or an EXPRESSION in named variables. Builds on the single-number grader (grader.py):same extraction/cleaning, same restricted parser and the same exact number equality (never a numeric tolerance).
grade(reference, submission, kind, variables="") -> (passed, reason) grade_safe(...) same, in a memory-capped subprocess with a timeout (use this in verifiers)
kind (fixed per task, stated in the task instruction): set {a, b, c}: order and repeats do not matter; braces optional tuple (a, b, c): order matters; parentheses optional interval [a, b), (-\\infty, c] \\cup [d, \\infty) ...: compared as SETS of reals (unions are merged exactly) expression one expression in the listed variables (e.g. "n" or "a,b"): equal as functions, proved by exact symbolic simplification to 0; random numeric evaluation can only rejectNumbers inside follow grader.py (exact values, functions only if the reference uses their family)."""import multiprocessing as mpimport randomimport reimport sysfrom pathlib import Path
import sympy
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))import grader as G # noqa: E402from grader import Reject # noqa: E402
__version__ = "1"_orig_nonzero = G._nonzero
def _nonzero_sym(d): """Divisors with variables are allowed unless identically zero; numeric divisors keep grader.py's check.""" if getattr(d, "free_symbols", None): if sympy.cancel(sympy.together(d)) == 0: raise Reject("division by zero") return d return _orig_nonzero(d)
G._nonzero = _nonzero_symKINDS = ("set", "tuple", "interval", "expression")MAX_ITEMS = 60_INF = re.compile(r"^\s*([+-]?)\s*\\infty\s*$|^\s*([+-]?)\s*\\inf\s*$|^\s*([+-]?)\s*oo\s*$")
# ---------------------------------------------------------------- shared helpersdef _top_level_boxes(text: str): out, i = [], 0 while True: m = G._BOX.search(text, i) if not m: return out depth, j = 1, m.end() while j < len(text) and depth: depth += {"{": 1, "}": -1}.get(text[j], 0) j += 1 out.append(re.sub(r"\s+", "", text[m.end():j - 1])) i = j
def _clean_struct(text: str) -> str: """grader.clean without its single-value wrapper stripping of commas; keeps \\{ \\} \\cup. Several top-level boxes with different contents are a hedge: rejected (review 2026-11-24).""" if len(set(_top_level_boxes(text or ""))) > 1: raise Reject("several different boxed answers") if len(text or "") > 20_000: raise Reject("answer too long") text = re.sub(r"\\\\(?=[A-Za-z{}])", r"\\", text) # shell-doubled backslashes: \\\\frac -> \\frac t = G.clean(text) # plain-text function names (agents often write ln(x), sin x): same as grader.clean does for sqrt( and pi t = re.sub(r"(?<![\\A-Za-z])(arcsin|arccos|arctan|ln|log|sin|cos|tan|exp)(?![A-Za-z])", r"\\\1 ", t) t = re.sub(r"\\lbrace|\\\{", "{", t) t = re.sub(r"\\rbrace|\\\}", "}", t) t = re.sub(r"\\(?:lbrack)", "[", t) t = re.sub(r"\\(?:rbrack)", "]", t) t = re.sub(r"\\(?:mathbb\{R\}|R)(?![A-Za-z])", "R", t) return t.strip()
def _split_top(s: str, sep: str = ","): out, depth, cur = [], 0, [] for ch in s: if ch in "([{": depth += 1 elif ch in ")]}": depth -= 1 if depth < 0: raise Reject("unbalanced brackets") if ch == sep and depth == 0: out.append("".join(cur)); cur = [] else: cur.append(ch) if depth != 0: raise Reject("unbalanced brackets") out.append("".join(cur)) return [x.strip() for x in out]
def _number(elem: str, allowed: set, is_reference: bool, labels: bool = True): """One exact real number (grader.py rules); also strips a leading 'x =' / 'x_1 =' unless labels=False.""" if not labels and re.match(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=", elem) and not is_reference: raise Reject("labelled tuple components (write the tuple in the asked order, without names)") e = re.sub(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*", "", elem.strip()) if not e: raise Reject("empty element") if re.search(r"\\(?:text|mathrm|mbox|operatorname)\{|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\infty|%", e): raise Reject("element is not a single exact number") toks = G._mixed_numbers(G.tokenize(e, sci="e" not in allowed), is_reference) v = G.Parser(toks, allowed).parse() if v.has(sympy.zoo, sympy.oo, -sympy.oo, sympy.nan) or v.is_finite is False: raise Reject("non-finite value") if v.is_real is False: raise Reject("not a real number") return v
def _strip_outer(t: str, pairs): for a, b in pairs: if t.startswith(a) and t.endswith(b): inner = t[len(a):len(t) - len(b)] try: _split_top(inner) # the outer pair must enclose everything (not "(1,2),(3,4)") except Reject: continue depth, ok = 0, True for ch in inner: depth += {"(": 1, "[": 1, "{": 1, ")": -1, "]": -1, "}": -1}.get(ch, 0) if depth < 0: ok = False break if ok: return inner.strip(), True return t, False
def _items(text: str, allowed: set, is_reference: bool, brackets, labels: bool = True): t = _clean_struct(text) if not t: raise Reject("empty") if len(t) > G.MAX_LEN * 2: raise Reject("answer too long") if re.search(r"\\(?:text|mbox)\{[^}]*[A-Za-z]{2,}|\b(?:or|and)\b", t) and not re.search(r"\\(?:text|mbox)\{\s*,?\s*\}", t): raise Reject("words in the answer (write only the list)") inner, _ = _strip_outer(t, brackets) parts = _split_top(inner) if len(parts) > MAX_ITEMS: raise Reject("too many items") if any(not p for p in parts): raise Reject("empty item") return [_number(p, allowed, is_reference, labels) for p in parts]
def _eq(a, b) -> bool: try: return G.exact_equal(a, b) except Exception: return False
def _dedup(vals): out = [] for v in vals: if not any(_eq(v, w) for w in out): out.append(v) return out
# ---------------------------------------------------------------- set / tupledef grade_set(reference, submission, allowed): g = _dedup(_items(reference, allowed, True, [("{", "}")])) s = _dedup(_items(submission, allowed, False, [("{", "}")])) if len(s) != len(g): return False, f"wrong number of elements ({len(s)} vs {len(g)})" left = list(g) for v in s: k = next((i for i, w in enumerate(left) if _eq(v, w)), None) if k is None: return False, "wrong element" left.pop(k) return True, "exact match"
def grade_tuple(reference, submission, allowed): g = _items(reference, allowed, True, [("(", ")"), ("[", "]"), ("{", "}")]) s = _items(submission, allowed, False, [("(", ")"), ("[", "]")], labels=False) if len(s) != len(g): return False, f"wrong length ({len(s)} vs {len(g)})" for v, w in zip(s, g): if not _eq(v, w): return False, "wrong component" return True, "exact match"
# ---------------------------------------------------------------- intervalsdef _endpoint(e, allowed, is_reference): m = _INF.match(e) if m: sign = "".join(x for x in m.groups() if x) return -sympy.oo if sign == "-" else sympy.oo return _number(e, allowed, is_reference)
def _intervals(text, allowed, is_reference): t = _clean_struct(text) if not t: raise Reject("empty") t = re.sub(r"^\s*[A-Za-z]\s*\\in\s*", "", t) # "x \in [1,2)" if re.fullmatch(r"R|\(-\\infty\s*,\s*\+?\\infty\)", t.replace(" ", "")): return [(-sympy.oo, False, sympy.oo, False)] pieces = [p.strip() for p in re.split(r"\\cup|∪|(?<![A-Za-z])U(?![A-Za-z])", t)] out = [] for p in pieces: if len(p) < 5 or p[0] not in "([" or p[-1] not in ")]": raise Reject("each piece must look like (a, b), [a, b], [a, b) or (a, b]") parts = _split_top(p[1:-1]) if len(parts) != 2: raise Reject("an interval needs exactly two endpoints") lo, hi = _endpoint(parts[0], allowed, is_reference), _endpoint(parts[1], allowed, is_reference) lc, hc = p[0] == "[", p[-1] == "]" if (lo in (sympy.oo, -sympy.oo) and lc) or (hi in (sympy.oo, -sympy.oo) and hc): raise Reject("infinite endpoint must be open") if lo == sympy.oo or hi == -sympy.oo: raise Reject("bad infinite endpoint") out.append((lo, lc, hi, hc)) return out
def _num(v): return float("inf") if v == sympy.oo else float("-inf") if v == -sympy.oo else float(sympy.N(v, 30))
def _cmp(a, b): """-1/0/1 exactly (0 only if PROVED equal).""" if a in (sympy.oo, -sympy.oo) or b in (sympy.oo, -sympy.oo): return 0 if a == b else (-1 if _num(a) < _num(b) else 1) if _eq(a, b): return 0 d = sympy.N(a - b, 60) if not d.is_Number or d == 0: raise Reject("cannot order interval endpoints") return -1 if d < 0 else 1
def _normalize(ivs): """Drop empty pieces, sort, merge overlapping / touching pieces: a canonical union.""" keep = [] for lo, lc, hi, hc in ivs: c = _cmp(lo, hi) if c > 0 or (c == 0 and not (lc and hc)): continue # empty piece keep.append((lo, lc, hi, hc)) keep.sort(key=lambda x: (_num(x[0]), not x[1])) out = [] for iv in keep: if out: lo, lc, hi, hc = out[-1] c = _cmp(iv[0], hi) if c < 0 or (c == 0 and (hc or iv[1])): # overlap, or touching with the shared point included c2 = _cmp(iv[2], hi) nhi, nhc = (iv[2], iv[3]) if c2 > 0 else (hi, hc or iv[3]) if c2 == 0 else (hi, hc) out[-1] = (lo, lc, nhi, nhc) continue out.append(iv) return out
def grade_interval(reference, submission, allowed): g = _normalize(_intervals(reference, allowed, True)) s = _normalize(_intervals(submission, allowed, False)) if len(s) != len(g): return False, "different set of reals" for (a, ac, b, bc), (c, cc, d, dc) in zip(s, g): if _cmp(a, c) != 0 or _cmp(b, d) != 0 or ac != cc or bc != dc: return False, "different set of reals" return True, "exact match"
# ---------------------------------------------------------------- expressions in variablesclass VarParser(G.Parser): """grader.Parser plus named variables (single letters or greek commands) and symbolic exponents."""
def __init__(self, tokens, allowed, variables): super().__init__(tokens, allowed) # positive: AoPS variables are lengths, counts and indices (sqrt(a^2) = a); review 2026-11-24 item F self.vars = {v: sympy.Symbol(v, real=True) for v in variables}
def term(self): """grader.Parser.term, but a number may follow ')', '}', ']' or a variable: (n+1)2^n, n2^n, 2^n3^n.""" v = self.unary() while True: k, s = self.peek() if (k, s) in (("sym", "*"), ("cmd", "cdot"), ("cmd", "times")): self.take(); v = v * self.unary() elif (k, s) == ("sym", "/"): self.take(); v = v / G._nonzero(self.unary()) elif self.starts_atom(): if k == "num": pk, pv = self.t[self.i - 1][:2] if not ((pk == "sym" and pv in ")}]") or (pk in ("let", "cmd") and pv in self.vars)): raise Reject("two numbers side by side") v = v * self.power() else: return v
def arg(self): k, v = self.peek() if k in ("let", "cmd") and v in self.vars: # \frac ab return self.atom() return super().arg()
def starts_atom(self): k, v = self.peek() return super().starts_atom() or ((k == "let" or k == "cmd") and v in self.vars)
def atom(self): k, v = self.peek() if (k == "let" or k == "cmd") and v in self.vars: self.take() if self.peek() == ("sym", "_"): raise Reject("subscripts not supported") return self.vars[v] return super().atom()
def _pow(self, base, exp): if exp.free_symbols or base.free_symbols: if exp.is_Rational and abs(exp) > 60: raise Reject("exponent too large") if exp.free_symbols and base.free_symbols: raise Reject("variable in base and exponent") if base.free_symbols and exp.is_Rational and exp.q > 1: return sympy.Pow(base, exp) return sympy.Pow(base, exp) return super()._pow(base, exp)
def _expr(text, allowed, variables, is_reference): raw = G._last_top_level_box(G._normalize_unicode(text or "")) or (text or "") m0 = re.match(r"^[\s$\\(\[]*([A-Za-z])\s*=", raw) if m0 and m0.group(1) in variables: raise Reject("an equation in the variable, not an expression") if is_reference and (re.search(r"\\\{|\\lbrace|\\(?:sin|cos|tan|ln|log|exp)\s*\d+\s*[A-Za-z]|/\s*[A-Za-z]\s*[A-Za-z]", raw)): raise Reject("ambiguous reference (braces, function of a product, or a/bc)") t = _clean_struct(text) m = re.match(r"^\s*([A-Za-z])(\([^()]*\))?(?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*(?=[^=]+$)", t) # "f(n) = ...", "S = ..." if m: if m.group(1) in variables and not m.group(2): raise Reject("an equation in the variable, not an expression") t = t[m.end():] if is_reference and (re.search(r"\\(?:sin|cos|tan|ln|log|exp)\s*\d+\s*[A-Za-z]", t) or "{" in re.sub(r"\\[A-Za-z]+\s*\{|[\^_]\s*\{|\}\s*\{", "", t).replace("\\{", "{") and re.search(r"\\\{", t) or re.search(r"/\s*[A-Za-z]\s*[A-Za-z]", t)): raise Reject("ambiguous reference (function of a product, braces, or a/bc)") if not t: raise Reject("empty") if len(t) > G.MAX_LEN: raise Reject("answer too long") if re.search(r"\\(?:text|mathrm|mbox|operatorname)\{|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\infty|,|%|\\sum|\\prod|\\int|!", t): raise Reject("not a single closed-form expression") toks = G.tokenize(t, sci=False) toks = [("sym", "_", "_") if x[0] == "sym" and x[1] == "_" else x for x in toks] v = VarParser(toks, allowed, variables).parse() if v.has(sympy.zoo, sympy.nan): raise Reject("undefined value") extra = {str(s) for s in v.free_symbols} - set(variables) if extra: raise Reject(f"unknown variables {sorted(extra)}") return v
def _points(syms, rng, k=6): """Random rational points away from 0 and 1 (positive, so radicals and logs of the variables stay real).""" return [{s: sympy.Rational(rng.randint(7, 97), rng.randint(3, 13)) for s in syms} for _ in range(k)]
def grade_expression(reference, submission, allowed, variables): g = _expr(reference, allowed, variables, True) s = _expr(submission, allowed, variables, False) d = s - g if d == 0: return True, "exact match" syms = sorted(d.free_symbols | g.free_symbols, key=str) rng = random.Random(0) for pt in _points(syms, rng): try: dv, gv = sympy.N(d.subs(pt), 40), sympy.N(g.subs(pt), 40) except Exception: continue if dv.is_Number and gv.is_Number and abs(dv) > sympy.Float("1e-25", 40) * max(1, abs(gv)): return False, "different expression" try: # equal up to a constant factor 1: a(sqrt6-sqrt2) = 2a sqrt(2-sqrt3) q = sympy.cancel(sympy.together(s / g)) if not q.free_symbols and q.is_number and _eq(q, sympy.Integer(1)): return True, "exact match" except Exception: pass for cand in (lambda e: sympy.cancel(sympy.together(e)), sympy.radsimp, sympy.simplify, lambda e: sympy.simplify(sympy.expand_log(sympy.expand_power_base(e, force=False)))): try: if cand(d) == 0: return True, "exact match" except Exception: pass return False, "could not prove the expressions equal"
# ---------------------------------------------------------------- entry pointsdef parse_variables(variables): vs = [v.strip().lstrip("\\") for v in re.split(r"[,\s]+", variables or "") if v.strip()] for v in vs: if not re.fullmatch(r"[A-Za-z]|alpha|beta|gamma|theta|lambda|mu|phi|omega|rho|sigma|tau", v) or v in ("e", "i"): raise Reject(f"unsupported variable name {v!r}") return vs
def grade(reference: str, submission: str, kind: str, variables: str = ""): if kind not in KINDS: return False, f"unknown kind {kind!r}" try: ref_clean = _clean_struct(reference) allowed = G.allowed_from_reference(ref_clean) vs = parse_variables(variables) if kind == "expression" else [] if kind == "expression": allowed.discard("e") if "e" in vs else None except Reject as e: return False, f"reference unusable: {e}" try: if kind == "set": return grade_set(reference, submission, allowed) if kind == "tuple": return grade_tuple(reference, submission, allowed) if kind == "interval": return grade_interval(reference, submission, allowed) return grade_expression(reference, submission, allowed, vs) except Reject as e: return False, f"format: {e}" except (RecursionError, ValueError, TypeError, ZeroDivisionError, OverflowError, AttributeError) as e: return False, f"format: {type(e).__name__}" except Exception as e: return False, f"could not grade ({type(e).__name__})"
def check_reference(reference: str, kind: str, variables: str = ""): """Reference parses under the kind's rules and matches itself.""" return grade(reference, reference, kind, variables)
def _worker(q, *args): try: import resource vm = 0 for line in open("/proc/self/status"): if line.startswith("VmSize:"): vm = int(line.split()[1]) * 1024 resource.setrlimit(resource.RLIMIT_AS, (vm + G.MEM_LIMIT, vm + G.MEM_LIMIT)) except Exception: pass try: q.put(grade(*args)) except MemoryError: q.put((False, "grader out of memory")) except Exception as e: q.put((False, f"grader error: {type(e).__name__}"))
def grade_safe(reference: str, submission: str, kind: str, variables: str = "", timeout: float = 20.0): ctx = mp.get_context("fork") q = ctx.Queue() p = ctx.Process(target=_worker, args=(q, reference, submission, kind, variables)) p.start(); p.join(timeout) if p.is_alive(): p.kill(); p.join() return False, "timeout" try: return q.get(timeout=1) except Exception: return False, "grader crashed"12345678910{ "answer": "$g(x)=2x^{3}+c, g(x)=-2x^{3}+c$", "task_id": "imo-bench-algebra-003", "category": "Algebra", "subcategory": "Functional Equation", "source": "IMO Shortlist 2021", "answer_kind": "literal", "kind": "literal", "variables": ""}12345678910111213#!/bin/bash# Reward 1 if /app/answer.txt holds an answer equal to the hidden reference (a set, tuple, interval or# expression; grader.py checks it exactly with sympy).# 0 is written before anything runs, so a crash, a timeout or a missing/linked/oversized answer scores 0.# Python runs isolated (-I -S); sympy/mpmath come from the pinned wheels in this directory (hash-checked, unpacked# offline into a new directory): nothing is installed and no network is used. ANSWER and VERIFIER_DIR override# the paths, to test the grader locally.case $0 in */*) here=${0%/*} ;; *) here=. ;; esacexport ANSWER=${ANSWER:-/app/answer.txt}export VERIFIER_DIR=${VERIFIER_DIR:-/logs/verifier}export TESTS_DIR=$here[ -d "$VERIFIER_DIR" ] && echo 0 > "$VERIFIER_DIR/reward.txt"timeout 150 python3 -B -I -S "$here/grade_task.py" || true12345# Problem
Let $u \ge 2$ be a given positive integer. Find the smallest real number $C$ such that for all real numbers $t$, $\frac{t^{2^u}+1}{2} \le (C(t-1)^2+t)^{2^{u-1}}$.
Write your final answer as an exact expression in these variables: u in `/app/answer.txt`. Do not include a derivation.1234567#!/bin/bashset -euanswer=${ANSWER:-/app/answer.txt}mkdir -p "$(dirname "$answer")"cat > "$answer" <<'ANSWER_EOF'$2^{u-2}$ANSWER_EOF12345678910111213141516171819202122232425262728schema_version = "1.4"artifacts = ["/app/answer.txt"]
[task]name = "imo-answerbench/imo-bench-algebra-004"version = "1.0.0"description = "IMO-AnswerBench v2 short-answer mathematics problem"keywords = ["math", "imo", "evaluation"]
[metadata]category = "Algebra"subcategory = "Inequality"source = "IMO Shortlist 2021"problem_id = "imo-bench-algebra-004"answer_kind = "expression"
[agent]network_mode = "allowlist"timeout_sec = 3600
[environment]docker_image = "docker.io/library/python:3.12-slim"cpus = 1memory_mb = 2048
[verifier]network_mode = "allowlist"timeout_sec = 180123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""Grade the answer file against tests/reference.json. Writes reward.txt (1/0), grade.json and a copy of theanswer (answer.txt) to VERIFIER_DIR. Any error -> reward 0. The sympy/mpmath wheels ship base64-encoded (plain gittext: the Hub stores binary files in LFS/Xet, which a plain `git checkout` without git-lfs cannot read)."""import base64import hashlibimport ioimport jsonimport osimport statimport sysimport tempfileimport zipfile
LIMIT = 10_000 # bytesWHEELS = {"sympy-1.14.0-py3-none-any.whl": "e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", "mpmath-1.3.0-py3-none-any.whl": "a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c"}
def read_own(path): """Bytes of the regular file at exactly `path`: every folder on the way and the file are opened without following links (a FIFO cannot block it); one link only; at most LIMIT bytes.""" parts = os.path.abspath(path).split("/")[1:] folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY) try: for part in parts[:-1]: inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder) os.close(folder) folder = inner fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder) finally: os.close(folder) with os.fdopen(fd, "rb") as stream: info = os.fstat(stream.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1: raise ValueError("answer is not a regular file of its own") data = stream.read(LIMIT + 1) if len(data) > LIMIT: raise ValueError(f"answer file larger than {LIMIT} bytes") return data
def write_new(path, text): try: os.unlink(path) except FileNotFoundError: pass fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o644) with os.fdopen(fd, "w") as stream: stream.write(text)
def load_grader(tests): lib = tempfile.mkdtemp(prefix="grader-lib-") for name, digest in WHEELS.items(): blob = base64.b64decode(open(os.path.join(tests, name + ".b64"), "rb").read()) if hashlib.sha256(blob).hexdigest() != digest: raise ValueError(f"wheel hash mismatch: {name}") with zipfile.ZipFile(io.BytesIO(blob)) as z: z.extractall(lib) sys.path[:0] = [lib, tests] import grader, grader_struct return grader, grader_struct
def main(): tests, out = os.environ["TESTS_DIR"], os.environ["VERIFIER_DIR"] os.makedirs(out, exist_ok=True) write_new(os.path.join(out, "reward.txt"), "0") passed, why, submission = False, "grader error", "" try: try: submission = read_own(os.environ["ANSWER"]).decode("utf-8", "replace") except FileNotFoundError: submission, why = None, "no answer file" except (OSError, ValueError) as e: submission, why = None, f"answer file rejected: {e}" if submission is not None: write_new(os.path.join(out, "answer.txt"), submission) ref = json.loads(open(os.path.join(tests, "reference.json")).read()) reference, kind, variables = ref["answer"], ref["kind"], ref.get("variables", "") if not submission.strip(): passed, why = False, "empty" elif kind == "literal": import unicodedata def normalize(s): # Preserve all mathematical characters, operators, punctuation and case. return " ".join(unicodedata.normalize("NFC", s).split()).strip() passed = normalize(reference) == normalize(submission) why = "literal match" if passed else "literal mismatch" else: grader, structured = load_grader(tests) if kind == "number": passed, why = grader.grade_safe(reference, submission, timeout=60) else: passed, why = structured.grade_safe(reference, submission, kind, variables, timeout=60) except Exception as e: passed, why = False, f"grader error: {type(e).__name__}: {str(e)[:200]}" if passed: write_new(os.path.join(out, "reward.txt"), "1") write_new(os.path.join(out, "grade.json"), json.dumps({"passed": passed, "why": why, "submission": (submission or "")[:500]})) print("reward:", 1 if passed else 0, "|", why)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501"""Strict, exact single-number grader for Harbor math tasks (v2).
Contract (one uniform instruction for every task): the final answer is ONE exact number, e.g. 42, -7, 3/8,\\frac{3}{8}, 2\\sqrt{3}, \\frac{\\pi}{4}. No units, words, variables, "x =", sets, ranges, percent, or approximations.
grade(reference, submission) -> (passed: bool, reason: str) grade_safe(reference, submission, timeout=10) -> same, run in a memory-capped subprocess (use this in verifiers)
How it works- Extract: the last top-level \\boxed{...} / \\fbox{...} (brace-matched; a box nested inside the chosen box is rejected), else the whole text. Normalize unicode (NFKC, every dash/minus, superscript digits, zero-width chars, BOM), strip markdown bold, "Answer:", $..$, \\(..\\), \\[..\\], a trailing period (repeatedly, so "$5$." works), \\left. \\right. (null delimiters), \\left/\\right, LaTeX spacing; plain-text forms sqrt(..), pi, ** become LaTeX. Digit grouping (1,024 / 1\\,024 / 1 024 / 1{,}024) is removed only when the whole number is grouped in threes. 0.\\overline{3} becomes 1/3 exactly.- Parse with a small recursive-descent parser over a restricted grammar: numbers, + - * / ^, \\frac (also with TeX single-token arguments, \\frac12 = 1/2), \\sqrt{x}, \\sqrt[n]{x} (odd roots of negatives are real: \\sqrt[3]{-8} = -2), \\pi, \\cdot, \\times, brackets, implicit multiplication. Functions (\\ln/\\log, \\exp/e, \\sin/\\cos/\\tan, \\arcsin/\\arccos/\\arctan) are allowed only if the REFERENCE uses their family, so the problem cannot be restated instead of solved (\\lfloor, \\binom, factorials, sums: never). Scientific notation (1e5) is off when the reference uses the constant e (so "4e+1" means 4e+1). "3\\frac{1}{6}" is a mixed number in a reference and is rejected as ambiguous in a submission. "\\sqrt 16" (TeX: sqrt(1)*6) is rejected. 0^0, division by zero, non-real and huge values are rejected; written decimals are exact rationals (0.25 = 1/4; 1.41421356 is NOT sqrt 2).- Compare EXACTLY, never with a numeric tolerance (a numeric check can only reject, for speed): rationals by equality; algebraic numbers by minimal_polynomial(s - g) == x; expressions with pi as polynomials in a symbol T with algebraic coefficients (pi is transcendental); anything with ln/e/trig only if sympy simplifies the difference to exactly 0. Anything that cannot be proved equal within the time limit fails."""import multiprocessing as mpimport reimport unicodedata
import sympyfrom sympy import Integer, Rational
__version__ = "2"MAX_LEN = 1000 # characters of the cleaned answerMAX_INT_DIGITS = 1000 # digits of any number literalMAX_EXPONENT = 3000 # |exponent| allowed in a power or in scientific notationMAX_POW_BITS = 100_000 # estimated size of an exact power before computing itMEM_LIMIT = 2 << 30 # extra address space allowed to the grade_safe worker (bytes)FUNCS = {"ln": sympy.log, "log": sympy.log, "sin": sympy.sin, "cos": sympy.cos, "tan": sympy.tan, "arcsin": sympy.asin, "arccos": sympy.acos, "arctan": sympy.atan, "exp": sympy.exp}FAMILIES = [{"ln", "log"}, {"exp", "e"}, {"sin", "cos", "tan"}, {"arcsin", "arccos", "arctan"}]TRANSCENDENTAL = (sympy.exp, sympy.log, sympy.sin, sympy.cos, sympy.tan, sympy.asin, sympy.acos, sympy.atan)_X, _T = sympy.Symbol("x"), sympy.Symbol("T")
class Reject(Exception): pass
# ---------------------------------------------------------------- extraction and cleaning_BOX = re.compile(r"\\(?:boxed|fbox)\s*\{")_SUPERSCRIPT = str.maketrans("\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079\u207b", "0123456789-")_DASHES = "\u2010\u2011\u2012\u2013\u2014\u2212\ufe63\uff0d"
def _last_top_level_box(text: str): """Content of the last \\boxed{..}/\\fbox{..} that is not inside another box; None if there is no box. Rejects an unbalanced last box and a box nested inside the chosen box.""" spans, i = [], 0 while True: m = _BOX.search(text, i) if not m: break depth, j = 1, m.end() while j < len(text) and depth: depth += {"{": 1, "}": -1}.get(text[j], 0) j += 1 if depth: raise Reject("unbalanced \\boxed") spans.append((m.end(), j - 1)) i = j # continue AFTER this box: inner boxes are not top level if not spans: return None a, b = spans[-1] inner = text[a:b] if _BOX.search(inner): raise Reject("box inside box") return inner
def _normalize_unicode(t: str) -> str: t = re.sub("[\ufeff\u200b\u200c\u200d\u2060\u00ad]", "", t) t = re.sub("[\u2070\u00b9\u00b2\u00b3\u2074-\u2079\u207b]+", lambda m: "^{" + m.group().translate(_SUPERSCRIPT) + "}", t) for ch in _DASHES: t = t.replace(ch, "-") t = t.replace("\u00d7", "\\times ").replace("\u00b7", "\\cdot ").replace("\u22c5", "\\cdot ") t = t.replace("\u03c0", "\\pi ").replace("\u221a", "\\sqrt") return unicodedata.normalize("NFKC", t)
def _repeating(m) -> str: whole, fixed, rep = m.group(1) or "0", m.group(2), m.group(3) num = Integer(int(fixed + rep)) - Integer(int(fixed or "0")) den = Integer(10) ** len(fixed) * (Integer(10) ** len(rep) - 1) v = Integer(int(whole)) + num / den return f"(\\frac{{{v.p}}}{{{v.q}}})"
_NOT_UNIT = re.compile(r"\b(?:or|and|to|for|if|is|not|no|none|either|approx|about|between|each|where|with)\b", re.I)_UNIT_TEXT = re.compile(r"\s*\\(?:text|mathrm|mbox|textrm|operatorname)\s*\{\s*([A-Za-z][A-Za-z ./^0-9-]{0,24})\}\s*$")_UNIT_WORD = re.compile(r"(?<=[\d})])\s+([A-Za-z]{2,12}(?:\s?/\s?[A-Za-z]{1,8})?(?:\^\{?\d\}?)?)\s*$")_DEGREES = re.compile(r"\s*(?:\^\s*\{?\s*\\circ\s*\}?|°|\\degree)\s*$")_LHS = re.compile(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*(?=[^=]+$)")
def strip_wrappers(t: str) -> str: """Remove a wrapper around ONE value: trailing units (30 ft/s, 111 meters, \\sqrt{109}\\text{ m}), a degree sign, or a single 'n =' prefix. Hedges ('32 \\text{ or } 33'), approximations and multi-part answers are untouched.""" prev = None while t != prev: prev = t m = _UNIT_TEXT.search(t) if m and not _NOT_UNIT.search(m.group(1)) and t[:m.start()].strip(): t = t[:m.start()].rstrip() m = _UNIT_WORD.search(t) if m and not _NOT_UNIT.search(m.group(1)): t = t[:m.start()].rstrip() if t[:-1].strip(): t = _DEGREES.sub("", t).rstrip() t = _LHS.sub("", t) return t
def clean(text: str) -> str: t = _normalize_unicode((text or "").strip()) boxed = _last_top_level_box(t) if boxed is not None: t = boxed prev = None while t != prev: # peel wrappers in any order: "**Answer:** $5$." -> 5 prev = t t = t.strip() t = re.sub(r"^(\*\*|__)(.*)\1$", r"\2", t, flags=re.S).strip() t = re.sub(r"^\**\s*(?:the\s+)?(?:final\s+)?answer\s*(?:is)?\s*[:=]?\s*\**\s*", "", t, flags=re.I).strip() for a, b in (("$$", "$$"), ("$", "$"), ("\\(", "\\)"), ("\\[", "\\]")): if t.startswith(a) and t.endswith(b) and len(t) > len(a) + len(b): t = t[len(a):-len(b)].strip() t = t.rstrip(". ").strip() t = re.sub(r"\\(?:left|right)\.", "", t) # null delimiters t = re.sub(r"\\(?:displaystyle|left|right|bigl|bigr|Bigl|Bigr|big|Big)(?![A-Za-z])", "", t) t = re.sub(r"\\mathrm\{e\}|\\mathit\{e\}", "e", t) t = re.sub(r"\\[dtc]frac(?![A-Za-z])", r"\\frac", t) t = re.sub(r"(\d*)\.(\d*)\\overline\{(\d+)\}", _repeating, t) t = re.sub(r"(?<=\d)\\[,;! ](?=\d{3}(?!\d))", "", t) # 2\,560\,320 -> 2560320 t = re.sub(r"\\[,;:! ]|~", " ", t) t = strip_wrappers(t) # 30 ft/s, n = 24^5, 30° -> the bare value t = re.sub(r"(?<=\d)\s*\{,\}\s*(?=\d{3}(?!\d))", "", t) # 3{,}100 if re.fullmatch(r"\s*-?\d{1,3}([, ]\d{3})+(\.\d+)?\s*", t) and len(set(re.findall(r"[, ]", t.strip()))) == 1: t = re.sub(r"[, ]", "", t) # 3,100 / 1,000.5 / 1 000 (one separator kind) t = t.replace("**", "^") # python power t = re.sub(r"(?<![\\A-Za-z])sqrt\s*(?=[({])", r"\\sqrt", t) # sqrt(2) -> \sqrt(2) t = re.sub(r"(?<![\\A-Za-z])pi(?![A-Za-z])", r"\\pi ", t) # pi/4 -> \pi/4 return re.sub(r"\s+", " ", t).strip()
# ---------------------------------------------------------------- parserTOKEN = re.compile(r"\s*(?:(?P<num>\d+\.\d*|\.\d+|\d+)(?:[eE](?P<exp>[+-]?\d+))?|(?P<cmd>\\[A-Za-z]+)|(?P<sym>[-+*/^(){}\[\]])|(?P<let>[A-Za-z]))")NUM_ONLY = re.compile(r"\s*(?P<num>\d+\.\d*|\.\d+|\d+)")
def tokenize(s: str, sci: bool = True): """Tokens are (kind, value, raw). sci=False turns scientific notation off (the reference uses the constant e).""" out, pos = [], 0 while pos < len(s): m = TOKEN.match(s, pos) if m and not sci and m.group("num") is not None and m.group("exp") is not None: m = NUM_ONLY.match(s, pos) # "4e+1" -> 4, e, +, 1 if not m or m.end() == pos: if s[pos:].strip() == "": break raise Reject(f"unexpected character {s[pos]!r}") pos = m.end() if m.group("num") is not None: num = m.group("num") if len(num.replace(".", "")) > MAX_INT_DIGITS: raise Reject("number too long") val = Rational(num) if "." in num else Integer(int(num)) exp = m.groupdict().get("exp") if exp is not None: if abs(int(exp)) > MAX_EXPONENT: raise Reject("exponent too large") val = val * Rational(10) ** int(exp) out.append(("num", val, m.group(0).strip())) elif m.group("cmd"): out.append(("cmd", m.group("cmd")[1:], m.group("cmd"))) elif m.group("sym"): out.append(("sym", m.group("sym"), m.group("sym"))) else: out.append(("let", m.group("let"), m.group("let"))) return out
def _mixed_numbers(tokens, is_reference: bool): """N\\frac{a}{b} with integer literals N, a, b: a mixed number (N + a/b) in a reference; ambiguous in a submission.""" out, i = [], 0 pat = ["num", ("cmd", "frac"), ("sym", "{"), "num", ("sym", "}"), ("sym", "{"), "num", ("sym", "}")] while i < len(tokens): win = tokens[i:i + 8] ok = len(win) == 8 and all((w[0] == p) if isinstance(p, str) else (w[0], w[1]) == p for w, p in zip(win, pat)) ok = ok and all(win[k][2].isdigit() for k in (0, 3, 6)) prev = out[-1] if out else None if ok and not (prev and (prev[0] == "cmd" or prev[:2] == ("sym", "^"))): if not is_reference: raise Reject("ambiguous mixed number (write 7/2, not 3\\frac{1}{2})") if win[6][1] == 0: raise Reject("division by zero") out.append(("num", win[0][1] + win[3][1] / win[6][1], "mixed")) i += 8 continue out.append(tokens[i]); i += 1 return out
def _nonzero(d): """Reject a zero divisor, including a disguised one (sqrt(3+2sqrt2)-1-sqrt2). Numeric check: reject-only.""" if d == 0 or d.is_zero: raise Reject("division by zero") if not d.is_Rational: try: v = sympy.N(d, 60) except Exception: raise Reject("cannot evaluate divisor") if not v.is_Number or abs(v) < sympy.Float("1e-45", 60): raise Reject("division by (numerically) zero") return d
def _pow_bits(expr) -> int: return sum(abs(int(r.p)).bit_length() + int(r.q).bit_length() for r in expr.atoms(sympy.Rational)) or 1
class Parser: """expr := term (('+'|'-') term)* ; term := unary (('*'|'/'|implicit) unary)* ; unary := ('-'|'+') unary | power power := atom ('^' exponent)? ; atom := number | group | \\frac A A | \\sqrt[n] A | \\pi | e | func arg"""
def __init__(self, tokens, allowed): self.t, self.i, self.allowed = list(tokens), 0, allowed
def peek(self): return self.t[self.i][:2] if self.i < len(self.t) else (None, None)
def take(self, kind=None, val=None): k, v = self.peek() if k is None or (kind and k != kind) or (val is not None and v != val): raise Reject(f"malformed near token {self.i}") self.i += 1 return v
def parse(self): if not self.t: raise Reject("empty") e = self.expr() if self.i != len(self.t): raise Reject("trailing input") return e
def expr(self): v = self.term() while self.peek() in (("sym", "+"), ("sym", "-")): op = self.take() r = self.term() v = v + r if op == "+" else v - r return v
def starts_atom(self): k, v = self.peek() return k == "num" or (k == "sym" and v in "({[") or (k == "cmd" and v in ({"frac", "sqrt", "pi"} | self.allowed)) \ or (k == "let" and v == "e" and "e" in self.allowed)
def term(self): v = self.unary() while True: k, s = self.peek() if (k, s) in (("sym", "*"), ("cmd", "cdot"), ("cmd", "times")): self.take(); v = v * self.unary() elif (k, s) == ("sym", "/"): self.take(); v = v / _nonzero(self.unary()) elif self.starts_atom(): if self.peek()[0] == "num": raise Reject("two numbers side by side") # "2 100" or "\sqrt 16" is malformed, not a product v = v * self.power() # implicit multiplication: 2\sqrt{3}, 3\pi, 2(1+x) else: return v
def unary(self): if self.peek() == ("sym", "-"): self.take(); return -self.unary() if self.peek() == ("sym", "+"): self.take(); return self.unary() return self.power()
def power(self): base = self.atom() if self.peek() != ("sym", "^"): return base self.take() if self.peek() == ("sym", "{"): exp = self.group() elif self.peek() in (("sym", "-"), ("sym", "+")): sign = -1 if self.take() == "-" else 1 # 2^-1 exp = sign * self.atom() else: exp = self.atom() if self.peek() == ("sym", "^"): raise Reject("power tower") return self._pow(base, exp)
def _pow(self, base, exp): if not exp.is_number or exp.is_real is False: raise Reject("non-numeric exponent") if not exp.is_Rational: if base == sympy.E and "e" in self.allowed and abs(sympy.N(exp, 15)) <= MAX_EXPONENT: return sympy.exp(exp) # e^{\ln 2} raise Reject("irrational exponent not supported") if abs(exp) > MAX_EXPONENT: raise Reject("exponent too large") if base == 0 and exp <= 0: raise Reject("0^0 or division by zero") if exp < 0: _nonzero(base) if _pow_bits(base) * max(1, abs(int(exp.p))) > MAX_POW_BITS: raise Reject("value too large") if base.is_negative and exp.q % 2 == 1 and exp.q > 1: return (-1) ** exp.p * (-base) ** exp # real odd root: (-8)^{1/3} = -2 return base ** exp
def group(self): open_ = self.take("sym") close = {"(": ")", "[": "]", "{": "}"}.get(open_) if close is None: raise Reject("unexpected symbol") v = self.expr() self.take("sym", close) return v
def arg(self): """A TeX macro argument: {..}, (..) / [..] (plain-text style), or ONE token (\\frac12, \\frac\\pi4, \\sqrt2).""" k, v = self.peek() if k == "sym" and v in "{([": return self.group() if k == "num": raw = self.t[self.i][2] if not raw.isdigit(): raise Reject("ambiguous unbraced argument") if len(raw) == 1: self.i += 1 return v self.t[self.i] = ("num", Integer(int(raw[1:])), raw[1:]) # TeX takes one digit: \frac12 = 1/2 return Integer(int(raw[0])) if (k == "cmd" and v == "pi") or (k == "let" and v == "e" and "e" in self.allowed): return self.atom() raise Reject("ambiguous unbraced argument")
def atom(self): k, v = self.peek() if k == "num": self.take(); return v if k == "sym" and v in "({[": return self.group() if k == "let" and v == "e" and "e" in self.allowed: self.take(); return sympy.E if k == "cmd": self.take() if v == "frac": n, d = self.arg(), self.arg() return n / _nonzero(d) if v == "sqrt": if self.peek() == ("sym", "["): self.take(); idx = self.expr(); self.take("sym", "]") if not (idx.is_Integer and 2 <= idx <= 50): raise Reject("bad root index") return self._pow(self.arg(), Rational(1, int(idx))) return self._pow(self.arg(), Rational(1, 2)) if v == "pi": return sympy.pi if v in FUNCS and v in self.allowed: if self.peek() in (("sym", "{"), ("sym", "("), ("sym", "[")): a = self.group() else: a = self.power() return FUNCS[v](a) raise Reject(f"\\{v} not allowed") if k == "let": raise Reject(f"variable or word {v!r}") raise Reject("malformed")
def allowed_from_reference(ref_clean: str) -> set: allowed = {c for c in FUNCS if re.search(r"\\" + c + r"(?![A-Za-z])", ref_clean)} if re.search(r"(?<![A-Za-z\\])e(?![A-Za-z])", re.sub(r"\\[A-Za-z]+", "", ref_clean)): allowed.add("e") for fam in FAMILIES: if allowed & fam: allowed |= fam return allowed
def value(text: str, allowed: set, is_reference: bool = False): t = clean(text) if not t: raise Reject("empty") if len(t) > MAX_LEN: raise Reject("answer too long") if re.search(r"\\(?:text|mathrm|mathbf|operatorname|boxed|fbox)\{|\\%|%|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\in(?![A-Za-z])|\\infty|\\circ|°|,", t): raise Reject("not a single exact number (units/text/relation/percent/approximation/list)") tokens = _mixed_numbers(tokenize(t, sci="e" not in allowed), is_reference) v = Parser(tokens, allowed).parse() if v.has(sympy.zoo, sympy.oo, -sympy.oo, sympy.nan) or v.is_finite is False: raise Reject("non-finite value") if v.is_real is False: raise Reject("not a real number") return v
def _is_transcendental(expr) -> bool: return expr.has(sympy.E) or any(expr.has(f) for f in TRANSCENDENTAL)
def exact_equal(s, g) -> bool: """True only if s == g is PROVED. Numeric evaluation is used to reject quickly, never to accept.""" if s.is_Rational and g.is_Rational: return s == g d = s - g if d == 0: return True try: dv, gv = sympy.N(d, 50), sympy.N(g, 50) if dv.is_Number and gv.is_Number and abs(dv) > sympy.Float("1e-30", 50) * max(1, abs(gv)): return False except Exception: pass if _is_transcendental(d): # ln / e / trig: only an exact simplification to 0 counts for cand in (sympy.expand_log(d), d): try: if sympy.simplify(cand) == 0: return True except Exception: pass return False if d.has(sympy.pi): # pi is transcendental: d == 0 iff every coefficient in T is 0 num = sympy.together(sympy.expand(d.subs(sympy.pi, _T))).as_numer_denom()[0] poly = sympy.Poly(sympy.expand(num), _T) return all(sympy.minimal_polynomial(c, _X) == _X for c in poly.coeffs()) return sympy.minimal_polynomial(d, _X) == _X
def grade(reference: str, submission: str): try: ref_clean = clean(reference) allowed = allowed_from_reference(ref_clean) g = value(reference, allowed, is_reference=True) except Reject as e: return False, f"reference unusable: {e}" except Exception as e: return False, f"reference unusable: {type(e).__name__}" try: s = value(submission, allowed) except Reject as e: return False, f"format: {e}" except (RecursionError, ValueError, TypeError, ZeroDivisionError, OverflowError) as e: return False, f"format: {type(e).__name__}" try: ok = exact_equal(s, g) except Exception as e: return False, f"could not prove equal ({type(e).__name__})" return (True, "exact match") if ok else (False, "wrong value")
def _worker(q, reference, submission): try: import resource # cap = current address space + MEM_LIMIT (an absolute cap breaks vm = 0 # workers forked from big parents: they hang instead of grading) for line in open("/proc/self/status"): if line.startswith("VmSize:"): vm = int(line.split()[1]) * 1024 resource.setrlimit(resource.RLIMIT_AS, (vm + MEM_LIMIT, vm + MEM_LIMIT)) except Exception: pass try: q.put(grade(reference, submission)) except MemoryError: q.put((False, "grader out of memory")) except Exception as e: q.put((False, f"grader error: {type(e).__name__}"))
def grade_safe(reference: str, submission: str, timeout: float = 10.0): ctx = mp.get_context("fork") q = ctx.Queue() p = ctx.Process(target=_worker, args=(q, reference, submission)) p.start(); p.join(timeout) if p.is_alive(): p.kill(); p.join() return False, "timeout" try: return q.get(timeout=1) except Exception: return False, "grader crashed"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476"""Exact grader for structured math answers (Loubna msg 1257): a SET or TUPLE of exact numbers, an INTERVAL / union ofintervals with exact endpoints, or an EXPRESSION in named variables. Builds on the single-number grader (grader.py):same extraction/cleaning, same restricted parser and the same exact number equality (never a numeric tolerance).
grade(reference, submission, kind, variables="") -> (passed, reason) grade_safe(...) same, in a memory-capped subprocess with a timeout (use this in verifiers)
kind (fixed per task, stated in the task instruction): set {a, b, c}: order and repeats do not matter; braces optional tuple (a, b, c): order matters; parentheses optional interval [a, b), (-\\infty, c] \\cup [d, \\infty) ...: compared as SETS of reals (unions are merged exactly) expression one expression in the listed variables (e.g. "n" or "a,b"): equal as functions, proved by exact symbolic simplification to 0; random numeric evaluation can only rejectNumbers inside follow grader.py (exact values, functions only if the reference uses their family)."""import multiprocessing as mpimport randomimport reimport sysfrom pathlib import Path
import sympy
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))import grader as G # noqa: E402from grader import Reject # noqa: E402
__version__ = "1"_orig_nonzero = G._nonzero
def _nonzero_sym(d): """Divisors with variables are allowed unless identically zero; numeric divisors keep grader.py's check.""" if getattr(d, "free_symbols", None): if sympy.cancel(sympy.together(d)) == 0: raise Reject("division by zero") return d return _orig_nonzero(d)
G._nonzero = _nonzero_symKINDS = ("set", "tuple", "interval", "expression")MAX_ITEMS = 60_INF = re.compile(r"^\s*([+-]?)\s*\\infty\s*$|^\s*([+-]?)\s*\\inf\s*$|^\s*([+-]?)\s*oo\s*$")
# ---------------------------------------------------------------- shared helpersdef _top_level_boxes(text: str): out, i = [], 0 while True: m = G._BOX.search(text, i) if not m: return out depth, j = 1, m.end() while j < len(text) and depth: depth += {"{": 1, "}": -1}.get(text[j], 0) j += 1 out.append(re.sub(r"\s+", "", text[m.end():j - 1])) i = j
def _clean_struct(text: str) -> str: """grader.clean without its single-value wrapper stripping of commas; keeps \\{ \\} \\cup. Several top-level boxes with different contents are a hedge: rejected (review 2026-11-24).""" if len(set(_top_level_boxes(text or ""))) > 1: raise Reject("several different boxed answers") if len(text or "") > 20_000: raise Reject("answer too long") text = re.sub(r"\\\\(?=[A-Za-z{}])", r"\\", text) # shell-doubled backslashes: \\\\frac -> \\frac t = G.clean(text) # plain-text function names (agents often write ln(x), sin x): same as grader.clean does for sqrt( and pi t = re.sub(r"(?<![\\A-Za-z])(arcsin|arccos|arctan|ln|log|sin|cos|tan|exp)(?![A-Za-z])", r"\\\1 ", t) t = re.sub(r"\\lbrace|\\\{", "{", t) t = re.sub(r"\\rbrace|\\\}", "}", t) t = re.sub(r"\\(?:lbrack)", "[", t) t = re.sub(r"\\(?:rbrack)", "]", t) t = re.sub(r"\\(?:mathbb\{R\}|R)(?![A-Za-z])", "R", t) return t.strip()
def _split_top(s: str, sep: str = ","): out, depth, cur = [], 0, [] for ch in s: if ch in "([{": depth += 1 elif ch in ")]}": depth -= 1 if depth < 0: raise Reject("unbalanced brackets") if ch == sep and depth == 0: out.append("".join(cur)); cur = [] else: cur.append(ch) if depth != 0: raise Reject("unbalanced brackets") out.append("".join(cur)) return [x.strip() for x in out]
def _number(elem: str, allowed: set, is_reference: bool, labels: bool = True): """One exact real number (grader.py rules); also strips a leading 'x =' / 'x_1 =' unless labels=False.""" if not labels and re.match(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=", elem) and not is_reference: raise Reject("labelled tuple components (write the tuple in the asked order, without names)") e = re.sub(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*", "", elem.strip()) if not e: raise Reject("empty element") if re.search(r"\\(?:text|mathrm|mbox|operatorname)\{|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\infty|%", e): raise Reject("element is not a single exact number") toks = G._mixed_numbers(G.tokenize(e, sci="e" not in allowed), is_reference) v = G.Parser(toks, allowed).parse() if v.has(sympy.zoo, sympy.oo, -sympy.oo, sympy.nan) or v.is_finite is False: raise Reject("non-finite value") if v.is_real is False: raise Reject("not a real number") return v
def _strip_outer(t: str, pairs): for a, b in pairs: if t.startswith(a) and t.endswith(b): inner = t[len(a):len(t) - len(b)] try: _split_top(inner) # the outer pair must enclose everything (not "(1,2),(3,4)") except Reject: continue depth, ok = 0, True for ch in inner: depth += {"(": 1, "[": 1, "{": 1, ")": -1, "]": -1, "}": -1}.get(ch, 0) if depth < 0: ok = False break if ok: return inner.strip(), True return t, False
def _items(text: str, allowed: set, is_reference: bool, brackets, labels: bool = True): t = _clean_struct(text) if not t: raise Reject("empty") if len(t) > G.MAX_LEN * 2: raise Reject("answer too long") if re.search(r"\\(?:text|mbox)\{[^}]*[A-Za-z]{2,}|\b(?:or|and)\b", t) and not re.search(r"\\(?:text|mbox)\{\s*,?\s*\}", t): raise Reject("words in the answer (write only the list)") inner, _ = _strip_outer(t, brackets) parts = _split_top(inner) if len(parts) > MAX_ITEMS: raise Reject("too many items") if any(not p for p in parts): raise Reject("empty item") return [_number(p, allowed, is_reference, labels) for p in parts]
def _eq(a, b) -> bool: try: return G.exact_equal(a, b) except Exception: return False
def _dedup(vals): out = [] for v in vals: if not any(_eq(v, w) for w in out): out.append(v) return out
# ---------------------------------------------------------------- set / tupledef grade_set(reference, submission, allowed): g = _dedup(_items(reference, allowed, True, [("{", "}")])) s = _dedup(_items(submission, allowed, False, [("{", "}")])) if len(s) != len(g): return False, f"wrong number of elements ({len(s)} vs {len(g)})" left = list(g) for v in s: k = next((i for i, w in enumerate(left) if _eq(v, w)), None) if k is None: return False, "wrong element" left.pop(k) return True, "exact match"
def grade_tuple(reference, submission, allowed): g = _items(reference, allowed, True, [("(", ")"), ("[", "]"), ("{", "}")]) s = _items(submission, allowed, False, [("(", ")"), ("[", "]")], labels=False) if len(s) != len(g): return False, f"wrong length ({len(s)} vs {len(g)})" for v, w in zip(s, g): if not _eq(v, w): return False, "wrong component" return True, "exact match"
# ---------------------------------------------------------------- intervalsdef _endpoint(e, allowed, is_reference): m = _INF.match(e) if m: sign = "".join(x for x in m.groups() if x) return -sympy.oo if sign == "-" else sympy.oo return _number(e, allowed, is_reference)
def _intervals(text, allowed, is_reference): t = _clean_struct(text) if not t: raise Reject("empty") t = re.sub(r"^\s*[A-Za-z]\s*\\in\s*", "", t) # "x \in [1,2)" if re.fullmatch(r"R|\(-\\infty\s*,\s*\+?\\infty\)", t.replace(" ", "")): return [(-sympy.oo, False, sympy.oo, False)] pieces = [p.strip() for p in re.split(r"\\cup|∪|(?<![A-Za-z])U(?![A-Za-z])", t)] out = [] for p in pieces: if len(p) < 5 or p[0] not in "([" or p[-1] not in ")]": raise Reject("each piece must look like (a, b), [a, b], [a, b) or (a, b]") parts = _split_top(p[1:-1]) if len(parts) != 2: raise Reject("an interval needs exactly two endpoints") lo, hi = _endpoint(parts[0], allowed, is_reference), _endpoint(parts[1], allowed, is_reference) lc, hc = p[0] == "[", p[-1] == "]" if (lo in (sympy.oo, -sympy.oo) and lc) or (hi in (sympy.oo, -sympy.oo) and hc): raise Reject("infinite endpoint must be open") if lo == sympy.oo or hi == -sympy.oo: raise Reject("bad infinite endpoint") out.append((lo, lc, hi, hc)) return out
def _num(v): return float("inf") if v == sympy.oo else float("-inf") if v == -sympy.oo else float(sympy.N(v, 30))
def _cmp(a, b): """-1/0/1 exactly (0 only if PROVED equal).""" if a in (sympy.oo, -sympy.oo) or b in (sympy.oo, -sympy.oo): return 0 if a == b else (-1 if _num(a) < _num(b) else 1) if _eq(a, b): return 0 d = sympy.N(a - b, 60) if not d.is_Number or d == 0: raise Reject("cannot order interval endpoints") return -1 if d < 0 else 1
def _normalize(ivs): """Drop empty pieces, sort, merge overlapping / touching pieces: a canonical union.""" keep = [] for lo, lc, hi, hc in ivs: c = _cmp(lo, hi) if c > 0 or (c == 0 and not (lc and hc)): continue # empty piece keep.append((lo, lc, hi, hc)) keep.sort(key=lambda x: (_num(x[0]), not x[1])) out = [] for iv in keep: if out: lo, lc, hi, hc = out[-1] c = _cmp(iv[0], hi) if c < 0 or (c == 0 and (hc or iv[1])): # overlap, or touching with the shared point included c2 = _cmp(iv[2], hi) nhi, nhc = (iv[2], iv[3]) if c2 > 0 else (hi, hc or iv[3]) if c2 == 0 else (hi, hc) out[-1] = (lo, lc, nhi, nhc) continue out.append(iv) return out
def grade_interval(reference, submission, allowed): g = _normalize(_intervals(reference, allowed, True)) s = _normalize(_intervals(submission, allowed, False)) if len(s) != len(g): return False, "different set of reals" for (a, ac, b, bc), (c, cc, d, dc) in zip(s, g): if _cmp(a, c) != 0 or _cmp(b, d) != 0 or ac != cc or bc != dc: return False, "different set of reals" return True, "exact match"
# ---------------------------------------------------------------- expressions in variablesclass VarParser(G.Parser): """grader.Parser plus named variables (single letters or greek commands) and symbolic exponents."""
def __init__(self, tokens, allowed, variables): super().__init__(tokens, allowed) # positive: AoPS variables are lengths, counts and indices (sqrt(a^2) = a); review 2026-11-24 item F self.vars = {v: sympy.Symbol(v, real=True) for v in variables}
def term(self): """grader.Parser.term, but a number may follow ')', '}', ']' or a variable: (n+1)2^n, n2^n, 2^n3^n.""" v = self.unary() while True: k, s = self.peek() if (k, s) in (("sym", "*"), ("cmd", "cdot"), ("cmd", "times")): self.take(); v = v * self.unary() elif (k, s) == ("sym", "/"): self.take(); v = v / G._nonzero(self.unary()) elif self.starts_atom(): if k == "num": pk, pv = self.t[self.i - 1][:2] if not ((pk == "sym" and pv in ")}]") or (pk in ("let", "cmd") and pv in self.vars)): raise Reject("two numbers side by side") v = v * self.power() else: return v
def arg(self): k, v = self.peek() if k in ("let", "cmd") and v in self.vars: # \frac ab return self.atom() return super().arg()
def starts_atom(self): k, v = self.peek() return super().starts_atom() or ((k == "let" or k == "cmd") and v in self.vars)
def atom(self): k, v = self.peek() if (k == "let" or k == "cmd") and v in self.vars: self.take() if self.peek() == ("sym", "_"): raise Reject("subscripts not supported") return self.vars[v] return super().atom()
def _pow(self, base, exp): if exp.free_symbols or base.free_symbols: if exp.is_Rational and abs(exp) > 60: raise Reject("exponent too large") if exp.free_symbols and base.free_symbols: raise Reject("variable in base and exponent") if base.free_symbols and exp.is_Rational and exp.q > 1: return sympy.Pow(base, exp) return sympy.Pow(base, exp) return super()._pow(base, exp)
def _expr(text, allowed, variables, is_reference): raw = G._last_top_level_box(G._normalize_unicode(text or "")) or (text or "") m0 = re.match(r"^[\s$\\(\[]*([A-Za-z])\s*=", raw) if m0 and m0.group(1) in variables: raise Reject("an equation in the variable, not an expression") if is_reference and (re.search(r"\\\{|\\lbrace|\\(?:sin|cos|tan|ln|log|exp)\s*\d+\s*[A-Za-z]|/\s*[A-Za-z]\s*[A-Za-z]", raw)): raise Reject("ambiguous reference (braces, function of a product, or a/bc)") t = _clean_struct(text) m = re.match(r"^\s*([A-Za-z])(\([^()]*\))?(?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*(?=[^=]+$)", t) # "f(n) = ...", "S = ..." if m: if m.group(1) in variables and not m.group(2): raise Reject("an equation in the variable, not an expression") t = t[m.end():] if is_reference and (re.search(r"\\(?:sin|cos|tan|ln|log|exp)\s*\d+\s*[A-Za-z]", t) or "{" in re.sub(r"\\[A-Za-z]+\s*\{|[\^_]\s*\{|\}\s*\{", "", t).replace("\\{", "{") and re.search(r"\\\{", t) or re.search(r"/\s*[A-Za-z]\s*[A-Za-z]", t)): raise Reject("ambiguous reference (function of a product, braces, or a/bc)") if not t: raise Reject("empty") if len(t) > G.MAX_LEN: raise Reject("answer too long") if re.search(r"\\(?:text|mathrm|mbox|operatorname)\{|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\infty|,|%|\\sum|\\prod|\\int|!", t): raise Reject("not a single closed-form expression") toks = G.tokenize(t, sci=False) toks = [("sym", "_", "_") if x[0] == "sym" and x[1] == "_" else x for x in toks] v = VarParser(toks, allowed, variables).parse() if v.has(sympy.zoo, sympy.nan): raise Reject("undefined value") extra = {str(s) for s in v.free_symbols} - set(variables) if extra: raise Reject(f"unknown variables {sorted(extra)}") return v
def _points(syms, rng, k=6): """Random rational points away from 0 and 1 (positive, so radicals and logs of the variables stay real).""" return [{s: sympy.Rational(rng.randint(7, 97), rng.randint(3, 13)) for s in syms} for _ in range(k)]
def grade_expression(reference, submission, allowed, variables): g = _expr(reference, allowed, variables, True) s = _expr(submission, allowed, variables, False) d = s - g if d == 0: return True, "exact match" syms = sorted(d.free_symbols | g.free_symbols, key=str) rng = random.Random(0) for pt in _points(syms, rng): try: dv, gv = sympy.N(d.subs(pt), 40), sympy.N(g.subs(pt), 40) except Exception: continue if dv.is_Number and gv.is_Number and abs(dv) > sympy.Float("1e-25", 40) * max(1, abs(gv)): return False, "different expression" try: # equal up to a constant factor 1: a(sqrt6-sqrt2) = 2a sqrt(2-sqrt3) q = sympy.cancel(sympy.together(s / g)) if not q.free_symbols and q.is_number and _eq(q, sympy.Integer(1)): return True, "exact match" except Exception: pass for cand in (lambda e: sympy.cancel(sympy.together(e)), sympy.radsimp, sympy.simplify, lambda e: sympy.simplify(sympy.expand_log(sympy.expand_power_base(e, force=False)))): try: if cand(d) == 0: return True, "exact match" except Exception: pass return False, "could not prove the expressions equal"
# ---------------------------------------------------------------- entry pointsdef parse_variables(variables): vs = [v.strip().lstrip("\\") for v in re.split(r"[,\s]+", variables or "") if v.strip()] for v in vs: if not re.fullmatch(r"[A-Za-z]|alpha|beta|gamma|theta|lambda|mu|phi|omega|rho|sigma|tau", v) or v in ("e", "i"): raise Reject(f"unsupported variable name {v!r}") return vs
def grade(reference: str, submission: str, kind: str, variables: str = ""): if kind not in KINDS: return False, f"unknown kind {kind!r}" try: ref_clean = _clean_struct(reference) allowed = G.allowed_from_reference(ref_clean) vs = parse_variables(variables) if kind == "expression" else [] if kind == "expression": allowed.discard("e") if "e" in vs else None except Reject as e: return False, f"reference unusable: {e}" try: if kind == "set": return grade_set(reference, submission, allowed) if kind == "tuple": return grade_tuple(reference, submission, allowed) if kind == "interval": return grade_interval(reference, submission, allowed) return grade_expression(reference, submission, allowed, vs) except Reject as e: return False, f"format: {e}" except (RecursionError, ValueError, TypeError, ZeroDivisionError, OverflowError, AttributeError) as e: return False, f"format: {type(e).__name__}" except Exception as e: return False, f"could not grade ({type(e).__name__})"
def check_reference(reference: str, kind: str, variables: str = ""): """Reference parses under the kind's rules and matches itself.""" return grade(reference, reference, kind, variables)
def _worker(q, *args): try: import resource vm = 0 for line in open("/proc/self/status"): if line.startswith("VmSize:"): vm = int(line.split()[1]) * 1024 resource.setrlimit(resource.RLIMIT_AS, (vm + G.MEM_LIMIT, vm + G.MEM_LIMIT)) except Exception: pass try: q.put(grade(*args)) except MemoryError: q.put((False, "grader out of memory")) except Exception as e: q.put((False, f"grader error: {type(e).__name__}"))
def grade_safe(reference: str, submission: str, kind: str, variables: str = "", timeout: float = 20.0): ctx = mp.get_context("fork") q = ctx.Queue() p = ctx.Process(target=_worker, args=(q, reference, submission, kind, variables)) p.start(); p.join(timeout) if p.is_alive(): p.kill(); p.join() return False, "timeout" try: return q.get(timeout=1) except Exception: return False, "grader crashed"12345678910{ "answer": "$2^{u-2}$", "task_id": "imo-bench-algebra-004", "category": "Algebra", "subcategory": "Inequality", "source": "IMO Shortlist 2021", "answer_kind": "expression", "kind": "expression", "variables": "u"}12345678910111213#!/bin/bash# Reward 1 if /app/answer.txt holds an answer equal to the hidden reference (a set, tuple, interval or# expression; grader.py checks it exactly with sympy).# 0 is written before anything runs, so a crash, a timeout or a missing/linked/oversized answer scores 0.# Python runs isolated (-I -S); sympy/mpmath come from the pinned wheels in this directory (hash-checked, unpacked# offline into a new directory): nothing is installed and no network is used. ANSWER and VERIFIER_DIR override# the paths, to test the grader locally.case $0 in */*) here=${0%/*} ;; *) here=. ;; esacexport ANSWER=${ANSWER:-/app/answer.txt}export VERIFIER_DIR=${VERIFIER_DIR:-/logs/verifier}export TESTS_DIR=$here[ -d "$VERIFIER_DIR" ] && echo 0 > "$VERIFIER_DIR/reward.txt"timeout 150 python3 -B -I -S "$here/grade_task.py" || true123456789# Problem
$p, q, r, s$ are positive real numbers satisfying $(p+s)(r+q) = ps + qr$. Find the smallest possible value of
\[\frac{p}{q} + \frac{r}{p} + \frac{s}{r} + \frac{q}{s}.\]
Write your final answer as a single exact number in `/app/answer.txt`. Do not include a derivation.1234567#!/bin/bashset -euanswer=${ANSWER:-/app/answer.txt}mkdir -p "$(dirname "$answer")"cat > "$answer" <<'ANSWER_EOF'8ANSWER_EOF12345678910111213141516171819202122232425262728schema_version = "1.4"artifacts = ["/app/answer.txt"]
[task]name = "imo-answerbench/imo-bench-algebra-005"version = "1.0.0"description = "IMO-AnswerBench v2 short-answer mathematics problem"keywords = ["math", "imo", "evaluation"]
[metadata]category = "Algebra"subcategory = "Inequality"source = "IMO Shortlist 2020"problem_id = "imo-bench-algebra-005"answer_kind = "number"
[agent]network_mode = "allowlist"timeout_sec = 3600
[environment]docker_image = "docker.io/library/python:3.12-slim"cpus = 1memory_mb = 2048
[verifier]network_mode = "allowlist"timeout_sec = 180123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""Grade the answer file against tests/reference.json. Writes reward.txt (1/0), grade.json and a copy of theanswer (answer.txt) to VERIFIER_DIR. Any error -> reward 0. The sympy/mpmath wheels ship base64-encoded (plain gittext: the Hub stores binary files in LFS/Xet, which a plain `git checkout` without git-lfs cannot read)."""import base64import hashlibimport ioimport jsonimport osimport statimport sysimport tempfileimport zipfile
LIMIT = 10_000 # bytesWHEELS = {"sympy-1.14.0-py3-none-any.whl": "e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", "mpmath-1.3.0-py3-none-any.whl": "a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c"}
def read_own(path): """Bytes of the regular file at exactly `path`: every folder on the way and the file are opened without following links (a FIFO cannot block it); one link only; at most LIMIT bytes.""" parts = os.path.abspath(path).split("/")[1:] folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY) try: for part in parts[:-1]: inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder) os.close(folder) folder = inner fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder) finally: os.close(folder) with os.fdopen(fd, "rb") as stream: info = os.fstat(stream.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1: raise ValueError("answer is not a regular file of its own") data = stream.read(LIMIT + 1) if len(data) > LIMIT: raise ValueError(f"answer file larger than {LIMIT} bytes") return data
def write_new(path, text): try: os.unlink(path) except FileNotFoundError: pass fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o644) with os.fdopen(fd, "w") as stream: stream.write(text)
def load_grader(tests): lib = tempfile.mkdtemp(prefix="grader-lib-") for name, digest in WHEELS.items(): blob = base64.b64decode(open(os.path.join(tests, name + ".b64"), "rb").read()) if hashlib.sha256(blob).hexdigest() != digest: raise ValueError(f"wheel hash mismatch: {name}") with zipfile.ZipFile(io.BytesIO(blob)) as z: z.extractall(lib) sys.path[:0] = [lib, tests] import grader, grader_struct return grader, grader_struct
def main(): tests, out = os.environ["TESTS_DIR"], os.environ["VERIFIER_DIR"] os.makedirs(out, exist_ok=True) write_new(os.path.join(out, "reward.txt"), "0") passed, why, submission = False, "grader error", "" try: try: submission = read_own(os.environ["ANSWER"]).decode("utf-8", "replace") except FileNotFoundError: submission, why = None, "no answer file" except (OSError, ValueError) as e: submission, why = None, f"answer file rejected: {e}" if submission is not None: write_new(os.path.join(out, "answer.txt"), submission) ref = json.loads(open(os.path.join(tests, "reference.json")).read()) reference, kind, variables = ref["answer"], ref["kind"], ref.get("variables", "") if not submission.strip(): passed, why = False, "empty" elif kind == "literal": import unicodedata def normalize(s): # Preserve all mathematical characters, operators, punctuation and case. return " ".join(unicodedata.normalize("NFC", s).split()).strip() passed = normalize(reference) == normalize(submission) why = "literal match" if passed else "literal mismatch" else: grader, structured = load_grader(tests) if kind == "number": passed, why = grader.grade_safe(reference, submission, timeout=60) else: passed, why = structured.grade_safe(reference, submission, kind, variables, timeout=60) except Exception as e: passed, why = False, f"grader error: {type(e).__name__}: {str(e)[:200]}" if passed: write_new(os.path.join(out, "reward.txt"), "1") write_new(os.path.join(out, "grade.json"), json.dumps({"passed": passed, "why": why, "submission": (submission or "")[:500]})) print("reward:", 1 if passed else 0, "|", why)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501"""Strict, exact single-number grader for Harbor math tasks (v2).
Contract (one uniform instruction for every task): the final answer is ONE exact number, e.g. 42, -7, 3/8,\\frac{3}{8}, 2\\sqrt{3}, \\frac{\\pi}{4}. No units, words, variables, "x =", sets, ranges, percent, or approximations.
grade(reference, submission) -> (passed: bool, reason: str) grade_safe(reference, submission, timeout=10) -> same, run in a memory-capped subprocess (use this in verifiers)
How it works- Extract: the last top-level \\boxed{...} / \\fbox{...} (brace-matched; a box nested inside the chosen box is rejected), else the whole text. Normalize unicode (NFKC, every dash/minus, superscript digits, zero-width chars, BOM), strip markdown bold, "Answer:", $..$, \\(..\\), \\[..\\], a trailing period (repeatedly, so "$5$." works), \\left. \\right. (null delimiters), \\left/\\right, LaTeX spacing; plain-text forms sqrt(..), pi, ** become LaTeX. Digit grouping (1,024 / 1\\,024 / 1 024 / 1{,}024) is removed only when the whole number is grouped in threes. 0.\\overline{3} becomes 1/3 exactly.- Parse with a small recursive-descent parser over a restricted grammar: numbers, + - * / ^, \\frac (also with TeX single-token arguments, \\frac12 = 1/2), \\sqrt{x}, \\sqrt[n]{x} (odd roots of negatives are real: \\sqrt[3]{-8} = -2), \\pi, \\cdot, \\times, brackets, implicit multiplication. Functions (\\ln/\\log, \\exp/e, \\sin/\\cos/\\tan, \\arcsin/\\arccos/\\arctan) are allowed only if the REFERENCE uses their family, so the problem cannot be restated instead of solved (\\lfloor, \\binom, factorials, sums: never). Scientific notation (1e5) is off when the reference uses the constant e (so "4e+1" means 4e+1). "3\\frac{1}{6}" is a mixed number in a reference and is rejected as ambiguous in a submission. "\\sqrt 16" (TeX: sqrt(1)*6) is rejected. 0^0, division by zero, non-real and huge values are rejected; written decimals are exact rationals (0.25 = 1/4; 1.41421356 is NOT sqrt 2).- Compare EXACTLY, never with a numeric tolerance (a numeric check can only reject, for speed): rationals by equality; algebraic numbers by minimal_polynomial(s - g) == x; expressions with pi as polynomials in a symbol T with algebraic coefficients (pi is transcendental); anything with ln/e/trig only if sympy simplifies the difference to exactly 0. Anything that cannot be proved equal within the time limit fails."""import multiprocessing as mpimport reimport unicodedata
import sympyfrom sympy import Integer, Rational
__version__ = "2"MAX_LEN = 1000 # characters of the cleaned answerMAX_INT_DIGITS = 1000 # digits of any number literalMAX_EXPONENT = 3000 # |exponent| allowed in a power or in scientific notationMAX_POW_BITS = 100_000 # estimated size of an exact power before computing itMEM_LIMIT = 2 << 30 # extra address space allowed to the grade_safe worker (bytes)FUNCS = {"ln": sympy.log, "log": sympy.log, "sin": sympy.sin, "cos": sympy.cos, "tan": sympy.tan, "arcsin": sympy.asin, "arccos": sympy.acos, "arctan": sympy.atan, "exp": sympy.exp}FAMILIES = [{"ln", "log"}, {"exp", "e"}, {"sin", "cos", "tan"}, {"arcsin", "arccos", "arctan"}]TRANSCENDENTAL = (sympy.exp, sympy.log, sympy.sin, sympy.cos, sympy.tan, sympy.asin, sympy.acos, sympy.atan)_X, _T = sympy.Symbol("x"), sympy.Symbol("T")
class Reject(Exception): pass
# ---------------------------------------------------------------- extraction and cleaning_BOX = re.compile(r"\\(?:boxed|fbox)\s*\{")_SUPERSCRIPT = str.maketrans("\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079\u207b", "0123456789-")_DASHES = "\u2010\u2011\u2012\u2013\u2014\u2212\ufe63\uff0d"
def _last_top_level_box(text: str): """Content of the last \\boxed{..}/\\fbox{..} that is not inside another box; None if there is no box. Rejects an unbalanced last box and a box nested inside the chosen box.""" spans, i = [], 0 while True: m = _BOX.search(text, i) if not m: break depth, j = 1, m.end() while j < len(text) and depth: depth += {"{": 1, "}": -1}.get(text[j], 0) j += 1 if depth: raise Reject("unbalanced \\boxed") spans.append((m.end(), j - 1)) i = j # continue AFTER this box: inner boxes are not top level if not spans: return None a, b = spans[-1] inner = text[a:b] if _BOX.search(inner): raise Reject("box inside box") return inner
def _normalize_unicode(t: str) -> str: t = re.sub("[\ufeff\u200b\u200c\u200d\u2060\u00ad]", "", t) t = re.sub("[\u2070\u00b9\u00b2\u00b3\u2074-\u2079\u207b]+", lambda m: "^{" + m.group().translate(_SUPERSCRIPT) + "}", t) for ch in _DASHES: t = t.replace(ch, "-") t = t.replace("\u00d7", "\\times ").replace("\u00b7", "\\cdot ").replace("\u22c5", "\\cdot ") t = t.replace("\u03c0", "\\pi ").replace("\u221a", "\\sqrt") return unicodedata.normalize("NFKC", t)
def _repeating(m) -> str: whole, fixed, rep = m.group(1) or "0", m.group(2), m.group(3) num = Integer(int(fixed + rep)) - Integer(int(fixed or "0")) den = Integer(10) ** len(fixed) * (Integer(10) ** len(rep) - 1) v = Integer(int(whole)) + num / den return f"(\\frac{{{v.p}}}{{{v.q}}})"
_NOT_UNIT = re.compile(r"\b(?:or|and|to|for|if|is|not|no|none|either|approx|about|between|each|where|with)\b", re.I)_UNIT_TEXT = re.compile(r"\s*\\(?:text|mathrm|mbox|textrm|operatorname)\s*\{\s*([A-Za-z][A-Za-z ./^0-9-]{0,24})\}\s*$")_UNIT_WORD = re.compile(r"(?<=[\d})])\s+([A-Za-z]{2,12}(?:\s?/\s?[A-Za-z]{1,8})?(?:\^\{?\d\}?)?)\s*$")_DEGREES = re.compile(r"\s*(?:\^\s*\{?\s*\\circ\s*\}?|°|\\degree)\s*$")_LHS = re.compile(r"^\s*[A-Za-z](?:_\{?[A-Za-z0-9]+\}?)?\s*=\s*(?=[^=]+$)")
def strip_wrappers(t: str) -> str: """Remove a wrapper around ONE value: trailing units (30 ft/s, 111 meters, \\sqrt{109}\\text{ m}), a degree sign, or a single 'n =' prefix. Hedges ('32 \\text{ or } 33'), approximations and multi-part answers are untouched.""" prev = None while t != prev: prev = t m = _UNIT_TEXT.search(t) if m and not _NOT_UNIT.search(m.group(1)) and t[:m.start()].strip(): t = t[:m.start()].rstrip() m = _UNIT_WORD.search(t) if m and not _NOT_UNIT.search(m.group(1)): t = t[:m.start()].rstrip() if t[:-1].strip(): t = _DEGREES.sub("", t).rstrip() t = _LHS.sub("", t) return t
def clean(text: str) -> str: t = _normalize_unicode((text or "").strip()) boxed = _last_top_level_box(t) if boxed is not None: t = boxed prev = None while t != prev: # peel wrappers in any order: "**Answer:** $5$." -> 5 prev = t t = t.strip() t = re.sub(r"^(\*\*|__)(.*)\1$", r"\2", t, flags=re.S).strip() t = re.sub(r"^\**\s*(?:the\s+)?(?:final\s+)?answer\s*(?:is)?\s*[:=]?\s*\**\s*", "", t, flags=re.I).strip() for a, b in (("$$", "$$"), ("$", "$"), ("\\(", "\\)"), ("\\[", "\\]")): if t.startswith(a) and t.endswith(b) and len(t) > len(a) + len(b): t = t[len(a):-len(b)].strip() t = t.rstrip(". ").strip() t = re.sub(r"\\(?:left|right)\.", "", t) # null delimiters t = re.sub(r"\\(?:displaystyle|left|right|bigl|bigr|Bigl|Bigr|big|Big)(?![A-Za-z])", "", t) t = re.sub(r"\\mathrm\{e\}|\\mathit\{e\}", "e", t) t = re.sub(r"\\[dtc]frac(?![A-Za-z])", r"\\frac", t) t = re.sub(r"(\d*)\.(\d*)\\overline\{(\d+)\}", _repeating, t) t = re.sub(r"(?<=\d)\\[,;! ](?=\d{3}(?!\d))", "", t) # 2\,560\,320 -> 2560320 t = re.sub(r"\\[,;:! ]|~", " ", t) t = strip_wrappers(t) # 30 ft/s, n = 24^5, 30° -> the bare value t = re.sub(r"(?<=\d)\s*\{,\}\s*(?=\d{3}(?!\d))", "", t) # 3{,}100 if re.fullmatch(r"\s*-?\d{1,3}([, ]\d{3})+(\.\d+)?\s*", t) and len(set(re.findall(r"[, ]", t.strip()))) == 1: t = re.sub(r"[, ]", "", t) # 3,100 / 1,000.5 / 1 000 (one separator kind) t = t.replace("**", "^") # python power t = re.sub(r"(?<![\\A-Za-z])sqrt\s*(?=[({])", r"\\sqrt", t) # sqrt(2) -> \sqrt(2) t = re.sub(r"(?<![\\A-Za-z])pi(?![A-Za-z])", r"\\pi ", t) # pi/4 -> \pi/4 return re.sub(r"\s+", " ", t).strip()
# ---------------------------------------------------------------- parserTOKEN = re.compile(r"\s*(?:(?P<num>\d+\.\d*|\.\d+|\d+)(?:[eE](?P<exp>[+-]?\d+))?|(?P<cmd>\\[A-Za-z]+)|(?P<sym>[-+*/^(){}\[\]])|(?P<let>[A-Za-z]))")NUM_ONLY = re.compile(r"\s*(?P<num>\d+\.\d*|\.\d+|\d+)")
def tokenize(s: str, sci: bool = True): """Tokens are (kind, value, raw). sci=False turns scientific notation off (the reference uses the constant e).""" out, pos = [], 0 while pos < len(s): m = TOKEN.match(s, pos) if m and not sci and m.group("num") is not None and m.group("exp") is not None: m = NUM_ONLY.match(s, pos) # "4e+1" -> 4, e, +, 1 if not m or m.end() == pos: if s[pos:].strip() == "": break raise Reject(f"unexpected character {s[pos]!r}") pos = m.end() if m.group("num") is not None: num = m.group("num") if len(num.replace(".", "")) > MAX_INT_DIGITS: raise Reject("number too long") val = Rational(num) if "." in num else Integer(int(num)) exp = m.groupdict().get("exp") if exp is not None: if abs(int(exp)) > MAX_EXPONENT: raise Reject("exponent too large") val = val * Rational(10) ** int(exp) out.append(("num", val, m.group(0).strip())) elif m.group("cmd"): out.append(("cmd", m.group("cmd")[1:], m.group("cmd"))) elif m.group("sym"): out.append(("sym", m.group("sym"), m.group("sym"))) else: out.append(("let", m.group("let"), m.group("let"))) return out
def _mixed_numbers(tokens, is_reference: bool): """N\\frac{a}{b} with integer literals N, a, b: a mixed number (N + a/b) in a reference; ambiguous in a submission.""" out, i = [], 0 pat = ["num", ("cmd", "frac"), ("sym", "{"), "num", ("sym", "}"), ("sym", "{"), "num", ("sym", "}")] while i < len(tokens): win = tokens[i:i + 8] ok = len(win) == 8 and all((w[0] == p) if isinstance(p, str) else (w[0], w[1]) == p for w, p in zip(win, pat)) ok = ok and all(win[k][2].isdigit() for k in (0, 3, 6)) prev = out[-1] if out else None if ok and not (prev and (prev[0] == "cmd" or prev[:2] == ("sym", "^"))): if not is_reference: raise Reject("ambiguous mixed number (write 7/2, not 3\\frac{1}{2})") if win[6][1] == 0: raise Reject("division by zero") out.append(("num", win[0][1] + win[3][1] / win[6][1], "mixed")) i += 8 continue out.append(tokens[i]); i += 1 return out
def _nonzero(d): """Reject a zero divisor, including a disguised one (sqrt(3+2sqrt2)-1-sqrt2). Numeric check: reject-only.""" if d == 0 or d.is_zero: raise Reject("division by zero") if not d.is_Rational: try: v = sympy.N(d, 60) except Exception: raise Reject("cannot evaluate divisor") if not v.is_Number or abs(v) < sympy.Float("1e-45", 60): raise Reject("division by (numerically) zero") return d
def _pow_bits(expr) -> int: return sum(abs(int(r.p)).bit_length() + int(r.q).bit_length() for r in expr.atoms(sympy.Rational)) or 1
class Parser: """expr := term (('+'|'-') term)* ; term := unary (('*'|'/'|implicit) unary)* ; unary := ('-'|'+') unary | power power := atom ('^' exponent)? ; atom := number | group | \\frac A A | \\sqrt[n] A | \\pi | e | func arg"""
def __init__(self, tokens, allowed): self.t, self.i, self.allowed = list(tokens), 0, allowed
def peek(self): return self.t[self.i][:2] if self.i < len(self.t) else (None, None)
def take(self, kind=None, val=None): k, v = self.peek() if k is None or (kind and k != kind) or (val is not None and v != val): raise Reject(f"malformed near token {self.i}") self.i += 1 return v
def parse(self): if not self.t: raise Reject("empty") e = self.expr() if self.i != len(self.t): raise Reject("trailing input") return e
def expr(self): v = self.term() while self.peek() in (("sym", "+"), ("sym", "-")): op = self.take() r = self.term() v = v + r if op == "+" else v - r return v
def starts_atom(self): k, v = self.peek() return k == "num" or (k == "sym" and v in "({[") or (k == "cmd" and v in ({"frac", "sqrt", "pi"} | self.allowed)) \ or (k == "let" and v == "e" and "e" in self.allowed)
def term(self): v = self.unary() while True: k, s = self.peek() if (k, s) in (("sym", "*"), ("cmd", "cdot"), ("cmd", "times")): self.take(); v = v * self.unary() elif (k, s) == ("sym", "/"): self.take(); v = v / _nonzero(self.unary()) elif self.starts_atom(): if self.peek()[0] == "num": raise Reject("two numbers side by side") # "2 100" or "\sqrt 16" is malformed, not a product v = v * self.power() # implicit multiplication: 2\sqrt{3}, 3\pi, 2(1+x) else: return v
def unary(self): if self.peek() == ("sym", "-"): self.take(); return -self.unary() if self.peek() == ("sym", "+"): self.take(); return self.unary() return self.power()
def power(self): base = self.atom() if self.peek() != ("sym", "^"): return base self.take() if self.peek() == ("sym", "{"): exp = self.group() elif self.peek() in (("sym", "-"), ("sym", "+")): sign = -1 if self.take() == "-" else 1 # 2^-1 exp = sign * self.atom() else: exp = self.atom() if self.peek() == ("sym", "^"): raise Reject("power tower") return self._pow(base, exp)
def _pow(self, base, exp): if not exp.is_number or exp.is_real is False: raise Reject("non-numeric exponent") if not exp.is_Rational: if base == sympy.E and "e" in self.allowed and abs(sympy.N(exp, 15)) <= MAX_EXPONENT: return sympy.exp(exp) # e^{\ln 2} raise Reject("irrational exponent not supported") if abs(exp) > MAX_EXPONENT: raise Reject("exponent too large") if base == 0 and exp <= 0: raise Reject("0^0 or division by zero") if exp < 0: _nonzero(base) if _pow_bits(base) * max(1, abs(int(exp.p))) > MAX_POW_BITS: raise Reject("value too large") if base.is_negative and exp.q % 2 == 1 and exp.q > 1: return (-1) ** exp.p * (-base) ** exp # real odd root: (-8)^{1/3} = -2 return base ** exp
def group(self): open_ = self.take("sym") close = {"(": ")", "[": "]", "{": "}"}.get(open_) if close is None: raise Reject("unexpected symbol") v = self.expr() self.take("sym", close) return v
def arg(self): """A TeX macro argument: {..}, (..) / [..] (plain-text style), or ONE token (\\frac12, \\frac\\pi4, \\sqrt2).""" k, v = self.peek() if k == "sym" and v in "{([": return self.group() if k == "num": raw = self.t[self.i][2] if not raw.isdigit(): raise Reject("ambiguous unbraced argument") if len(raw) == 1: self.i += 1 return v self.t[self.i] = ("num", Integer(int(raw[1:])), raw[1:]) # TeX takes one digit: \frac12 = 1/2 return Integer(int(raw[0])) if (k == "cmd" and v == "pi") or (k == "let" and v == "e" and "e" in self.allowed): return self.atom() raise Reject("ambiguous unbraced argument")
def atom(self): k, v = self.peek() if k == "num": self.take(); return v if k == "sym" and v in "({[": return self.group() if k == "let" and v == "e" and "e" in self.allowed: self.take(); return sympy.E if k == "cmd": self.take() if v == "frac": n, d = self.arg(), self.arg() return n / _nonzero(d) if v == "sqrt": if self.peek() == ("sym", "["): self.take(); idx = self.expr(); self.take("sym", "]") if not (idx.is_Integer and 2 <= idx <= 50): raise Reject("bad root index") return self._pow(self.arg(), Rational(1, int(idx))) return self._pow(self.arg(), Rational(1, 2)) if v == "pi": return sympy.pi if v in FUNCS and v in self.allowed: if self.peek() in (("sym", "{"), ("sym", "("), ("sym", "[")): a = self.group() else: a = self.power() return FUNCS[v](a) raise Reject(f"\\{v} not allowed") if k == "let": raise Reject(f"variable or word {v!r}") raise Reject("malformed")
def allowed_from_reference(ref_clean: str) -> set: allowed = {c for c in FUNCS if re.search(r"\\" + c + r"(?![A-Za-z])", ref_clean)} if re.search(r"(?<![A-Za-z\\])e(?![A-Za-z])", re.sub(r"\\[A-Za-z]+", "", ref_clean)): allowed.add("e") for fam in FAMILIES: if allowed & fam: allowed |= fam return allowed
def value(text: str, allowed: set, is_reference: bool = False): t = clean(text) if not t: raise Reject("empty") if len(t) > MAX_LEN: raise Reject("answer too long") if re.search(r"\\(?:text|mathrm|mathbf|operatorname|boxed|fbox)\{|\\%|%|\\approx|\\pm|\\mp|=|<|>|\\le|\\ge|\\ne|\\in(?![A-Za-z])|\\infty|\\circ|°|,", t): raise Reject("not a single exact number (units/text/relation/percent/approximation/list)") tokens = _mixed_numbers(tokenize(t, sci="e" not in allowed), is_reference) v = Parser(tokens, allowed).parse() if v.has(sympy.zoo, sympy.oo, -sympy.oo, sympy.nan) or v.is_finite is False: raise Reject("non-finite value") if v.is_real is False: raise Reject("not a real number") return v
def _is_transcendental(expr) -> bool: return expr.has(sympy.E) or any(expr.has(f) for f in TRANSCENDENTAL)
def exact_equal(s, g) -> bool: """True only if s == g is PROVED. Numeric evaluation is used to reject quickly, never to accept.""" if s.is_Rational and g.is_Rational: return s == g d = s - g if d == 0: return True try: dv, gv = sympy.N(d, 50), sympy.N(g, 50) if dv.is_Number and gv.is_Number and abs(dv) > sympy.Float("1e-30", 50) * max(1, abs(gv)): return False except Exception: pass if _is_transcendental(d): # ln / e / trig: only an exact simplification to 0 counts for cand in (sympy.expand_log(d), d): try: if sympy.simplify(cand) == 0: return True except Exception: pass return False if d.has(sympy.pi): # pi is transcendental: d == 0 iff every coefficient in T is 0 num = sympy.together(sympy.expand(d.subs(sympy.pi, _T))).as_numer_denom()[0] poly = sympy.Poly(sympy.expand(num), _T) return all(sympy.minimal_polynomial(c, _X) == _X for c in poly.coeffs()) return sympy.minimal_polynomial(d, _X) == _X
def grade(reference: str, submission: str): try: ref_clean = clean(reference) allowed = allowed_from_reference(ref_clean) g = value(reference, allowed, is_reference=True) except Reject as e: return False, f"reference unusable: {e}" except Exception as e: return False, f"reference unusable: {type(e).__name__}" try: s = value(submission, allowed) except Reject as e: return False, f"format: {e}" except (RecursionError, ValueError, TypeError, ZeroDivisionError, OverflowError) as e: return False, f"format: {type(e).__name__}" try: ok = exact_equal(s, g) except Exception as e: return False, f"could not prove equal ({type(e).__name__})" return (True, "exact match") if ok else (False, "wrong value")
def _worker(q, reference, submission): try: import resource # cap = current address space + MEM_LIMIT (an absolute cap breaks vm = 0 # workers forked from big parents: they hang instead of grading) for line in open("/proc/self/status"): if line.startswith("VmSize:"): vm = int(line.split()[1]) * 1024 resource.setrlimit(resource.RLIMIT_AS, (vm + MEM_LIMIT, vm + MEM_LIMIT)) except Exception: pass try: q.put(grade(reference, submission)) except MemoryError: q.put((False, "grader out of memory")) except Exception as e: q.put((False, f"grader error: {type(e).__name__}"))
def grade_safe(reference: str, submission: str, timeout: float = 10.0): ctx = mp.get_context("fork") q = ctx.Queue() p = ctx.Process(target=_worker, args=(q, reference, submission)) p.start(); p.join(timeout) if p.is_alive(): p.kill(); p.join() return False, "timeout" try: return q.get(timeout=1) except Exception: return False, "grader crashed"README.mdAdded+60
subsets/algebra.jsonlAdded+100
subsets/combinatorics.jsonlAdded+100
subsets/geometry.jsonlAdded+100
subsets/number_theory.jsonlAdded+100
tasks/imo-bench-algebra-001/instruction.mdAdded+5
tasks/imo-bench-algebra-001/solution/solve.shAdded+7
tasks/imo-bench-algebra-001/task.tomlAdded+28
tasks/imo-bench-algebra-001/tests/grade_task.pyAdded+104
tasks/imo-bench-algebra-001/tests/grader.pyAdded+501
tasks/imo-bench-algebra-001/tests/grader_struct.pyAdded+476
tasks/imo-bench-algebra-001/tests/mpmath-1.3.0-py3-none-any.whl.b64Added
tasks/imo-bench-algebra-001/tests/reference.jsonAdded+10
tasks/imo-bench-algebra-001/tests/sympy-1.14.0-py3-none-any.whl.b64Added
tasks/imo-bench-algebra-001/tests/test.shAdded+13
tasks/imo-bench-algebra-002/instruction.mdAdded+6
tasks/imo-bench-algebra-002/solution/solve.shAdded+7
tasks/imo-bench-algebra-002/task.tomlAdded+28
tasks/imo-bench-algebra-002/tests/grade_task.pyAdded+104
tasks/imo-bench-algebra-002/tests/grader.pyAdded+501
tasks/imo-bench-algebra-002/tests/grader_struct.pyAdded+476
tasks/imo-bench-algebra-002/tests/mpmath-1.3.0-py3-none-any.whl.b64Added
tasks/imo-bench-algebra-002/tests/reference.jsonAdded+10
tasks/imo-bench-algebra-002/tests/sympy-1.14.0-py3-none-any.whl.b64Added
tasks/imo-bench-algebra-002/tests/test.shAdded+13
tasks/imo-bench-algebra-003/instruction.mdAdded+12
tasks/imo-bench-algebra-003/solution/solve.shAdded+7
tasks/imo-bench-algebra-003/task.tomlAdded+28
tasks/imo-bench-algebra-003/tests/grade_task.pyAdded+104
tasks/imo-bench-algebra-003/tests/grader.pyAdded+501
tasks/imo-bench-algebra-003/tests/grader_struct.pyAdded+476
tasks/imo-bench-algebra-003/tests/mpmath-1.3.0-py3-none-any.whl.b64Added
tasks/imo-bench-algebra-003/tests/reference.jsonAdded+10
tasks/imo-bench-algebra-003/tests/sympy-1.14.0-py3-none-any.whl.b64Added
tasks/imo-bench-algebra-003/tests/test.shAdded+13
tasks/imo-bench-algebra-004/instruction.mdAdded+5
tasks/imo-bench-algebra-004/solution/solve.shAdded+7
tasks/imo-bench-algebra-004/task.tomlAdded+28
tasks/imo-bench-algebra-004/tests/grade_task.pyAdded+104
tasks/imo-bench-algebra-004/tests/grader.pyAdded+501
tasks/imo-bench-algebra-004/tests/grader_struct.pyAdded+476
tasks/imo-bench-algebra-004/tests/mpmath-1.3.0-py3-none-any.whl.b64Added
tasks/imo-bench-algebra-004/tests/reference.jsonAdded+10
tasks/imo-bench-algebra-004/tests/sympy-1.14.0-py3-none-any.whl.b64Added
tasks/imo-bench-algebra-004/tests/test.shAdded+13
tasks/imo-bench-algebra-005/instruction.mdAdded+9
tasks/imo-bench-algebra-005/solution/solve.shAdded+7
tasks/imo-bench-algebra-005/task.tomlAdded+28
tasks/imo-bench-algebra-005/tests/grade_task.pyAdded+104
tasks/imo-bench-algebra-005/tests/grader.pyAdded+501